Beispiel #1
0
def equilibrateSystem(pdbfile,
                      psffile,
                      outpdb,
                      numsteps=30000,
                      minimplatform='CPU',
                      equilplatform='CUDA',
                      device=0,
                      temp=300,
                      minimize=500000,
                      minimizetol=100,
                      charmmfolder=None):
    pdb = Molecule(pdbfile)
    watcoo = pdb.get('coords', 'water')
    celld = unit.Quantity((watcoo.max(axis=0) - watcoo.min(axis=0)).squeeze(),
                          unit=unit.angstrom)

    psf = app.CharmmPsfFile(psffile)
    pdb = app.PDBFile(pdbfile)
    psf.setBox(celld[0], celld[1], celld[2])

    params = _readCharmmParameters(charmmfolder, defaultCharmmFiles)

    system = psf.createSystem(params,
                              nonbondedMethod=app.PME,
                              nonbondedCutoff=1 * unit.nanometer,
                              constraints=app.HBonds)
    system.addForce(
        mm.MonteCarloBarostat(1 * unit.atmospheres, temp * unit.kelvin, 25))

    platform, prop = _getPlatform(minimplatform, device)
    integrator = mm.LangevinIntegrator(temp * unit.kelvin, 1 / unit.picosecond,
                                       0.002 * unit.picoseconds)
    simulation = app.Simulation(psf.topology, system, integrator, platform,
                                prop)
    simulation.context.setPositions(pdb.positions)

    # Perform minimization
    _printEnergies(simulation, 'Energy before minimization')
    simulation.minimizeEnergy(tolerance=minimizetol * unit.kilojoule /
                              unit.mole,
                              maxIterations=minimize)
    _printEnergies(simulation, 'Energy after minimization')

    # Copy coordinates from miminization context to equilibration context
    state = simulation.context.getState(getPositions=True)
    pos = state.getPositions()

    # Set up the equilibration simulation
    platform, prop = _getPlatform(equilplatform, device)
    integrator = mm.LangevinIntegrator(temp * unit.kelvin, 1 / unit.picosecond,
                                       0.002 * unit.picoseconds)
    simulation = app.Simulation(psf.topology, system, integrator, platform,
                                prop)
    simulation.context.setPositions(pos)

    # Generate initial velocities
    simulation.context.setVelocitiesToTemperature(temp)

    from htmd.membranebuilder.pdbreporter import PDBReporter
    simulation.reporters.append(
        PDBReporter(outpdb, numsteps, enforcePeriodicBox=False))
    simulation.reporters.append(
        app.StateDataReporter(stdout,
                              int(numsteps / 10),
                              step=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              totalEnergy=True,
                              temperature=True,
                              progress=True,
                              speed=True,
                              remainingTime=True,
                              totalSteps=numsteps,
                              separator='\t'))
    simulation.step(numsteps)
Beispiel #2
0
                            properties)
simulation.context.setPositions(modeller.positions)

# minimize
print('Minimizing...')
simulation.minimizeEnergy()

# equilibrate for 100 steps
simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
print('Equilibrating...')
simulation.step(100)

# append reporters
simulation.reporters.append(app.DCDReporter('trajectory_tip5p.dcd', 1000))
simulation.reporters.append(
    app.StateDataReporter(stdout,
                          1000,
                          step=True,
                          potentialEnergy=True,
                          temperature=True,
                          progress=True,
                          remainingTime=True,
                          speed=True,
                          totalSteps=25000000,
                          separator='\t'))

# run 50 ns of production simulation
print('Running Production...')
simulation.step(25000000)
print('Done!')
        system.getForce(i).setFrequency(1000)

applyHarmonicPositionalRestraints(system, 1.0, inpcrd, Chunk_Heavy_Atoms)
applyLigandChunkRestraint(system, 1.0, 10.0, 2 * u.angstrom, 3 * u.angstrom,
                          4 * u.angstrom, keyInteraction)

simulation = app.Simulation(prmtop.topology, system, integrator, platform,
                            platformProperties)
simulation.context.setPositions(positions)

simulation.reporters.append(
    app.StateDataReporter("heating.csv",
                          1000,
                          time=True,
                          potentialEnergy=True,
                          temperature=True,
                          density=True,
                          remainingTime=True,
                          speed=True,
                          totalSteps=35000))
simulation.reporters.append(app.PDBReporter('heating.pdb', 1000))

simulation.step(35000)  # i.e. 20,000 fs == 20 ps == 0.02 ns

# Save the positions and velocities
positions = simulation.context.getState(getPositions=True).getPositions()
velocities = simulation.context.getState(getVelocities=True).getVelocities()

#clear reporters
simulation.reporters = []
Beispiel #4
0
# Create the OpenMM system
topology = generateTopologyFromOEMol(mol)
system = forcefield.createSystem(topology, [mol])

# Set up an OpenMM simulation
integrator = openmm.LangevinIntegrator(temperature, friction, time_step)
platform = openmm.Platform.getPlatformByName('Reference')
simulation = app.Simulation(topology, system, integrator)
simulation.context.setPositions(positions)
simulation.context.setVelocitiesToTemperature(temperature)
netcdf_reporter = NetCDFReporter('trajectory.nc', trj_freq)
simulation.reporters.append(netcdf_reporter)
simulation.reporters.append(
    app.StateDataReporter('data.csv',
                          data_freq,
                          step=True,
                          potentialEnergy=True,
                          temperature=True,
                          density=True))

# Run the simulation
print("Starting simulation")
start = time.clock()
simulation.step(num_steps)
end = time.clock()

print("Elapsed time %.2f seconds" % (end - start))
netcdf_reporter.close()
print("Done!")
Beispiel #5
0
def do_equlibrate(force_constant_equilibrate=1.0, gpu_id=0):
    # Find the interations
    keyInteraction = cal_ints.find_interaction()
    # Platform definition
    platform = mm.Platform_getPlatformByName("OpenCL")
    platformProperties = {}
    platformProperties['OpenCLPrecision'] = 'mixed'
    platformProperties["OpenCLDeviceIndex"] = gpu_id
    print("loading pickle")
    pickle_in = open('complex_system.pickle', 'rb')
    combined_pmd = pickle.load(pickle_in)[0]
    combined_pmd.symmetry = None
    pickle_in.close()
    ##################
    ##################
    #  Minimisation  #
    ##################
    ##################
    print('Minimising...')
    # Define system
    system = combined_pmd.createSystem(nonbondedMethod=app.PME,
                                       nonbondedCutoff=9 * u.angstrom)
    # Get indexes of heavy atoms in chunk
    Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd)
    # Apply force on all havy atoms of chunk
    duck_stuff.applyHarmonicPositionalRestraints(system,
                                                 force_constant_equilibrate,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    # Integrator
    integrator = mm.VerletIntegrator(1 * u.femtosecond)
    # Define Simulation
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.context.setPositions(combined_pmd.positions)
    print(simulation.context.getPlatform().getName())
    for key in simulation.context.getPlatform().getPropertyNames():
        print(
            key,
            simulation.context.getPlatform().getPropertyValue(
                simulation.context, key))
    # Minimizing energy
    simulation.minimizeEnergy(maxIterations=1000)
    # Saving minimised positions
    positions = simulation.context.getState(getPositions=True).getPositions()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('minimisation.pdb', 'w'))
    ##########################
    ##########################
    # Equlibration - heating #
    ##########################
    ##########################
    #new minimised positions, however using old restraints
    # Define new system
    system = combined_pmd.createSystem(nonbondedMethod=app.PME,
                                       nonbondedCutoff=9 * u.angstrom,
                                       constraints=app.HBonds,
                                       hydrogenMass=None)
    # Apply force on all havy atoms of chunk and apply restraint for the ligand-chunk distance
    duck_stuff.applyHarmonicPositionalRestraints(system,
                                                 force_constant_equilibrate,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    duck_stuff.applyLigandChunkRestraint(system, force_constant_equilibrate,
                                         10.0, 2 * u.angstrom, 3 * u.angstrom,
                                         4 * u.angstrom, keyInteraction)
    # Intergator
    integrator = mm.LangevinIntegrator(300 * u.kelvin, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    # Define Simulation
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.context.setPositions(
        positions)  #changing coordintes to minimized
    # Reporters
    simulation.reporters.append(
        app.StateDataReporter("heating.csv",
                              1000,
                              time=True,
                              potentialEnergy=True,
                              temperature=True,
                              density=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=50000))
    simulation.reporters.append(app.DCDReporter("heating.dcd", 1000))
    # Heating the system
    print("Heating ... ")
    simulation.step(50000)  # 0.01 ns
    # Save the positions and velocities
    positions = simulation.context.getState(getPositions=True).getPositions()
    velocities = simulation.context.getState(
        getVelocities=True).getVelocities()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('heating_final.pdb', 'w'))
    #clear reporters
    simulation.reporters = []
    ##########################
    ##########################
    # Equlibration - density #
    ##########################
    ##########################
    simulation = duck_stuff.setUpNPTEquilibration(system, combined_pmd,
                                                  platform, platformProperties,
                                                  positions, velocities)
    # Reporters
    simulation.reporters.append(
        app.StateDataReporter("density.csv",
                              1000,
                              time=True,
                              potentialEnergy=True,
                              temperature=True,
                              density=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=50000))
    # Correcting the density
    print("Correcting density")
    simulation.step(50000)  # 0.01 ns
    # Save the positions and velocities
    positions = simulation.context.getState(getPositions=True).getPositions()
    velocities = simulation.context.getState(
        getVelocities=True).getVelocities()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('density_final.pdb', 'w'))
    #saving simulation stage
    checkpoint = 'equil.chk'
    simulation.saveCheckpoint(checkpoint)
    return [checkpoint]
Beispiel #6
0
    def run(self,
            production_steps=200,
            start='ala2_1stFrame.pdb',
            production='ala2_production.pdb'):  #### ?!!!!!!!!!!!!!!!!
        #from __future__ import print_function
        from simtk.openmm import app
        import simtk.openmm as mm
        from simtk import unit
        from sys import stdout

        nonbondedCutoff = 1.0 * unit.nanometers
        timestep = 2.0 * unit.femtoseconds
        temperature = 300 * unit.kelvin
        #save_frequency = 100 #Every 100 steps, save the trajectory
        save_frequency = 10  #Every 1 steps, save the trajectory

        pdb = app.PDBFile(start)
        forcefield = app.ForceField('amber99sb.xml', 'tip3p.xml')
        ala2_model = app.Modeller(pdb.topology, pdb.positions)

        #Hydrogens will be constrained after equilibrating
        system = forcefield.createSystem(ala2_model.topology,
                                         nonbondedMethod=app.PME,
                                         nonbondedCutoff=nonbondedCutoff,
                                         constraints=app.HBonds,
                                         rigidWater=True,
                                         ewaldErrorTolerance=0.0005)

        system.addForce(mm.MonteCarloBarostat(
            1 * unit.bar, temperature,
            100))  #Apply Monte Carlo Pressure changes in 100 timesteps
        integrator = mm.LangevinIntegrator(temperature, 1.0 / unit.picoseconds,
                                           timestep)
        integrator.setConstraintTolerance(0.00001)

        platform = mm.Platform.getPlatformByName('CPU')
        simulation = app.Simulation(ala2_model.topology, system, integrator,
                                    platform)
        simulation.context.setPositions(ala2_model.positions)

        simulation.context.setVelocitiesToTemperature(temperature)

        simulation.reporters.append(app.PDBReporter(production,
                                                    save_frequency))
        simulation.reporters.append(
            app.StateDataReporter('stateReporter_constantPressure.txt',
                                  1000,
                                  step=True,
                                  totalEnergy=True,
                                  temperature=True,
                                  volume=True,
                                  progress=True,
                                  remainingTime=True,
                                  speed=True,
                                  totalSteps=production_steps,
                                  separator='\t'))

        print('Running Production...')
        simulation.step(production_steps)
        print('Done!')

        import mdtraj as md
        trj = md.load(production)
        return trj
Beispiel #7
0
def getReporters(totalSteps=None, outfname=None, **opt):
    """
    Creates 3 OpenMM Reporters for the simulation.

    Parameters
    ----------
    totalSteps : int
        The total number of simulation steps
    reportInterval : (opt), int, default=1000
        Step frequency to write to reporter file.
    outfname : str
        Specifies the filename prefix for the reporters.

    Returns
    -------
    reporters : list of three openmm.app.simulation.reporters
        (0) state_reporter: writes energies to '.log' file.
        (1) progress_reporter: prints simulation progress to 'sys.stdout'
        (2) traj_reporter: writes trajectory to file. Supported format .nc, .dcd, .hdf5
    """
    if totalSteps is None:
        totalSteps = opt['steps']
    if outfname is None:
        outfname = opt['outfname']

    reporters = []

    if opt['reporter_interval']:
        state_reporter = app.StateDataReporter(outfname+'.log', separator="\t",
                                               reportInterval=opt['reporter_interval'],
                                               step=True,
                                               potentialEnergy=True, totalEnergy=True,
                                               volume=True, density=True, temperature=True)

        reporters.append(state_reporter)

        progress_reporter = app.StateDataReporter(stdout, separator="\t",
                                                  reportInterval=opt['reporter_interval'],
                                                  step=True, totalSteps=totalSteps,
                                                  time=True, speed=True, progress=True,
                                                  elapsedTime=True, remainingTime=True)

        reporters.append(progress_reporter)

    if opt['trajectory_interval']:

        trj_fname = outfname
        # Trajectory file format selection
        if opt['trajectory_filetype'] == 'NetCDF':
            trj_fname += '.nc'
            traj_reporter = mdtraj.reporters.NetCDFReporter(trj_fname, opt['trajectory_interval'])
        elif opt['trajectory_filetype'] == 'DCD':
            trj_fname += '.dcd'
            traj_reporter = app.DCDReporter(trj_fname, opt['trajectory_interval'])
        elif opt['trajectory_filetype'] == 'HDF5':
            trj_fname += '.hdf5'
            mdtraj.reporters.HDF5Reporter(trj_fname, opt['trajectory_interval'])
        else:
            oechem.OEThrow.Fatal("The selected trajectory file format is not supported: {}"
                                 .format(opt['trajectory_filetype']))

        opt['molecule'].SetData(oechem.OEGetTag("Trj_fname"), trj_fname)

        reporters.append(traj_reporter)

    return reporters
Beispiel #8
0
def openmm_simulate_amber_fs_pep(pdb_file,
                                 check_point=None,
                                 GPU_index=0,
                                 output_traj="output.dcd",
                                 output_log="output.log",
                                 output_cm=None,
                                 report_time=10 * u.picoseconds,
                                 sim_time=10 * u.nanoseconds):
    """
    Start and run an OpenMM NVT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.2 nm and LJ switch distance at 1.0 nm, which commonly used with
    Charmm force field. Long-range nonbonded interactions were handled with PME.  

    Parameters
    ----------
    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 
   
    check_point : None or check point file to load 
        
    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. Use Strings, '0,1'
        for example, to use more than 1 GPU
  
    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 
  
    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, potential
        energy, temperature, speed, etc.
 
    output_cm : the h5 file contains contact map information

    report_time : 10 ps
        The program writes its information to the output every 10 ps by default 

    sim_time : 10 ns
        The timespan of the simulation trajectory
    """

    pdb = pmd.load_file(pdb_file)
    forcefield = app.ForceField('amber99sbildn.xml', 'amber99_obc.xml')

    system = forcefield.createSystem(pdb.topology,
                                     nonbondedMethod=app.CutoffNonPeriodic,
                                     nonbondedCutoff=1.0 * u.nanometer,
                                     constraints=app.HBonds)
    dt = 0.002 * u.picoseconds
    integrator = omm.LangevinIntegrator(300 * u.kelvin, 91.0 / u.picosecond,
                                        dt)
    integrator.setConstraintTolerance(0.00001)

    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        properties = {'DeviceIndex': str(GPU_index)}

    simulation = app.Simulation(pdb.topology, system, integrator, platform,
                                properties)

    pdb_index = random.randint(0, len(pdb.get_coordinates()) - 1)
    simulation.context.setPositions(pdb.get_coordinates()[pdb_index])

    simulation.context.setVelocitiesToTemperature(300 * u.kelvin)

    simulation.minimizeEnergy()

    report_freq = int(report_time / dt)
    simulation.context.setVelocitiesToTemperature(10 * u.kelvin,
                                                  random.randint(1, 10000))
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(ContactMapReporter(output_cm, report_freq))
    simulation.reporters.append(
        app.StateDataReporter(output_log,
                              report_freq,
                              step=True,
                              time=True,
                              speed=True,
                              potentialEnergy=True,
                              temperature=True,
                              totalEnergy=True))
    simulation.reporters.append(
        app.CheckpointReporter('checkpnt.chk', report_freq))

    if check_point:
        simulation.loadCheckpoint(check_point)
    nsteps = int(sim_time / dt)
    simulation.step(nsteps)
Beispiel #9
0
    def simulationSpawner(self, protocol, label='NPT', kind='equilibration', index=0):
        
        
        self.energy=self.simulation.context.getState(getEnergy=True).getTotalEnergy()

        print(f'Spwaning new simulation:')
        print(f'\tSystem total energy: {self.energy}')
        
        
        if kind == 'minimization':
            
            self.simulation.minimizeEnergy()
            self.structures['minimization']=self.writePDB(self.topology, self.positions, name='minimization')
            print(f'\tPerforming energy minimization: {Ei}')
        
        else:
            
            name=f'{kind}_{label}'
            trj_file=f'{self.workdir}/{kind}_{label}'
        
            #If there are user defined costum forces
            try:
                if protocol['restrained_sets']:
                    self.system=self.setRestraints(protocol['restrained_sets'])

            except KeyError:    
                pass

            if label == 'NPT':
            
                #TODO: frequency is hardcoded to 25, make it go away. Check units throughout!
                print(f'\tAdding MC barostat for {name} ensemble')      
                self.system.addForce(omm.MonteCarloBarostat(self.pressure, self.temperature, 25)) 
        
            self.simulation.context.setPositions(self.positions)
        
            if index == 1 and kind == 'equilibration':
                print(f'\tFirst equilibration run {name}. Assigning velocities to {self.temperature}')
                self.simulation.context.setVelocitiesToTemperature(self.temperature)
        
            # Define reporters
            self.simulation.reporters.append(DCDReporter(f'{trj_file}.dcd', protocol['report']))           
            self.simulation.reporters.append(HDF5Reporter(f'{trj_file}.h5', protocol['report'], atomSubset=self.trj_indices))
            self.simulation.reporters.append(app.StateDataReporter(f'{trj_file}.csv', 
                                                          protocol['report'], 
                                                          step=True, 
                                                          totalEnergy=True, 
                                                          temperature=True,
                                                          density=True,
                                                          progress=True, 
                                                          remainingTime=True, 
                                                          speed=True, 
                                                          totalSteps=protocol['step'], 
                                                          separator='\t'))
        
            positions_first = self.simulation.context.getState(getPositions=True).getPositions()
        
            self.structures['f{name}_ref']=self.writePDB(self.simulation.topology, positions_first, name=f'{name}_0')
        
            #############
            ## WARNIN ##
            #############
        
            trj_time=protocol['step']*self.dt
            print(f'\t{kind} simulation in {label} ensemble ({trj_time})...')
            self.simulation.step(protocol['step'])
        
            
            #############
            ## WARNOUT ##
            #############

            print(f'\t{kind} simulation in {label} ensemble ({trj_time}) completed.')
            self.structures[f'{name}']=self.writePDB(self.simulation.topology, self.positions, name='{name}')

        state=self.simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True)
        self.positions = state.getPositions()
        self.velocities = state.getVelocities()
        self.energy=state.getPotentialEnergy()


        

        
        #Remove Costum forces (always initialized in next run)
        if label == 'NPT':
            self.system=self.forceHandler(self.system, kinds=['CustomExternalForce', 'MonteCarloBarostat'])
        elif label == 'NVT':
            self.system=self.forceHandler(self.system, kinds=['CustomExternalForce'])
            
        return self.simulation
                             nonbondedMethod=app.PME,
                             rigidWater=True)

    ## Do a short equilibration run to get it around 300K
    integrator = openmm.LangevinIntegrator(300 * unit.kelvin,
                                           1.0 / unit.picosecond,
                                           2.0 * unit.femtosecond)
    simulation = app.Simulation(topology, system, integrator)
    simulation.context.setPeriodicBoxVectors(*box_vectors)
    simulation.context.setPositions(positions)
    print('\tMinimizing...')
    simulation.minimizeEnergy(tolerance=100 * unit.kilojoule / unit.mole)
    simulation.reporters.append(
        app.StateDataReporter(sys.stdout,
                              250,
                              step=True,
                              potentialEnergy=True,
                              temperature=True))
    simulation.step(50000)
    state = simulation.context.getState(getPositions=True)
    positions = state.getPositions()

    with open(crdfile, 'w') as fp:
        fp.write('%d 3\n' % n_atoms)
        for atom in positions:
            x = atom[0].value_in_unit(unit.angstroms)
            y = atom[1].value_in_unit(unit.angstroms)
            z = atom[2].value_in_unit(unit.angstroms)
            fp.write("%16.10f%16.10f%16.10f\n" % (x, y, z))

    with open(cppfile, 'w') as fp:
Beispiel #11
0
    restart=str(start-1)
    with open(trjPath+jobname+'.'+restart+'.rst', 'r') as f:  # the .rst file should only be used if .chk restart file cannot be loaded
        simulation.context.setState(mm.XmlSerializer.deserialize(f.read()))

nsavcrd=50000 # save coordinates every 100 ps
nstep=10000000 # write dcd files every 20 ns
nprint=50000 # report every 1 ns

for ii in range(start,stop+1):
    dcd=app.DCDReporter(trjPath+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) # "reporters" aka. write out
    simulation.reporters.append(app.StateDataReporter(wkPath+jobname+'.'+str(ii)+'.out', nprint, step=True, time=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True))
    """StateDataReporter options: step, time, progress, remainingTime, potentialEnergy, kineticEnergy, totalEnergy, temperature, volume, density, speed, totalSteps. Default separator=','"""
    simulation.step(nstep) # run the simulation
    simulation.reporters.pop() # temporally keep to continue the loop
    simulation.reporters.pop()
    dcd._out.close() # close the dcd file to make sure the buffers are written.
 
    # write restart file
    state = simulation.context.getState( getPositions=True, getVelocities=True )
    with open(trjPath+jobname+'.'+str(ii)+'.rst', 'w') as f:
        f.write(mm.XmlSerializer.serialize(state))

    # move the dcd back to home
    #cmdstr='mv '+trjPath+jobname+'.'+str(ii)+'.dcd .'
    #call(cmdstr, shell=True)
Beispiel #12
0
simulation.context.setPositions(positions)
print('Minimizing...')
simulation.minimizeEnergy()

simulation.context.setVelocitiesToTemperature(temperature)
print('Equilibrating...')

simulation.step(discard_steps)  # Don't even save the first XXX ps

simulation.reporters.append(app.DCDReporter(dcd_filename, output_frequency))
simulation.reporters.append(app.PDBReporter(out_pdb_filename, n_steps - 1))
simulation.reporters.append(
    app.StateDataReporter(open(log_filename, 'w'),
                          output_frequency,
                          step=True,
                          time=True,
                          speed=True,
                          potentialEnergy=True,
                          temperature=True,
                          density=True))
simulation.step(n_steps)

del simulation
del system
t = md.load(dcd_filename, top=out_pdb_filename)
t0 = t[-1]
t0.unitcell_lengths = t.unitcell_lengths.mean(0)
t0.save(out_pdb_filename)

del t
del t0
t = md.load(dcd_filename, top=out_pdb_filename)[-1]
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 = False
    isPeriodic = True
    #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, z0)^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(nstep)
    """#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()
timestep = args.time_step * unit.femtoseconds
integrator = mm.LangevinIntegrator(temp * unit.kelvin, fric / unit.picoseconds,
                                   timestep)
integrator.setConstraintTolerance(0.00001)

platform = mm.Platform.getPlatformByName('CUDA')
simulation = app.Simulation(topology, system, integrator, platform)

#load positions saved from htmd.
traj = mdtraj.load('input_coor.dcd', top='input.pdb')
simulation.context.setPositions(traj.openmm_positions(0))

if args.output_path != "":
    output_path = args.output_path + "/"
else:
    output_path = os.path.splitext(pdb_str)[0]

simulation.context.setVelocitiesToTemperature(temp * unit.kelvin)

# equilibrate
print("Running MD ...")
nsteps = int(t_sim * unit.nanoseconds / timestep)
log_interval = int(args.log_interval * unit.nanoseconds / timestep)
simulation.reporters.append(app.DCDReporter('traj.dcd', log_interval))
simulation.reporters.append(app.StateDataReporter(sys.stdout, log_interval, step=True, time=True, progress=True,
                                                  potentialEnergy=True, temperature=True, remainingTime=True,
                                                  speed=True, totalSteps=nsteps, separator=','))
simulation.step(nsteps)

if keyInteraction == []:
    print('Did not select key interaction')

print('selected interaction: ' + str(keyInteraction))

applyHarmonicPositionalRestraints(system, 1.0, inpcrd, Chunk_Heavy_Atoms)

integrator = mm.VerletIntegrator(1 * u.femtosecond)
simulation = app.Simulation(prmtop.topology, system, integrator, platform,
                            platformProperties)
simulation.context.setPositions(inpcrd.positions)

simulation.reporters.append(
    app.StateDataReporter("minimisation.csv",
                          1,
                          step=True,
                          potentialEnergy=True))

simulation.minimizeEnergy(maxIterations=1000)

#Saving minimised positions
positions = simulation.context.getState(getPositions=True).getPositions()
app.PDBFile.writeFile(simulation.topology, positions,
                      open('minimisation.pdb', 'w'))

#Equlibration - heating
#new minimised positions, however using old restraints
print('Heating system under NVT...')

system = prmtop.createSystem(nonbondedMethod=app.PME,
                             nonbondedCutoff=9 * u.angstrom,
Beispiel #16
0
    def production_NPT(self, protocol):      
        

        prod_trj=f'{self.workdir}/production_NPT'

        self.simulation.context.setPositions(self.positions)
        
        # =============================================================================
        # NO need for now since NPT eq protocols are not removing the barostat
        #         # add MC barostat for NPT     
        #         self.system.addForce(omm.MonteCarloBarostat(self.pressure, 
        #                                                     self.temperature, 
        #                                                     25)) 
        #         #TODO: force is hardcoded, make it go away. Check units throughout!
        # =============================================================================
                
                
        # Define reporters

        #TODO: Decide on wether same extent as steps for reporter
        #TODO: Link to mlflow or streamz
        
        
        #TODO: Use append on DCD for control of continuation
        self.simulation.reporters.append(DCDReporter(f'{prod_trj}.dcd', protocol['report']))           
        self.simulation.reporters.append(HDF5Reporter(f'{prod_trj}.h5', protocol['report'], atomSubset=self.trj_indices))
        self.simulation.reporters.append(app.StateDataReporter(f'{prod_trj}.csv', 
                                                          protocol['report'], 
                                                          step=True, 
                                                          totalEnergy=True, 
                                                          temperature=True,
                                                          density=True,
                                                          progress=True, 
                                                          remainingTime=True, 
                                                          speed=True, 
                                                          totalSteps=protocol['step'], 
                                                          separator='\t'))
        
        
        positions_first = self.simulation.context.getState(getPositions=True, getVelocities=True).getPositions()
        self.writePDB(self.simulation.topology, positions_first, name='production_NPT_0')
        
        #############
        ## WARNIN ##
        #############
        trj_time=protocol['step']*self.dt
        print(f"NPT production ({trj_time})...")
        
        self.simulation.step(protocol['step'])

        #############
        ## WARNOUT ##
        #############

        state=self.simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True)
        self.positions = state.getPositions()
        self.velocities = state.getVelocities()
        self.energy=state.getPotentialEnergy()


        print('NPT production finished.')
        
        self.EQ_NPT_PDB=self.writePDB(self.simulation.topology, self.positions, name='production_NPT')
        Eo=self.simulation.context.getState(getEnergy=True).getPotentialEnergy()
        
        print(f'System energy: {Eo}')
        
            
        return self.simulation        
### System has been created, but before the Simulation is created.

# Create a Simulation object by putting together the objects above
simulation = app.Simulation(pdb.topology, system, integrator, platform)

# Set positions in the Simulation object
simulation.context.setPositions(pdb.positions)

# Minimize the energy of the system (intentionally doing a rough minimization)
print('Minimizing...')
simulation.minimizeEnergy(maxIterations=20, tolerance=100)

# Initialize the random velocities of the system from a Maxwell-Boltzmann distribution
simulation.context.setVelocitiesToTemperature(300*unit.kelvin)

# Add reporters to the simulation object, which do things at regular intervals
# while the simulation is running.
# This reporter creates a DCD trajectory file
# A: Christian Bale
simulation.reporters.append(app.DCDReporter('trajectory.dcd', 100))

# This reporter prints information to the terminal
simulation.reporters.append(app.StateDataReporter(stdout, 100, step=True, 
    potentialEnergy=True, temperature=True, density=True, progress=True, 
    remainingTime=True, speed=True, totalSteps=10000, separator='\t'))

# Run the simulation itself
print('Running Production...')
simulation.step(10000)
print('Done!')
Beispiel #18
0
    def equilibration_NVT(self, protocol, index=0):      
            
        eq_trj=f'{self.workdir}/equilibration_NVT'

        if protocol['restrained_sets']:

            #call to setRestraints, returns updated system. Check protocol['restrained_sets'] definitions on setSimulation.            
            self.system=self.setRestraints(protocol['restrained_sets'])

# =============================================================================    
#         self.system.addForce(omm.MonteCarloBarostat(self.pressure, 
#                                                     self.temperature, 
#                                                     25)) 
#         #TODO: force is hardcoded, make it go away. Check units throughout!
# =============================================================================
        
        
        self.simulation.context.setPositions(self.positions)
        
        if index == 0:
        
            self.simulation.context.setVelocitiesToTemperature(self.temperature)
        
        # Define reporters
        self.simulation.reporters.append(DCDReporter(f'{eq_trj}.dcd', protocol['report']))           
        self.simulation.reporters.append(HDF5Reporter(f'{eq_trj}.h5', protocol['report'], atomSubset=self.trj_indices))
        self.simulation.reporters.append(app.StateDataReporter(f'{eq_trj}.csv', 
                                                          protocol['report'], 
                                                          step=True, 
                                                          totalEnergy=True, 
                                                          temperature=True,
                                                          density=True,
                                                          progress=True, 
                                                          remainingTime=True, 
                                                          speed=True, 
                                                          totalSteps=protocol['step'], 
                                                          separator='\t'))
        
        positions_first = self.simulation.context.getState(getPositions=True).getPositions()
        
        self.writePDB(self.simulation.topology, positions_first, name='equilibration_NVT_0')
        
        #############
        ## WARNIN ##
        #############
        
        trj_time=protocol['step']*self.dt
        print(f"Restrained NVT equilibration ({trj_time})...")
        
        self.simulation.step(protocol['step'])
        
        #############
        ## WARNOUT ##
        #############

        state=self.simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True)
        self.positions = state.getPositions()
        self.velocities = state.getVelocities()
        self.energy=state.getPotentialEnergy()

        print('NVT equilibration finished.')
        
        self.EQ_NPT_PDB=self.writePDB(self.simulation.topology, self.positions, name='equilibration_NVT')

        self.system=self.forceHandler(self.system, kinds=['CustomExternalForce'])
        #Remove implemented forces (only costum)
        #TODO: remove MC for fresh delivery
            
        return self.simulation
Beispiel #19
0
    logging.info('Releasing position restraints')
    system.removeForce(0)

    # Save minimized system to disk
    positions = state.getPositions()
    with open("{}_EM.pdb".format(rootname), 'w') as handle:
        app.PDBFile.writeFile(simulation.topology, positions, handle)

    ##
    # Setup reporters: logger and checkpointing
    reporters.append(
        app.StateDataReporter(logfile,
                              5000,
                              step=True,
                              time=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              totalEnergy=True,
                              temperature=True,
                              speed=True,
                              separator='\t'))

    reporters.append(app.CheckpointReporter(
        cpt_file, 5000))  # Save every 10 ps # noqa: E501

    ##
    # Equilibration
    nvt_state = '{}_NVT.xml'.format(rootname)
    if os.path.isfile(nvt_state):
        logging.info('Found saved NVT equilibrated state: {}'.format(
            nvt_state))  # noqa: E501
        simulation.loadState(nvt_state)
Beispiel #20
0
                                mm.Platform.getPlatformByName('OpenCL'))

    simulation.context.setPositions(inpcrd.positions)
    simulation.minimizeEnergy()
    simulation.context.setVelocitiesToTemperature(settings["temperature"])

    simulation.reporters.append(
        NetCDFReporter(path+window+'/'+settings["traj_file"],
                       settings["write_freq"])
    )

    simulation.reporters.append(
        app.StateDataReporter(
            path + window + "/openmm_equil.log",
            settings["write_freq"],
            step=True,
            potentialEnergy=True,
            temperature=True,
            speed=True
        )
    )

    simulation.reporters.append(
        RestartReporter(
            path + window + "/openmm_equil.rst7",
            settings["num_steps"]
        )
    )

    simulation.step(settings["num_steps"])
Beispiel #21
0
pdb_filename = "./1am7_equil.pdb"
dcd_filename = "./1am7.dcd"
log_filename = "./1am7.log"

traj = mdtraj.load(pdb_filename)
top, bonds = traj.top.to_dataframe()
atom_indices = top.index[top.chainID == 0].values

pdb = app.PDBFile(pdb_filename)
topology = pdb.topology
positions = pdb.positions

ff = app.ForceField('amber99sbnmr.xml', 'tip3p-fb.xml')

platform = mm.Platform.getPlatformByName("CUDA")

system = ff.createSystem(topology, nonbondedMethod=app.PME, nonbondedCutoff=cutoff, constraints=app.HBonds)

integrator = mm.LangevinIntegrator(temperature, 1.0 / u.picoseconds, 2.0 * u.femtoseconds)
system.addForce(mm.MonteCarloBarostat(pressure, temperature, 25))

simulation = app.Simulation(topology, system, integrator, platform=platform)
simulation.context.setPositions(positions)
simulation.context.setVelocitiesToTemperature(temperature)

print("Using platform %s" % simulation.context.getPlatform().getName())

simulation.reporters.append(mdtraj.reporters.DCDReporter(dcd_filename, output_frequency, atomSubset=atom_indices))
simulation.reporters.append(app.StateDataReporter(open(log_filename, 'w'), 5000, step=True, time=True, speed=True))
simulation.step(n_steps)
Beispiel #22
0
    def _simulate(self, directory, context, integrator):
        """Performs the simulation using a given context
        and integrator.

        Parameters
        ----------
        directory: str
            The directory the trajectory is being run in.
        context: simtk.openmm.Context
            The OpenMM context to run with.
        integrator: simtk.openmm.Integrator
            The integrator to evolve the simulation with.
        """

        # Define how many steps should be taken.
        total_number_of_steps = (self.total_number_of_iterations *
                                 self.steps_per_iteration)

        # Try to load the current state from any available checkpoint information
        current_step = self._resume_from_checkpoint(context)

        if current_step == total_number_of_steps:
            return

        # Build the reporters which we will use to report the state
        # of the simulation.
        append_trajectory = is_file_and_not_empty(self._local_trajectory_path)
        dcd_reporter = app.DCDReporter(self._local_trajectory_path, 0,
                                       append_trajectory)

        statistics_file = open(self._local_statistics_path, "a+")

        statistics_reporter = app.StateDataReporter(
            statistics_file,
            0,
            step=True,
            potentialEnergy=True,
            kineticEnergy=True,
            totalEnergy=True,
            temperature=True,
            volume=True,
            density=True,
            speed=True,
        )

        # Create the object which will transfer simulation output to the
        # reporters.
        topology = app.PDBFile(self.input_coordinate_file).topology

        with open(self.system_path, "r") as file:
            system = openmm.XmlSerializer.deserialize(file.read())

        simulation = self._Simulation(integrator, topology, system,
                                      current_step)

        # Perform the simulation.
        checkpoint_counter = 0

        while current_step < total_number_of_steps:

            steps_to_take = min(self.output_frequency,
                                total_number_of_steps - current_step)
            integrator.step(steps_to_take)

            current_step += steps_to_take

            state = context.getState(
                getPositions=True,
                getEnergy=True,
                getVelocities=False,
                getForces=False,
                getParameters=False,
                enforcePeriodicBox=self.enable_pbc,
            )

            simulation.currentStep = current_step

            # Write out the current state using the reporters.
            dcd_reporter.report(simulation, state)
            statistics_reporter.report(simulation, state)

            if checkpoint_counter >= self.checkpoint_frequency:
                # Save to the checkpoint file if needed.
                self._write_checkpoint_file(current_step, context)
                checkpoint_counter = 0

            checkpoint_counter += 1

        # Save out the final positions.
        self._write_checkpoint_file(current_step, context)

        final_state = context.getState(getPositions=True)

        positions = final_state.getPositions()
        topology.setPeriodicBoxVectors(final_state.getPeriodicBoxVectors())

        self.output_coordinate_file = os.path.join(directory, "output.pdb")

        with open(self.output_coordinate_file, "w+") as configuration_file:
            app.PDBFile.writeFile(topology, positions, configuration_file)
Beispiel #23
0
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()
    dcd._out.close(
    )  # close the dcd file to make sure the buffers are written.

    # write restart file
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    with open(jobname + '.' + str(ii) + '.rst', 'w') as f:
        f.write(mm.XmlSerializer.serialize(state))
    with open(jobname + '.' + str(ii) + '.chk', 'wb') as f:
Beispiel #24
0
integrator = mm.LangevinIntegrator(temperature, equil_friction, equil_timestep / 10.)
system.addForce(mm.MonteCarloBarostat(pressure, temperature, barostat_frequency))

simulation = app.Simulation(topology, system, integrator)
simulation.context.setPositions(positions)
print('Minimizing...')
simulation.minimizeEnergy()

simulation.context.setVelocitiesToTemperature(temperature)
print('Equilibrating...')

simulation.step(discard_steps)  # Don't even save the first XXX ps
integrator.setStepSize(equil_timestep)

simulation.reporters.append(app.DCDReporter(dcd_filename, n_steps - 1))
simulation.reporters.append(app.PDBReporter(out_pdb_filename, n_steps - 1))
simulation.reporters.append(app.StateDataReporter(open(log_filename, 'w'), output_frequency, step=True, time=True, speed=True, density=True))
simulation.step(n_steps)

del simulation
del system
t = md.load(dcd_filename, top=out_pdb_filename)
t0 = t[-1]
t0.unitcell_lengths = t.unitcell_lengths.mean(0)
t0.save(out_pdb_filename)

del t
del t0
t = md.load(dcd_filename, top=out_pdb_filename)[-1]
t.save(final_step_pdb_filename)
Beispiel #25
0
    def production(self):
        utils.make_path('production/')
        self.production_dcd_filename = "production/" + self.identifier + "_production.dcd"
        self.production_pdb_filename = "production/" + self.identifier + "_production.pdb"
        self.production_data_filename = "production/" + self.identifier + "_production.csv"

        utils.make_path(self.production_dcd_filename)

        if os.path.exists(self.production_pdb_filename):
            return

        if self.ran_equilibrate:
            pdb = app.PDBFile(self.equil_pdb_filename)
            topology = pdb.topology
            positions = pdb.positions
        else:
            positions = self.packed_trj.openmm_positions(0)
            topology = self.packed_trj.top.to_openmm()
            topology.setUnitCellDimensions(
                mm.Vec3(*self.packed_trj.unitcell_lengths[0]) * u.nanometer)

        ff = self.ffxml

        system = ff.createSystem(topology,
                                 nonbondedMethod=app.PME,
                                 nonbondedCutoff=self.cutoff,
                                 constraints=app.HBonds)
        integrator = mm.LangevinIntegrator(self.temperature, self.friction,
                                           self.timestep)
        system.addForce(
            mm.MonteCarloBarostat(self.pressure, self.temperature,
                                  self.barostat_frequency))

        simulation = app.Simulation(topology, system, integrator)
        simulation.context.setPositions(positions)

        if not self.ran_equilibrate:
            print('Minimizing.')
            simulation.minimizeEnergy()

        simulation.context.setVelocitiesToTemperature(self.temperature)
        print('Production.')
        simulation.reporters.append(
            app.DCDReporter(self.production_dcd_filename,
                            self.output_frequency))
        simulation.reporters.append(
            app.StateDataReporter(self.production_data_filename,
                                  self.output_data_frequency,
                                  step=True,
                                  potentialEnergy=True,
                                  temperature=True,
                                  density=True))

        converged = False
        while not converged:
            simulation.step(self.n_steps)
            d = pd.read_csv(self.production_data_filename,
                            names=["step", "U", "Temperature", "Density"],
                            skiprows=1)
            density_ts = np.array(d.Density)
            [t0, g, Neff] = ts.detectEquilibration(density_ts, nskip=1000)
            density_ts = density_ts[t0:]
            density_mean_stderr = density_ts.std() / np.sqrt(Neff)
            if density_mean_stderr < self.stderr_tolerance:
                converged = True

        del (simulation)
        if self.ran_equilibrate:
            traj = md.load(self.production_dcd_filename,
                           top=self.equil_pdb_filename)[-1]
        else:
            traj = md.load(self.production_dcd_filename,
                           top=self.box_pdb_filename)[-1]
        traj.save(self.production_pdb_filename)
def openmm_simulate_amber_nvt(top_file,
                              pdb_file,
                              GPU_index=0,
                              output_traj="output.dcd",
                              output_log="output.log",
                              output_cm=None,
                              report_time=10 * u.picoseconds,
                              sim_time=10 * u.nanoseconds):
    """
    Start and run an OpenMM NVT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.0 nm, which commonly used along with Amber force field. Long-range
    nonbonded interactions were handled with PME. 

    Parameters
    ----------
    top_file : topology file (.top, .prmtop, ...)
        This is the topology file discribe all the interactions within the MD 
        system. 

    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 

    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. Use Strings, '0,1'
        for example, to use more than 1 GPU

    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 

    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, potential
        energy, temperature, speed, etc.

    report_time : 10 ps
        The program writes its information to the output every 10 ps by default 

    sim_time : 10 ns
        The timespan of the simulation trajectory
    """

    top = pmd.load_file(top_file, xyz=pdb_file)

    system = top.createSystem(nonbondedMethod=app.PME,
                              nonbondedCutoff=1.2 * u.nanometer,
                              constraints=app.HBonds)
    dt = 0.002 * u.picoseconds
    integrator = omm.LangevinIntegrator(300 * u.kelvin, 1 / u.picosecond, dt)

    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        properties = {'DeviceIndex': str(GPU_index)}

    simulation = app.Simulation(top.topology, system, integrator, platform,
                                properties)

    simulation.context.setPositions(top.positions)

    simulation.minimizeEnergy()

    report_freq = int(report_time / dt)
    simulation.context.setVelocitiesToTemperature(10 * u.kelvin,
                                                  random.randint(1, 10000))
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(ContactMapReporter(output_cm, report_freq))
    simulation.reporters.append(
        app.StateDataReporter(output_log,
                              report_freq,
                              step=True,
                              time=True,
                              speed=True,
                              potentialEnergy=True,
                              temperature=True,
                              totalEnergy=True))

    nsteps = int(sim_time / dt)
    simulation.step(nsteps)
Beispiel #27
0
def production(coords, velocities, box):

    # Create OpenMM System
    file = open(xml_filename, 'r')
    serialized_system = file.read()
    system = XmlSerializer.deserialize(serialized_system)

    # Select Integrator
    integrator = mm.LangevinIntegrator(TEMPERATURE, PROD_FRICTION,
                                       PROD_TIME_STEP)

    # Set Barostat
    system.addForce(
        mm.MonteCarloBarostat(PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY))

    # Set Simulation
    simulation = app.Simulation(prmtop.topology, system, integrator,
                                PROD_PLATFORM, PROD_PROPERTIES)

    # Set Position and velocities
    simulation.context.setPositions(coords)
    if velocities is not None:
        simulation.context.setVelocities(velocities)
    else:  #reset
        simulation.context.setVelocitiesToTemperature(TEMPERATURE)

    # Set Box
    #box = box.in_units_of(nanometer)
    simulation.context.setPeriodicBoxVectors(box[0], box[1], box[2])

    # Set Reporter
    simulation.reporters.append(
        app.DCDReporter(prod_dcd_filename, PROD_OUTPUT_FREQ))
    simulation.reporters.append(
        app.StateDataReporter(prod_data_filename,
                              PROD_DATA_FREQ,
                              step=True,
                              potentialEnergy=True,
                              temperature=True,
                              density=True))

    state = simulation.context.getState(getEnergy=True)

    if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole):
        raise ValueError("The Potential Energy before Production is NaN")

    print('PRODUCTION...\n')

    converged = False

    while not converged:

        simulation.step(PROD_STEPS)

        d = pd.read_csv(prod_data_filename,
                        names=["step", "U", "Temperature", "Density"],
                        skiprows=1)
        density_ts = np.array(d.Density)
        [t0, g, Neff] = ts.detectEquilibration(density_ts, nskip=1000)
        density_ts = density_ts[t0:]
        density_mean_stderr = density_ts.std() / np.sqrt(Neff)

        print("Current density mean std error = %f g/mL" % density_mean_stderr)

        if density_mean_stderr < STD_ERROR_TOLERANCE:
            converged = True
            print("...Convergence is OK\n")

    state = simulation.context.getState(getPositions=True,
                                        getVelocities=True,
                                        getEnergy=True)

    if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole):
        raise ValueError("The Potential Energy after Production is NaN")

    coords = state.getPositions()
    velocities = state.getVelocities()
    box = state.getPeriodicBoxVectors()

    return coords, velocities, box
Beispiel #28
0
def perform_md(
    checkpoint_in_file,
    checkpoint_out_file,
    csv_out_file,
    pdb_out_file,
    force_constant_ligand=1.0,
    md_len=1.0,
    force_constant_chunk=0.1,
    gpu_id=0,
):
    if os.path.isfile(checkpoint_out_file):
        return
    print("loading pickle")
    pickle_in = open("complex_system.pickle", "rb")
    combined_pmd = pickle.load(pickle_in)[0]
    print(dir(combined_pmd))
    key_interaction = cal_ints.find_interaction()
    pickle_in.close()
    MD_len = md_len * u.nanosecond
    sim_steps = round(MD_len / (0.002 * u.picosecond))
    # Platform definition
    platform = mm.Platform_getPlatformByName("OpenCL")
    platformProperties = {}
    platformProperties["OpenCLPrecision"] = "mixed"
    platformProperties["OpenCLDeviceIndex"] = gpu_id
    # Get indexes of heavy atoms in chunk
    Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd)
    # Setting System
    system = combined_pmd.createSystem(
        nonbondedMethod=app.PME,
        nonbondedCutoff=9 * u.angstrom,
        constraints=app.HBonds,
        hydrogenMass=None,
    )
    # Apply force on all havy atoms of chunk and apply restraint for the ligand-chunk distance
    duck_stuff.applyHarmonicPositionalRestraints(system, force_constant_chunk,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    duck_stuff.applyLigandChunkRestraint(
        system,
        force_constant_ligand,
        10.0,
        2 * u.angstrom,
        3 * u.angstrom,
        4 * u.angstrom,
        key_interaction,
    )
    # Integrator
    integrator = mm.LangevinIntegrator(300 * u.kelvin, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    # Setting Simulation object and loading the checkpoint
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.loadCheckpoint(checkpoint_in_file)
    # Simulation reporters
    simulation.reporters.append(
        app.StateDataReporter(
            csv_out_file,
            2000,
            step=True,
            time=True,
            totalEnergy=True,
            kineticEnergy=True,
            potentialEnergy=True,
            temperature=True,
            density=True,
            progress=True,
            totalSteps=sim_steps,
            speed=True,
        ))
    simulation.reporters.append(app.DCDReporter("md.dcd", 100000))
    # Production
    simulation.step(sim_steps)
    # Save state in checkpoint file and save coordinates in PDB file
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open(pdb_out_file, "w"))
    simulation.saveCheckpoint(checkpoint_out_file)
def SMD(system, prmtop, platform, platformProperties, temperature, positions,
        velocities, keyInteraction, spring_k, dist_in, dist_fin, SMD_num,
        save_step, move_force_step):

    # See page 456 of http://ambermd.org/doc12/Amber17.pdf
    pullforce = mm.CustomExternalForce('k_sp*0.5*(dx^2+dy^2+dz^2); \
                                       dx=x-(x0+displace_x); \
                                       dy=y-(y0+displace_y); \
                                       dz=z-(z0+displace_z);')

    pullforce.addPerParticleParameter('k_sp')
    pullforce.addPerParticleParameter('x0')
    pullforce.addPerParticleParameter('y0')
    pullforce.addPerParticleParameter('z0')

    pullforce.addGlobalParameter("displace_x", 0.0 * u.nanometer)
    pullforce.addGlobalParameter("displace_y", 0.0 * u.nanometer)
    pullforce.addGlobalParameter("displace_z", 0.0 * u.nanometer)

    keyInteraction_pos = [
        positions[keyInteraction[0]], positions[keyInteraction[1]]
    ]
    keyInteraction_dist = np.linalg.norm(keyInteraction_pos[0] -
                                         keyInteraction_pos[1])
    keyInteraction_vect = (keyInteraction_pos[1] -
                           keyInteraction_pos[0]) / keyInteraction_dist
    keyInteraction_vect = u.Quantity(value=keyInteraction_vect,
                                     unit=u.nanometers)
    pullto = keyInteraction_pos[0] + 0.25 * keyInteraction_vect
    pullto_old = pullto

    pullforce.addParticle(keyInteraction[1],
                          [spring_k, pullto[0], pullto[1], pullto[2]])
    system.addForce(pullforce)

    integrator = mm.LangevinIntegrator(temperature, 4 / u.picosecond,
                                       0.002 * u.picosecond)

    simulation = app.Simulation(prmtop.topology, system, integrator, platform,
                                platformProperties)
    simulation.context.setPositions(positions)
    simulation.context.setVelocities(velocities)

    force_val_old = -spring_k * (keyInteraction_dist - dist_in)
    energy_val_old = u.Quantity(value=0, unit=u.kilocalorie / u.mole)

    f = open(
        'duck_' + str(temperature).split()[0].replace('.0', 'K') + '_' +
        str(SMD_num) + '.dat', 'w')
    steps = int(
        (dist_fin.value_in_unit(u.nanometer) / 0.000001 -
         dist_in.value_in_unit(u.nanometer) / 0.000001)) / move_force_step
    pull_distance = 0.000001 * move_force_step

    #write trajectory
    top = md.load_prmtop('system_solv.prmtop')
    atom_subset = top.select('not water')
    simulation.reporters.append(
        app.StateDataReporter(
            "smd_" + str(temperature).split()[0].replace('.0', 'K') + "_" +
            str(SMD_num) + ".csv",
            move_force_step,
            step=True,
            time=True,
            totalEnergy=True,
            kineticEnergy=True,
            potentialEnergy=True,
            temperature=True,
            density=True,
            progress=True,
            totalSteps=move_force_step,
            speed=True))

    simulation.reporters.append(
        HDF5Reporter("smd_" + str(temperature).split()[0].replace('.0', 'K') +
                     "_" + str(SMD_num) + ".h5",
                     move_force_step * 20,
                     atomSubset=atom_subset))

    for i in range(steps):
        state = simulation.context.getState(getPositions=True)
        pos_keyInt = state.getPositions()
        keyInteraction_pos = [
            pos_keyInt[keyInteraction[0]], pos_keyInt[keyInteraction[1]]
        ]

        keyInteraction_dist = np.linalg.norm(keyInteraction_pos[0] -
                                             keyInteraction_pos[1])
        keyInteraction_vect = (keyInteraction_pos[1] -
                               keyInteraction_pos[0]) / keyInteraction_dist
        keyInteraction_vect = u.Quantity(value=keyInteraction_vect,
                                         unit=u.nanometers)
        pullto = keyInteraction_pos[0] + (
            0.25 + float(i) * pull_distance) * keyInteraction_vect

        displace = pullto - pullto_old

        simulation.context.setParameter('displace_x', displace[0])
        simulation.context.setParameter('displace_y', displace[1])
        simulation.context.setParameter('displace_z', displace[2])
        if i == 0:
            distance = 0.0
        else:
            distance = pull_distance
        dist_spring = (0.25 + float(i) * pull_distance) * u.nanometer
        force_val = -spring_k * (keyInteraction_dist - dist_spring)
        energy_val = energy_val_old + (distance * u.nanometer) * 0.5 * (
            force_val + force_val_old)
        force_val_old = force_val
        energy_val_old = energy_val
        if (i % int(save_step / move_force_step)) == 0:
            f.write(
                str(i) + ' ' + str(dist_spring) + ' ' +
                str(keyInteraction_dist) + ' ' + str(force_val) + ' ' +
                str(energy_val) + '\n')

        simulation.step(move_force_step)

    #f.write(str(i)+' '+str(dist_spring)+' '+str(keyInteraction_dist)+' '+str(force_val)+' '+str(energy_val)+'\n')
    f.close()
simulation = app.Simulation(pdb.topology, system, integrator, platform)
print("[STATUS] Set up compute platform")
simulation.context.setPositions(pdb.positions)
print("[STATUS] Set atomic positions")

print('[STATUS] Minimizing...')
simulation.minimizeEnergy()
print('[STATUS] Equilibrating...')
simulation.step(100)

simulation.reporters.append(app.DCDReporter('trajectory.dcd', 1000))
simulation.reporters.append(
    app.StateDataReporter(stdout,
                          1000,
                          step=True,
                          potentialEnergy=True,
                          totalEnergy=True,
                          temperature=True,
                          separator='\t'))
print("[STATUS] Set up reporters")

print('[STATUS] Running Production...')

increment = 1000

for i in range(0, 100000, increment):
    print("[STATUS] Step %s" % (i))
    simulation.step(increment)

print('[END] Done!')