Exemple #1
0
 def found(raise_error: bool = False) -> bool:
     """Whether adcc harness is ready for operation.
     Parameters
     ----------
     raise_error: bool
         Passed on to control negative return between False and ModuleNotFoundError raised.
     Returns
     -------
     bool
         If adcc and psi4 are found, returns True.
         If raise_error is False and adcc or psi4 is missing, returns False.
         If raise_error is True and adcc or psi4 are missing, the error message is raised.
     """
     found_adcc = which_import(
         "adcc",
         return_bool=True,
         raise_error=raise_error,
         raise_msg="Please install via `conda install adcc -c adcc`.",
     )
     found_psi4 = which_import(
         "psi4",
         return_bool=True,
         raise_error=raise_error,
         raise_msg=
         "Please install psi4 for adcc harness via `conda install psi4 -c psi4`.",
     )
     return found_adcc and found_psi4
Exemple #2
0
    def found(raise_error: bool = False) -> bool:
        # this harness requires RDKit as well, so this needs checking too
        rdkit_found = RDKitHarness.found(raise_error=raise_error)

        openff_found = which_import(
            "openforcefield",
            return_bool=True,
            raise_error=raise_error,
            raise_msg=
            "Please install via `conda install openforcefield -c omnia`.",
        )

        openmm_found = which_import(
            ".openmm",
            return_bool=True,
            raise_error=raise_error,
            package="simtk",
            raise_msg="Please install via `conda install openmm -c omnia`.",
        )

        openmmff_found = which_import(
            ".generators",
            return_bool=True,
            raise_error=raise_error,
            package="openmmforcefields",
            raise_msg=
            "Please install via `conda install openmmforcefields -c conda-forge`",
        )

        return rdkit_found and openff_found and openmm_found and openmmff_found
Exemple #3
0
    def found(raise_error: bool = False) -> bool:
        psithon = which("psi4", return_bool=True)
        psiapi = which_import("psi4", return_bool=True)

        if psithon and not psiapi:
            with popen([which("psi4"), "--module"]) as exc:
                exc["proc"].wait(timeout=30)
            if "module does not exist" in exc["stderr"]:
                pass
            else:
                sys.path.append(exc["stdout"].split()[-1])

        if psiapi and not psithon:
            psiimport = str(Path(which_import("psi4")).parent.parent)
            env = os.environ.copy()
            env["PYTHONPATH"] = psiimport
            with popen(
                ["python", "-c", "import psi4; print(psi4.executable[:-5])"],
                    popen_kwargs={"env": env}) as exc:
                exc["proc"].wait(timeout=30)
            os.environ["PATH"] += os.pathsep + exc["stdout"].split()[-1]

        if psithon or psiapi:
            return True

        return which(
            "psi4",
            return_bool=True,
            raise_error=raise_error,
            raise_msg="Please install via `conda install psi4 -c psi4`.",
        )
Exemple #4
0
    def is_available(cls) -> bool:
        """
        Check if any of the requested backend toolkits can be used.
        """
        if len(cls._toolkits) == 1:
            # the package needs a specific toolkit so raise the error
            raise_error = True
        else:
            raise_error = False

        for toolkit in cls._toolkits:
            if toolkit == "openeye":
                oe = which_import(
                    ".oechem",
                    package="openeye",
                    return_bool=True,
                    raise_error=raise_error,
                    raise_msg="Please install via `conda install openeye-toolkits -c openeye`.",
                )
                if oe:
                    return True
            elif toolkit == "rdkit":
                rdkit = which_import(
                    "rdkit",
                    return_bool=True,
                    raise_error=raise_error,
                    raise_msg="Please install via `conda install rdkit -c conda-forge`.",
                )
                if rdkit:
                    return True
        # if we are here both toolkits are missing
        raise ModuleNotFoundError(
            f"Openeye or RDKit is required to use this component please install via `conda install openeye-toolkits -c openeye` or `conda install rdkit -c conda-forge`."
        )
Exemple #5
0
 def is_available(cls) -> bool:
     """
     Make sure geometric and torsiondrive are installed.
     """
     geo = which_import(
         "geometric",
         return_bool=True,
         raise_error=True,
         raise_msg=
         "Please install via `conda install geometric -c conda-forge`.",
     )
     tdrive = which_import(
         "torsiondrive",
         return_bool=True,
         raise_error=True,
         raise_msg=
         "Please install via `conda install torsiondrive -c conda-forge`.",
     )
     engine = which_import(
         "qcengine",
         return_bool=True,
         raise_error=True,
         raise_msg=
         "Please install via `conda install qcengine -c conda-forge`.",
     )
     return geo and tdrive and engine
Exemple #6
0
def load_options(options):
    """Initialize program options defaults onto `options`."""

    load_qcdb_defaults(options)
    if which('xcfour') and which_import('psi4'):
        load_cfour_defaults_from_psi4(options)
    if which('nwchem'):
        load_nwchem_defaults(options)
    if which('rungms'):
        load_gamess_defaults(options)
    if which('psi4') and which_import('psi4'):
        load_psi4_defaults(options)
    if which_import('resp'):
        resp.load_defaults(nu_options)
Exemple #7
0
def template_helper(*args):
    """
    Store the _kind of object_ we want to I/O and _its dimensions_.
    But in practice, given one piece of information, we can deduce the other.
    If there's one dimension, it must be a Vector.
    If there are two dimensions, it must be written to disk as a Matrix.
    If it's a BlockedTensor, we can just read the dimensions.
    """
    template = []
    for arg in args:
        if isinstance(arg, core.Vector):
            template.append([arg.dimpi()])
        elif isinstance(arg, (core.Matrix, core.dpdfile2, core.dpdbuf4)):
            template.append([arg.rowdim(), arg.coldim()])
        elif isinstance(arg, float):
            template.append(float(0))
        elif which_import("ambit", return_bool=True):
            import ambit
            if isinstance(arg, ambit.BlockedTensor):
                template.append(ambit.BlockedTensor)
            else:
                raise TypeError("Unrecognized object type for DIIS.")
        else:
            raise TypeError("Unrecognized object type for DIIS.")

    return template
Exemple #8
0
 def found(raise_error: bool = False) -> bool:
     return which_import(
         "torchani",
         return_bool=True,
         raise_error=raise_error,
         raise_msg="Please install via `pip install torchani`.",
     )
Exemple #9
0
    def copier(self, x, new_name: str):
        """ Copy the object x and give it a new_name. Save it to disk if needed. """
        if isinstance(x, (core.Matrix, core.Vector)):
            copy = x.clone()
        elif isinstance(x, (core.dpdbuf4, core.dpdfile2)):
            copy = core.Matrix(x)
        elif isinstance(x, float):
            # Never cache a _number_.
            return x
        elif which_import("ambit", return_bool=True):
            import ambit
            if isinstance(x, ambit.BlockedTensor):
                copy = x.clone()
            else:
                raise TypeError("Unrecognized object type for DIIS.")
        else:
            raise TypeError("Unrecognized object type for DIIS.")
        copy.name = new_name

        if self.storage_policy == StoragePolicy.OnDisk:
            psio = core.IO.shared_object()
            if isinstance(copy, core.Vector):
                copy.save(psio, psif.PSIF_LIBDIIS)
            elif isinstance(copy, core.Matrix):
                copy.save(psio, psif.PSIF_LIBDIIS, core.SaveType.SubBlocks)
            elif isinstance(copy, ambit.BlockedTensor):
                filename = f"libdiis.{copy.name}"
                copy.save(filename)
                self.created_files.add(filename)
            else:
                raise TypeError("Unrecognized object type for DIIS. This shouldn't be possible.")
            copy = None

        return copy
Exemple #10
0
Fichier : pe.py Projet : qcdb/qcdb
def load_program_options(options: Keywords) -> None:
    """Initialize program keywords with defaults onto `options`."""

    load_qcdb_keywords(options)
    if which("xcfour"):
        load_cfour_keywords(options)
    if which("nwchem"):
        load_nwchem_keywords(options)
    if which("rungms"):
        load_gamess_keywords(options)
    if which("psi4") and which_import("psi4"):
        load_psi4_keywords(options)
    if which_import("resp_qcdb"):
        pass

        resp.load_keywords(nu_options)
Exemple #11
0
    def found(raise_error: bool=False) -> bool:
        is_found = which_import("torchani", return_bool=True)

        if not is_found and raise_error:
            raise ModuleNotFoundError("Could not find 'torchani' in the Python path. Please 'pip install torchani'.")

        return is_found
Exemple #12
0
 def found(self, raise_error: bool = False) -> bool:
     return which_import(
         'geometric',
         return_bool=True,
         raise_error=raise_error,
         raise_msg=
         'Please install via `conda install geometric -c conda-forge`.')
Exemple #13
0
 def found(raise_error: bool = False) -> bool:
     return which_import(
         "rdkit",
         return_bool=True,
         raise_error=raise_error,
         raise_msg="Please install via `conda install rdkit -c conda-forge`.",
     )
Exemple #14
0
def test_mbis_available():
    """MBIS should always be available with the latest version of psi4."""
    if which_import("psi4", return_bool=True, raise_error=False):
        assert MBISCharges.is_available() is True
    else:
        with pytest.raises(ModuleNotFoundError):
            MBISCharges.is_available()
Exemple #15
0
    def load_quantity(self, name, entry_num, item_num, force_new = True):
        """ Load quantity from wherever it's stored, constructing a new object if needed. """
        template_object = self.template[name][item_num]
        if isinstance(template_object, float) or self.storage_policy == StoragePolicy.InCore:
            quantity = self.stored_vectors[entry_num][name][item_num]
            try:
                quantity = quantity.clone()
            except AttributeError:
                # The quantity must have been a float. No need to clone.
                pass
        elif self.storage_policy == StoragePolicy.OnDisk:
            full_name = self.get_name(name, entry_num, item_num)
            psio = core.IO.shared_object()
            if hasattr(template_object, "__len__"):
                # Looks like we have dimensions.
                if len(template_object) == 2:
                    quantity = core.Matrix(full_name, *template_object)
                    quantity.load(psio, psif.PSIF_LIBDIIS, core.SaveType.SubBlocks)
                elif len(template_object) == 1:
                    quantity = core.Vector(full_name, *template_object)
                    quantity.load(psio, psif.PSIF_LIBDIIS)
            elif which_import("ambit", return_bool=True):
                import ambit
                if template_object == ambit.BlockedTensor:
                    quantity = ambit.BlockedTensor.load_and_build(f"libdiis.{full_name}")
        else:
            raise Exception(f"StoragePolicy {self.storage_policy} not recognized. This is a bug: contact developers.")

        return quantity
Exemple #16
0
    def found(raise_error: bool = False) -> bool:
        """Whether NWChem harness is ready for operation, with both the QC program and any particular dependencies found.

        Parameters
        ----------
        raise_error: bool
            Passed on to control negative return between False and ModuleNotFoundError raised.

        Returns
        -------
        bool
            If both nwchem and its harness dependency networkx are found, returns True.
            If raise_error is False and nwchem or networkx are missing, returns False.
            If raise_error is True and nwchem or networkx are missing, the error message for the first missing one is raised.

        """
        qc = which(
            "nwchem",
            return_bool=True,
            raise_error=raise_error,
            raise_msg=
            "Please install via http://www.nwchem-sw.org/index.php/Download",
        )

        dep = which_import(
            "networkx",
            return_bool=True,
            raise_error=raise_error,
            raise_msg=
            "For NWChem harness, please install via `conda install networkx -c conda-forge`.",
        )

        return qc and dep
Exemple #17
0
 def found(self, raise_error: bool = False) -> bool:
     return which_import(
         "berny",
         return_bool=True,
         raise_error=raise_error,
         raise_msg="Please install via `pip install pyberny`.",
     )
Exemple #18
0
    def found(raise_error: bool = False) -> bool:
        """Whether Psi4 harness is ready for operation.

        Parameters
        ----------
        raise_error: bool
            Passed on to control negative return between False and ModuleNotFoundError raised.

        Returns
        -------
        bool
            If psi4 (psithon or psiapi) is found, returns True.
            If raise_error is False and psi4 is missing, returns False.
            If raise_error is True and psi4 is missing, the error message is raised.

        """
        psithon = which("psi4", return_bool=True)
        psiapi = which_import("psi4", return_bool=True)

        if psithon and not psiapi:
            with popen([which("psi4"), "--module"]) as exc:
                exc["proc"].wait(timeout=30)
            if "module does not exist" in exc["stderr"]:
                pass  # --module argument only in Psi4 DDD branch
            else:
                sys.path.append(exc["stdout"].split()[-1])

        if psiapi and not psithon:
            psiimport = str(Path(which_import("psi4")).parent.parent)
            env = os.environ.copy()
            env["PYTHONPATH"] = psiimport
            with popen(
                ["python", "-c", "import psi4; print(psi4.executable[:-5])"],
                    popen_kwargs={"env": env}) as exc:
                exc["proc"].wait(timeout=30)
            os.environ["PATH"] += os.pathsep + exc["stdout"].split()[-1]

        if psithon or psiapi:
            return True

        return which(
            "psi4",
            return_bool=True,
            raise_error=raise_error,
            raise_msg=
            "Please install via `conda install psi4 -c psi4`. Check it's in your PATH with `which psi4`.",
        )
Exemple #19
0
 def is_available(cls) -> bool:
     qforce = which_import(
         "qforce",
         return_bool=True,
         raise_error=True,
         raise_msg="Please install via `pip install qforce`.",
     )
     return qforce
Exemple #20
0
 def found(self, raise_error: bool = False) -> bool:
     return which_import(
         "torsiondrive",
         return_bool=True,
         raise_error=raise_error,
         raise_msg=
         "Please install via `conda install torsiondrive -c conda-forge`.",
     )
Exemple #21
0
 def is_available(cls) -> bool:
     off = which_import(
         "openff.toolkit",
         return_bool=True,
         raise_error=True,
         raise_msg="Please install via `conda install openff-toolkit`.",
     )
     return off
Exemple #22
0
 def found(self, raise_error: bool = False) -> bool:
     return which_import(
         "qcore",
         return_bool=True,
         raise_error=raise_error,
         raise_msg=
         "Please install via `conda install py-qcore -c entos -c conda-forge`.",
     )
Exemple #23
0
 def found(self, raise_error: bool = False) -> bool:
     return which_import(
         "optking",
         return_bool=True,
         raise_error=raise_error,
         raise_msg=
         "Please install via `conda install optking -c psi4/label/dev`.",
     )
Exemple #24
0
 def is_available(cls) -> bool:
     """Make sure forcebalance can be imported."""
     fb = which_import(
         "forcebalance",
         return_bool=True,
         raise_error=True,
         raise_msg=
         "Please install via `conda install forcebalance -c conda-forge`.",
     )
     openmm = which_import(
         ".openmm",
         return_bool=True,
         raise_error=True,
         package="simtk",
         raise_msg=
         "Please install via `conda install openmm -c conda-forge`.",
     )
     return fb and openmm
Exemple #25
0
    def found(raise_error: bool = False) -> bool:
        is_found = which_import("rdkit", return_bool=True)

        if not is_found and raise_error:
            raise ModuleNotFoundError(
                "Could not find 'rdkit' in the Python path. Please 'conda install rdkit -c conda-forge'."
            )

        return is_found
Exemple #26
0
    def found(raise_error: bool = False) -> bool:
        """Check for the availability of the Python API of xtb"""

        return which_import(
            "xtb",
            return_bool=True,
            raise_error=raise_error,
            raise_msg="Please install via `conda install xtb-python -c conda-forge`.",
        )
Exemple #27
0
    def get_version(self) -> str:
        self.found(raise_error=True)

        which_prog = which_import('torchani')
        if which_prog not in self.version_cache:
            import torchani
            self.version_cache[which_prog] = safe_version(torchani.__version__)

        return self.version_cache[which_prog]
Exemple #28
0
    def found(raise_error: bool = False) -> bool:
        """Check for the availability of the Python API of dftd4"""

        return which_import(
            "dftd4",
            return_bool=True,
            raise_error=raise_error,
            raise_msg=
            "Please install via a dftd4 version with enabled Python API",
        )
Exemple #29
0
    def get_version(self) -> str:
        self.found(raise_error=True)

        which_prog = which_import("optking")
        if which_prog not in self.version_cache:
            import optking

            self.version_cache[which_prog] = safe_version(optking.__version__)

        return self.version_cache[which_prog]
Exemple #30
0
    def get_version(self) -> str:
        self.found(raise_error=True)

        which_prog = which_import("qcore")
        if which_prog not in self.version_cache:
            import qcore

            self.version_cache[which_prog] = safe_version(qcore.__version__)

        return self.version_cache[which_prog]
Exemple #31
0
def is_numpy_new_enough(version_feature_introduced):
    if not which_import('numpy', return_bool=True):
        return False
    import numpy
    return parse_version(numpy.version.version) >= parse_version(version_feature_introduced)
Exemple #32
0
def is_psi4_new_enough(version_feature_introduced):
    if not which_import('psi4', return_bool=True):
        return False
    import psi4
    return parse_version(psi4.__version__) >= parse_version(version_feature_introduced)
Exemple #33
0
    ------
    ModuleNotFoundError
        When `raises_error=True` and command not found.

    """
    lenv = (os.pathsep.join([os.path.abspath(x) for x in os.environ.get('PSIPATH', '').split(os.pathsep) if x != '']) +
            os.pathsep + os.environ.get('PATH', ''))

    return which(command=command, return_bool=return_bool, raise_error=raise_error, raise_msg=raise_msg, env=lenv)


_addons_ = {
    "ambit": _CMake_to_Py_boolean("@ENABLE_ambit@"),
    "chemps2": _CMake_to_Py_boolean("@ENABLE_CheMPS2@"),
    "dkh": _CMake_to_Py_boolean("@ENABLE_dkh@"),
    "libefp": which_import("pylibefp", return_bool=True),
    "erd": _CMake_to_Py_boolean("@ENABLE_erd@"),
    "gdma": _CMake_to_Py_boolean("@ENABLE_gdma@"),
    "pcmsolver": _CMake_to_Py_boolean("@ENABLE_PCMSolver@"),
    "simint": _CMake_to_Py_boolean("@ENABLE_simint@"),
    "dftd3": psi4_which("dftd3", return_bool=True),
    "cfour": psi4_which("xcfour", return_bool=True),
    "mrcc": psi4_which("dmrcc", return_bool=True),
    "gcp": psi4_which("gcp", return_bool=True),
    "v2rdm_casscf": which_import("v2rdm_casscf", return_bool=True),
    "gpu_dfcc": which_import("gpu_dfcc", return_bool=True),
    "forte": which_import("forte", return_bool=True),
    "snsmp2": which_import("snsmp2", return_bool=True),
    "resp": which_import("resp", return_bool=True),
}
Exemple #34
0
            return gpu_dfcc.cudaGetDeviceCount() > 0
    else:
        try:
            ngpu = len(GPUtil.getGPUs())
        except FileNotFoundError:
            # no `nvidia-smi`
            return False
        else:
            return ngpu > 0


hardware_nvidia_gpu = pytest.mark.skipif(is_nvidia_gpu_present() is False,
                                         reason='Psi4 not detecting Nvidia GPU via `nvidia-smi`. Install one')

using_memory_profiler = pytest.mark.skipif(
    which_import('memory_profiler', return_bool=True) is False,
    reason='Not detecting module memory_profiler. Install package if necessary and add to envvar PYTHONPATH')

using_psi4 = pytest.mark.skipif(
    False, reason='Not detecting module psi4. Install package if necessary and add to envvar PYTHONPATH')

using_qcdb = pytest.mark.skipif(
    True, reason='Not detecting common driver. Install package if necessary and add to envvar PYTHONPATH')

using_dftd3 = pytest.mark.skipif(
    which('dftd3', return_bool=True) is False,
    reason='Not detecting executable dftd3. Install package if necessary and add to envvar PATH or PSIPATH')

using_dftd3_321 = pytest.mark.skipif(is_dftd3_new_enough("3.2.1") is False,
                                     reason='DFTD3 does not include 3.2.1 features. Update package and add to PATH')