Beispiel #1
0
    def getMolecules(self, group="all"):
        """Return a list containing all of the molecules in the specified group.

           Parameters
           ----------

           group : str
               The name of the molecule group.

           Returns
           -------

           molecules : [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`]
               The list of molecules in the group.
        """

        if type(group) is not str:
            raise TypeError("'group' must be of type 'str'")

        # Try to extract the molecule group.
        try:
            molgrp = self._sire_object.group(_SireMol.MGName(group))
        except:
            raise ValueError("No molecules in group '%s'" % group)

        # Return a molecules container.
        return _Molecules(molgrp.molecules())
Beispiel #2
0
    def removeWaterMolecules(self):
        """Remove all of the water molecules from the system."""

        # Get the list of water molecules.
        waters = self.getWaterMolecules()

        # Remove the molecules in the system.
        self._sire_object.remove(waters._sire_object, _SireMol.MGName("all"))

        # Reset the index mappings.
        self._reset_mappings()

        # Update the molecule numbers.
        self._mol_nums = self._sire_object.molNums()
Beispiel #3
0
    def removeMolecules(self, molecules):
        """Remove a molecule, or list of molecules from the system.

           Parameters
           ----------

           molecules : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`, \
                       :class:`Molecules <BioSimSpace._SireWrappers.Molecules>`, \
                       [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`]
              A Molecule, Molecules object, or list of Molecule objects.
        """

        # Whether the molecules are in a Sire container.
        is_sire_container = False

        # Convert tuple to a list.
        if type(molecules) is tuple:
            molecules = list(molecules)

        # A Molecule object.
        if type(molecules) is _Molecule:
            molecules = [molecules]

        # A Molecules object.
        if type(molecules) is _Molecules:
            is_sire_container = True

        # A list of Molecule objects.
        elif type(molecules) is list and all(isinstance(x, _Molecule) for x in molecules):
            pass

        # Invalid argument.
        else:
            raise TypeError("'molecules' must be of type 'BioSimSpace._SireWrappers.Molecule' "
                            "or a list of 'BioSimSpace._SireWrappers.Molecule' types.")

        # Remove the molecules in the system.
        if is_sire_container:
            self._sire_object.remove(molecules._sire_object, _SireMol.MGName("all"))
        else:
            for mol in molecules:
                self._sire_object.remove(mol._sire_object.number())

        # Reset the index mappings.
        self._reset_mappings()

        # Update the molecule numbers.
        self._mol_nums = self._sire_object.molNums()
Beispiel #4
0
    def updateMolecules(self, molecules):
        """Update a molecule, or list of molecules in the system.

           Parameters
           ----------

           molecules : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`, \
                       [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`]
              A Molecule, or list of Molecule objects.
        """

        # Convert tuple to a list.
        if type(molecules) is tuple:
            molecules = list(molecules)

        # A Molecule object.
        if type(molecules) is _Molecule:
            molecules = [molecules]

        # A list of Molecule objects.
        elif type(molecules) is list and all(isinstance(x, _Molecule) for x in molecules):
            pass

        # Invalid argument.
        else:
            raise TypeError("'molecules' must be of type 'BioSimSpace._SireWrappers.Molecule' "
                            "or a list of 'BioSimSpace._SireWrappers.Molecule' types.")

        # Update each of the molecules.
        # TODO: Currently the Sire.System.update method doesn't work correctly
        # for certain changes to the Molecule molInfo object. As such, we remove
        # the old molecule from the system, then add the new one in.
        for mol in molecules:
            try:
                self._sire_object.update(mol._sire_object)
            except:
                self._sire_object.remove(mol._sire_object.number())
                self._sire_object.add(mol._sire_object, _SireMol.MGName("all"))

        # Reset the index mappings.
        self._reset_mappings()

        # Update the molecule numbers.
        self._mol_nums = self._sire_object.molNums()
Beispiel #5
0
    def getMolecules(self, group="all"):
        """Return a list containing all of the molecules in the specified group.

           Parameters
           ----------

           group : str
               The name of the molecule group.

           Returns
           -------

           molecules : [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`]
               The list of molecules in the group.
        """

        if type(group) is not str:
            raise TypeError("'group' must be of type 'str'")

        # Try to extract the molecule group.
        try:
            molgrp = self._sire_system.group(_SireMol.MGName(group))
        except:
            raise ValueError("No molecules in group '%s'" % group)

        # Create a list to store the molecules.
        mols = []

        # Get a list of the MolNums in the group and sort them.
        nums = molgrp.molNums()

        # Loop over all of the molecules in the group and append to the list.
        for num in nums:
            mols.append(_Molecule(molgrp.molecule(num)))

            # This is a merged molecule.
            if mols[-1]._sire_molecule.hasProperty("is_perturbable"):
                mols[-1]._is_merged = True

        return mols
Beispiel #6
0
    def addMolecules(self, molecules):
        """Add a molecule, or list of molecules to the system.

           Parameters
           ----------

           molecules : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`, \
                       [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`]
              A Molecule, or list of Molecule objects.
        """

        # Convert tuple to a list.
        if type(molecules) is tuple:
            molecules = list(molecules)

        # A Molecule object.
        if type(molecules) is _Molecule:
            molecules = [molecules]

        # A list of Molecule objects.
        elif type(molecules) is list and all(isinstance(x, _Molecule) for x in molecules):
            pass

        # Invalid argument.
        else:
            raise TypeError("'molecules' must be of type 'BioSimSpace._SireWrappers.Molecule' "
                            "or a list of 'BioSimSpace._SireWrappers.Molecule' types.")

        # The system is empty: create a new Sire system from the molecules.
        if self._sire_system.nMolecules() == 0:
            self._sire_system = self._createSireSystem(molecules)

        # Otherwise, add the molecules to the existing "all" group.
        else:
            for mol in molecules:
                self._sire_system.add(mol._sire_molecule, _SireMol.MGName("all"))
Beispiel #7
0
    def addMolecules(self, molecules):
        """Add a molecule, or list of molecules to the system.

           Parameters
           ----------

           molecules : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`, \
                       :class:`Molecules <BioSimSpace._SireWrappers.Molecules>`, \
                       [:class:`Molecule <BioSimSpace._SireWrappers.Molecule>`], \
                       :class:`System <BioSimSpace._SireWrappers.System>`
              A Molecule, Molecules object, a list of Molecule objects, or a System containing molecules.
        """

        # Whether the molecules are in a Sire container.
        is_sire_container = False

        # Convert tuple to a list.
        if type(molecules) is tuple:
            molecules = list(molecules)

        # A Molecule object.
        if type(molecules) is _Molecule:
            molecules = [molecules]

        # A Molecules object.
        if type(molecules) is _Molecules:
            is_sire_container = True

        # A System object.
        elif type(molecules) is System:
            is_sire_container = True

        # A list of Molecule objects.
        elif type(molecules) is list and all(isinstance(x, _Molecule) for x in molecules):
            pass

        # Invalid argument.
        else:
            raise TypeError("'molecules' must be of type 'BioSimSpace._SireWrappers.Molecule', "
                            ", 'BioSimSpace._SireWrappers.System', or a list of "
                            "'BioSimSpace._SireWrappers.Molecule' types.")

        # The system is empty: create a new Sire system from the molecules.
        if self._sire_object.nMolecules() == 0:
            self._sire_object = self._createSireSystem(molecules)

        # Otherwise, add the molecules to the existing "all" group.
        else:
            if is_sire_container:
                if type(molecules) is _Molecules:
                    molecules = molecules._sire_object
                else:
                    try:
                        molecules = molecules._sire_object.at(_SireMol.MGNum(1))
                    except:
                        molecules = molecules._sire_object.molecules()
                self._sire_object.add(molecules, _SireMol.MGName("all"))
            else:
                for mol in molecules:
                    self._sire_object.add(mol._sire_object, _SireMol.MGName("all"))

        # Reset the index mappings.
        self._reset_mappings()

        # Update the molecule numbers.
        self._mol_nums = self._sire_object.molNums()
Beispiel #8
0
    def _initialise_runner(self, system0, system1):
        """Internral helper function to initialise the process runner.

           Parameters
           ----------

           system0 : :class:`System <BioSimSpace._SireWrappers.System>`
               The system for the first free energy leg.

           system1 : :class:`System <BioSimSpace._SireWrappers.System>`
               The system for the second free energy leg.
        """

        if type(system0) is not _System:
            raise TypeError(
                "'system0' must be of type 'BioSimSpace._SireWrappers.System'")

        if type(system1) is not _System:
            raise TypeError(
                "'system1' must be of type 'BioSimSpace._SireWrappers.System'")

        # Initialise lists to store the processes for each leg.
        leg0 = []
        leg1 = []

        # Get the simulation type.
        sim_type = self.__class__.__name__

        # Store the working directories for the legs.

        if sim_type == "Solvation":
            self._dir0 = "%s/free" % self._work_dir
            self._dir1 = "%s/vacuum" % self._work_dir
        elif sim_type == "Binding":
            self._dir0 = "%s/bound" % self._work_dir
            self._dir1 = "%s/free" % self._work_dir
        else:
            raise TypeError("Unsupported FreeEnergy simulation: '%s'" %
                            sim_type)

        # Try to get the water model property of the system.
        try:
            water_model = system0._sire_system.property(
                "water_model").toString()
        # Default to TIP3P.
        except:
            water_model = "tip3p"

        if self._engine == "SOMD":
            # Reformat all of the water molecules so that they match the expected
            # AMBER topology template. (Required by SOMD.)
            waters0 = _SireIO.setAmberWater(
                system0._sire_system.search("water"), water_model)
            waters1 = _SireIO.setAmberWater(
                system1._sire_system.search("water"), water_model)

            # Loop over all of the renamed water molecules, delete the old one
            # from the system, then add the renamed one back in.
            # TODO: This is a hack since the "update" method of Sire.System
            # doesn't work properly at present.
            system0.removeWaterMolecules()
            system1.removeWaterMolecules()
            for wat in waters0:
                system0._sire_system.add(wat, _SireMol.MGName("all"))
            for wat in waters1:
                system1._sire_system.add(wat, _SireMol.MGName("all"))

        # Get the lambda values from the protocol.
        lam_vals = self._protocol.getLambdaValues()

        # Loop over all of the lambda values.
        for lam in lam_vals:
            # Update the protocol lambda values.
            self._protocol.setLambdaValues(lam=lam, lam_vals=lam_vals)

            # Create and append the required processes for each leg.
            # Nest the working directories inside self._work_dir.

            # SOMD.
            if self._engine == "SOMD":
                # TODO: This is currently hard-coded to use SOMD with the CUDA platform.
                leg0.append(
                    _Process.Somd(system0,
                                  self._protocol,
                                  platform="CUDA",
                                  work_dir="%s/lambda_%5.4f" %
                                  (self._dir0, lam)))

                leg1.append(
                    _Process.Somd(system1,
                                  self._protocol,
                                  platform="CUDA",
                                  work_dir="%s/lambda_%5.4f" %
                                  (self._dir1, lam)))

            # GROMACS.
            elif self._engine == "GROMACS":
                # TODO: This is currently hard-coded to use SOMD with the CUDA platform.
                leg0.append(
                    _Process.Gromacs(system0,
                                     self._protocol,
                                     work_dir="%s/lambda_%5.4f" %
                                     (self._dir0, lam)))

                leg1.append(
                    _Process.Gromacs(system1,
                                     self._protocol,
                                     work_dir="%s/lambda_%5.4f" %
                                     (self._dir1, lam)))

        # Initialise the process runner. All processes have already been nested
        # inside the working directory so no need to re-nest.
        self._runner = _Process.ProcessRunner(leg0 + leg1,
                                              work_dir=self._work_dir,
                                              nest_dirs=False)
Beispiel #9
0
def _solvate(molecule,
             box,
             shell,
             model,
             num_point,
             ion_conc,
             is_neutral,
             work_dir=None,
             property_map={}):
    """Internal function to add solvent using 'gmx solvate'.

       Parameters
       ----------

       molecule : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>`, \
                  :class:`System <BioSimSpace._SireWrappers.System>`
           A molecule, or system of molecules.

       box : [:class:`Length <BioSimSpace.Types.Length>`]
           A list containing the box size in each dimension (in nm).

       shell : :class:`Length` <BioSimSpace.Types.Length>`
           Thickness of the water shell around the solute.

       model : str
           The name of the water model.

       num_point : int
           The number of atoms in the water model.

       ion_conc : float
           The ion concentration in (mol per litre).

       is_neutral : bool
           Whether to neutralise the system.

       work_dir : str
           The working directory for the process.

       property_map : dict
           A dictionary that maps system "properties" to their user defined
           values. This allows the user to refer to properties with their
           own naming scheme, e.g. { "charge" : "my-charge" }


       Returns
       -------

       system : :class:`System <BioSimSpace._SireWrappers.System>`
           The solvated system.
    """

    if molecule is not None:
        # Store the centre of the molecule.
        center = molecule._getAABox(property_map).center()

        # Work out the vector from the centre of the molecule to the centre of the
        # water box, converting the distance in each direction to Angstroms.
        vec = []
        for x, y in zip(box, center):
            vec.append(0.5 * x.angstroms().magnitude() - y)

        # Translate the molecule. This allows us to create a water box
        # around the molecule.
        molecule.translate(vec, property_map)

        if type(molecule) is _System:

            # Reformat all of the water molecules so that they match the
            # expected GROMACS topology template.
            waters = _SireIO.setGromacsWater(
                molecule._sire_system.search("water"), model)

            # Loop over all of the renamed water molecules, delete the old one
            # from the system, then add the renamed one back in.
            # TODO: This is a hack since the "update" method of Sire.System
            # doesn't work properly at present.
            molecule.removeWaterMolecules()
            for wat in waters:
                molecule._sire_system.add(wat, _SireMol.MGName("all"))

    # Create a temporary working directory and store the directory name.
    if work_dir is None:
        tmp_dir = _tempfile.TemporaryDirectory()
        work_dir = tmp_dir.name

    # Run the solvation in the working directory.
    with _Utils.cd(work_dir):

        # Create the gmx command.
        if num_point == 3:
            mod = "spc216"
        else:
            mod = model
        command = "%s solvate -cs %s" % (_gmx_exe, mod)

        if molecule is not None:
            # Write the molecule/system to a GRO files.
            _IO.saveMolecules("input", molecule, "gro87")
            _os.rename("input.gro87", "input.gro")

            # Update the command.
            command += " -cp input.gro"

            # Add the box information.
            if box is not None:
                command += " -box %f %f %f" % (box[0].nanometers().magnitude(),
                                               box[1].nanometers().magnitude(),
                                               box[2].nanometers().magnitude())

            # Add the shell information.
            if shell is not None:
                command += " -shell %f" % shell.nanometers().magnitude()

        # Just add box information.
        else:
            command += " -box %f %f %f" % (box[0].nanometers().magnitude(),
                                           box[1].nanometers().magnitude(),
                                           box[2].nanometers().magnitude())

        # Add the output file.
        command += " -o output.gro"

        with open("README.txt", "w") as file:
            # Write the command to file.
            file.write("# gmx solvate was run with the following command:\n")
            file.write("%s\n" % command)

        # Create files for stdout/stderr.
        stdout = open("solvate.out", "w")
        stderr = open("solvate.err", "w")

        # Run gmx solvate as a subprocess.
        proc = _subprocess.run(command,
                               shell=True,
                               stdout=stdout,
                               stderr=stderr)
        stdout.close()
        stderr.close()

        # gmx doesn't return sensible error codes, so we need to check that
        # the expected output was generated.
        if not _os.path.isfile("output.gro"):
            raise RuntimeError("'gmx solvate failed to generate output!")

        # Extract the water lines from the GRO file.
        water_lines = []
        with open("output.gro", "r") as file:
            for line in file:
                if _re.search("SOL", line):
                    # Store the SOL atom record.
                    water_lines.append(line)

            # Add any box information. This is the last line in the GRO file.
            water_lines.append(line)

        # Write a GRO file that contains only the water atoms.
        if len(water_lines) - 1 > 0:
            with open("water.gro", "w") as file:
                file.write("BioSimSpace %s water box\n" % model.upper())
                file.write("%d\n" % (len(water_lines) - 1))

                for line in water_lines:
                    file.write("%s" % line)
        else:
            raise ValueError(
                "No water molecules were generated. Try increasing "
                "the 'box' size or 'shell' thickness.")

        # Create a TOP file for the water model. By default we use the Amber03
        # force field to generate a dummy topology for the water model.
        with open("water_ions.top", "w") as file:
            file.write("#define FLEXIBLE 1\n\n")
            file.write("; Include AmberO3 force field\n")
            file.write('#include "amber03.ff/forcefield.itp"\n\n')
            file.write("; Include %s water topology\n" % model.upper())
            file.write('#include "amber03.ff/%s.itp"\n\n' % model)
            file.write("; Include ions\n")
            file.write('#include "amber03.ff/ions.itp"\n\n')
            file.write("[ system ] \n")
            file.write("BioSimSpace %s water box\n\n" % model.upper())
            file.write("[ molecules ] \n")
            file.write(";molecule name    nr.\n")
            file.write("SOL               %d\n" %
                       ((len(water_lines) - 1) / num_point))

        # Load the water box.
        water = _IO.readMolecules(["water.gro", "water_ions.top"])

        # Create a new system by adding the water to the original molecule.
        if molecule is not None:
            # Translate the molecule and water back to the original position.
            vec = [-x for x in vec]
            molecule.translate(vec, property_map)
            water.translate(vec)

            if type(molecule) is _System:
                # Extract the non-water molecules from the original system.
                non_waters = [
                    mol for mol in molecule.getMolecules()
                    if not mol.isWater()
                ]

                # Create a system by adding these to the water molecules from
                # gmx solvate, which will include the original waters.
                system = _System(non_waters + water.getMolecules())

            else:
                system = molecule + water.getMolecules()

            # Add all of the water box properties to the new system.
            for prop in water._sire_system.propertyKeys():
                prop = property_map.get(prop, prop)

                # Add the space property from the water system.
                system._sire_system.setProperty(
                    prop, water._sire_system.property(prop))
        else:
            system = water

        # Now we add ions to the system and neutralise the charge.
        if ion_conc > 0 or is_neutral:

            # Write the molecule + water system to file.
            _IO.saveMolecules("solvated", system, "gro87")
            _IO.saveMolecules("solvated", system, "grotop")
            _os.rename("solvated.gro87", "solvated.gro")
            _os.rename("solvated.grotop", "solvated.top")

            # First write an mdp file.
            with open("ions.mdp", "w") as file:
                file.write("; Neighbour searching\n")
                file.write("cutoff-scheme           = Verlet\n")
                file.write("rlist                   = 1.1\n")
                file.write("pbc                     = xyz\n")
                file.write("verlet-buffer-tolerance = -1\n")
                file.write("\n; Electrostatics\n")
                file.write("coulombtype             = cut-off\n")
                file.write("\n; VdW\n")
                file.write("rvdw                    = 1.0\n")

            # Create the grompp command.
            command = "%s grompp -f ions.mdp -po ions.out.mdp -c solvated.gro -p solvated.top -o ions.tpr" % _gmx_exe

            with open("README.txt", "a") as file:
                # Write the command to file.
                file.write(
                    "\n# gmx grompp was run with the following command:\n")
                file.write("%s\n" % command)

            # Create files for stdout/stderr.
            stdout = open("grommp.out", "w")
            stderr = open("grommp.err", "w")

            # Run grompp as a subprocess.
            proc = _subprocess.run(command,
                                   shell=True,
                                   stdout=stdout,
                                   stderr=stderr)
            stdout.close()
            stderr.close()

            # Flag whether to break out of the ion adding stage.
            is_break = False

            # Check for the tpr output file.
            if not _os.path.isfile("ions.tpr"):
                if shell is None:
                    raise RuntimeError(
                        "'gmx grommp' failed to generate output! "
                        "Perhaps your box is too small?")
                else:
                    is_break = True
                    _warnings.warn(
                        "Unable to achieve target ion concentration, try using "
                        "'box' option instead of 'shell'.")

            # Only continue if grommp was successful. This allows us to skip the remainder
            # of the code if the ion addition failed when the 'shell' option was chosen, i.e.
            # because the estimated simulation box was too small.
            if not is_break:
                is_break = False

                # The ion concentration is unset.
                if ion_conc == 0:
                    # Get the current molecular charge.
                    charge = system.charge()

                    # Round to the nearest integer value.
                    charge = round(charge.magnitude())

                    # Create the genion command.
                    command = "echo SOL | %s genion -s ions.tpr -o solvated_ions.gro -p solvated.top -neutral" % _gmx_exe

                    # Add enough counter ions to neutralise the charge.
                    if charge > 0:
                        command += " -nn %d" % abs(charge)
                    else:
                        command += " -np %d" % abs(charge)
                else:
                    # Create the genion command.
                    command = "echo SOL | %s genion -s ions.tpr -o solvated_ions.gro -p solvated.top -%s -conc %f" \
                        % (_gmx_exe, "neutral" if is_neutral else "noneutral", ion_conc)

                with open("README.txt", "a") as file:
                    # Write the command to file.
                    file.write(
                        "\n# gmx genion was run with the following command:\n")
                    file.write("%s\n" % command)

                # Create files for stdout/stderr.
                stdout = open("genion.out", "w")
                stderr = open("genion.err", "w")

                # Run genion as a subprocess.
                proc = _subprocess.run(command,
                                       shell=True,
                                       stdout=stdout,
                                       stderr=stderr)
                stdout.close()
                stderr.close()

                # Check for the output GRO file.
                if not _os.path.isfile("solvated_ions.gro"):
                    if shell is None:
                        raise RuntimeError(
                            "'gmx genion' failed to add ions! Perhaps your box is too small?"
                        )
                    else:
                        is_break = True
                        _warnings.warn(
                            "Unable to achieve target ion concentration, try using "
                            "'box' option instead of 'shell'.")

                if not is_break:
                    # Counters for the number of SOL, NA, and CL atoms.
                    num_sol = 0
                    num_na = 0
                    num_cl = 0

                    # We now need to loop through the GRO file to extract the lines
                    # corresponding to water or ion atoms.
                    water_ion_lines = []

                    with open("solvated_ions.gro", "r") as file:
                        for line in file:
                            # This is a Sodium atom.
                            if _re.search("NA", line):
                                water_ion_lines.append(line)
                                num_na += 1

                            # This is a Chlorine atom.
                            if _re.search("CL", line):
                                water_ion_lines.append(line)
                                num_cl += 1

                            # This is a water atom.
                            elif _re.search("SOL", line):
                                water_ion_lines.append(line)
                                num_sol += 1

                    # Add any box information. This is the last line in the GRO file.
                    water_ion_lines.append(line)

                    # Write a GRO file that contains only the water and ion atoms.
                    if len(water_ion_lines) - 1 > 0:
                        with open("water_ions.gro", "w") as file:
                            file.write("BioSimSpace %s water box\n" %
                                       model.upper())
                            file.write("%d\n" % (len(water_ion_lines) - 1))

                            for line in water_ion_lines:
                                file.write("%s" % line)

                    # Ions have been added. Update the TOP file fo the water model
                    # with the new atom counts.
                    if num_na > 0 or num_cl > 0:
                        with open("water_ions.top", "w") as file:
                            file.write("#define FLEXIBLE 1\n\n")
                            file.write("; Include AmberO3 force field\n")
                            file.write(
                                '#include "amber03.ff/forcefield.itp"\n\n')
                            file.write("; Include %s water topology\n" %
                                       model.upper())
                            file.write('#include "amber03.ff/%s.itp"\n\n' %
                                       model)
                            file.write("; Include ions\n")
                            file.write('#include "amber03.ff/ions.itp"\n\n')
                            file.write("[ system ] \n")
                            file.write("BioSimSpace %s water box\n\n" %
                                       model.upper())
                            file.write("[ molecules ] \n")
                            file.write(";molecule name    nr.\n")
                            file.write("SOL               %d\n" %
                                       (num_sol / num_point))
                            if num_na > 0:
                                file.write("NA                %d\n" % num_na)
                            if num_cl > 0:
                                file.write("CL                %d\n" % num_cl)

                    # Load the water/ion box.
                    water_ions = _IO.readMolecules(
                        ["water_ions.gro", "water_ions.top"])

                    # Create a new system by adding the water to the original molecule.
                    if molecule is not None:

                        if type(molecule) is _System:
                            # Extract the non-water molecules from the original system.
                            non_waters = [
                                mol for mol in molecule.getMolecules()
                                if not mol.isWater()
                            ]

                            # Create a system by adding these to the water and ion
                            # molecules from gmx solvate, which will include the
                            # original waters.
                            system = _System(non_waters +
                                             water_ions.getMolecules())
                        else:
                            system = molecule + water_ions.getMolecules()

                        # Add all of the water molecules' properties to the new system.
                        for prop in water_ions._sire_system.propertyKeys():
                            prop = property_map.get(prop, prop)

                            # Add the space property from the water system.
                            system._sire_system.setProperty(
                                prop, water_ions._sire_system.property(prop))
                    else:
                        system = water_ions

        # Store the name of the water model as a system property.
        system._sire_system.setProperty("water_model", _SireBase.wrap(model))

    return system