Beispiel #1
0
def test_phase_creation():
    """Phases are initialized correctly by Yank.create()."""
    phase_name = 'my-solvent-phase'
    toluene = testsystems.TolueneImplicit()
    protocol = AbsoluteAlchemicalFactory.defaultSolventProtocolImplicit()
    atom_indices = find_components(toluene.system, toluene.topology, 'resname TOL')

    phase = AlchemicalPhase(phase_name, toluene.system, toluene.topology,
                            toluene.positions, atom_indices, protocol)
    thermodynamic_state = ThermodynamicState(temperature=300.0*unit.kelvin)

    # Create new simulation.
    with enter_temp_directory():
        output_dir = 'output'
        utils.config_root_logger(verbose=False)
        yank = Yank(store_directory=output_dir)
        yank.create(thermodynamic_state, phase)

        # Netcdf dataset has been created
        nc_path = os.path.join(output_dir, phase_name + '.nc')
        assert os.path.isfile(nc_path)

        # Read data
        try:
            nc_file = netcdf.Dataset(nc_path, mode='r')
            metadata_group = nc_file.groups['metadata']
            serialized_topology = metadata_group.variables['topology'][0]
        finally:
            nc_file.close()

        # Topology has been stored correctly
        deserialized_topology = utils.deserialize_topology(serialized_topology)
        assert deserialized_topology == mdtraj.Topology.from_openmm(toluene.topology)
Beispiel #2
0
def setup_binding_gromacs(args):
    """
    Set up ligand binding free energy calculation using gromacs prmtop/inpcrd files.

    Parameters
    ----------
    args : dict
       Command-line arguments dict from docopt.

    Returns
    -------
    phases : list of str
       Phases (thermodynamic legs) of the calculation.
    systems : dict
       systems[phase] is the OpenMM System reference object for phase 'phase'.
    positions : dict
       positions[phase] is a set of positions (or list of positions) for initializing replicas.
    atom_indices : dict
       atom_indices[phase][component] is list of atom indices for component 'component' in phase 'phase'.

    """
    verbose = args['--verbose']

    # Implicit solvent
    if args['--gbsa']:
        implicitSolvent = getattr(app, args['--gbsa'])
    else:
        implicitSolvent = None

    # Select nonbonded treatment
    # TODO: Carefully check whether input file is periodic or not.
    if args['--nbmethod']:
        nonbondedMethod = getattr(app, args['--nbmethod'])
    else:
        nonbondedMethod = None

    # Constraints
    if args['--constraints']:
        constraints = getattr(app, args['--constraints'])
    else:
        constraints = None

    # Cutoff
    if args['--cutoff']:
        nonbondedCutoff = process_unit_bearing_arg(args, '--cutoff', unit.nanometers)
    else:
        nonbondedCutoff = None

    # COM removal
    removeCMMotion = False

    # Prepare phases of calculation.
    phase_prefixes = ['solvent', 'complex'] # list of calculation phases (thermodynamic legs) to set up
    components = ['ligand', 'receptor', 'solvent'] # components of the binding system
    systems = dict() # systems[phase] is the System object associated with phase 'phase'
    positions = dict() # positions[phase] is a list of coordinates associated with phase 'phase'
    atom_indices = dict() # ligand_atoms[phase] is a list of ligand atom indices associated with phase 'phase'
    setup_directory = args['--setupdir'] # Directory where prmtop/inpcrd files are to be found
    for phase_prefix in phase_prefixes:
        if verbose: logger.info("reading phase %s: " % phase_prefix)
        # Read gromacs input files.
        gro_filename = os.path.join(setup_directory, '%s.gro' % phase_prefix)
        top_filename = os.path.join(setup_directory, '%s.top' % phase_prefix)
        if verbose: logger.info('reading gromacs .gro file: %s' % gro_filename)
        gro = app.GromacsGroFile(gro_filename)
        if verbose: logger.info('reading gromacs .top file "%s" using gromacs include directory "%s"' % (top_filename, args['--gromacsinclude']))
        top = app.GromacsTopFile(top_filename, unitCellDimensions=gro.getUnitCellDimensions(), includeDir=args['--gromacsinclude'])
        # Assume explicit solvent.
        # TODO: Modify this if we can have implicit solvent.
        is_periodic = True
        phase_suffix = 'explicit'
        # Adjust nonbondedMethod.
        # TODO: Ensure that selected method is appropriate.
        if nonbondedMethod == None:
            if is_periodic:
                nonbondedMethod = app.CutoffPeriodic
            else:
                nonbondedMethod = app.NoCutoff
        # TODO: Check to make sure both prmtop and inpcrd agree on explicit/implicit.
        phase = '%s-%s' % (phase_prefix, phase_suffix)
        systems[phase] = top.createSystem(nonbondedMethod=nonbondedMethod, nonbondedCutoff=nonbondedCutoff, constraints=constraints, removeCMMotion=removeCMMotion)
        positions[phase] = gro.getPositions(asNumpy=True)
        # Check to make sure number of atoms match between prmtop and inpcrd.
        prmtop_natoms = systems[phase].getNumParticles()
        inpcrd_natoms = positions[phase].shape[0]
        if prmtop_natoms != inpcrd_natoms:
            raise Exception("Atom number mismatch: prmtop %s has %d atoms; inpcrd %s has %d atoms." % (prmtop_filename, prmtop_natoms, inpcrd_filename, inpcrd_natoms))

        # Find ligand atoms and receptor atoms.
        ligand_dsl = args['--ligand'] # MDTraj DSL that specifies ligand atoms
        atom_indices[phase] = find_components(top.topology, ligand_dsl)

    phases = systems.keys()

    return [phases, systems, positions, atom_indices]
Beispiel #3
0
def setup_binding_gromacs(args):
    """
    Set up ligand binding free energy calculation using gromacs prmtop/inpcrd files.

    Parameters
    ----------
    args : dict
       Command-line arguments dict from docopt.

    Returns
    -------
    alchemical_phases : list of AlchemicalPhase
       Phases (thermodynamic legs) of the calculation.

    """
    verbose = args["--verbose"]

    # Implicit solvent
    if args["--gbsa"]:
        implicitSolvent = getattr(app, args["--gbsa"])
    else:
        implicitSolvent = None

    # Select nonbonded treatment
    # TODO: Carefully check whether input file is periodic or not.
    if args["--nbmethod"]:
        nonbondedMethod = getattr(app, args["--nbmethod"])
    else:
        nonbondedMethod = None

    # Constraints
    if args["--constraints"]:
        constraints = getattr(app, args["--constraints"])
    else:
        constraints = None

    # Cutoff
    if args["--cutoff"]:
        nonbondedCutoff = process_unit_bearing_arg(args, "--cutoff", unit.nanometers)
    else:
        nonbondedCutoff = None

    # COM removal
    removeCMMotion = False

    # Prepare phases of calculation.
    phase_prefixes = ["solvent", "complex"]  # list of calculation phases (thermodynamic legs) to set up
    components = ["ligand", "receptor", "solvent"]  # components of the binding system
    systems = dict()  # systems[phase] is the System object associated with phase 'phase'
    topologies = dict()  # topologies[phase] is the Topology object associated with phase 'phase'
    positions = dict()  # positions[phase] is a list of coordinates associated with phase 'phase'
    atom_indices = dict()  # ligand_atoms[phase] is a list of ligand atom indices associated with phase 'phase'
    setup_directory = args["--setupdir"]  # Directory where prmtop/inpcrd files are to be found
    for phase_prefix in phase_prefixes:
        if verbose:
            logger.info("reading phase %s: " % phase_prefix)
        # Read gromacs input files.
        gro_filename = os.path.join(setup_directory, "%s.gro" % phase_prefix)
        top_filename = os.path.join(setup_directory, "%s.top" % phase_prefix)
        if verbose:
            logger.info("reading gromacs .gro file: %s" % gro_filename)
        gro = app.GromacsGroFile(gro_filename)
        if verbose:
            logger.info(
                'reading gromacs .top file "%s" using gromacs include directory "%s"'
                % (top_filename, args["--gromacsinclude"])
            )
        top = app.GromacsTopFile(
            top_filename, unitCellDimensions=gro.getUnitCellDimensions(), includeDir=args["--gromacsinclude"]
        )
        # Assume explicit solvent.
        # TODO: Modify this if we can have implicit solvent.
        is_periodic = True
        phase_suffix = "explicit"
        # Adjust nonbondedMethod.
        # TODO: Ensure that selected method is appropriate.
        if nonbondedMethod == None:
            if is_periodic:
                nonbondedMethod = app.CutoffPeriodic
            else:
                nonbondedMethod = app.NoCutoff
        # TODO: Check to make sure both prmtop and inpcrd agree on explicit/implicit.
        phase = "%s-%s" % (phase_prefix, phase_suffix)
        systems[phase] = top.createSystem(
            nonbondedMethod=nonbondedMethod,
            nonbondedCutoff=nonbondedCutoff,
            constraints=constraints,
            removeCMMotion=removeCMMotion,
        )
        topologies[phase] = top.topology
        positions[phase] = gro.getPositions(asNumpy=True)
        # Check to make sure number of atoms match between prmtop and inpcrd.
        prmtop_natoms = systems[phase].getNumParticles()
        inpcrd_natoms = positions[phase].shape[0]
        if prmtop_natoms != inpcrd_natoms:
            raise Exception(
                "Atom number mismatch: prmtop %s has %d atoms; inpcrd %s has %d atoms."
                % (prmtop_filename, prmtop_natoms, inpcrd_filename, inpcrd_natoms)
            )

        # Find ligand atoms and receptor atoms.
        ligand_dsl = args["--ligand"]  # MDTraj DSL that specifies ligand atoms
        atom_indices[phase] = find_components(systems[phase], top.topology, ligand_dsl)

    phases = systems.keys()

    alchemical_phases = [None, None]
    protocols = {
        "complex-explicit": AbsoluteAlchemicalFactory.defaultComplexProtocolExplicit(),
        "solvent-explicit": AbsoluteAlchemicalFactory.defaultSolventProtocolImplicit(),
    }
    for i, name in enumerate(phases):
        alchemical_phases[i] = AlchemicalPhase(
            name, systems[name], topologies[name], positions[name], atom_indices[name], protocols[name]
        )

    return alchemical_phases