Esempio n. 1
0
    def add_reporters(self):

        self.simulation.reporters.append(PDBReporter("output.pdb", 5000))

        if self.configuration.fn_state:
            self.simulation.reporters.append(
                StateDataReporter(
                    self.configuration.fn_state,
                    self.configuration.fr_save,
                    step=True,
                    potentialEnergy=True,
                    kineticEnergy=True,
                    totalEnergy=True,
                    temperature=True,
                    separator="  ||  ",
                    volume=True,
                    density=True,
                    speed=True,
                ))

        if self.configuration.fn_state:
            self.simulation.reporters.append(
                DCDReporter(
                    self.configuration.fn_traj,
                    self.configuration.fr_save,
                ))
Esempio n. 2
0
def run_md_simulation(random_seed, simulation, pdb, args):
    if args.SIM_RUN_SIMULATION:
        print("Running simulation...")
        if args.SIM_SET_INITIAL_VELOCITIES:
            print(f"   Setting up initial velocities at temperature {args.SIM_TEMP}")
            simulation.context.setVelocitiesToTemperature(args.SIM_TEMP, random_seed)
        reporting_to_screen_freq = max(1, int(round(args.SIM_N_STEPS / args.REP_STATE_N_SCREEN)))
        reporting_to_file_freq = max(1, int(round(args.SIM_N_STEPS / args.REP_STATE_N_FILE)))
        trajectory_freq = max(1, int(round(args.SIM_N_STEPS / args.TRJ_FRAMES)))

        total_time = args.SIM_N_STEPS * args.SIM_TIME_STEP
        print("   Number of steps:                 {} steps".format(args.SIM_N_STEPS))
        print("   Time step:                       {}".format(args.SIM_TIME_STEP))
        print("   Temperature:                     {}".format(args.SIM_TEMP))
        print("   Total simulation time:           {}".format(total_time.in_units_of(simtk.unit.nanoseconds)))
        print("   Number of state reads:           {} reads".format(args.REP_STATE_N_SCREEN))
        print("   State reporting to screen every: {} step".format(reporting_to_screen_freq))
        print("   State reporting to file every:   {} step".format(reporting_to_file_freq))
        print("   Number of trajectory frames:     {} frames".format(args.TRJ_FRAMES))
        print("   Trajectory frame every:          {} step".format(trajectory_freq))
        print("   Trajectory frame every:          {}".format(trajectory_freq * args.SIM_TIME_STEP))
        print('   Random seed:', random_seed)
        print()
        if args.TRJ_FILENAME_PDB:
            simulation.reporters.append(PDBReporter(args.TRJ_FILENAME_PDB, trajectory_freq))
        if args.TRJ_FILENAME_DCD:
            simulation.reporters.append(DCDReporter(args.TRJ_FILENAME_DCD, trajectory_freq))
        simulation.reporters.append(StateDataReporter(sys.stdout, reporting_to_screen_freq,
                                                      step=True, progress=True, potentialEnergy=True,
                                                      totalSteps=args.SIM_N_STEPS))
        if args.REP_STATE_FILE_PATH:
            simulation.reporters.append(StateDataReporter(args.REP_STATE_FILE_PATH, reporting_to_file_freq,
                                                          step=True, potentialEnergy=True))
        if args.REP_STATE_FILE_H5_PATH:
            simulation.reporters.append(HDF5Reporter(args.REP_STATE_FILE_H5_PATH, reporting_to_file_freq, velocities=True))

        print('Running simulation...')
        simulation.step(args.SIM_N_STEPS)
        if args.TRJ_LAST_FRAME_PDB:
            last_frame_file_name = args.TRJ_LAST_FRAME_PDB
            state = simulation.context.getState(getPositions=True)
            PDBFile.writeFile(pdb.topology, state.getPositions(), open(last_frame_file_name, 'w'))
        if args.REP_PLOT_FILE_NAME:
            plot_data(args.REP_STATE_FILE_PATH, args.REP_PLOT_FILE_NAME)
Esempio n. 3
0
                        atom_subset = None

                    simulation.reporters.append(
                        md.reporters.DCDReporter(output_file,
                                                 opts['stride'],
                                                 atomSubset=atom_subset))

                    print(
                        'Writing stride %d to file `%s` with selection `%s`' %
                        (opts['stride'], opts['filename'], opts['selection']))

    else:
        # use defaults from arguments
        output_file = os.path.join(output, 'output.dcd')
        simulation.reporters.append(
            DCDReporter(output_file, args.interval_store))

    if not args.restart:
        # if not a restart write first frame
        state = simulation.context.getState(getPositions=True)
        for r in simulation.reporters:
            r.report(simulation, state)

    if args.report and args.verbose:
        output_stride = args.interval_store
        if types:
            output_stride = min([oty['stride'] for oty in types.values()])
        simulation.reporters.append(
            StateDataReporter(
                stdout,
                output_stride,
Esempio n. 4
0
# Loop extrusion force
le_force = mm.HarmonicBondForce()
le_force.addBond(
    48, 50, 1 * u.angstrom,
    LE_FORCE_MATRIX[2][0] * u.kilocalories_per_mole / u.angstroms**2)
for i in range(2, 35):
    p1, p2 = 49 - i, 49 + i
    le_force.addBond(
        p1, p2, 1 * u.angstrom,
        LE_FORCE_MATRIX[1][0] * u.kilocalories_per_mole / u.angstroms**2)
system.addForce(le_force)

simulation = Simulation(pdb.topology, system, integrator)
simulation.context.setPositions(pdb.positions)
simulation.minimizeEnergy()
simulation.reporters.append(DCDReporter('trj.dcd', 1))
simulation.reporters.append(
    StateDataReporter(stdout,
                      1000,
                      step=True,
                      potentialEnergy=True,
                      temperature=True))
simulation.reporters.append(
    StateDataReporter(STATE_FNAME, 10, step=True, potentialEnergy=True))

simulation.step(STEPS_PER_CYCLE)

for i in range(2, 35):
    p1, p2 = 49 - i, 49 + i
    for j in range(0, STEPS_PER_CYCLE):
        le_force.setBondParameters(
Esempio n. 5
0
       # noinspection PyCallByClass,PyTypeChecker
       print('(%d) %s' % (no_platform, Platform.getPlatform(no_platform).getName()))
   print(os.environ)
   print(Platform.getPluginLoadFailures())
   print(Platform.getDefaultPluginsDirectory())
 simulation.context.setPositions(pdb.positions)
 pbv = system.getDefaultPeriodicBoxVectors()
 simulation.context.setPeriodicBoxVectors(*pbv)
 # set velocities to temperature in integrator
 temperature = integrator.getTemperature()
 dt = integrator.getStepSize()
 simulation.context.setVelocitiesToTemperature(temperature)
 simulation.reporters.append(StateDataReporter(stdout, 1000, step=True,
 potentialEnergy=True, temperature=True)) 
 if args.save_traj=='True':
   simulation.reporters.append(DCDReporter(args.path+'/iter'+str(args.iter)+'_traj'+str(i)+'.dcd', args.trajstride)) 
 steps=args.md_steps #1000=2sec each, 10000=20sec
 start=datetime.now()
 simulation.step(steps)
 end = datetime.now()
 elapsed = end -start
 time=elapsed.seconds + elapsed.microseconds*1e-6
 print('Integrated %d steps in %g seconds' % (steps, time))
 print('%g ns/day' % (dt*steps*86400/time).value_in_unit(u.nanoseconds))
 state = simulation.context.getState(getPositions=True, getVelocities=True,getEnergy=True)
 pbv = state.getPeriodicBoxVectors(asNumpy=True)
 vel = state.getVelocities(asNumpy=True)
 pos = state.getPositions(asNumpy=True)
 print(state.getPotentialEnergy(), state.getKineticEnergy())
 PDBFile.writeFile(simulation.topology, pos, open(args.path+'/iter'+str(args.iter)+'_out'+str(i)+'.pdb', 'a'))
 del simulation, integrator, system
Esempio n. 6
0
    PDBFile.writeFile(
        modeller.topology,
        context.getState(getPositions=True,
                         enforcePeriodicBox=False).getPositions(),
        file=outfile,
        keepIds=True)

# equilibrate
simulation.context.setVelocitiesToTemperature(temperature)
print('Equilibrating ...')
simulation.step(equilibration_steps)

# Run the simulation.
# The enforcePeriodicBox arg to the reporters is important.
# It's a bit counter-intuitive that the value needs to be False, but this is needed to ensure that
# all parts of the simulation end up in the same periodic box when being output.
# simulation.reporters.append(PDBReporter(output_traj_pdb, reporting_interval, enforcePeriodicBox=False))
simulation.reporters.append(
    DCDReporter(output_traj_dcd, reporting_interval, enforcePeriodicBox=False))
simulation.reporters.append(
    StateDataReporter(sys.stdout,
                      reporting_interval * 5,
                      step=True,
                      potentialEnergy=True,
                      temperature=True))
print('Starting simulation with', num_steps, 'steps ...')
t0 = time.time()
simulation.step(num_steps)
t1 = time.time()
print('Simulation complete in', t1 - t0, 'seconds at', temperature)
Esempio n. 7
0
bar_freq = int(MD_steps / print_freq)

integrator = LangevinIntegrator(Temp, 1.0 / unit.picoseconds, dt)
barostat = MonteCarloBarostat(Pres, Temp, 100)
system.addForce(barostat)

# Simulation Object
simulation = Simulation(coords.topology, system, integrator,
                        Platform.getPlatformByName('CUDA'), {
                            'CudaDeviceIndex': '0',
                            'CudaPrecision': 'single'
                        })
simulation.context.setPositions(coords.positions)

simulation.reporters.append(
    DCDReporter(os.path.join('simulations', 'npt_production', 'test.dcd'),
                out_freq, False))
simulation.reporters.append(
    StateDataReporter(
        os.path.join('simulations', 'npt_production', 'test.log'),
        out_freq,
        step=True,
        kineticEnergy=True,
        potentialEnergy=True,
        totalEnergy=True,
        temperature=True,
        totalSteps=MD_steps,
        progress=True,
        remainingTime=True,
        speed=True,
        separator=",",
    ))
def loop_extrusion(STEPS, LE_FORCE_SCALE, MATRIX_LENGTH, STEPS_PER_CYCLE, STEPS_PER_IT):
    STATE_FNAME = '2sided-state.csv'
    #STEPS = 10000
    #LE_FORCE_SCALE = 3
    #MATRIX_LENGTH = 200
    #STEPS_PER_CYCLE = 10
    #STEPS_PER_IT = 1

#Macierz z parametrami sił wiązań
#Dodano funkcje generacji macierzy o wartościach sinusoidalnych. Funkcja ta przyjmuje dwa argumenty. Pierwszy oznacza liczbę kroków które ma posiadać macierz a drugi
#stanowi regulacje maksymalnej siły (tzn jeśli wstawimy 3 to maksymalna siła bedzie tyle wynosić)
    LE_FORCE_MATRIX = gen_sin_array(MATRIX_LENGTH,LE_FORCE_SCALE)
    LE_FORCE_MATRIX[1][0] = 0
    LE_FORCE_MATRIX[2][-1] = 0
#print(LE_FORCE_MATRIX)

    pdb = PDBFile('initial_structure.pdb')
    forcefield = ForceField('polymer_ff.xml')
    system = forcefield.createSystem(pdb.topology, nonbondedCutoff=1 * u.nanometer)
    integrator = mm.LangevinIntegrator(100 * u.kelvin, 0.2, 1 * u.femtoseconds)

# Distance constraint
    for i in range(system.getNumParticles() - 1):
        system.addConstraint(i, i + 1, 0.1 * u.nanometer)

# Pinning ends with rubber
    pin_force = mm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)")
    pin_force.addGlobalParameter("k", 50 * u.kilocalories_per_mole / u.angstroms ** 2)
    pin_force.addPerParticleParameter("x0")
    pin_force.addPerParticleParameter("y0")
    pin_force.addPerParticleParameter("z0")
    pin_force.addParticle(0, [15 * u.angstrom, 0 * u.angstrom, 0 * u.angstrom])
    pin_force.addParticle(system.getNumParticles() - 1, [-15 * u.angstrom, 0 * u.angstrom, 0 * u.angstrom])
    system.addForce(pin_force)


# Loop extrusion force
    le_force = mm.HarmonicBondForce()
    le_force.addBond(48, 50, 1 * u.angstrom, LE_FORCE_SCALE * u.kilocalories_per_mole / u.angstroms ** 2)
    for i in range(2, 35):
        p1, p2 = 49 - i, 49 + i
        le_force.addBond(p1, p2, 1 * u.angstrom, 0.000001 * u.kilocalories_per_mole / u.angstroms ** 2)
    system.addForce(le_force)
    

    simulation = Simulation(pdb.topology, system, integrator)
    simulation.context.setPositions(pdb.positions)
    simulation.minimizeEnergy()
    simulation.reporters.append(DCDReporter('wyniki/2sided-trj.dcd', 1))
    simulation.reporters.append(StateDataReporter(stdout, 1000, step=True, potentialEnergy=True, temperature=True))
    simulation.reporters.append(StateDataReporter(STATE_FNAME, 10, step=True, potentialEnergy=True))

    simulation.step(1)

    for i in range(2, 35):
        p1, p2 = 49 - i, 49 + i
        for j in range(MATRIX_LENGTH):
            le_force_one = LE_FORCE_MATRIX[1][j] * u.kilocalories_per_mole / u.angstroms ** 2 #ROSNĄCA
            le_force_two = LE_FORCE_MATRIX[2][j] * u.kilocalories_per_mole / u.angstroms ** 2 #MALEJĄCA
            le_force.setBondParameters(i - 2, p1 + 1, p2 - 1, 1 * u.angstrom,
                                    le_force_two)
            le_force.setBondParameters(i - 1, p1, p2, 1 * u.angstrom, le_force_one)
            le_force.updateParametersInContext(simulation.context)
        #print(le_force_one)
        #print(le_force_two)
        #simulation.minimizeEnergy()
            simulation.step(STEPS_PER_IT)
#    for i in range(STEPS_PER_CYCLE):
#        simulation.step(1)
        simulation.step(200)
        plot_data(STATE_FNAME, '2sided-energy.png')

    print('#1: repr stick; color white; color red :1,100; repr sphere :1,100; vdwdefine 0.5')
    print('#1: color green :49,51; repr sphere :49,51; color #ffffa2e8a2e8 :50;')
    for i in range(1, 35):
        p1, p2 = 50 - i - 1, 50 + i + 1
        print(
            f'#{i*STEPS_PER_CYCLE+1}: color green :{p1},{p2}; repr sphere :{p1},{p2}; repr stick :{p1+1},{p2-1}; color #ffffa2e8a2e8 :{p1+1}-{p2-1};')

    print("Done")
Esempio n. 9
0
                                 saveFrequency=250,
                                 biasDir='./biases')
integrator = mm.LangevinIntegrator(temperature, 1.0 / unit.picosecond,
                                   0.004 * unit.picoseconds)
print("Done specifying integrator.")
simulation = Simulation(molecule.topology, system, integrator)
simulation.context.setPositions(pdb.positions)
print("Done specifying simulation.")

# equilibration
simulation.context.setVelocitiesToTemperature(temperature)
simulation.step(100)
print("Done 100 steps of equilibration.")

# set simulation reporters
simulation.reporters.append(DCDReporter('mtd_2JIU.dcd', reportInterval=250))
simulation.reporters.append(
    StateDataReporter('mtd_2JIU.out',
                      reportInterval=5000,
                      step=True,
                      potentialEnergy=True,
                      temperature=True,
                      progress=True,
                      remainingTime=True,
                      speed=True,
                      totalSteps=10000000,
                      separator='\t'))

# Run small-scale simulation (20ns, 10^7 steps) and plot the free energy landscape
meta.step(simulation, 10000000)
#plot.imshow(meta.getFreeEnergy())
Esempio n. 10
0
                        biasDir='./biases')
integrator = mm.LangevinIntegrator(310.15 * unit.kelvin, 1.0 / unit.picosecond,
                                   0.002 * unit.picoseconds)
print("Done specifying integrator.")
simulation = Simulation(molecule.topology, system, integrator)
print("Done specifying simulation.")
simulation.context.setPositions(positions)
print("Done setting up the simulation.")

# equilibration
simulation.context.setVelocitiesToTemperature(310.15 * unit.kelvin)
simulation.step(100)
print("Done 100 steps of equilibration.")

# set simulation reporters
simulation.reporters.append(DCDReporter('mtd_5UG9.dcd', 5000))
simulation.reporters.append(
    StateDataReporter('mtd_5UG9.out',
                      5000,
                      step=True,
                      potentialEnergy=True,
                      temperature=True,
                      progress=True,
                      remainingTime=True,
                      speed=True,
                      totalSteps=5000000,
                      separator='\t'))

# Run small-scale simulation (10ns, 5*10^6 steps) and plot the free energy landscape
meta.step(simulation, 5000000)
#plot.imshow(meta.getFreeEnergy())
Esempio n. 11
0
 def reporter(self):
     from simtk.openmm.app import DCDReporter
     return DCDReporter(self.file,
                        self.reportInterval,
                        append=self.append,
                        enforcePeriodicBox=self.enforcePeriodicBox)
Esempio n. 12
0
# all parts of the simulation end up in the same periodic box when being output.

simulation.context.setVelocitiesToTemperature(opt.temp)

simulation.reporters.append(
    parmed.openmm.StateDataReporter(opt.output,
                                    reportInterval=opt.interval,
                                    volume=True,
                                    density=True,
                                    separator='\t'))
simulation.reporters.append(
    parmed.openmm.ProgressReporter(
        str(opt.output) + '.info', opt.interval, opt.num_steps))
simulation.reporters.append(
    #parmed.openmm.NetCDFReporter(opt.trajectory, opt.interval*10)
    DCDReporter(opt.trajectory, opt.interval * 10, enforcePeriodicBox=False))
#simulation.reporters.append(
#        parmed.openmm.RestartReporter(opt.restart, opt.interval*100, netcdf=True)
#)
print('Starting simulation with', opt.num_steps, 'steps ...')

#simulation.context.setPositions(modeller.positions)
#simulation.context.setVelocitiesToTemperature(opt.temp)

t0 = time.time()
simulation.step(opt.num_steps)
t1 = time.time()
print('Simulation complete in', t1 - t0, 'seconds at', opt.temp * unit.kelvin)

import mdtraj as md
Esempio n. 13
0
def main(argdict):
    """ Main function for entry point checking.

    Expects a dictionary of command line arguments.
    """

    # are we continuing from logfile or starting from fresh PDB?
    if argdict["log"] is None:

        # keep track of restart number:
        argdict["restart_number"] = int(0)

        # write arguments to a file to keep a record:
        with open(argdict["outname"] + "_parameters.log", 'w') as f:
            print(json.dumps(argdict, sort_keys=True, indent=4), file=f)
    else:

        # load configuration from logfile:
        logfile = argdict["log"]
        with open(argdict["log"], 'r') as f:
            argdict = json.load(f)

        # make sure log file has appropriate entry:
        argdict["log"] = logfile

        # increment restart number:
        argdict["restart_number"] += 1

        # write unnumbered parameters file (for easy restarts):
        with open(argdict["outname"] + "_parameters.log", 'w') as f:
            print(json.dumps(argdict, sort_keys=True, indent=4), file=f)

    # write numbered parameters file (for record keeping):
    with open(
            argdict["outname"] + "_" + str(argdict["restart_number"]) +
            "_parameters.log", 'w') as f:
        print(json.dumps(argdict, sort_keys=True, indent=4), file=f)

    # load system initial configuration:
    pdb = pdb_file_nonstandard_bonds(argdict["pdb"])
    print("--> input topology: ", end="")
    print(pdb.topology)

    # get XML file from absolute path:
    xmlfile = os.path.abspath(argdict["xml"])

    # set box size in topology to values from XML file:
    box_vectors = periodic_box_vectors_from_xml(xmlfile)
    pdb.topology.setPeriodicBoxVectors(box_vectors)

    # physical parameters of simulation:
    sim_temperature = argdict["temperature"] * kelvin
    sim_andersen_coupling = 1 / picosecond
    sim_pressure = (
        (argdict["pressure"], argdict["pressure"], argdict["pressure"]) * bar)
    sim_scale_x = True
    sim_scale_y = True
    sim_scale_z = True

    # simulation control parameters:
    sim_timestep = argdict["timestep"] * femtoseconds
    sim_num_steps = argdict["num_steps"]
    sim_traj_rep_steps = argdict["report_freq"]
    sim_state_rep_steps = argdict["report_freq"]
    sim_checkpoint_steps = argdict["report_freq"]

    # restraints parameters:
    sim_restr_fc = argdict["restr_fc"] * kilojoule_per_mole / nanometer**2

    # create force field object:
    ff = ForceField(*argdict["ff"])

    # build a simulation system from topology and force field:
    # (note that AMOEBA is intended to be run without constraints)
    # (note that mutualInducedtargetEpsilon defaults to 0.01 unlike what is
    # specified in the documentation which claims 0.00001)
    sys = ff.createSystem(
        pdb.topology,
        nonbondedMethod=PME,
        nonbondedCutoff=argdict["nonbonded_cutoff"] * nanometer,
        vdwCutoff=argdict["vdw_cutoff"] * nanometer,
        ewaldErrorTolerance=argdict["ewald_error_tolerance"],
        polarisation=argdict["polarisation"],
        mutualInducedTargetEpsilon=argdict["mutual_induced_target_epsilon"],
        constraints=None,
        rigidWater=False,
        removeCMMotion=True  # removes centre of mass motion
    )

    # overwrite the polarisation method set at system creation; this is
    # necessary as openMM always sets polarisation method to "mutual" of the
    # target epsilon is specified at system creation; this way, target epsilon
    # is ignored for all but the mutual method
    multipole_force = sys.getForce(9)
    print("--> using polarisation method " + str(argdict["polarisation"]))
    if argdict["polarisation"] == "mutual":
        multipole_force.setPolarizationType(multipole_force.Mutual)
    elif argdict["polarisation"] == "extrapolated":
        multipole_force.setPolarizationType(multipole_force.Extrapolated)
    elif argdict["polarisation"] == "direct":
        multipole_force.setPolarizationType(multipole_force.Direct)
    else:
        raise Exception("Polarisation method " + str(argdict["polarisation"]) +
                        " not supported!")

    # will use Andersen thermostat here:
    # (Inhibits particle dynamics somewhat, but little or no ergodicity
    # issues (from Gromacs documenation). However, only alternative is full
    # Langevin dynamics, which is even worse wrt dynamics. Bussi/v-rescale is
    # not available at the moment, it seems (it is available in tinker, but
    # without GPU acceleration))
    sys.addForce(AndersenThermostat(sim_temperature, sim_andersen_coupling))

    # use anisotropic barostat:
    # (note that this corresponds to semiisotropic pressure coupling in Gromacs
    # if the pressure is identical for the x- and y/axes)
    # (note that by default this attempts an update every 25 steps)
    sys.addForce(
        MonteCarloAnisotropicBarostat(sim_pressure, sim_temperature,
                                      sim_scale_x, sim_scale_y, sim_scale_z))

    # prepare harmonic restraining potential:
    # (note that periodic distance is absolutely necessary here to prevent
    # system from blowing up, as otherwise periodic image position may be used
    # resulting in arbitrarily large forces)
    force = CustomExternalForce("k*periodicdistance(x, y, z, x0, y0, z0)^2")
    force.addGlobalParameter("k", sim_restr_fc)
    force.addPerParticleParameter("x0")
    force.addPerParticleParameter("y0")
    force.addPerParticleParameter("z0")

    # apply harmonic restraints to C-alphas:
    if argdict["restr"] == "capr":
        print("--> applying harmonic positional restraints to CA atoms")
        for atm in pdb.topology.atoms():
            if atm.name == "CA":
                force.addParticle(atm.index, pdb.positions[atm.index])
    elif argdict["restr"] == "hapr":
        sys.exit("Restraints mode " + str(argdict["restr"]) +
                 "is not implemented.")
    elif argdict["restr"] == "none":
        print("--> applying no harmonic positional restraints to any atom")
    else:
        sys.exit("Restraints mode " + str(argdict["restr"]) +
                 "is not implemented.")

    # add restraining force to system:
    sys.addForce(force)

    # make special group for nonbonded forces:
    for f in sys.getForces():
        if (isinstance(f, AmoebaMultipoleForce)
                or isinstance(f, AmoebaVdwForce)
                or isinstance(f, AmoebaGeneralizedKirkwoodForce)
                or isinstance(f, AmoebaWcaDispersionForce)):
            f.setForceGroup(1)

    # read umbrella parameters from file:

    with open(argdict["umbrella_target"], "r") as f:
        umbrella_target = json.load(f)

    # obtain index from atom to be restrained:
    umbrella_index = umbrella_target["target_particle"]["index"]
    umbrella_fc = (umbrella_target["umbrella_params"]["fc"] *
                   kilojoule_per_mole / nanometer**2)
    umbrella_cv = umbrella_target["umbrella_params"]["cv"] * nanometer

    # inform user:
    print("--> applying umbrella potential to " +
          str(list(pdb.topology.atoms())[umbrella_index]) + " at position " +
          str(pdb.positions[umbrella_index]))

    # additional restraining force applied to ion under umbrella restraints:
    umbrella_force = CustomExternalForce(
        "k*periodicdistance(0.0, 0.0, z, 0.0, 0.0, z0)^2")
    umbrella_force.addGlobalParameter("k", umbrella_fc)
    # z0 is set to value in JSON file rather than initial particle coordinate to
    # allow for a few steps of energy minimisation to avoid clashes between the
    # restrained umbrella target and surrounding atoms:
    umbrella_force.addGlobalParameter("z0", umbrella_cv)

    # select integrator:
    if argdict["integrator"] == "mts":

        # use multiple timestep RESPA integrator:
        print("--> using RESPA/MTS integrator")
        integrator = MTSIntegrator(sim_timestep,
                                   [(0, argdict["inner_ts_frac"]), (1, 1)])

    elif argdict["integrator"] == "verlet":

        # use Leapfrog Verlet integrator here:
        print("--> using Verlet integrator")
        integrator = VerletIntegrator(sim_timestep)

    else:

        # no other integrators supported:
        raise Exception("Integrator " + str(argdict["integrator"]) +
                        " is not supported.")

    # select a platform:
    platform = Platform.getPlatformByName(argdict["platform"])
    properties = {
        "CudaPrecision": argdict["precision"],
        "CudaDeviceIndex": "0"
    }

    # prepare a simulation from topology, system, and integrator and set initial
    # positions as in PDB file:
    sim = Simulation(pdb.topology, sys, integrator, platform, properties)

    # is this initial simulation or restart from checkpoint?
    if argdict["log"] is None:

        # load positions and velocities from XML file:
        print("--> loading simulation state from XML file...")
        sim.loadState(xmlfile)

        # find all particles bonded to ion (i.e. Drude particles):
        idx_bonded = atom_idx_from_bonds(sim.topology, umbrella_index)
        idx_shift = idx_bonded + [umbrella_index]

        # shift target particle into position:
        pos = (sim.context.getState(getPositions=True).getPositions(
            asNumpy=True))
        pos[idx_shift, :] = (umbrella_target["target_particle"]["init_pos"] *
                             nanometer)
        print("--> target particle now placed at " + str(pos[idx_shift, :]))

        # set new particle positions in context:
        sim.context.setPositions(pos)
        e_pot = sim.context.getState(getEnergy=True).getPotentialEnergy()
        print("--> potential energy after target placement is: " + str(e_pot))

        # minimise energy to remove clashes:
        # (too many steps might ruin everythin!)
        print("--> running energy minimisation...")
        sim.minimizeEnergy(maxIterations=argdict["minimisation_steps"])
        e_pot = sim.context.getState(getEnergy=True).getPotentialEnergy()
        print(
            "--> " + str(argdict["minimisation_steps"]) +
            " steps of energy minimisation reduced the potential energy to " +
            str(e_pot))

        # reduce time step for equilibration period:
        print("--> running equilibration at reduced time step...")
        sim.integrator.setStepSize(0.1 * sim.integrator.getStepSize())
        sim.context.setTime(0.0 * picosecond)

        # will write report about equilibration phase:
        sim.reporters.append(
            StateDataReporter(stdout,
                              int(argdict["equilibration_steps"] / 10),
                              step=True,
                              time=True,
                              speed=True,
                              progress=True,
                              remainingTime=True,
                              totalSteps=argdict["equilibration_steps"],
                              separator="\t"))

        # run equilibration steps:
        sim.step(argdict["equilibration_steps"])

        # reset step size to proper value:
        sim.integrator.setStepSize(10.0 * sim.integrator.getStepSize())
        sim.context.setTime(0.0 * picosecond)
        sim.reporters.clear()

    else:

        # load checkpoint file:
        checkpoint_file = (str(argdict["outname"]) + "_" +
                           str(argdict["restart_number"] - 1) + ".chk")
        print("--> loading checkpoint file " + checkpoint_file)
        sim.loadCheckpoint(checkpoint_file)

    # write collective variable value to file:
    sample_outname = (argdict["outname"] + "_" +
                      str(argdict["restart_number"]) + str(".dat"))
    sim.reporters.append(
        CollectiveVariableReporter(sample_outname, argdict["umbrella_freq"],
                                   umbrella_index))

    # write simulation trajectory to DCD file:
    dcd_outname = (argdict["outname"] + "_" + str(argdict["restart_number"]) +
                   str(".dcd"))
    sim.reporters.append(DCDReporter(dcd_outname, sim_traj_rep_steps))

    # write state data to tab-separated CSV file:
    state_outname = (argdict["outname"] + "_" +
                     str(argdict["restart_number"]) + str(".csv"))
    sim.reporters.append(
        StateDataReporter(state_outname,
                          sim_state_rep_steps,
                          step=True,
                          time=True,
                          progress=False,
                          remainingTime=True,
                          potentialEnergy=True,
                          kineticEnergy=True,
                          totalEnergy=True,
                          temperature=True,
                          volume=True,
                          density=False,
                          speed=True,
                          totalSteps=sim_num_steps,
                          separator="\t"))

    # write limited state information to standard out:
    sim.reporters.append(
        StateDataReporter(stdout,
                          sim_state_rep_steps,
                          step=True,
                          time=True,
                          speed=True,
                          progress=True,
                          remainingTime=True,
                          totalSteps=sim_num_steps,
                          separator="\t"))

    # write checkpoint files regularly:
    checkpoint_outname = (argdict["outname"] + "_" +
                          str(argdict["restart_number"]) + ".chk")
    sim.reporters.append(
        CheckpointReporter(checkpoint_outname, sim_checkpoint_steps))

    # run simulation:
    sim.step(argdict["num_steps"])

    # save final simulation state:
    sim.saveState(argdict["outname"] + "_" + str(argdict["restart_number"]) +
                  ".xml")
    positions = sim.context.getState(getPositions=True).getPositions()
    PDBFile.writeFile(
        sim.topology, positions,
        open(
            argdict["outname"] + "_" + str(argdict["restart_number"]) + ".pdb",
            "w"))
Esempio n. 14
0
# system.addForce(openmm.MonteCarloBarostat(1*unit.atmospheres, temperature, 25))
print('Uses Periodic box:', system.usesPeriodicBoundaryConditions(),
    ', Default Periodic box:', system.getDefaultPeriodicBoxVectors())

simulation = Simulation(modeller.topology, system, integrator, platform=platform)
simulation.context.setPositions(modeller.positions)
print('Minimising ...')
simulation.minimizeEnergy()

# write out the minimised PDB
with open(output_min, 'w') as outfile:
    PDBFile.writeFile(modeller.topology, simulation.context.getState(getPositions=True, enforcePeriodicBox=False).getPositions(), file=outfile, keepIds=True)

# equilibrate
simulation.context.setVelocitiesToTemperature(temperature)
print('Equilibrating ...')
simulation.step(equilibration_steps)

# Run the simulation.
# The enforcePeriodicBox arg to the reporters is important.
# It's a bit counter-intuitive that the value needs to be False, but this is needed to ensure that
# all parts of the simulation end up in the same periodic box when being output.
# simulation.reporters.append(PDBReporter(output_traj_pdb, reporting_interval, enforcePeriodicBox=False))
simulation.reporters.append(DCDReporter(output_traj_dcd, reporting_interval, enforcePeriodicBox=False))
simulation.reporters.append(StateDataReporter(sys.stdout, reporting_interval * 5, step=True, potentialEnergy=True, temperature=True))
print('Starting simulation with', num_steps, 'steps ...')
t0 = time.time()
simulation.step(num_steps)
t1 = time.time()
print('Simulation complete in', t1 - t0, 'seconds at', temperature)