def refine(atmsel): # at T=1000, max_atom_shift for 4fs is cca 0.15 A. md = molecular_dynamics(cap_atom_shift=0.39, md_time_step=4.0, md_return='FINAL') init_vel = True for (its, equil, temps) in ((200, 20, (150.0, 250.0, 400.0, 700.0, 1000.0)), (200, 600, (1000.0, 800.0, 600.0, 500.0, 400.0, 300.0))): for temp in temps: md.optimize(atmsel, init_velocities=init_vel, temperature=temp, max_iterations=its, equilibrate=equil) init_vel = False
def Optimizemodel(pdb_file): """ This functions returns a file with the optimized model from the input pdb. It also returns the energies. """ env = environ() env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') code, ext = pdb_file.split('.') mdl = complete_pdb(env, pdb_file) mdl.write(file=code + '.ini') # Select all atoms: atmsel = selection(mdl) mpdf2 = atmsel.energy() # Generate the restraints: #mdl.restraints.make(atmsel, restraint_type='improper', spline_on_site=False) #mdl.restraints.make(atmsel, restraint_type='bond', spline_on_site=False) #mdl.restraints.make(atmsel, restraint_type='sphere', spline_on_site=False) mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) mdl.restraints.write(file=code + '.rsr') mpdf1 = atmsel.energy() # Create optimizer objects and set defaults for all further optimizations cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') # Open a file to get basic stats on each optimization trcfil = open(code + '.D00000001', 'w') # Run CG on the all-atom selection; write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=actions.trace(5, trcfil)) # Run MD; write out a PDB structure (called '1fas.D9999xxxx.pdb') every # 10 steps during the run, and write stats every 10 steps md.optimize(atmsel, temperature=300, max_iterations=50, actions=[ actions.write_structure(10, code + '.D9999%04d.pdb'), actions.trace(10, trcfil) ]) #refine(atmsel, code, trcfil) # Finish off with some more CG, and write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=[actions.trace(5, trcfil)]) mpdf = atmsel.energy() print("The initial energy of " + code + " is " + str(mpdf1[0])) print("The final energy of " + code + " is " + str(mpdf[0])) print("The final energy of " + code + " is " + str(mpdf2[0])) mdl.write(file=code + '_optimized.pdb')
def Optimizemodel(pdb_file, optimize): print("Calculating the energy of the model...") output_path_optimized = "/".join(pdb_file.split('/')[:-1]) sys.stdout = open(os.devnull, 'w') env = environ() env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') filename = pdb_file.split("/")[-1] code = filename.split('.')[0] mdl = complete_pdb(env, pdb_file) mdl.write(file=output_path_optimized + "/" + code + '.ini') # Select all atoms: atmsel = selection(mdl) mpdf2 = atmsel.energy() sys.stdout = sys.__stdout__ if optimize: print('Optimizing the model...') sys.stdout = open(os.devnull, 'w') # Generate the restraints: mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) mdl.restraints.write(file=output_path_optimized + "/" + code + '.rsr') # Create optimizer objects and set defaults for all further optimizations cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') # Run CG on the all-atom selection cg.optimize(atmsel, max_iterations=20) # Run MD md.optimize(atmsel, temperature=300, max_iterations=50) # Finish off with some more CG cg.optimize(atmsel, max_iterations=20) mpdf = atmsel.energy() # Create .pdb mdl.write(file=output_path_optimized + "/" + code + '_optimized.pdb') # Remove interdmediate files os.remove(output_path_optimized + "/" + code + ".ini") os.remove(output_path_optimized + "/" + code + ".rsr") sys.stdout = sys.__stdout__ return mpdf2[0], mpdf[0] else: os.remove(output_path_optimized + "/" + code + '.ini') return mpdf2[0]
def sgmdrefine(atmsel, actions, cap, timestep, equil_its, equil_equil, equil_temps, sampl_its, sampl_equil, sampl_temps): from modeller.optimizers import molecular_dynamics mdl = atmsel.get_model() md = molecular_dynamics(cap_atom_shift=cap, md_time_step=timestep, md_return='FINAL', output=mdl.optimize_output, actions=actions,friction=0,guide_factor=0,guide_time=0) init_vel = True # First run for equilibration, the second for sampling: for (its, equil, temps) in ((equil_its, equil_equil, equil_temps),(sampl_its, sampl_equil, sampl_temps)): for temp in temps: md.optimize(atmsel, max_iterations=its, equilibrate=equil, temperature=temp, init_velocities=init_vel) init_vel=False
def optimize(directory, number): log.none() env = environ() env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') filename = directory + "/model_" + str(number) + ".pdb" #read model files code = directory + "/model_" + str(number) mdl = complete_pdb(env, filename) # Select all atoms: atmsel = selection(mdl) # Generate the restraints: mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) # Create optimizer objects and set defaults for all further optimizations cg = conjugate_gradients(output='NO_REPORT') md = molecular_dynamics(output='NO_REPORT') if not os.path.exists(directory + '/optimization_stats'): os.makedirs(directory + '/optimization_stats') # Open a file to get basic stats on each optimization trcfil = open( directory + '/optimization_stats/model_' + str(number) + '.D00000001', 'w') # Run CG on the all-atom selection; write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=actions.trace(5, trcfil)) # Run MD; write out a PDB structure (called '1fas.D9999xxxx.pdb') every # 10 steps during the run, and write stats every 10 steps md.optimize(atmsel, temperature=300, max_iterations=50, actions=[actions.trace(10, trcfil)]) # Finish off with some more CG, and write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=[actions.trace(5, trcfil)]) #mpdf = atmsel.energy() mdl.write(file=code + '.pdb')
def optimize(pdb, pdb_path): print(1, pdb_path) # Environ data env = environ(0) env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') code = pdb.split('.')[0] mdl = complete_pdb(env, pdb) mdl.write(file=code+'.ini') # Select all atoms: atmsel = selection(mdl) # Generate the restraints: mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) mdl.restraints.write(file=code+'.rsr') mpdf_prior = atmsel.energy() # Create optimizer objects and set defaults for all further optimizations cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') # Open a file to get basic stats on each optimization trcfil = open(code+'.D00000001', 'w') # Run CG on the all-atom selection; write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=actions.trace(5, trcfil)) # Run MD; write out a PDB structure (called '1fas.D9999xxxx.pdb') every # 10 steps during the run, and write stats every 10 steps md.optimize(atmsel, temperature=300, max_iterations=50, actions=[actions.write_structure(10, code+'.D9999%04d.pdb'), actions.trace(10, trcfil)]) # Finish off with some more CG, and write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=[actions.trace(5, trcfil)]) mpdf_after = atmsel.energy() mdl.write(file=os.path.join(pdb_path, 'optimized.pdb')) return (mpdf_prior, mpdf_after)
def refine(atmsel): # at T=1000, max_atom_shift for 4fs is cca 0.15 A. md = molecular_dynamics( cap_atom_shift=0.39, md_time_step= 4.0, ## cap_atom_shifts limita a distância (A) de movimento ao longo de um eixo md_return='FINAL' ) ## estrutura final pode não ser a mínima de toda a trajectória - 'MINIMAL' init_vel = True for (its, equil, temps) in ((200, 20, (150.0, 250.0, 400.0, 700.0, 1000.0)), (200, 600, (1000.0, 800.0, 600.0, 500.0, 400.0, 300.0))): for temp in temps: md.optimize( atmsel, init_velocities=init_vel, temperature=temp, max_iterations=its, equilibrate=equil ) ## equilibrate = re-escalonamento das velocidades após equil passos (200 < 600???) init_vel = False ## usa as mesmas velocidades da corrida anterior
code = '1fas' mdl = complete_pdb(env, code) mdl.write(file=code+'.ini') # Select all atoms: atmsel = selection(mdl) # Generate the restraints: mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) mdl.restraints.write(file=code+'.rsr') mpdf = atmsel.energy() # Create optimizer objects and set defaults for all further optimizations cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') # Open a file to get basic stats on each optimization trcfil = file(code+'.D00000001', 'w') # Run CG on the all-atom selection; write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=actions.trace(5, trcfil)) # Run MD; write out a PDB structure (called '1fas.D9999xxxx.pdb') every # 10 steps during the run, and write stats every 10 steps md.optimize(atmsel, temperature=300, max_iterations=50, actions=[actions.write_structure(10, code+'.D9999%04d.pdb'), actions.trace(10, trcfil)]) # Finish off with some more CG, and write stats every 5 steps cg.optimize(atmsel, max_iterations=20, actions=[actions.trace(5, trcfil)])
dih_lib_only=True) mdl.restraints.make(all_atoms, aln=aln, restraint_type='PHI_DIHEDRAL',spline_on_site=True, dih_lib_only=True) mdl.restraints.make(all_atoms, aln=aln, restraint_type='PSI_DIHEDRAL',spline_on_site=True, dih_lib_only=True) mdl.restraints.condense() # energy data env.edat.dynamic_lennard = True # Prepare optimizer scaling_factors = physical.values(default=1.0, em_density=0) MD = molecular_dynamics(output='REPORT',cap_atom_shift=0.0001, md_time_step=0.05,temperature=params.temperature, init_velocities=True,md_return=params.md_return, equilibrate = params.equilibrate, schedule_scale=scaling_factors) w=actions.write_structure(params.skip_its_for_writing, 'md-%03d.pdb', write_all_atoms=True, first=True, last=True, start=0) # optimize MD.optimize(all_atoms, max_iterations=params.max_iterations,actions=[w]) for c in mdl.chains: c.name = 'A' mdl.remark ="" mdl.reorder_atoms() mdl.write(params.output_pdb_file, model_format='PDB')
# Generate two copies of a segment: mdl = complete_pdb(env, '2abx', model_segment=('1:A', '74:B')) mdl.rename_segments(segment_ids=('A', 'B'), renumber_residues=(1, 1)) myedat = energy_data(dynamic_sphere=False) atmsel = selection(mdl) atmsel.energy(edat=myedat) atmsel.randomize_xyz(deviation=6.0) # Define the two segments (chains in this case) to be identical: defsym(mdl, seg1=('1:A', '74:A'), seg2=('1:B', '74:B')) # Create optimizer objects cg = conjugate_gradients() md = molecular_dynamics(md_return='FINAL') # Make them identical by optimizing the initial randomized structure # without any other restraints: atmsel.energy(edat=myedat) mdl.write(file='define_symmetry-1.atm') cg.optimize(atmsel, max_iterations=300, edat=myedat) mdl.write(file='define_symmetry-2.atm') atmsel.energy(edat=myedat) # Now optimize with stereochemical restraints so that the # result is not so distorted a structure (still distorted # because optimization is not thorough): myedat.dynamic_sphere = True mdl.restraints.make(atmsel, restraint_type='stereo',
def run(self): int_seed=randint(0,2**8) env = environ(rand_seed=int_seed) env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') ###################### reading the density ###################### den = density(env, file=self.path + '/' + self.em_map_file, em_density_format=self.format, em_map_size=self.box_size, density_type='GAUSS', voxel_size=self.apix, resolution=self.res,px=self.x,py=self.y,pz=self.z) env.edat.density = den env.edat.dynamic_sphere = True ###################### read pdb file ###################### aln = alignment(env) mdl2 = model(env, file=self.input_pdb_file) aln.append_model(mdl2, align_codes=self.input_pdb_file, atom_files=self.input_pdb_file) mdl = model(env, file=self.input_pdb_file) aln.append_model(mdl, align_codes=self.code, atom_files=self.code) aln.align(gap_penalties_1d=(-600, -400)) mdl.clear_topology() mdl.generate_topology(aln[self.input_pdb_file]) mdl.transfer_xyz(aln) mdl.build(initialize_xyz=False, build_method='INTERNAL_COORDINATES') ####################### Remove chain names ###################### for c in mdl.chains: c.name = ' ' mdl.write(file=self.code+'_ini.pdb') ###################### Select the mobile atoms ###################### sel_all = selection(mdl) sel_fixed=[] if(self.fixed_filename!=''): # read the list of fixed residues read_selection_list(self.path,mdl,sel_fixed,self.fixed_filename) # select the non fixed, those ones that are going to be optimized mobile_atoms = [] for n in sel_all: mobile =True for m in sel_fixed: if n in m: mobile=False break if mobile: mobile_atoms.append(n) # print "mobile atom ..",n print "number of mobile atoms ..",len(mobile_atoms) sel_mobile=selection(mobile_atoms) # selection of mobile residues ###################### RESTRAINTS FOR MOBILE ATOMS ############ # STEREOCHEMICAL restraints (based on the model) mdl.restraints.make(sel_mobile, restraint_type='STEREO', spline_on_site=False) # MAINCHAIN homology restraints forcing to look in the library # (dih_lib_only = True) and ignore the template. mdl.restraints.make(sel_mobile, aln=aln, restraint_type='PHI-PSI_BINORMAL',spline_on_site=True, dih_lib_only=True) mdl.restraints.make(sel_mobile, aln=aln, restraint_type='OMEGA_DIHEDRAL',spline_on_site=True, dih_lib_only=True) # SIDECHAIN homology restraints forcing to look in the library # (dih_lib_only = True) and ignore the template. mdl.restraints.make(sel_mobile, aln=aln, restraint_type='CHI1_DIHEDRAL',spline_on_site=True, dih_lib_only=True) mdl.restraints.make(sel_mobile, aln=aln, restraint_type='CHI2_DIHEDRAL',spline_on_site=True, dih_lib_only=True) ###################### define rigid bodies ###################### sel_rigid=[] rand_rigid=[] if(self.rigid_filename != ''): load_rigid(self.path,mdl,sel_rigid,rand_rigid,self.rigid_filename) for n in sel_rigid: include_it=True # Only add not fixed rigid bodies. Adding fixed ones is superfluous for m in sel_fixed: if(n in m): include_it=False break if(include_it): print "Considering rigid body ...",n # for at in n: # print "atom ...",at mdl.restraints.rigid_bodies.append(rigid_body(n)) # Remove duplicated restraints mdl.restraints.unpick_redundant() # Write all the restraints to a file mdl.restraints.write(file=self.code+'.rsr') ###################### MOLECULAR DYNAMICS ANNEALING ################ print "MD annealing" scal_for_annealing = physical.values(default=1.0, em_density=10000) cap=0.39 timestep=5.0 icount=0 trc_file = open('MD'+self.run_num+'.trc', "a") ###################### loop for number of cycles a,b = 1,self.cycles while a <= b: equil_its=self.equil_its_for_heating equil_equil=20 equil_temps= self.equil_temps_for_heating trc_step=5 init_vel = True # during heating simulations, FINAL structure is always returned. # If the MINIMAL would be returned, no heating would be achieved. MD = molecular_dynamics(cap_atom_shift=cap, md_time_step=timestep, md_return='FINAL', output='REPORT', schedule_scale=scal_for_annealing) ###################### heating the system for (its, equil, temps) in [(equil_its, equil_equil, equil_temps)]: for temp in temps: # optimize the mobile atoms MD.optimize(sel_mobile, max_iterations=its, temperature=temp, init_velocities=init_vel, equilibrate=equil, actions=[actions.trace(trc_step,trc_file)]) # print progress scal = physical.values(default=0.0, em_density=1.0) (molpdf, terms) = sel_all.energy(schedule_scale=scal) print "HEATING: iteration number= %s step= %d %d "\ "temp= %d EM score= %.3f" %(a,icount,its,int(temp),-molpdf) icount=icount+equil_its init_vel=False ###################### cooling the system equil_its=self.equil_its_for_cooling equil_temps= self.equil_temps_for_cooling # during the cooling MD simulations the structure returned can be # FINAL or MINIMAL acording to the option selected MD = molecular_dynamics(cap_atom_shift=cap, md_time_step=timestep, md_return=self.md_return, output='REPORT', schedule_scale=scal_for_annealing) for (its, equil, temps) in [(equil_its, equil_equil, equil_temps)]: for temp in temps: MD.optimize(sel_mobile, max_iterations=its, temperature=temp, init_velocities=init_vel, equilibrate=equil, actions=[actions.trace(trc_step,trc_file)]) scal = physical.values(default=0.0, em_density=1.0) (molpdf, terms) = sel_all.energy(schedule_scale=scal) print "COOLING: iteration number= %s step= %d %d " \ "temp= %d EM score= %.3f" %(a,icount,its,int(temp),-molpdf) icount=icount+equil_its filename='md'+self.run_num+'_'+str(a)+'.pdb' sel_all.write(file=filename) a+=1 trc_file.close() print "MD FINAL: step= %d: energy all (with scaling 1:10000)" % icount eval = sel_all.energy(schedule_scale=scal_for_annealing) ################## final minimization with and without CC restraints. ################## Optimize all atoms for refinement CG = conjugate_gradients() print " final conjugate_gradients" CG.optimize(sel_all, output='REPORT', max_iterations=200, schedule_scale=scal_for_annealing) eval = sel_all.energy(schedule_scale=scal_for_annealing) scal = physical.values(default=1.0, em_density=0.0) CG.optimize(sel_all, output='REPORT', max_iterations=200, schedule_scale=scal) eval = sel_all.energy(schedule_scale=scal) sel_all.write(file='final'+self.run_num+'_mdcg.pdb') os.system("rm -f *.MRC")
def Optimizemodel(pdb_file): """ It creates a PDB file with the optimized model from the input pdb, with its energies and restraint contributions. Also it will create pdbs on every step of the Molecular Dynamics optimization. The energy is returned as the total value of Modeller's objective function, molpdf. It also shows the topt 10 contributors to the molpdf before and after optimization """ # Setting up env = environ() env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') code, ext = pdb_file.split('.') # Complete the pdb and make a model mdl = complete_pdb(env, pdb_file) mdl.write(file=code + '.ini') # Select all atoms from the model, make restraints and save them in a file atmsel = selection(mdl) mdl.restraints.make(atmsel, restraint_type='stereo', spline_on_site=False) mdl.restraints.write(file=code + '.rsr') # Check the energy before optimization and save it in a var initial_mpdf = atmsel.energy() # Create optimizer objects cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') # Open a file to get basic stats on each optimization stats_file = open(code + '_opt.stats', 'w') # Run MD. Write out a PDB structure every 10 steps during the run. # Write stats every 10 steps md.optimize(atmsel, temperature=300, max_iterations=50, actions=[ actions.write_structure(10, code + '.MD%04d.pdb'), actions.trace(10, stats_file) ]) # Run CG, and write stats every 5 steps cg.optimize(atmsel, max_iterations=50, actions=[actions.trace(5, stats_file)]) # Final energy final_mpdf = atmsel.energy() # Assess DOPE atmsel.assess_dope(output='ENERGY_PROFILE NO_REPORT', file='TvLDH.profile', normalize_profile=True, smoothing_window=15) # Print the energies and the contributions initial_cont_all = dict(initial_mpdf[1]) top_init_conts = dict( sorted(initial_cont_all.items(), key=itemgetter(1), reverse=True)[:5]) l.info("\n\nThe initial energy of " + code + " is " + str(initial_mpdf[0])) print("\n\nThe initial energy of " + code + " is " + str(initial_mpdf[0])) print("The top 10 initial contributions the restraints are:\n") for keys, values in top_init_conts.items(): print(keys, ":", values) final_cont_all = dict(final_mpdf[1]) top_final_conts = dict( sorted(final_cont_all.items(), key=itemgetter(1), reverse=True)[:5]) l.info("\n\nThe final energy of " + code + " is " + str(final_mpdf[0])) print("\n\nThe final energy of " + code + " is " + str(final_mpdf[0])) print("Final contributions the restraints are:\n") for keys, values in top_final_conts.items(): print(keys, ":", values) mdl.write(file=code + '_optimized.pdb')
def optimization(pdb_file, options): """This function needs as an input a PDB file (the model), and gives as an output the optimized model.""" env = environ() env.io.atom_files_directory = ['../atom_files'] env.edat.dynamic_sphere = True env.libs.topology.read(file='$(LIB)/top_heav.lib') env.libs.parameters.read(file='$(LIB)/par.lib') path, ext = pdb_file.split('.') list = path.split('/') #if results/4g83/4g83model.pdb list[0]=results list[1]=4g83 list[2]=4g83model dir = list[0] + "/" + list[1] code = list[2] mdl = complete_pdb(env, pdb_file) mdl.write(file=path + '.ini') atmsel = selection(mdl) mpdf_ini = atmsel.energy() z_score_ini = mdl.assess_normalized_dope() mdl_ep_ini = atmsel.get_dope_profile() mdl_ep_ini_smoothed = mdl_ep_ini.get_smoothed() energy_profile_txt_path = dir + '/' + code + '_DOPE_EnergyProfile.txt' mdl_ep_ini_smoothed.write_to_file(energy_profile_txt_path) print("The unoptimized model's energy of " + code + " is: " + str(mpdf_ini[0])) print("The unoptimized Z-score of " + code + " is: " + str(z_score_ini)) energy_profile_txt_path_opt = None if options.optimize: cg = conjugate_gradients(output='REPORT') md = molecular_dynamics(output='REPORT') trcfil = open(path + '.D00000001', 'w') cg.optimize(atmsel, max_iterations=20, actions=actions.trace(5, trcfil)) md.optimize(atmsel, temperature=300, max_iterations=50, actions=[ actions.write_structure(10, path + '.D9999%04d.pdb'), actions.trace(10, trcfil) ]) cg.optimize(atmsel, max_iterations=20, actions=[actions.trace(5, trcfil)]) mpdf = atmsel.energy() z_score = mdl.assess_normalized_dope() print("The final model energy of " + path + " is " + str(mpdf[0])) print("The final model energy of " + path + " is " + str(mpdf_ini[0])) print("The final z-score of " + code + " is: " + str(z_score)) mdl.write(file=path + '_optimized.pdb') mdl_final = atmsel.get_dope_profile() mdl_final_smoothed = mdl_final.get_smoothed(window=50) energy_profile_txt_path_opt = dir + '/' + code + '_optimized_DOPE_EnergyProfile.txt' mdl_final_smoothed.write_to_file(energy_profile_txt_path_opt) mdl.write(file=dir + '/' + code + '_optimized.pdb') energy_profile_plot(options, dir, code, energy_profile_txt_path, energy_profile_txt_path_opt)