def main(): print("Reading the PSF file"); # Read the PSF file psf = app.CharmmPsfFile('g1_25mm.psf'); boxsize = 5 # Boxsize in nm psf.setBox(boxsize*nanometer, boxsize*nanometer, boxsize*nanometer); print("Reading the pdb file") pdb = app.PDBFile('g1_25mm.pdb'); # Load the parameter set lib = 'toppar/' #params = app.CharmmParameterSet('toppar/top_all36_cgenff.rtf','toppar/par_all36_cgenff.prm','toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') params = app.CharmmParameterSet('toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') #platform = openmm.Platform.getPlatformByName('CUDA'); platform = openmm.Platform.getPlatformByName('Reference'); # Creating the system system = psf.createSystem(params, nonbondedMethod=app.PME, nonbondedCutoff=1.2*nanometer, switchDistance=1.0*nanometer, ewaldErrorTolerance= 0.0001, constraints=app.HBonds); # Thermostat @ 298 K system.addForce(openmm.AndersenThermostat(298*kelvin, 1/picosecond)) # adding the barostat for now system.addForce(openmm.MonteCarloBarostat(1*bar, 298*kelvin)); integrator = openmm.VerletIntegrator(0.001*picoseconds) simulation = app.Simulation(psf.topology, system, integrator, platform) simulation.context.setPositions(pdb.getPositions()) simulation.minimizeEnergy(maxIterations = 500) #nsavcrd = 10000 # save coordinates every 10 ps #nstep = 2000000 # write dcd files every 2 ps #nprint = 2000 # report every 2 ps nsavcrd = 10 # save coordinates every 10 ps nstep = 200 # write dcd files every 2 ps nprint = 20 # report every 2 ps firstDcdStep = nsavcrd ; # Reporters dcd = app.DCDReporter('g1_new.dcd', nsavcrd) dcd._dcd = app.DCDFile(dcd._out, simulation.topology, simulation.integrator.getStepSize(), firstDcdStep, nsavcrd) simulation.reporters.append(dcd) simulation.reporters.append(app.StateDataReporter('g1_new.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True)) simulation.step(nstep) simulation.reporters.pop() simulation.reporters.pop() dcd._out.close()
def test_dcd(self): """ Test the DCD file """ fname = tempfile.mktemp(suffix='.dcd') pdbfile = app.PDBFile('systems/alanine-dipeptide-implicit.pdb') natom = len(list(pdbfile.topology.atoms())) with open(fname, 'wb') as f: dcd = app.DCDFile(f, pdbfile.topology, 0.001) for i in range(5): dcd.writeModel([mm.Vec3(random(), random(), random()) for j in range(natom)]*unit.angstroms) os.remove(fname)
def testLongTrajectory(self): """Test writing a trajectory that has more than 2^31 steps.""" fname = tempfile.mktemp(suffix='.dcd') pdbfile = app.PDBFile('systems/alanine-dipeptide-implicit.pdb') natom = len(list(pdbfile.topology.atoms())) with open(fname, 'wb') as f: dcd = app.DCDFile(f, pdbfile.topology, 0.001, interval=1000000000) for i in range(5): dcd.writeModel([mm.Vec3(random(), random(), random()) for j in range(natom)]*unit.angstroms) os.remove(fname)
if args.save_configs: # Create PDB file to view with the (binary) dcd file. positions = context.getState( getPositions=True, enforcePeriodicBox=True).getPositions(asNumpy=True) pdbfile = open(args.out + '.pdb', 'w') app.PDBFile.writeHeader(wbox.topology, file=pdbfile) app.PDBFile.writeModel(wbox.topology, positions, file=pdbfile, modelIndex=0) pdbfile.close() # Create a DCD file system configurations dcdfile = open(args.out + '.dcd', 'wb') dcd = app.DCDFile(file=dcdfile, topology=wbox.topology, dt=timestep) # Initialize SAMS adaptor initial_guess = 317.0 # Initializing the bias using the free energy to insert a single salt molecule bias = np.arange(args.saltmax + 1) * initial_guess adaptor = SAMSAdaptor(nstates=args.saltmax + 1, zetas=bias, beta=0.6, flat_hist=0.1) state_counts = np.zeros(args.saltmax + 1) # Proposal mechanism for SAMS def gen_penalty(nsalt, bias, saltmax): if nsalt == saltmax: penalty = [0.0, bias[nsalt - 1] - bias[nsalt]]
units.nanoseconds) / md_step.value_in_unit(units.nanoseconds) logging.info('Running production simulation:') logging.info(' saving to {}'.format(production_dcd)) logging.info(' {:6.3f} ns'.format(remainder.value_in_unit(units.nanoseconds))) current_step = 0 _steps = 500 reporter_freq = 5000 dcd_freq = 5000 cpt_freq = 5000 dof = _compute_dof(system) * units.MOLAR_GAS_CONSTANT_R _dcd_handle = open(production_dcd, 'wb') dcd_file = app.DCDFile(_dcd_handle, pdb.topology, integrator.getStepSize(), 0, dcd_freq) logging.info( 'Progress\tTime (ps)\tTotal Energy (kJ/mol)\tTemperature (K)\tSpeed (ns/day)' ) while current_step < total_steps: steps_left = int(total_steps - current_step) # force to be int if steps_left < 0.01: break elif steps_left < _steps: _steps = steps_left start_time = datetime.now() integrator.step(_steps) end_time = datetime.now()
def main(): print("Reading the PSF file") # Read the PSF file #psf = app.CharmmPsfFile('g1_25mm.psf'); psf = app.CharmmPsfFile('holo_neutr.psf') boxsize = 4.895883 # Boxsize in nm psf.setBox(boxsize * nanometer, boxsize * nanometer, boxsize * nanometer) print("Reading the pdb file") #pdb = app.PDBFile('g1_25mm.pdb'); #pdb = app.PDBFile('md_298k_100ns.pdb') pdb = app.PDBFile('holo_neutr.pdb') # Load the parameter set lib = 'toppar/' #params = app.CharmmParameterSet('toppar/top_all36_cgenff.rtf','toppar/par_all36_cgenff.prm','toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') #params = app.CharmmParameterSet('toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') params = app.CharmmParameterSet('toppar/cgenff3.0.1/top_all36_cgenff.rtf', 'toppar/cgenff3.0.1/par_all36_cgenff.prm', 'g1_new.str', 'oah_groups.str', 'toppar_water_ions.str') platform = openmm.Platform.getPlatformByName('CUDA') isShortSim = False #isShortSim = True isPeriodic = True #isPeriodic = False #if not isPeriodic : # isShortSim = True; # Creating the system if (isPeriodic): print("PME is being used") system = psf.createSystem(params, nonbondedMethod=app.PME, nonbondedCutoff=1.2 * nanometer, switchDistance=1.0 * nanometer, ewaldErrorTolerance=0.0001, constraints=app.HBonds) else: print("PME is not being used") system = psf.createSystem( params, # nonbondedMethod=app.PME, nonbondedCutoff=1.2 * nanometer, switchDistance=1.0 * nanometer, ewaldErrorTolerance=0.0001, constraints=app.HBonds) #for force in system.getForces(): # print(force, force.usesPeriodicBoundaryConditions()) # Thermostat @ 298 K #system.addForce(openmm.AndersenThermostat(298*kelvin, 1/picosecond)) # adding the barostat for now #system.addForce(openmm.MonteCarloBarostat(1*bar, 298*kelvin)); # adding positional restriants if isPeriodic: force = openmm.CustomExternalForce( "k*periodicdistance(x, y, z, x0, y0, z0)^2") else: force = openmm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)") #force = openmm.CustomExternalForce("k*periodicdistance(x, y, z, x0, y0, z0)^2"); force.addGlobalParameter("k", 0.1 * kilocalories_per_mole / angstroms**2) force.addPerParticleParameter("x0") force.addPerParticleParameter("y0") force.addPerParticleParameter("z0") topology = pdb.getTopology() positions = pdb.getPositions() #for atom in topology.atoms(): # print(atom) host = [] guest = [] for res in topology.residues(): if res.name == 'OAH': for atom in res.atoms(): host.append(atom.index) force.addParticle(atom.index, positions[atom.index]) #force.addParticle(atom.index, (0, 0, 0)*nanometers) if res.name == 'GOA': for atom in res.atoms(): guest.append(atom.index) system.addForce(force) print("Does customExternalForce use periodic boundary condition : ", force.usesPeriodicBoundaryConditions()) # adding restraint between the host and guest # this will be inside the umbrella sampling loop host_guest_centroid_force = openmm.CustomCentroidBondForce( 2, "0.5*k*(distance(g1,g2)-d0)^2") host_guest_centroid_force.addGlobalParameter( "k", 10.0 * kilocalories_per_mole / angstroms**2) #d0_global_parameter_index = force.addGlobalParameter("d0", 2.0*angstroms); #d0_perBond_parameter_index = force.addPerBondParameter("d0", 2.0*angstroms); d0_perBond_parameter_index = host_guest_centroid_force.addPerBondParameter( "d0") group1 = host_guest_centroid_force.addGroup(host) group2 = host_guest_centroid_force.addGroup(guest) host_guest_bond = host_guest_centroid_force.addBond([group1, group2]) host_guest_centroid_force.setBondParameters(host_guest_bond, [group1, group2], [20 * angstroms]) system.addForce(host_guest_centroid_force) #sys.exit(0) """ # Restrain along z axis # adding positional restriants if isPeriodic : z_force = openmm.CustomExternalForce("k*periodicdistance(x, x0)^2"); else : z_force = openmm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2)"); #force = openmm.CustomExternalForce("k*periodicdistance(x, y, z, x0, y0, z0)^2"); z_force.addGlobalParameter("k", 0.1*kilocalories_per_mole/angstroms**2); z_force.addPerParticleParameter("x0"); z_force.addPerParticleParameter("y0"); for res in topology.residues(): if res.name == 'GOA' : for atom in res.atoms(): pos = list(positions[atom.index]) print(pos[2]) z_force.addParticle(atom.index, [pos[0], pos[1]]) system.addForce(z_force) """ # langevin integrator integrator = openmm.LangevinIntegrator( 298 * kelvin, # Temperature 1.0 / picoseconds, # Friction coefficient 0.001 * picoseconds # Time step ) #integrator = openmm.VerletIntegrator(0.001*picoseconds); simulation = app.Simulation(psf.topology, system, integrator, platform) simulation.context.setPositions(pdb.getPositions()) #currentState = simulation.context.getState(getPositions=True) #pdbr = app.PDBReporter("pdbreport.pdb",1); #pdbr.report(simulation, currentState) print("Minimizing...") simulation.minimizeEnergy(maxIterations=2000) print("Equilibrating...") simulation.context.setVelocitiesToTemperature(298 * kelvin) #currentState = simulation.context.getState(getPositions=True) #pdbr = app.PDBReporter("pdbreport_after_min.pdb",1); #pdbr.report(simulation, currentState) #pdbr = app.PDBReporter("pdbreport_after_step1.pdb",1); nsavcrd = 10000 # save coordinates every 10 ps nprint = 2000 # report every 2 ps if isShortSim: nstep = 20000 # run the simulation for 0.2ns else: nstep = 2000000 # run the simulation for 2ns firstDcdStep = nsavcrd # Reporters dcdReportInterval = 10000 # save coordinates every 10 ps dcd = app.DCDReporter('umb_3.dcd', dcdReportInterval) dcd._dcd = app.DCDFile(dcd._out, simulation.topology, simulation.integrator.getStepSize(), firstDcdStep, nsavcrd) stateReporter = app.StateDataReporter('umb_3.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True) simulation.reporters.append(dcd) simulation.reporters.append(stateReporter) #simulation.reporters.append(pdbr); #simulation.reporters.append(app.StateDataReporter('umb.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True)) # Run the simulation print("Simulation begins ...") #simulation.step(1) #sys.exit(0) for i in range(15): print("Simulation for umbrella : ", i) host_guest_centroid_force.setBondParameters(host_guest_bond, [group1, group2], [(5 + 3 * i) * angstroms]) #force.setGlobalParameterDefaultValue(d0_global_parameter_index, (2+i)*angstroms) host_guest_centroid_force.updateParametersInContext(simulation.context) print("host guest bond parameters", host_guest_centroid_force.getBondParameters(host_guest_bond)) #serialized = openmm.XmlSerializer.serialize(simulation.system) #of = open("serial_sim_"+str(i)+".xml",'w'); #of.write(serialized); #of.close(); #simulation.saveState("state_"+str(i)+".xml"); simulation.step(nstep) simulation.reporters.pop() simulation.reporters.pop() dcd._out.close()
def main(): traj = md.load(TRAJECTORY, stride=STRIDE, top=TOPOLOGY) print 'Rotating frames so that they fit in the smallest possible box...' for i in progress(range(traj.n_frames)): traj.xyz[i] = rotate_to_pack(traj.xyz[i]) top = app.PDBFile(TOPOLOGY).topology #boxes = np.empty((traj.n_frames, 3)) n_atoms = np.empty(traj.n_frames) #print 'Solvating all of the frames with padding %s...' % PADDING #for i in progress(range(traj.n_frames)): # modeller = app.Modeller(top, traj.xyz[i].tolist()) # modeller.addSolvent(FF, model='tip3p', boxSize=None, padding=PADDING) # boxes[i] = modeller.topology.getUnitCellDimensions().value_in_unit(unit.nanometers) # n_atoms[i] = md.utils.ilen(modeller.topology.atoms()) # Now, find the largest box, and solvate all of the frames to that box size. #print 'Initial number of atoms in each solvated box:' #print n_atoms #print 'Initial box volumes:' #print np.prod(boxes, axis=1) #largest_frame = np.argmax(np.prod(boxes, axis=1)) #largest_box = unit.Quantity(boxes[largest_frame].tolist(), unit.nanometers) largest_box = unit.Quantity([8.067393779754639, 8.067393779754639, 8.067393779754639], unit.nanometers) #print 'Largest box: %d' % largest_frame #print 'Dimensions: %s' % largest_box #print 'N atoms : %d' % n_atoms[largest_frame] print '\nRe-solvating all frames into this box...' modellers = [] for i in progress(range(traj.n_frames)): modeller = app.Modeller(top, traj.xyz[i].tolist()) modeller.addSolvent(FF, model='tip3p', boxSize=largest_box) n_atoms[i] = md.utils.ilen(modeller.topology.atoms()) modellers.append(modeller) print 'After resolvation, the number of atoms in each solvated box:' print n_atoms n_remove_by_frame = np.asarray((n_atoms - np.min(n_atoms)) / SITES_PER_WATER, dtype=int) print '\nNumber of waters to remove from each frame:' print n_remove_by_frame print '\nRemoving waters from each frame until we get the same number per box' for modeller, n_remove in progress(zip(modellers, n_remove_by_frame)): waters = [res for res in modeller.topology.residues() if res.name == 'HOH'] np.random.shuffle(waters) modeller.delete(waters[0:n_remove]) print 'Final number of atoms in each frame' print [md.utils.ilen(mod.topology.atoms()) for mod in modellers] with open(OUT_TOPOLOGY, 'w') as f: # Debugging an issue where there seems to be a confusion between # positions having some floats in it and some np.float64s. Lets try to # standardize it. positions = unit.Quantity(np.array(modellers[0].positions._value).tolist(), unit.nanometers) app.PDBFile.writeFile(modellers[0].topology, positions, f) with open(SOLVATED_DCD, 'w') as f: print 'Saving solvated structures' dcdfile = app.DCDFile(f, modellers[0].topology, TIMESTEP) for modeller in progress(modellers): assert all(a.name == b.name for a, b in zip(modeller.topology.atoms(), modellers[0].topology.atoms())) dcdfile.writeModel(modeller.positions, modeller.topology.getUnitCellDimensions())
if args.save_configs: # Create PDB file to view with the (binary) dcd file. positions = context.getState( getPositions=True, enforcePeriodicBox=True).getPositions(asNumpy=True) pdbfile = open(args.out + '.pdb', 'w') app.PDBFile.writeHeader(testsys.topology, file=pdbfile) app.PDBFile.writeModel(testsys.topology, positions, file=pdbfile, modelIndex=0) pdbfile.close() # Create a DCD file system configurations dcdfile = open(args.out + '.dcd', 'wb') dcd = app.DCDFile(file=dcdfile, topology=testsys.topology, dt=timestep) # The actual simulation k = 0 for iteration in range(args.iterations): # Propagate configurations and salt concentrations t0 = time() langevin.step(args.steps) salinator.update(nattempts=1) iter_time = time() - t0 if iteration % args.save_freq == 0: # Record the simulation data Record.record_netcdf(ncfile, context, salinator.swapper, k,
# simulation.context.setState(mm.XmlSerializer.deserialize(f.read())) with open(jobname + '.' + restart + '.chk', 'rb') as f: simulation.context.loadCheckpoint(f.read()) nsavcrd = 50000 # save coordinates every 100 ps nstep = 50000000 # write dcd files every 100 ns nprint = 5000000 # report every 10 ns for ii in range(start, stop + 1): dcd = app.DCDReporter(prefix + jobname + '.' + str(ii) + '.dcd', nsavcrd) firstdcdstep = ii * nstep + nsavcrd while (firstdcdstep > 2000000000): # reset frame number to avoid charmm overfloat firstdcdstep -= 2000000000 dcd._dcd = app.DCDFile(dcd._out, simulation.topology, simulation.integrator.getStepSize(), firstdcdstep, nsavcrd) # charmm doesn't like first step to be 0 simulation.reporters.append(dcd) simulation.reporters.append( app.StateDataReporter(jobname + '.' + str(ii) + '.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True)) simulation.step(nstep) simulation.reporters.pop() simulation.reporters.pop()