Beispiel #1
0
def test2(a,radius,box=100.0,fbase=None):
    # l.test2(5.0797,15)

    if fbase is None:
        fbase = "{}_{}".format(box,radius)
    
    top = "{}.top".format(fbase)
    struct = "{}.pdb".format(fbase)
    sol = "{}.sol.pdb".format(fbase)
    ndx = "{}.ndx".format(fbase)
    
    origin = box/2.
    pts=fcc_sphere(a, radius)
    w=writer("{}.pdb".format(fbase))
    w.CRYST1([box,box,box,90.00,90.00,90.00])
    
    
    for index,atom in enumerate(pts):
        w.ATOM(serial=index+1, name="AU", resName="NP", resSeq=1, 
               chainID="A", segID="AUNP", element="AU",
               x=atom[0]+origin, y=atom[1]+origin, z=atom[2]+origin)
        
    w.close()
    
    #make_index("{}.pdb".format(fbase), "{}.ndx".format(fbase))
    
    with file(top, "w") as t:
        t.write(top_src)
        t.write("Au    {}\n".format(pts.shape[0]))
        
    gromacs.genbox(p=top, cp=struct, cs="spc216.gro", o=sol, vdwd="0.15")       #@UndefinedVariable
    
    rc,out,nothing = gromacs.make_ndx(f=sol, n=None, o=ndx, stdout=False,       #@UndefinedVariable
                                      input=('', '', 'q')) 
    
    gromacs.grompp(f="md2.mdp", o="{}.tpr".format(fbase), c=sol, p=top, n=ndx)  #@UndefinedVariable
    
    with file("{}.sh".format(fbase), "w") as f:
        f.write("#!/bin/bash\n")
        f.write("#PBS -k o\n")
        f.write("#PBS -l nodes=1:ppn=12:ccvt,walltime=24:00:00\n")
        f.write("#PBS -M [email protected]\n")
        f.write("#PBS -m abe\n")
        f.write("#PBS -N {}\n".format(fbase))
        f.write("#PBS -j oe\n")
        f.write("#PBS -q pg\n")
        f.write("#PBS -d /N/dc/scratch/somogyie/Au\n")

        f.write("mpirun mdrun -deffnm {}".format(fbase))
Beispiel #2
0
def solvate(struct='top/protein.pdb',
            top='top/system.top',
            distance=0.9,
            boxtype='dodecahedron',
            concentration=0,
            cation='NA',
            anion='CL',
            water='spc',
            solvent_name='SOL',
            with_membrane=False,
            ndx='main.ndx',
            mainselection='"Protein"',
            dirname='solvate',
            **kwargs):
    """Put protein into box, add water, add counter-ions.

    Currently this really only supports solutes in water. If you need
    to embedd a protein in a membrane then you will require more
    sophisticated approaches.

    However, you *can* supply a protein already inserted in a
    bilayer. In this case you will probably want to set *distance* =
    ``None`` and also enable *with_membrane* = ``True`` (using extra
    big vdw radii for typical lipids).

    .. Note:: The defaults are suitable for solvating a globular
       protein in a fairly tight (increase *distance*!) dodecahedral
       box.

    :Arguments:
      *struct* : filename
          pdb or gro input structure
      *top* : filename
          Gromacs topology
      *distance* : float
          When solvating with water, make the box big enough so that
          at least *distance* nm water are between the solute *struct*
          and the box boundary.
          Set *boxtype*  to ``None`` in order to use a box size in the input
          file (gro or pdb).
      *boxtype* or *bt*: string
          Any of the box types supported by :class:`~gromacs.tools.Editconf`
          (triclinic, cubic, dodecahedron, octahedron). Set the box dimensions
          either with *distance* or the *box* and *angle* keywords.

          If set to ``None`` it will ignore *distance* and use the box
          inside the *struct* file.

          *bt* overrides the value of *boxtype*.
      *box*
          List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`
          in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.
          Setting *box* overrides *distance*.
      *angles*
          List of three angles (only necessary for triclinic boxes).
      *concentration* : float
          Concentration of the free ions in mol/l. Note that counter
          ions are added in excess of this concentration.
      *cation* and *anion* : string
          Molecule names of the ions. This depends on the chosen force field.
      *water* : string
          Name of the water model; one of "spc", "spce", "tip3p",
          "tip4p". This should be appropriate for the chosen force
          field. If an alternative solvent is required, simply supply the path to a box
          with solvent molecules (used by :func:`~gromacs.genbox`'s  *cs* argument)
          and also supply the molecule name via *solvent_name*.
      *solvent_name*
          Name of the molecules that make up the solvent (as set in the itp/top).
          Typically needs to be changed when using non-standard/non-water solvents.
          ["SOL"]
      *with_membrane* : bool
           ``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on
           lipids. Default is ``False``.
      *ndx* : filename
          How to name the index file that is produced by this function.
      *mainselection* : string
          A string that is fed to :class:`~gromacs.tools.Make_ndx` and
          which should select the solute.
      *dirname* : directory name
          Name of the directory in which all files for the solvation stage are stored.
      *includes*
          List of additional directories to add to the mdp include path
      *kwargs*
          Additional arguments are passed on to
          :class:`~gromacs.tools.Editconf` or are interpreted as parameters to be
          changed in the mdp file.

    """
    structure = realpath(struct)
    topology = realpath(top)

    # arguments for editconf that we honour
    editconf_keywords = [
        "box", "bt", "angles", "c", "center", "aligncenter", "align",
        "translate", "rotate", "princ"
    ]
    editconf_kwargs = dict((k, kwargs.pop(k, None)) for k in editconf_keywords)
    editconf_boxtypes = [
        "triclinic", "cubic", "dodecahedron", "octahedron", None
    ]

    # needed for topology scrubbing
    scrubber_kwargs = {'marker': kwargs.pop('marker', None)}

    # sanity checks and argument dependencies
    bt = editconf_kwargs.pop('bt')
    boxtype = bt if bt else boxtype  # bt takes precedence over boxtype
    if not boxtype in editconf_boxtypes:
        msg = "Unsupported boxtype {boxtype!r}: Only {boxtypes!r} are possible.".format(
            **vars())
        logger.error(msg)
        raise ValueError(msg)
    if editconf_kwargs['box']:
        distance = None  # if box is set then user knows what she is doing...

    # handle additional include directories (kwargs are also modified!)
    mdp_kwargs = cbook.add_mdp_includes(topology, kwargs)

    if water.lower() in ('spc', 'spce'):
        water = 'spc216'
    elif water.lower() == 'tip3p':
        water = 'spc216'
        logger.warning(
            "TIP3P water model selected: using SPC equilibrated box "
            "for initial solvation because it is a reasonable starting point "
            "for any 3-point model. EQUILIBRATE THOROUGHLY!")

    # By default, grompp should not choke on a few warnings because at
    # this stage the user cannot do much about it (can be set to any
    # value but is kept undocumented...)
    grompp_maxwarn = kwargs.pop('maxwarn', 10)

    # clean topology (if user added the marker; the default marker is
    # ; Gromacs auto-generated entries follow:
    n_removed = cbook.remove_molecules_from_topology(topology,
                                                     **scrubber_kwargs)

    with in_dir(dirname):
        logger.info(
            "[{dirname!s}] Solvating with water {water!r}...".format(**vars()))
        if boxtype is None:
            hasBox = False
            ext = os.path.splitext(structure)[1]
            if ext == '.gro':
                hasBox = True
            elif ext == '.pdb':
                with open(structure) as struct:
                    for line in struct:
                        if line.startswith('CRYST'):
                            hasBox = True
                            break
            if not hasBox:
                msg = "No box data in the input structure {structure!r} and boxtype is set to None".format(
                    **vars())
                logger.exception(msg)
                raise MissingDataError(msg)
            distance = boxtype = None  # ensures that editconf just converts
        editconf_kwargs.update({
            'f': structure,
            'o': 'boxed.gro',
            'bt': boxtype,
            'd': distance
        })
        gromacs.editconf(**editconf_kwargs)

        if with_membrane:
            vdwradii_dat = get_lipid_vdwradii()  # need to clean up afterwards
            logger.info("Using special vdW radii for lipids {0!r}".format(
                vdw_lipid_resnames))

        try:
            gromacs.genbox(p=topology,
                           cp='boxed.gro',
                           cs=water,
                           o='solvated.gro')
        except:
            if with_membrane:
                # remove so that it's not picked up accidentally
                utilities.unlink_f(vdwradii_dat)
            raise
        logger.info("Solvated system with %s", water)

        with open('none.mdp', 'w') as mdp:
            mdp.write(
                '; empty mdp file\ninclude = {include!s}\nrcoulomb = 1\nrvdw = 1\nrlist = 1\n'
                .format(**mdp_kwargs))
        qtotgmx = cbook.grompp_qtot(f='none.mdp',
                                    o='topol.tpr',
                                    c='solvated.gro',
                                    p=topology,
                                    stdout=False,
                                    maxwarn=grompp_maxwarn)
        qtot = round(qtotgmx)
        logger.info(
            "[{dirname!s}] After solvation: total charge qtot = {qtotgmx!r} = {qtot!r}"
            .format(**vars()))

        if concentration != 0:
            logger.info(
                "[{dirname!s}] Adding ions for c = {concentration:f} M...".
                format(**vars()))
            # target concentration of free ions c ==>
            #    N = N_water * c/c_water
            # add ions for concentration to the counter ions (counter ions are less free)
            #
            # get number of waters (count OW ... works for SPC*, TIP*P water models)
            rc, output, junk = gromacs.make_ndx(f='topol.tpr',
                                                o='ow.ndx',
                                                input=('keep 0', 'del 0',
                                                       'a OW*', 'name 0 OW',
                                                       '', 'q'),
                                                stdout=False)
            groups = cbook.parse_ndxlist(output)
            gdict = {g['name']: g for g in groups}  # overkill...
            N_water = gdict['OW']['natoms']  # ... but dict lookup is nice
            N_ions = int(N_water * concentration /
                         CONC_WATER)  # number of monovalents
        else:
            N_ions = 0

        # neutralize (or try -neutral switch of genion???)
        n_cation = n_anion = 0
        if qtot > 0:
            n_anion = int(abs(qtot))
        elif qtot < 0:
            n_cation = int(abs(qtot))

        n_cation += N_ions
        n_anion += N_ions

        if n_cation != 0 or n_anion != 0:
            # sanity check:
            assert qtot + n_cation - n_anion < 1e-6
            logger.info(
                "[{dirname!s}] Adding n_cation = {n_cation:d} and n_anion = {n_anion:d} ions..."
                .format(**vars()))
            gromacs.genion(s='topol.tpr',
                           o='ionized.gro',
                           p=topology,
                           pname=cation,
                           nname=anion,
                           np=n_cation,
                           nn=n_anion,
                           input=solvent_name)
        else:
            # fake ionized file ... makes it easier to continue without too much fuzz
            try:
                os.unlink('ionized.gro')
            except OSError, err:
                if err.errno != errno.ENOENT:
                    raise
            os.symlink('solvated.gro', 'ionized.gro')

        qtot = cbook.grompp_qtot(f='none.mdp',
                                 o='ionized.tpr',
                                 c='ionized.gro',
                                 p=topology,
                                 stdout=False,
                                 maxwarn=grompp_maxwarn)

        if abs(qtot) > 1e-4:
            wmsg = "System has non-zero total charge qtot = {qtot:g} e.".format(
                **vars())
            warnings.warn(wmsg, category=BadParameterWarning)
            logger.warn(wmsg)

        # make main index
        try:
            make_main_index('ionized.tpr', selection=mainselection, ndx=ndx)
        except GromacsError, err:
            # or should I rather fail here?
            wmsg = "Failed to make main index file %r ... maybe set mainselection='...'.\n"\
                   "The error message was:\n%s\n" % (ndx, str(err))
            logger.warn(wmsg)
            warnings.warn(wmsg, category=GromacsFailureWarning)
Beispiel #3
0
def solvate(struct='top/protein.pdb', top='top/system.top',
            distance=0.9, boxtype='dodecahedron',
            concentration=0, cation='NA', anion='CL',
            water='spc', solvent_name='SOL', with_membrane=False,
            ndx = 'main.ndx', mainselection = '"Protein"',
            dirname='solvate',
            **kwargs):
    """Put protein into box, add water, add counter-ions.

    Currently this really only supports solutes in water. If you need
    to embedd a protein in a membrane then you will require more
    sophisticated approaches.

    However, you *can* supply a protein already inserted in a
    bilayer. In this case you will probably want to set *distance* =
    ``None`` and also enable *with_membrane* = ``True`` (using extra
    big vdw radii for typical lipids).

    .. Note:: The defaults are suitable for solvating a globular
       protein in a fairly tight (increase *distance*!) dodecahedral
       box.

    :Arguments:
      *struct* : filename
          pdb or gro input structure
      *top* : filename
          Gromacs topology
      *distance* : float
          When solvating with water, make the box big enough so that
          at least *distance* nm water are between the solute *struct*
          and the box boundary.
          Set *boxtype*  to ``None`` in order to use a box size in the input
          file (gro or pdb).
      *boxtype* or *bt*: string
          Any of the box types supported by :class:`~gromacs.tools.Editconf`
          (triclinic, cubic, dodecahedron, octahedron). Set the box dimensions
          either with *distance* or the *box* and *angle* keywords.

          If set to ``None`` it will ignore *distance* and use the box
          inside the *struct* file.

          *bt* overrides the value of *boxtype*.
      *box*
          List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`
          in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.
          Setting *box* overrides *distance*.
      *angles*
          List of three angles (only necessary for triclinic boxes).
      *concentration* : float
          Concentration of the free ions in mol/l. Note that counter
          ions are added in excess of this concentration.
      *cation* and *anion* : string
          Molecule names of the ions. This depends on the chosen force field.
      *water* : string
          Name of the water model; one of "spc", "spce", "tip3p",
          "tip4p". This should be appropriate for the chosen force
          field. If an alternative solvent is required, simply supply the path to a box
          with solvent molecules (used by :func:`~gromacs.genbox`'s  *cs* argument)
          and also supply the molecule name via *solvent_name*.
      *solvent_name*
          Name of the molecules that make up the solvent (as set in the itp/top).
          Typically needs to be changed when using non-standard/non-water solvents.
          ["SOL"]
      *with_membrane* : bool
           ``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on
           lipids. Default is ``False``.
      *ndx* : filename
          How to name the index file that is produced by this function.
      *mainselection* : string
          A string that is fed to :class:`~gromacs.tools.Make_ndx` and
          which should select the solute.
      *dirname* : directory name
          Name of the directory in which all files for the solvation stage are stored.
      *includes*
          List of additional directories to add to the mdp include path
      *kwargs*
          Additional arguments are passed on to
          :class:`~gromacs.tools.Editconf` or are interpreted as parameters to be
          changed in the mdp file.

    """
    structure = realpath(struct)
    topology = realpath(top)

    # arguments for editconf that we honour
    editconf_keywords = ["box", "bt", "angles", "c", "center", "aligncenter",
                         "align", "translate", "rotate", "princ"]
    editconf_kwargs = dict((k,kwargs.pop(k,None)) for k in editconf_keywords)
    editconf_boxtypes = ["triclinic", "cubic", "dodecahedron", "octahedron", None]

    # needed for topology scrubbing
    scrubber_kwargs = {'marker': kwargs.pop('marker',None)}

    # sanity checks and argument dependencies
    bt = editconf_kwargs.pop('bt')
    boxtype = bt if bt else boxtype   # bt takes precedence over boxtype
    if not boxtype in editconf_boxtypes:
        msg = "Unsupported boxtype {boxtype!r}: Only {boxtypes!r} are possible.".format(**vars())
        logger.error(msg)
        raise ValueError(msg)
    if editconf_kwargs['box']:
        distance = None    # if box is set then user knows what she is doing...

    # handle additional include directories (kwargs are also modified!)
    mdp_kwargs = cbook.add_mdp_includes(topology, kwargs)

    if water.lower() in ('spc', 'spce'):
        water = 'spc216'
    elif water.lower() == 'tip3p':
        water = 'spc216'
        logger.warning("TIP3P water model selected: using SPC equilibrated box "
                       "for initial solvation because it is a reasonable starting point "
                       "for any 3-point model. EQUILIBRATE THOROUGHLY!")

    # By default, grompp should not choke on a few warnings because at
    # this stage the user cannot do much about it (can be set to any
    # value but is kept undocumented...)
    grompp_maxwarn = kwargs.pop('maxwarn',10)

    # clean topology (if user added the marker; the default marker is
    # ; Gromacs auto-generated entries follow:
    n_removed = cbook.remove_molecules_from_topology(topology, **scrubber_kwargs)

    with in_dir(dirname):
        logger.info("[{dirname!s}] Solvating with water {water!r}...".format(**vars()))
        if boxtype is None:
            hasBox = False
            ext = os.path.splitext(structure)[1]
            if ext == '.gro':
                hasBox = True
            elif ext == '.pdb':
                with open(structure) as struct:
                    for line in struct:
                        if line.startswith('CRYST'):
                            hasBox = True
                            break
            if not hasBox:
                msg = "No box data in the input structure {structure!r} and boxtype is set to None".format(**vars())
                logger.exception(msg)
                raise MissingDataError(msg)
            distance = boxtype = None   # ensures that editconf just converts
        editconf_kwargs.update({'f': structure, 'o': 'boxed.gro',
                                'bt': boxtype, 'd': distance})
        gromacs.editconf(**editconf_kwargs)

        if with_membrane:
            vdwradii_dat = get_lipid_vdwradii()  # need to clean up afterwards
            logger.info("Using special vdW radii for lipids {0!r}".format(vdw_lipid_resnames))

        try:
            gromacs.genbox(p=topology, cp='boxed.gro', cs=water, o='solvated.gro')
        except:
            if with_membrane:
                # remove so that it's not picked up accidentally
                utilities.unlink_f(vdwradii_dat)
            raise
        logger.info("Solvated system with %s", water)

        with open('none.mdp','w') as mdp:
            mdp.write('; empty mdp file\ninclude = {include!s}\nrcoulomb = 1\nrvdw = 1\nrlist = 1\n'.format(**mdp_kwargs))
        qtotgmx = cbook.grompp_qtot(f='none.mdp', o='topol.tpr', c='solvated.gro',
                                            p=topology, stdout=False, maxwarn=grompp_maxwarn)
        qtot = round(qtotgmx)
        logger.info("[{dirname!s}] After solvation: total charge qtot = {qtotgmx!r} = {qtot!r}".format(**vars()))

        if concentration != 0:
            logger.info("[{dirname!s}] Adding ions for c = {concentration:f} M...".format(**vars()))
            # target concentration of free ions c ==>
            #    N = N_water * c/c_water
            # add ions for concentration to the counter ions (counter ions are less free)
            #
            # get number of waters (count OW ... works for SPC*, TIP*P water models)
            rc,output,junk = gromacs.make_ndx(f='topol.tpr', o='ow.ndx',
                                              input=('keep 0', 'del 0', 'a OW*', 'name 0 OW', '', 'q'),
                                              stdout=False)
            groups = cbook.parse_ndxlist(output)
            gdict = {g['name']: g for g in groups}   # overkill...
            N_water = gdict['OW']['natoms']                  # ... but dict lookup is nice
            N_ions = int(N_water * concentration/CONC_WATER) # number of monovalents
        else:
            N_ions = 0

        # neutralize (or try -neutral switch of genion???)
        n_cation = n_anion = 0
        if qtot > 0:
            n_anion = int(abs(qtot))
        elif qtot < 0:
            n_cation = int(abs(qtot))

        n_cation += N_ions
        n_anion  += N_ions

        if n_cation != 0 or n_anion != 0:
            # sanity check:
            assert qtot + n_cation - n_anion < 1e-6
            logger.info("[{dirname!s}] Adding n_cation = {n_cation:d} and n_anion = {n_anion:d} ions...".format(**vars()))
            gromacs.genion(s='topol.tpr', o='ionized.gro', p=topology,
                           pname=cation, nname=anion, np=n_cation, nn=n_anion,
                           input=solvent_name)
        else:
            # fake ionized file ... makes it easier to continue without too much fuzz
            try:
                os.unlink('ionized.gro')
            except OSError, err:
                if err.errno != errno.ENOENT:
                    raise
            os.symlink('solvated.gro', 'ionized.gro')

        qtot = cbook.grompp_qtot(f='none.mdp', o='ionized.tpr', c='ionized.gro',
                                         p=topology, stdout=False, maxwarn=grompp_maxwarn)

        if abs(qtot) > 1e-4:
            wmsg = "System has non-zero total charge qtot = {qtot:g} e.".format(**vars())
            warnings.warn(wmsg, category=BadParameterWarning)
            logger.warn(wmsg)

        # make main index
        try:
            make_main_index('ionized.tpr', selection=mainselection, ndx=ndx)
        except GromacsError, err:
            # or should I rather fail here?
            wmsg = "Failed to make main index file %r ... maybe set mainselection='...'.\n"\
                   "The error message was:\n%s\n" % (ndx, str(err))
            logger.warn(wmsg)
            warnings.warn(wmsg, category=GromacsFailureWarning)
Beispiel #4
0
def test2(a, radius, box=100.0, fbase=None):
    # l.test2(5.0797,15)

    if fbase is None:
        fbase = "{}_{}".format(box, radius)

    top = "{}.top".format(fbase)
    struct = "{}.pdb".format(fbase)
    sol = "{}.sol.pdb".format(fbase)
    ndx = "{}.ndx".format(fbase)

    origin = box / 2.
    pts = fcc_sphere(a, radius)
    w = writer("{}.pdb".format(fbase))
    w.CRYST1([box, box, box, 90.00, 90.00, 90.00])

    for index, atom in enumerate(pts):
        w.ATOM(serial=index + 1,
               name="AU",
               resName="NP",
               resSeq=1,
               chainID="A",
               segID="AUNP",
               element="AU",
               x=atom[0] + origin,
               y=atom[1] + origin,
               z=atom[2] + origin)

    w.close()

    #make_index("{}.pdb".format(fbase), "{}.ndx".format(fbase))

    with file(top, "w") as t:
        t.write(top_src)
        t.write("Au    {}\n".format(pts.shape[0]))

    gromacs.genbox(p=top, cp=struct, cs="spc216.gro", o=sol,
                   vdwd="0.15")  #@UndefinedVariable

    rc, out, nothing = gromacs.make_ndx(
        f=sol,
        n=None,
        o=ndx,
        stdout=False,  #@UndefinedVariable
        input=('', '', 'q'))

    gromacs.grompp(f="md2.mdp", o="{}.tpr".format(fbase), c=sol, p=top,
                   n=ndx)  #@UndefinedVariable

    with file("{}.sh".format(fbase), "w") as f:
        f.write("#!/bin/bash\n")
        f.write("#PBS -k o\n")
        f.write("#PBS -l nodes=1:ppn=12:ccvt,walltime=24:00:00\n")
        f.write("#PBS -M [email protected]\n")
        f.write("#PBS -m abe\n")
        f.write("#PBS -N {}\n".format(fbase))
        f.write("#PBS -j oe\n")
        f.write("#PBS -q pg\n")
        f.write("#PBS -d /N/dc/scratch/somogyie/Au\n")

        f.write("mpirun mdrun -deffnm {}".format(fbase))
Beispiel #5
0
def solvate_sol(struct='top/protein.pdb',
                top='top/system.top',
                distance=0.9,
                boxtype='dodecahedron',
                water='tip4p',
                solvent_name='SOL',
                with_membrane=False,
                dirname='solvate',
                **kwargs):
    structure = realpath(struct)
    topology = realpath(top)

    # arguments for editconf that we honour
    editconf_keywords = [
        "box", "bt", "angles", "c", "center", "aligncenter", "align",
        "translate", "rotate", "princ"
    ]
    editconf_kwargs = dict((k, kwargs.pop(k, None)) for k in editconf_keywords)
    editconf_boxtypes = [
        "triclinic", "cubic", "dodecahedron", "octahedron", None
    ]

    # needed for topology scrubbing
    scrubber_kwargs = {'marker': kwargs.pop('marker', None)}

    # sanity checks and argument dependencies
    bt = editconf_kwargs.pop('bt')
    boxtype = bt if bt else boxtype  # bt takes precedence over boxtype
    if not boxtype in editconf_boxtypes:
        msg = "Unsupported boxtype {boxtype!r}: Only {boxtypes!r} are possible.".format(
            **vars())
        logger.error(msg)
        raise ValueError(msg)
    if editconf_kwargs['box']:
        distance = None  # if box is set then user knows what she is doing...

    if water.lower() in ('spc', 'spce'):
        water = 'spc216'
    elif water.lower() == 'tip3p':
        water = 'spc216'
        logger.warning(
            "TIP3P water model selected: using SPC equilibrated box "
            "for initial solvation because it is a reasonable starting point "
            "for any 3-point model. EQUILIBRATE THOROUGHLY!")

    # clean topology (if user added the marker; the default marker is
    # ; Gromacs auto-generated entries follow:
    n_removed = cbook.remove_molecules_from_topology(topology,
                                                     **scrubber_kwargs)

    with in_dir(dirname):
        logger.info(
            "[{dirname!s}] Solvating with water {water!r}...".format(**vars()))
        if boxtype is None:
            hasBox = False
            ext = os.path.splitext(structure)[1]
            if ext == '.gro':
                hasBox = True
            elif ext == '.pdb':
                with open(structure) as struct:
                    for line in struct:
                        if line.startswith('CRYST'):
                            hasBox = True
                            break
            if not hasBox:
                msg = "No box data in the input structure {structure!r} and boxtype is set to None".format(
                    **vars())
                logger.exception(msg)
                raise MissingDataError(msg)
            distance = boxtype = None  # ensures that editconf just converts
        editconf_kwargs.update({
            'f': structure,
            'o': 'boxed.gro',
            'bt': boxtype,
            'd': distance
        })
        gromacs.editconf(**editconf_kwargs)

        if with_membrane:
            vdwradii_dat = get_lipid_vdwradii()  # need to clean up afterwards
            logger.info("Using special vdW radii for lipids {0!r}".format(
                vdw_lipid_resnames))

        try:
            gromacs.genbox(p=topology,
                           cp='boxed.gro',
                           cs=water,
                           o='solvated.gro')
        except:
            if with_membrane:
                # remove so that it's not picked up accidentally
                utilities.unlink_f(vdwradii_dat)
            raise
        logger.info("Solvated system with %s", water)
    return {
        'struct': realpath(dirname, 'solvated.gro'),
    }
Beispiel #6
0
def solvate_sol(struct='top/protein.pdb', top='top/system.top',
                distance=0.9, boxtype='dodecahedron',
                water='tip4p', solvent_name='SOL', with_membrane=False,
                dirname='solvate',
                **kwargs):
    structure = realpath(struct)
    topology = realpath(top)

    # arguments for editconf that we honour
    editconf_keywords = ["box", "bt", "angles", "c", "center", "aligncenter",
                         "align", "translate", "rotate", "princ"]
    editconf_kwargs = dict((k,kwargs.pop(k,None)) for k in editconf_keywords)
    editconf_boxtypes = ["triclinic", "cubic", "dodecahedron", "octahedron", None]

    # needed for topology scrubbing
    scrubber_kwargs = {'marker': kwargs.pop('marker',None)}

    # sanity checks and argument dependencies
    bt = editconf_kwargs.pop('bt')
    boxtype = bt if bt else boxtype   # bt takes precedence over boxtype
    if not boxtype in editconf_boxtypes:
        msg = "Unsupported boxtype {boxtype!r}: Only {boxtypes!r} are possible.".format(**vars())
        logger.error(msg)
        raise ValueError(msg)
    if editconf_kwargs['box']:
        distance = None    # if box is set then user knows what she is doing...

    if water.lower() in ('spc', 'spce'):
        water = 'spc216'
    elif water.lower() == 'tip3p':
        water = 'spc216'
        logger.warning("TIP3P water model selected: using SPC equilibrated box "
                       "for initial solvation because it is a reasonable starting point "
                       "for any 3-point model. EQUILIBRATE THOROUGHLY!")

    # clean topology (if user added the marker; the default marker is
    # ; Gromacs auto-generated entries follow:
    n_removed = cbook.remove_molecules_from_topology(topology, **scrubber_kwargs)

    with in_dir(dirname):
        logger.info("[{dirname!s}] Solvating with water {water!r}...".format(**vars()))
        if boxtype is None:
            hasBox = False
            ext = os.path.splitext(structure)[1]
            if ext == '.gro':
                hasBox = True
            elif ext == '.pdb':
                with open(structure) as struct:
                    for line in struct:
                        if line.startswith('CRYST'):
                            hasBox = True
                            break
            if not hasBox:
                msg = "No box data in the input structure {structure!r} and boxtype is set to None".format(**vars())
                logger.exception(msg)
                raise MissingDataError(msg)
            distance = boxtype = None   # ensures that editconf just converts
        editconf_kwargs.update({'f': structure, 'o': 'boxed.gro',
                                'bt': boxtype, 'd': distance})
        gromacs.editconf(**editconf_kwargs)

        if with_membrane:
            vdwradii_dat = get_lipid_vdwradii()  # need to clean up afterwards
            logger.info("Using special vdW radii for lipids {0!r}".format(vdw_lipid_resnames))

        try:
            gromacs.genbox(p=topology, cp='boxed.gro', cs=water, o='solvated.gro')
        except:
            if with_membrane:
                # remove so that it's not picked up accidentally
                utilities.unlink_f(vdwradii_dat)
            raise
        logger.info("Solvated system with %s", water)
    return {'struct': realpath(dirname, 'solvated.gro'),}