def create_simulation(base_dir, starting_dir, gpu_index,tic_index, plumed_script, sim_save_rate, platform): print("Creating simulation for tic %d"%tic_index) os.chdir((os.path.join(base_dir,"tic_%d"%tic_index))) state, system, integrator, pdb = load_sim_files(starting_dir) with open("./plumed_script.dat",'w') as f: f.writelines(plumed_script) new_f = PlumedForce(str(plumed_script)) force_group = 30 new_f.setForceGroup(force_group) system.addForce(new_f) platform, properties = get_platform(platform,gpu_index) simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) if os.path.isfile("./checkpt.chk"): with open("checkpt.chk",'rb') as f: simulation.context.loadCheckpoint(f.read()) else: simulation.context.setState(state) print("Done creating simulation for tic %d"%tic_index) f = open("./speed_report.txt",'w') backup("trajectory.dcd") simulation.reporters.append(app.DCDReporter('trajectory.dcd', sim_save_rate)) simulation.reporters.append(app.StateDataReporter(f, 1000, step=True,\ potentialEnergy=True, temperature=True, progress=True, remainingTime=True,\ speed=True, totalSteps=200*100, separator='\t')) return simulation, force_group
def create_simulation(base_dir, tic_index, plumed_script): print("Creating simulation for tic %d" % tic_index) starting_dir = os.path.join(base_dir, "starting_coordinates") os.chdir((os.path.join(base_dir, "tic_%d" % tic_index))) if os.path.isfile("./state.xml"): state = XmlSerializer.deserialize(open("./state.xml").read()) else: state = XmlSerializer.deserialize( open("%s/state0.xml" % starting_dir).read()) system = XmlSerializer.deserialize( open("%s/system.xml" % starting_dir).read()) integrator = XmlSerializer.deserialize( open("%s/integrator.xml" % starting_dir).read()) pdb = app.PDBFile("%s/0.pdb" % starting_dir) new_f = PlumedForce(plumed_script) new_f.setForceGroup(1) system.addForce(new_f) platform = Platform.getPlatformByName("CUDA") properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': str(tic_index)} simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) if os.path.isfile("./checkpt.chk"): with open("checkpt.chk", 'rb') as f: simulation.context.loadCheckpoint(f.read()) else: simulation.context.setState(state) print("Done creating simulation for tic %d" % tic_index) f = open("./speed_report.txt", 'w') backup("trajectory.dcd") simulation.reporters.append(app.DCDReporter('trajectory.dcd', 100000)) simulation.reporters.append(app.StateDataReporter(f, 1000, step=True,\ potentialEnergy=True, temperature=True, progress=True, remainingTime=True,\ speed=True, totalSteps=200*100, separator='\t')) return simulation
def continue_running(): print(plumed_script) if os.path.isfile("./state.xml"): state = XmlSerializer.deserialize(open("./state.xml").read()) else: state = XmlSerializer.deserialize( open("../../starting_coordinates/state.xml").read()) system = XmlSerializer.deserialize( open("../../starting_coordinates/system.xml").read()) integrator = XmlSerializer.deserialize( open("../../starting_coordinates/integrator.xml").read()) pdb = app.PDBFile("../../starting_coordinates/0.pdb") system.addForce(PlumedForce(plumed_script)) print("here") platform = Platform.getPlatformByName("CUDA") properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': str(0)} simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) simulation.context.setState(state) backup("trajectory.dcd") f = open("./speed_report.txt", 'w') simulation.reporters.append(app.DCDReporter('trajectory.dcd', 5000)) simulation.reporters.append(app.StateDataReporter(f, 5000, step=True,\ potentialEnergy=True, temperature=True, progress=True, remainingTime=True,\ speed=True, totalSteps=200*100000, separator='\t')) #run for 23hrs simulation.runForClockTime(3, stateFile="state.xml") backup("state.xml") state=simulation.context.getState(getPositions=True, getVelocities=True,\ getForces=True,getEnergy=True,getParameters=True,enforcePeriodicBox=True) serializeObject(state, 'state.xml')
def testForce(self): # Create a System that applies a force based on the distance between two atoms. numParticles = 4 system = mm.System() positions = np.empty((numParticles, 3)) for i in range(numParticles): system.addParticle(1.0) positions[i] = [i, 0.1 * i, -0.3 * i] script = ''' d: DISTANCE ATOMS=1,3 BIASVALUE ARG=d ''' force = PlumedForce(script) system.addForce(force) integ = mm.LangevinIntegrator(300.0, 1.0, 1.0) context = mm.Context(system, integ, mm.Platform.getPlatformByName('Reference')) context.setPositions(positions) # Compute the forces and energy. state = context.getState(getEnergy=True, getForces=True) delta = positions[0] - positions[2] dist = np.sqrt(np.sum(delta**2)) zero = np.zeros(3) self.assertAlmostEqual( dist, state.getPotentialEnergy().value_in_unit(unit.kilojoules_per_mole)) self.assertTrue( np.allclose(-delta / dist, state.getForces(asNumpy=True)[0])) self.assertTrue(np.allclose(zero, state.getForces(asNumpy=True)[1])) self.assertTrue( np.allclose(delta / dist, state.getForces(asNumpy=True)[2])) self.assertTrue(np.allclose(zero, state.getForces(asNumpy=True)[3]))
def run_simulation(force_constant): assert (os.path.exists(folder_to_store_output_files)) input_pdb_file_of_molecule = args.starting_pdb_file force_field_file = 'amber99sb.xml' water_field_file = 'tip3p.xml' pdb_reporter_file = '%s/output_fc_%f_pc_%s.pdb' % ( folder_to_store_output_files, force_constant, str(potential_center).replace(' ', '')) if not args.out_traj is None: pdb_reporter_file = args.out_traj state_data_reporter_file = pdb_reporter_file.replace( 'output_fc', 'report_fc').replace('.pdb', '.txt') # check if the file exist for item_filename in [pdb_reporter_file, state_data_reporter_file]: Helper_func.backup_rename_file_if_exists(item_filename) index_of_backbone_atoms = CONFIG_57[0] flag_random_seed = 0 # whether we need to fix this random seed simulation_temperature = args.temperature time_step = CONFIG_22 # simulation time step, in ps pdb = PDBFile(input_pdb_file_of_molecule) modeller = Modeller(pdb.topology, pdb.getPositions(frame=args.starting_frame)) solvent_opt = 'no_water' if solvent_opt == 'explicit': forcefield = ForceField(force_field_file, water_field_file) modeller.addSolvent(forcefield, model=water_field_file.split('.xml')[0], boxSize=Vec3(3, 3, 3) * nanometers, ionicStrength=0 * molar) system = forcefield.createSystem(modeller.topology, nonbondedMethod=PME, nonbondedCutoff=1.0 * nanometers, constraints=AllBonds, ewaldErrorTolerance=0.0005) else: forcefield = ForceField(force_field_file) system = forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff, constraints=AllBonds) if args.bias_method == "US": if float(force_constant) != 0: force = ANN_Force() force.set_layer_types(layer_types) force.set_data_type_in_input_layer(args.data_type_in_input_layer) force.set_list_of_index_of_atoms_forming_dihedrals_from_index_of_backbone_atoms( index_of_backbone_atoms) force.set_index_of_backbone_atoms(index_of_backbone_atoms) if args.data_type_in_input_layer == 2: force.set_list_of_pair_index_for_distances(CONFIG_80) force.set_num_of_nodes(num_of_nodes) force.set_potential_center(potential_center) force.set_force_constant(float(force_constant)) unit_scaling = 1.0 # TODO: check unit scaling force.set_scaling_factor( float(scaling_factor) / unit_scaling) # since default unit is nm in OpenMM # TODO: need to fix following for multi-hidden layer cases temp_coeffs, temp_bias = np.load(autoencoder_info_file) for item_layer_index in [0, 1]: assert (len(temp_coeffs[item_layer_index]) == num_of_nodes[item_layer_index] * num_of_nodes[item_layer_index + 1]), ( len(temp_coeffs[item_layer_index]), (num_of_nodes[item_layer_index], num_of_nodes[item_layer_index + 1])) assert (len(temp_bias[item_layer_index]) == num_of_nodes[ item_layer_index + 1]), (len(temp_bias[item_layer_index]), num_of_nodes[item_layer_index + 1]) # need tolist() since C++ only accepts Python list force.set_coeffients_of_connections( [item_w.tolist() for item_w in temp_coeffs]) force.set_values_of_biased_nodes( [item_w.tolist() for item_w in temp_bias]) system.addForce(force) elif args.bias_method == "US_on_phipsi": from openmmplumed import PlumedForce kappa_string = ','.join( [str(force_constant) for _ in potential_center]) plumed_force_string = """ phi: TORSION ATOMS=5,7,9,15 psi: TORSION ATOMS=7,9,15,17 restraint: RESTRAINT ARG=phi,psi AT=%f,%f KAPPA=%s PRINT STRIDE=10 ARG=* FILE=COLVAR """ % (potential_center[0], potential_center[1], kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "MTD": from openmmplumed import PlumedForce plumed_force_string = Alanine_dipeptide.get_expression_script_for_plumed( ) with open(autoencoder_info_file, 'r') as f_in: plumed_force_string += f_in.read() # note that dimensionality of MTD is determined by potential_center string plumed_script_ANN_mode = 'ANN' if plumed_script_ANN_mode == 'native': mtd_output_layer_string = [ 'l_2_out_%d' % item for item in range(len(potential_center)) ] elif plumed_script_ANN_mode == 'ANN': mtd_output_layer_string = [ 'ann_force.%d' % item for item in range(len(potential_center)) ] else: raise Exception('mode error') mtd_output_layer_string = ','.join(mtd_output_layer_string) mtd_sigma_string = ','.join( [str(args.MTD_sigma) for _ in range(len(potential_center))]) if args.MTD_WT: mtd_well_tempered_string = 'TEMP=%d BIASFACTOR=%f' % ( args.temperature, args.MTD_biasfactor) else: mtd_well_tempered_string = "" plumed_force_string += """ metad: METAD ARG=%s PACE=%d HEIGHT=%f SIGMA=%s FILE=temp_MTD_hills.txt %s PRINT STRIDE=%d ARG=%s,metad.bias FILE=temp_MTD_out.txt """ % (mtd_output_layer_string, args.MTD_pace, args.MTD_height, mtd_sigma_string, mtd_well_tempered_string, record_interval, mtd_output_layer_string) # print plumed_force_string system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "SMD": # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = '1000,1000' plumed_force_string = """ phi: TORSION ATOMS=5,7,9,15 psi: TORSION ATOMS=7,9,15,17 restraint: MOVINGRESTRAINT ARG=phi,psi AT0=-1.5,1.0 STEP0=0 KAPPA0=%s AT1=1.0,-1.0 STEP1=%d KAPPA1=%s PRINT STRIDE=10 ARG=* FILE=COLVAR """ % (kappa_string, total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "TMD": # targeted MD # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = '10000' plumed_force_string = """ phi: TORSION ATOMS=5,7,9,15 psi: TORSION ATOMS=7,9,15,17 rmsd: RMSD REFERENCE=../resources/alanine_ref_1_TMD.pdb TYPE=OPTIMAL restraint: MOVINGRESTRAINT ARG=rmsd AT0=0 STEP0=0 KAPPA0=0 AT1=0 STEP1=%d KAPPA1=%s PRINT STRIDE=10 ARG=* FILE=COLVAR """ % (total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "plumed_other": from openmmplumed import PlumedForce with open(args.plumed_file, 'r') as f_in: plumed_force_string = f_in.read().strip() + args.plumed_add_string system.addForce(PlumedForce(plumed_force_string)) else: raise Exception('bias method error') # end of biased force integrator = LangevinIntegrator(simulation_temperature * kelvin, 1 / picosecond, time_step * picoseconds) if flag_random_seed: integrator.setRandomNumberSeed(1) # set random seed platform = Platform.getPlatformByName(args.platform) platform.loadPluginsFromDirectory( CONFIG_25) # load the plugin from specific directory simulation = Simulation(modeller.topology, system, integrator, platform) simulation.context.setPositions(modeller.positions) if args.minimize_energy: print('begin Minimizing energy...') print(datetime.datetime.now()) simulation.minimizeEnergy() print('Done minimizing energy.') print(datetime.datetime.now()) else: print('energy minimization not required') simulation.step(args.equilibration_steps) if out_format == '.pdb': simulation.reporters.append( PDBReporter(pdb_reporter_file, record_interval)) elif out_format == '.dcd': simulation.reporters.append( DCDReporter(pdb_reporter_file.replace('.pdb', '.dcd'), record_interval)) simulation.reporters.append( StateDataReporter( state_data_reporter_file, record_interval, step=True, potentialEnergy=True, kineticEnergy=True, speed=True, temperature=True, progress=True, remainingTime=True, totalSteps=total_number_of_steps + args.equilibration_steps, )) simulation.step(total_number_of_steps) print('Done biased simulation!') return pdb_reporter_file
def run_simulation(force_constant, number_of_simulation_steps): if not os.path.exists(folder_to_store_output_files): try: os.makedirs(folder_to_store_output_files) except: pass assert(os.path.exists(folder_to_store_output_files)) force_field_file = {'Trp_cage': 'amber03.xml', '2src': 'amber03.xml', '1y57': 'amber03.xml', 'BetaHairpin': 'amber03.xml', 'C24':'charmm36.xml', 'BPTI': 'amber03.xml' }[args.molecule] water_field_file = {'Trp_cage': 'tip4pew.xml', '2src': 'tip3p.xml', '1y57': 'tip3p.xml', 'BetaHairpin': 'tip3p.xml', 'C24':'charmm36/spce.xml', 'BPTI': 'tip4pew.xml'}[args.molecule] water_model = water_field_file.replace('.xml', '').replace('charmm36/', '') ionic_strength = {'Trp_cage': 0 * molar, '2src': 0.5 * .15 * molar, '1y57': 0.5 * .15 * molar, 'BetaHairpin': 0 * molar, 'C24': 0 * molar, 'BPTI': 0 * molar}[args.molecule] implicit_solvent_force_field = 'amber03_obc.xml' pdb_reporter_file = '%s/output_fc_%s_pc_%s_T_%d_%s_%s.pdb' % (folder_to_store_output_files, force_constant, str(potential_center).replace(' ', ''), temperature, args.whether_to_add_water_mol_opt, args.ensemble_type) if args.starting_pdb_file == 'auto': input_pdb_file_of_molecule = {'Trp_cage': '../resources/1l2y.pdb', '2src': '../resources/2src.pdb', '1y57': '../resources/1y57.pdb', 'BetaHairpin': '../resources/BetaHairpin.pdb', 'C24': '../resources/C24.pdb', 'BPTI': '../resources/bpti.pdb'}[args.molecule] else: input_pdb_file_of_molecule = args.starting_pdb_file pdb_reporter_file = pdb_reporter_file.split('.pdb')[0] + '_sf_%s.pdb' % \ args.starting_pdb_file.split('_sf_')[0].split('.pdb')[0].split('/')[-1] # 'sf' means 'starting_from' print("start_pdb = %s" % input_pdb_file_of_molecule) if args.starting_frame != 0: pdb_reporter_file = pdb_reporter_file.split('.pdb')[0] + '_ff_%d.pdb' % args.starting_frame # 'ff' means 'from_frame' if not args.out_traj is None: pdb_reporter_file = args.out_traj state_data_reporter_file = pdb_reporter_file.replace('output_fc', 'report_fc').replace('.pdb', '.txt') checkpoint_file = pdb_reporter_file.replace('output_fc', 'checkpoint_fc').replace('.pdb', '.chk') if args.fast_equilibration: checkpoint_file = checkpoint_file.replace(str(force_constant), str(args.force_constant)) # check existence for item_filename in [pdb_reporter_file, state_data_reporter_file]: Helper_func.backup_rename_file_if_exists(item_filename) flag_random_seed = 0 # whether we need to fix this random seed box_size = {'Trp_cage': 4.5, '2src': 8.0, '1y57': 8.0, 'BetaHairpin': 5, 'C24': 5, 'BPTI': 5.1263}[args.molecule] time_step = CONFIG_22 # simulation time step, in ps index_of_backbone_atoms = {'Trp_cage': CONFIG_57[1], '2src': CONFIG_57[2], '1y57': CONFIG_57[2], 'BetaHairpin': CONFIG_57[3], 'C24': CONFIG_57[4], 'BPTI': None}[args.molecule] layer_types = CONFIG_27 simulation_constraints = HBonds pdb = PDBFile(input_pdb_file_of_molecule) modeller = Modeller(pdb.topology, pdb.getPositions(frame=args.starting_frame)) if args.whether_to_add_water_mol_opt == 'explicit': forcefield = ForceField(force_field_file, water_field_file) modeller.addHydrogens(forcefield) modeller.addSolvent(forcefield, model=water_model, boxSize=Vec3(box_size, box_size, box_size)*nanometers, ionicStrength=ionic_strength) if not water_model == 'spce': modeller.addExtraParticles(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=PME, nonbondedCutoff=1.0 * nanometers, constraints = simulation_constraints, ewaldErrorTolerance = 0.0005) elif args.whether_to_add_water_mol_opt == 'implicit': forcefield = ForceField(force_field_file, implicit_solvent_force_field) modeller.addHydrogens(forcefield) modeller.addExtraParticles(forcefield) system = forcefield.createSystem(pdb.topology,nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=5 * nanometers, constraints=simulation_constraints, rigidWater=True, removeCMMotion=True) elif args.whether_to_add_water_mol_opt == 'no_water' or args.whether_to_add_water_mol_opt == 'water_already_included': forcefield = ForceField(force_field_file, water_field_file) modeller.addExtraParticles(forcefield) modeller.addHydrogens(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff,nonbondedCutoff=1.0 * nanometers, constraints = simulation_constraints) else: raise Exception("parameter error") # print modeller.topology.getPeriodicBoxVectors() system.addForce(AndersenThermostat(temperature*kelvin, 1/picosecond)) if args.ensemble_type == "NPT" and args.whether_to_add_water_mol_opt == 'explicit': system.addForce(MonteCarloBarostat(1*atmospheres, temperature*kelvin, 25)) # add custom force (only for biased simulation) if args.bias_method == "US": if float(force_constant) != 0: force = ANN_Force() force.set_layer_types(layer_types) force.set_data_type_in_input_layer(args.data_type_in_input_layer) force.set_list_of_index_of_atoms_forming_dihedrals_from_index_of_backbone_atoms(index_of_backbone_atoms) force.set_index_of_backbone_atoms(index_of_backbone_atoms) if args.data_type_in_input_layer == 2: force.set_list_of_pair_index_for_distances(CONFIG_80) force.set_num_of_nodes(num_of_nodes) force.set_potential_center(potential_center) force.set_force_constant(float(force_constant)) unit_scaling = 1.0 # TODO: check unit scaling force.set_scaling_factor(float(scaling_factor) / unit_scaling) # since default unit is nm in OpenMM with open(autoencoder_info_file, 'r') as f_in: content = f_in.readlines() # TODO: need to fix following for multi-hidden layer cases temp_coeffs = [ast.literal_eval(content[0].strip())[0], ast.literal_eval(content[1].strip())[0]] temp_bias = [ast.literal_eval(content[2].strip())[0], ast.literal_eval(content[3].strip())[0]] for item_layer_index in [0, 1]: assert (len(temp_coeffs[item_layer_index]) == num_of_nodes[item_layer_index] * num_of_nodes[item_layer_index + 1]), \ (len(temp_coeffs[item_layer_index]), num_of_nodes[item_layer_index], num_of_nodes[item_layer_index + 1]) assert (len(temp_bias[item_layer_index]) == num_of_nodes[item_layer_index + 1]), (len(temp_bias[item_layer_index]), num_of_nodes[item_layer_index + 1]) force.set_coeffients_of_connections(temp_coeffs) force.set_values_of_biased_nodes(temp_bias) system.addForce(force) elif args.bias_method == "MTD": from openmmplumed import PlumedForce molecule_type = {'Trp_cage': Trp_cage, '2src': Src_kinase, '1y57': Src_kinase, 'BetaHairpin': BetaHairpin}[args.molecule] plumed_force_string = molecule_type.get_expression_script_for_plumed() with open(autoencoder_info_file, 'r') as f_in: plumed_force_string += f_in.read() # note that dimensionality of MTD is determined by potential_center string mtd_output_layer_string = ['l_2_out_%d' % item for item in range(len(potential_center))] mtd_output_layer_string = ','.join(mtd_output_layer_string) mtd_sigma_string = ','.join([str(args.MTD_sigma) for _ in range(len(potential_center))]) if args.MTD_WT: mtd_well_tempered_string = 'TEMP=%d BIASFACTOR=%f' % (args.temperature, args.MTD_biasfactor) else: mtd_well_tempered_string = "" plumed_force_string += """ metad: METAD ARG=%s PACE=%d HEIGHT=%f SIGMA=%s FILE=temp_MTD_hills.txt %s PRINT STRIDE=%d ARG=%s,metad.bias FILE=temp_MTD_out.txt """ % (mtd_output_layer_string, args.MTD_pace, args.MTD_height, mtd_sigma_string, mtd_well_tempered_string, record_interval, mtd_output_layer_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "TMD": # targeted MD # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = str(args.force_constant) plumed_force_string = """ rmsd: RMSD REFERENCE=../resources/1y57_TMD.pdb TYPE=OPTIMAL restraint: MOVINGRESTRAINT ARG=rmsd AT0=0.4 STEP0=0 KAPPA0=%s AT1=0 STEP1=%d KAPPA1=%s PRINT STRIDE=500 ARG=* FILE=COLVAR """ % (kappa_string, total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "US_on_ANN_plumed": # in this case, all ANN related parts (including scripts for inputs) have been stored in # args.plumed_file, only need to add biasing plumed script for umbrella sampling from openmmplumed import PlumedForce with open(args.plumed_file, 'r') as f_in: plumed_force_string = f_in.read() arg_string = ','.join(['ann_force.%d' % _2 for _2 in range(len(potential_center))]) pc_string = ','.join([str(_2) for _2 in potential_center]) kappa_string = ','.join([str(force_constant) for _ in potential_center]) plumed_force_string += """\nmypotential: RESTRAINT ARG=%s AT=%s KAPPA=%s""" % ( arg_string, pc_string, kappa_string, ) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "plumed_other": from openmmplumed import PlumedForce with open(args.plumed_file, 'r') as f_in: plumed_force_string = f_in.read().strip() + args.plumed_add_string system.addForce(PlumedForce(plumed_force_string)) else: raise Exception('bias method error') # end add custom force integrator = VerletIntegrator(time_step*picoseconds) if flag_random_seed: integrator.setRandomNumberSeed(1) # set random seed if args.platform == "CUDA" and args.device != 'none': properties = {'CudaDeviceIndex': args.device} simulation = Simulation(modeller.topology, system, integrator, platform, properties) else: simulation = Simulation(modeller.topology, system, integrator, platform) # print "positions = " # print (modeller.positions) simulation.context.setPositions(modeller.positions) print(datetime.datetime.now()) if args.starting_checkpoint != 'none': if args.starting_checkpoint == "auto": # restart from checkpoint if it exists if os.path.isfile(checkpoint_file): print("resume simulation from %s" % checkpoint_file) simulation.loadCheckpoint(checkpoint_file) else: print("resume simulation from %s" % args.starting_checkpoint) simulation.loadCheckpoint(args.starting_checkpoint) # the topology is already set by pdb file, and the positions in the pdb file will be overwritten by those in the starting_checkpoing file if args.minimize_energy: print('begin Minimizing energy...') print(datetime.datetime.now()) simulation.minimizeEnergy() print('Done minimizing energy.') print(datetime.datetime.now()) else: print('energy minimization not required') print("begin equilibrating...") print(datetime.datetime.now()) simulation.step(args.equilibration_steps) previous_distance_to_potential_center = 100 current_distance_to_potential_center = 90 if args.auto_equilibration: distance_change_tolerance = 0.05 while abs(previous_distance_to_potential_center - current_distance_to_potential_center) > distance_change_tolerance: temp_pdb_reporter_file_for_auto_equilibration = pdb_reporter_file.replace('.pdb', '_temp.pdb') simulation.reporters.append(PDBReporter(temp_pdb_reporter_file_for_auto_equilibration, record_interval)) simulation.step(args.equilibration_steps) previous_distance_to_potential_center = current_distance_to_potential_center current_distance_to_potential_center = get_distance_between_data_cloud_center_and_potential_center( temp_pdb_reporter_file_for_auto_equilibration) subprocess.check_output(['rm', temp_pdb_reporter_file_for_auto_equilibration]) print("previous_distance_to_potential_center = %f\ncurrent_distance_to_potential_center = %f" % ( previous_distance_to_potential_center, current_distance_to_potential_center )) print("Done equilibration") print(datetime.datetime.now()) if out_format == '.pdb': simulation.reporters.append(PDBReporter(pdb_reporter_file, record_interval)) elif out_format == '.dcd': simulation.reporters.append(DCDReporter(pdb_reporter_file.replace('.pdb', '.dcd'), record_interval)) simulation.reporters.append(StateDataReporter(state_data_reporter_file, record_interval, time=True, step=True, potentialEnergy=True, kineticEnergy=True, speed=True, temperature=True, progress=True, remainingTime=True, volume = True,density=True, totalSteps=number_of_simulation_steps + args.equilibration_steps, )) simulation.step(number_of_simulation_steps) if args.checkpoint: Helper_func.backup_rename_file_if_exists(checkpoint_file) simulation.saveCheckpoint(checkpoint_file) print('Done!') print(datetime.datetime.now()) return pdb_reporter_file
from openmmplumed import PlumedForce psf = CharmmPsfFile('dia2.psf') pdb = PDBFile('dia2.pdb') params = CharmmParameterSet('par_all27_prot_lipid.prm', permissive=True) system = psf.createSystem(params, nonbondedMethod=NoCutoff, nonbondedCutoff=1 * nanometer, constraints=None) plumedScript = "diala.plumed.nocont" with open(plumedScript) as f: script = f.read() plumedForce = PlumedForce(script) req_plt = Platform.getPlatformByName('CUDA') integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 1 * femtoseconds) simulation = Simulation(psf.topology, system, integrator, req_plt, {'DeviceIndex': '1'}) ctx = simulation.context platform = ctx.getPlatform() print(f"Using platform {platform.getName()} with properties:") for prop in platform.getPropertyNames(): print(f" {prop}\t\t{platform.getPropertyValue(ctx,prop)}") L = 32.0 ctx.setPeriodicBoxVectors([L, 0, 0], [0, L, 0], [0, 0, L])
def run_simulation(force_constant): if not os.path.exists(folder_to_store_output_files): try: os.makedirs(folder_to_store_output_files) except: pass assert (os.path.exists(folder_to_store_output_files)) input_pdb_file_of_molecule = args.starting_pdb_file force_field_file = 'amber99sb.xml' pdb_reporter_file = '%s/output_fc_%f_pc_%s.pdb' % ( folder_to_store_output_files, force_constant, str(potential_center).replace(' ', '')) if not args.output_pdb is None: pdb_reporter_file = args.output_pdb state_data_reporter_file = pdb_reporter_file.replace( 'output_fc', 'report_fc').replace('.pdb', '.txt') # check if the file exist if os.path.isfile(pdb_reporter_file): os.rename(pdb_reporter_file, pdb_reporter_file.split('.pdb')[0] + "_bak_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".pdb") # ensure the file extension stays the same if os.path.isfile(state_data_reporter_file): os.rename( state_data_reporter_file, state_data_reporter_file.split('.txt')[0] + "_bak_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".txt") k1 = force_constant k2 = force_constant list_of_index_of_atoms_forming_dihedrals = [[2, 5, 7, 9], [5, 7, 9, 15], [7, 9, 15, 17], [9, 15, 17, 19]] index_of_backbone_atoms = CONFIG_57[0] # FIXME: following expression is out-of-date due to the change in API for higher-dimensional cases if CONFIG_28 == "CustomManyParticleForce": with open(autoencoder_info_file, 'r') as f_in: energy_expression = f_in.read() [xi_1_0, xi_2_0] = potential_center if CONFIG_20: # whether the PC space is periodic in [- pi, pi], True for circular network, False for Tanh network, this affect the form of potential function energy_expression = ''' %f * d1_square + %f * d2_square; d1_square = min( min( (PC0 - %s)^2, (PC0 - %s + 6.2832)^2 ), (PC0 - %s - 6.2832)^2 ); d2_square = min( min( (PC1 - %s)^2, (PC1 - %s + 6.2832)^2 ), (PC1 - %s - 6.2832)^2 ); ''' % (k1, k2, xi_1_0, xi_1_0, xi_1_0, xi_2_0, xi_2_0, xi_2_0) + energy_expression else: energy_expression = ''' %f * (PC0 - %s)^2 + %f * (PC1 - %s)^2; ''' % (k1, xi_1_0, k2, xi_2_0) + energy_expression flag_random_seed = 0 # whether we need to fix this random seed simulation_temperature = args.temperature time_step = CONFIG_22 # simulation time step, in ps pdb = PDBFile(input_pdb_file_of_molecule) modeller = Modeller(pdb.topology, pdb.getPositions(frame=args.starting_frame)) forcefield = ForceField(force_field_file) # without water system = forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff, constraints=AllBonds) if args.bias_method == "US": if CONFIG_28 == "CustomManyParticleForce": force = CustomManyParticleForce(22, energy_expression) for _ in range(system.getNumParticles()): force.addParticle( "", 0 ) # what kinds of types should we specify here for each atom? system.addForce(force) elif CONFIG_28 == "ANN_Force": if force_constant != '0' and force_constant != 0: force = ANN_Force() force.set_layer_types(layer_types) force.set_data_type_in_input_layer( args.data_type_in_input_layer) force.set_list_of_index_of_atoms_forming_dihedrals( list_of_index_of_atoms_forming_dihedrals) force.set_index_of_backbone_atoms(index_of_backbone_atoms) force.set_num_of_nodes(num_of_nodes) force.set_potential_center(potential_center) force.set_force_constant(float(force_constant)) force.set_scaling_factor(float(scaling_factor)) # set coefficient with open(autoencoder_info_file, 'r') as f_in: content = f_in.readlines() force.set_coeffients_of_connections([ ast.literal_eval(content[0].strip())[0], ast.literal_eval(content[1].strip())[0] ]) force.set_values_of_biased_nodes([ ast.literal_eval(content[2].strip())[0], ast.literal_eval(content[3].strip())[0] ]) system.addForce(force) elif args.bias_method == "MTD": from openmmplumed import PlumedForce plumed_force_string = Alanine_dipeptide.get_expression_script_for_plumed( ) with open(autoencoder_info_file, 'r') as f_in: plumed_force_string += f_in.read() # note that dimensionality of MTD is determined by potential_center string mtd_output_layer_string = [ 'l_2_out_%d' % item for item in range(len(potential_center)) ] mtd_output_layer_string = ','.join(mtd_output_layer_string) mtd_sigma_string = ','.join( [str(args.MTD_sigma) for _ in range(len(potential_center))]) if args.MTD_WT: mtd_well_tempered_string = 'TEMP=%d BIASFACTOR=%f' % ( args.temperature, args.MTD_biasfactor) else: mtd_well_tempered_string = "" plumed_force_string += """ metad: METAD ARG=%s PACE=%d HEIGHT=%f SIGMA=%s FILE=temp_MTD_hills.txt %s PRINT STRIDE=%d ARG=%s,metad.bias FILE=temp_MTD_out.txt """ % (mtd_output_layer_string, args.MTD_pace, args.MTD_height, mtd_sigma_string, mtd_well_tempered_string, record_interval, mtd_output_layer_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "SMD": # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = '1000,1000' plumed_force_string = """ phi: TORSION ATOMS=5,7,9,15 psi: TORSION ATOMS=7,9,15,17 restraint: MOVINGRESTRAINT ARG=phi,psi AT0=-1.5,1.0 STEP0=0 KAPPA0=%s AT1=1.0,-1.0 STEP1=%d KAPPA1=%s PRINT STRIDE=10 ARG=* FILE=COLVAR """ % (kappa_string, total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "TMD": # targeted MD # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = '10000' plumed_force_string = """ phi: TORSION ATOMS=5,7,9,15 psi: TORSION ATOMS=7,9,15,17 rmsd: RMSD REFERENCE=../resources/alanine_ref_1_TMD.pdb TYPE=OPTIMAL restraint: MOVINGRESTRAINT ARG=rmsd AT0=0 STEP0=0 KAPPA0=0 AT1=0 STEP1=%d KAPPA1=%s PRINT STRIDE=10 ARG=* FILE=COLVAR """ % (total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "plumed_other": from openmmplumed import PlumedForce with open(args.plumed_file, 'r') as f_in: plumed_force_string = f_in.read() system.addForce(PlumedForce(plumed_force_string)) else: raise Exception('bias method error') # end of biased force integrator = LangevinIntegrator(simulation_temperature * kelvin, 1 / picosecond, time_step * picoseconds) if flag_random_seed: integrator.setRandomNumberSeed(1) # set random seed platform = Platform.getPlatformByName(args.platform) platform.loadPluginsFromDirectory( CONFIG_25) # load the plugin from specific directory simulation = Simulation(modeller.topology, system, integrator, platform) simulation.context.setPositions(modeller.positions) if args.minimize_energy: print('begin Minimizing energy...') print datetime.datetime.now() simulation.minimizeEnergy() print('Done minimizing energy.') print datetime.datetime.now() else: print('energy minimization not required') simulation.step(args.equilibration_steps) simulation.reporters.append(PDBReporter(pdb_reporter_file, record_interval)) simulation.reporters.append( StateDataReporter( state_data_reporter_file, record_interval, step=True, potentialEnergy=True, kineticEnergy=True, speed=True, temperature=True, progress=True, remainingTime=True, totalSteps=total_number_of_steps + args.equilibration_steps, )) simulation.step(total_number_of_steps) print('Done biased simulation!') return pdb_reporter_file
def run_omm(options): inp = Config(options.input) dt = float(inp.getWithDefault("timestep", 4)) * u.femtosecond temperature = float(inp.getWithDefault("temperature", 300)) * u.kelvin thermostattemperature = float( inp.getWithDefault("thermostattemperature", 300)) * u.kelvin logPeriod = 1 * u.picosecond trajectoryPeriod = int(inp.getWithDefault("trajectoryperiod", 25000)) * dt run_steps = int(inp.run) basename = "output" trajectory_file = basename + ".dcd" if 'PME' in inp and not inp.getboolean('PME'): nonbondedMethod = app.NoCutoff else: nonbondedMethod = app.PME nonbondedCutoff = float(inp.getWithDefault("cutoff", 9.0)) * u.angstrom switchDistance = float(inp.getWithDefault("switchdistance", 7.5)) * u.angstrom frictionCoefficient = float(inp.getWithDefault("thermostatdamping", 0.1)) / u.picosecond endTime = run_steps * dt util.check_openmm() if options.platform is None: print("Selecting best platform:") req_platform_name = util.get_best_platform() else: print(f"Requesting platform {options.platform}") req_platform_name = options.platform req_platform = mm.Platform.getPlatformByName(req_platform_name) req_properties = {} # {'UseBlockingSync':'true'} if options.device is not None and 'DeviceIndex' in req_platform.getPropertyNames( ): print(" Setting DeviceIndex = " + options.device) req_properties['DeviceIndex'] = options.device if options.precision is not None and 'Precision' in req_platform.getPropertyNames( ): print(" Setting Precision = " + options.precision) req_properties['Precision'] = options.precision # Same logic as https://software.acellera.com/docs/latest/acemd3/reference.html if dt > 2 * u.femtosecond: hydrogenMass = 4 * u.amu constraints = app.AllBonds rigidWater = True elif dt > 0.5 * u.femtosecond: hydrogenMass = None constraints = app.HBonds rigidWater = True else: hydrogenMass = None constraints = None rigidWater = False print(f""" Host: {socket.gethostname()} Date: {datetime.datetime.now().ctime()} Timestep: {dt} Constraints: {constraints} Rigid water: {rigidWater} Nonbonded: {nonbondedMethod} Hydrogen mass repartitioning: {hydrogenMass} """) _printPluginInfo() if 'parmfile' in inp: print(f"Creating an AMBER system...") if 'structure' in inp: print("Warning: 'structure' given but ignored for AMBER") prmtop = app.AmberPrmtopFile(inp.parmfile) system = prmtop.createSystem(nonbondedMethod=nonbondedMethod, nonbondedCutoff=nonbondedCutoff, switchDistance=switchDistance, constraints=constraints, hydrogenMass=hydrogenMass, rigidWater=rigidWater) topology = prmtop.topology else: print(f"Creating a CHARMM system...") psf = app.CharmmPsfFile(inp.structure) params = app.CharmmParameterSet(inp.parameters, permissive=True) psf.setBox(50. * u.angstrom, 50. * u.angstrom, 50. * u.angstrom) # otherwise # refuses # PME system = psf.createSystem(params, nonbondedMethod=nonbondedMethod, nonbondedCutoff=nonbondedCutoff, switchDistance=switchDistance, constraints=constraints, hydrogenMass=hydrogenMass, rigidWater=rigidWater) topology = psf.topology if 'barostat' in inp and inp.getboolean('barostat'): pressure = float(inp.barostatpressure) * u.bar print(f"Enabling barostat at {pressure}...") system.addForce(mm.MonteCarloBarostat(pressure, thermostattemperature)) if 'plumedfile' in inp: print("Attempting to load PLUMED plugin...") from openmmplumed import PlumedForce plines = util.plumed_parser(inp.plumedfile) system.addForce(PlumedForce(plines)) integrator = mm.LangevinIntegrator(thermostattemperature, frictionCoefficient, dt) integrator.setConstraintTolerance(1e-5) simulation = app.Simulation(topology, system, integrator, req_platform, req_properties) ctx = simulation.context platform = ctx.getPlatform() print(f"Got platform {platform.getName()} with properties:") for prop in platform.getPropertyNames(): print(f" {prop}\t\t{platform.getPropertyValue(ctx,prop)}") print("") resuming = False if os.path.exists(checkpoint_file): with open(checkpoint_file, 'rb') as cf: ctx.loadCheckpoint(cf.read()) # ctx.loadCheckpoint(str(checkpoint_file)) util.round_state_time(ctx, 10 * dt) print(f"Successfully loaded {checkpoint_file}, resuming simulation...") resuming = True else: print( f"File {checkpoint_file} absent, starting simulation from the beginning..." ) coords = util.get_coords(inp) ctx.setPositions(coords) if not resuming: (boxa, boxb, boxc) = util.get_box_size(inp) ctx.setPeriodicBoxVectors(boxa, boxb, boxc) if 'minimize' in inp: print(f'Minimizing for max {inp.minimize} iterations...') simulation.minimizeEnergy(maxIterations=int(inp.minimize)) simulation.saveState(f"miniomm_minimized.xml") else: if 'binvelocities' in inp: print(f"Reading velocities from NAMDBin: " + inp.binvelocities) vels = NAMDBin(inp.binvelocities).getVelocities() ctx.setVelocities(vels) else: print(f"Resetting thermal velocities at {temperature}") ctx.setVelocitiesToTemperature(temperature) # ------------------------------------------------------- print("") inp.printWarnings() # ------------------------------------------------------- print("") startTime = ctx.getState().getTime() startTime_f = startTime.in_units_of(u.nanoseconds).format("%.3f") endTime_f = endTime.in_units_of(u.nanoseconds).format("%.3f") remaining_steps = round((endTime - startTime) / dt) remaining_ns = remaining_steps * dt.value_in_unit(u.nanosecond) print( f"Current simulation time is {startTime_f}, running up to {endTime_f}." ) print( f"Will run for {remaining_steps} timesteps = {remaining_ns:.3f} ns...") print("") log_every = util.every(logPeriod, dt) save_every = util.every(trajectoryPeriod, dt) if remaining_steps % save_every != 0: raise ValueError( "Remaining steps is not a multiple of trajectoryperiod") util.add_reporters(simulation, trajectory_file, log_every, save_every, remaining_steps, resuming, checkpoint_file) # ---------------------------------------- simulation.saveState(f"miniomm_pre.xml") # ---------------------------------------- simulation.step(remaining_steps) # ---------------------------------------- simulation.saveState(f"miniomm_post.xml") final_state = simulation.context.getState(getPositions=True, getVelocities=True) final_coor = final_state.getPositions(asNumpy=True) NAMDBin(final_coor).write_file(f"{basename}.coor") final_box = final_state.getPeriodicBoxVectors(asNumpy=True) write_xsc(f"{basename}.xsc", remaining_steps, final_state.getTime(), final_box) # ---------------------------------------- print('Done!') return
from openmmplumed import PlumedForce psf = CharmmPsfFile('dia2.psf') pdb = PDBFile('minimized.pdb') params = CharmmParameterSet('par_all27_prot_lipid.prm', permissive=True) system = psf.createSystem(params, nonbondedMethod=NoCutoff, nonbondedCutoff=1 * nanometer, constraints=None) plumedScript = "diala.plumed.nocont" with open(plumedScript) as f: script = f.read() system.addForce(PlumedForce(script)) req_plt = Platform.getPlatformByName('CUDA') integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 1 * femtoseconds) simulation = Simulation(psf.topology, system, integrator, req_plt, {'DeviceIndex': '0'}) ctx = simulation.context platform = ctx.getPlatform() print(f"Using platform {platform.getName()} with properties:") for prop in platform.getPropertyNames(): print(f" {prop}\t\t{platform.getPropertyValue(ctx,prop)}") L = 32.0 ctx.setPeriodicBoxVectors([L, 0, 0], [0, L, 0], [0, 0, L])
#pdb = PDBFile("w.pdb") system = prmtop.createSystem(nonbondedMethod=PME, nonbondedCutoff=9 * angstrom, constraints=HBonds) #r: RESTRAINT ARG=d AT=5 KAPPA=150 #UNITS LENGTH=A plumedScript = """ d: DISTANCE ATOMS=1,2758 r: RESTRAINT ARG=d AT=.5 KAPPA=1500 PRINT ARG=* FILE=COLVAR """ system.addForce(PlumedForce(plumedScript)) integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 0.002 * picoseconds) req_plt = Platform.getPlatformByName('CUDA') simulation = Simulation(prmtop.topology, system, integrator, req_plt) simulation.context.setPositions(inpcrd.positions) if inpcrd.boxVectors is not None: simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors) simulation.saveState("pre.xml") print("Minimizing")
def run_simulation(force_constant, number_of_simulation_steps): if not os.path.exists(folder_to_store_output_files): try: os.makedirs(folder_to_store_output_files) except: pass assert(os.path.exists(folder_to_store_output_files)) force_field_file = {'Trp_cage': 'amber03.xml', '2src': 'amber03.xml', '1y57': 'amber03.xml', 'Alanine_pentapeptide': 'amber03.xml'}[args.molecule] water_field_file = {'Trp_cage': 'tip4pew.xml', '2src': 'tip3p.xml', '1y57': 'tip3p.xml', 'Alanine_pentapeptide': 'tip4pew.xml'}[args.molecule] water_model = {'Trp_cage': 'tip4pew', '2src': 'tip3p', '1y57': 'tip3p', 'Alanine_pentapeptide': 'tip4pew'}[args.molecule] ionic_strength = {'Trp_cage': 0 * molar, '2src': 0.5 * .15 * molar, '1y57': 0.5 * .15 * molar, 'Alanine_pentapeptide': 0 * molar}[args.molecule] implicit_solvent_force_field = 'amber03_obc.xml' pdb_reporter_file = '%s/output_fc_%s_pc_%s_T_%d_%s.pdb' % (folder_to_store_output_files, force_constant, str(potential_center).replace(' ', ''), temperature, args.whether_to_add_water_mol_opt) state_data_reporter_file = pdb_reporter_file.replace('output_fc', 'report_fc').replace('.pdb', '.txt') checkpoint_file = pdb_reporter_file.replace('output_fc', 'checkpoint_fc').replace('.pdb', '.chk') if args.fast_equilibration: checkpoint_file = checkpoint_file.replace(str(force_constant), str(args.force_constant)) if args.starting_pdb_file == 'auto': input_pdb_file_of_molecule = {'Trp_cage': '../resources/1l2y.pdb', '2src': '../resources/2src.pdb', '1y57': '../resources/1y57.pdb', 'Alanine_pentapeptide': '../resources/Alanine_pentapeptide.pdb'}[args.molecule] else: input_pdb_file_of_molecule = args.starting_pdb_file pdb_reporter_file = pdb_reporter_file.split('.pdb')[0] + '_sf_%s.pdb' % \ args.starting_pdb_file.split('.pdb')[0].split('/')[-1] # 'sf' means 'starting_from' state_data_reporter_file = state_data_reporter_file.split('.txt')[0] + '_sf_%s.txt' % \ args.starting_pdb_file.split('.pdb')[0].split('/')[-1] print "start_pdb = %s" % input_pdb_file_of_molecule if args.starting_frame != 0: pdb_reporter_file = pdb_reporter_file.split('.pdb')[0] + '_ff_%d.pdb' % args.starting_frame # 'ff' means 'from_frame' state_data_reporter_file = state_data_reporter_file.split('.txt')[0] + '_ff_%d.txt' % args.starting_frame if os.path.isfile(pdb_reporter_file): os.rename(pdb_reporter_file, pdb_reporter_file.split('.pdb')[0] + "_bak_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".pdb") # ensure the file extension stays the same if os.path.isfile(state_data_reporter_file): os.rename(state_data_reporter_file, state_data_reporter_file.split('.txt')[0] + "_bak_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".txt") flag_random_seed = 0 # whether we need to fix this random seed box_size = {'Trp_cage': 4.5, '2src': 8.0, '1y57': 8.0, 'Alanine_pentapeptide': 4.5}[args.molecule] time_step = CONFIG_22 # simulation time step, in ps index_of_backbone_atoms = {'Trp_cage': CONFIG_57[1], '2src': 'TODO', '1y57': 'TODO', 'Alanine_pentapeptide': CONFIG_57[2]}[args.molecule] # TODO layer_types = CONFIG_27 simulation_constraints = HBonds pdb = PDBFile(input_pdb_file_of_molecule) modeller = Modeller(pdb.topology, pdb.getPositions(frame=args.starting_frame)) if args.whether_to_add_water_mol_opt == 'explicit': forcefield = ForceField(force_field_file, water_field_file) modeller.addHydrogens(forcefield) modeller.addSolvent(forcefield, model=water_model, boxSize=Vec3(box_size, box_size, box_size)*nanometers, ionicStrength=ionic_strength) modeller.addExtraParticles(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=PME, nonbondedCutoff=1.0 * nanometers, constraints = simulation_constraints, ewaldErrorTolerance = 0.0005) elif args.whether_to_add_water_mol_opt == 'implicit': forcefield = ForceField(force_field_file, implicit_solvent_force_field) modeller.addHydrogens(forcefield) modeller.addExtraParticles(forcefield) system = forcefield.createSystem(pdb.topology,nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=5 * nanometers, constraints=simulation_constraints, rigidWater=True, removeCMMotion=True) elif args.whether_to_add_water_mol_opt == 'no_water' or args.whether_to_add_water_mol_opt == 'water_already_included': forcefield = ForceField(force_field_file, water_field_file) modeller.addHydrogens(forcefield) modeller.addExtraParticles(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff,nonbondedCutoff=1.0 * nanometers, constraints = simulation_constraints) else: raise Exception("parameter error") system.addForce(AndersenThermostat(temperature*kelvin, 1/picosecond)) if args.ensemble_type == "NPT" and args.whether_to_add_water_mol_opt == 'explicit': system.addForce(MonteCarloBarostat(1*atmospheres, temperature*kelvin, 25)) # add custom force (only for biased simulation) if args.bias_method == "US": if float(force_constant) != 0: force = ANN_Force() force.set_layer_types(layer_types) force.set_data_type_in_input_layer(args.data_type_in_input_layer) force.set_list_of_index_of_atoms_forming_dihedrals_from_index_of_backbone_atoms(index_of_backbone_atoms) force.set_index_of_backbone_atoms(index_of_backbone_atoms) force.set_num_of_nodes(CONFIG_3[:4]) force.set_potential_center(potential_center) force.set_force_constant(float(force_constant)) force.set_scaling_factor(float(scaling_factor)) with open(autoencoder_info_file, 'r') as f_in: content = f_in.readlines() force.set_coeffients_of_connections( [ast.literal_eval(content[0].strip())[0], ast.literal_eval(content[1].strip())[0]]) force.set_values_of_biased_nodes([ ast.literal_eval(content[2].strip())[0], ast.literal_eval(content[3].strip())[0] ]) system.addForce(force) elif args.bias_method == "MTD": from openmmplumed import PlumedForce molecule_type = {'Trp_cage': Trp_cage, '2src': None, '1y57': None, 'Alanine_pentapeptide': None}[args.molecule] # TODO plumed_force_string = molecule_type.get_expression_script_for_plumed() with open(autoencoder_info_file, 'r') as f_in: plumed_force_string += f_in.read() # note that dimensionality of MTD is determined by potential_center string mtd_output_layer_string = ['l_2_out_%d' % item for item in range(len(potential_center))] mtd_output_layer_string = ','.join(mtd_output_layer_string) mtd_sigma_string = ','.join([str(args.MTD_sigma) for _ in range(len(potential_center))]) plumed_force_string += """ metad: METAD ARG=%s PACE=%d HEIGHT=%f SIGMA=%s FILE=temp_MTD_hills.txt PRINT STRIDE=%d ARG=%s,metad.bias FILE=temp_MTD_out.txt """ % (mtd_output_layer_string, args.MTD_pace, args.MTD_height, mtd_sigma_string, record_interval, mtd_output_layer_string) system.addForce(PlumedForce(plumed_force_string)) elif args.bias_method == "TMD": # targeted MD # TODO: this is temporary version from openmmplumed import PlumedForce kappa_string = str(args.force_constant) plumed_force_string = """ rmsd: RMSD REFERENCE=../resources/1y57_TMD.pdb TYPE=OPTIMAL restraint: MOVINGRESTRAINT ARG=rmsd AT0=0 STEP0=0 KAPPA0=0 AT1=0 STEP1=%d KAPPA1=%s PRINT STRIDE=500 ARG=* FILE=COLVAR """ % (total_number_of_steps, kappa_string) system.addForce(PlumedForce(plumed_force_string)) else: raise Exception('bias method error') # end add custom force integrator = VerletIntegrator(time_step*picoseconds) if flag_random_seed: integrator.setRandomNumberSeed(1) # set random seed if args.platform == "CUDA": properties = {'CudaDeviceIndex': args.device} simulation = Simulation(modeller.topology, system, integrator, platform, properties) else: simulation = Simulation(modeller.topology, system, integrator, platform) # print "positions = " # print (modeller.positions) simulation.context.setPositions(modeller.positions) print datetime.datetime.now() if args.starting_checkpoint != 'none': if args.starting_checkpoint == "auto": # restart from checkpoint if it exists if os.path.isfile(checkpoint_file): print ("resume simulation from %s" % checkpoint_file) simulation.loadCheckpoint(checkpoint_file) else: print ("resume simulation from %s" % args.starting_checkpoint) simulation.loadCheckpoint(args.starting_checkpoint) # the topology is already set by pdb file, and the positions in the pdb file will be overwritten by those in the starting_checkpoint file if args.minimize_energy: print('begin Minimizing energy...') print datetime.datetime.now() simulation.minimizeEnergy() print('Done minimizing energy.') print datetime.datetime.now() else: print('energy minimization not required') print("begin equilibrating...") print datetime.datetime.now() simulation.step(args.equilibration_steps) previous_distance_to_potential_center = 100 current_distance_to_potential_center = 90 if args.auto_equilibration: distance_change_tolerance = 0.05 while abs(previous_distance_to_potential_center - current_distance_to_potential_center) > distance_change_tolerance: temp_pdb_reporter_file_for_auto_equilibration = pdb_reporter_file.replace('.pdb', '_temp.pdb') simulation.reporters.append(PDBReporter(temp_pdb_reporter_file_for_auto_equilibration, record_interval)) simulation.step(args.equilibration_steps) previous_distance_to_potential_center = current_distance_to_potential_center current_distance_to_potential_center = get_distance_between_data_cloud_center_and_potential_center( temp_pdb_reporter_file_for_auto_equilibration) subprocess.check_output(['rm', temp_pdb_reporter_file_for_auto_equilibration]) print "previous_distance_to_potential_center = %f\ncurrent_distance_to_potential_center = %f" % ( previous_distance_to_potential_center, current_distance_to_potential_center ) print("Done equilibration") print datetime.datetime.now() simulation.reporters.append(PDBReporter(pdb_reporter_file, record_interval)) simulation.reporters.append(StateDataReporter(state_data_reporter_file, record_interval, time=True, step=True, potentialEnergy=True, kineticEnergy=True, speed=True, temperature=True, progress=True, remainingTime=True, totalSteps=number_of_simulation_steps + args.equilibration_steps, )) print "Running production" simulation.step(number_of_simulation_steps) print "Done production" if args.checkpoint: if os.path.isfile(checkpoint_file): os.rename(checkpoint_file, checkpoint_file.split('.chk')[0] + "_bak_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".chk") simulation.saveCheckpoint(checkpoint_file) print('Done!') print datetime.datetime.now() return pdb_reporter_file