Пример #1
0
    def run(self) -> ElectronicStructureDriverResult:
        atoms = self._atoms
        charge = self._charge
        multiplicity = self._multiplicity
        units = self._units
        basis = self.basis
        method = self.method

        q_mol = compute_integrals(
            atoms=atoms,
            units=units.value,
            charge=charge,
            multiplicity=multiplicity,
            basis=basis.value,
            method=method.value,
            tol=self._tol,
            maxiters=self._maxiters,
        )

        q_mol.origin_driver_name = "PYQUANTE"
        cfg = [
            f"atoms={atoms}",
            f"units={units.value}",
            f"charge={charge}",
            f"multiplicity={multiplicity}",
            f"basis={basis.value}",
            f"method={method.value}",
            f"tol={self._tol}",
            f"maxiters={self._maxiters}",
            "",
        ]
        q_mol.origin_driver_config = "\n".join(cfg)

        return ElectronicStructureDriverResult.from_legacy_driver_result(q_mol)
Пример #2
0
    def run(self) -> ElectronicStructureDriverResult:
        cfg = self._config
        while not cfg.endswith("\n\n"):
            cfg += "\n"

        logger.debug(
            "User supplied configuration raw: '%s'",
            cfg.replace("\r", "\\r").replace("\n", "\\n"),
        )
        logger.debug("User supplied configuration\n%s", cfg)

        # To the Gaussian section of the input file passed here as section string
        # add line '# Symm=NoInt output=(matrix,i4labels,mo2el) tran=full'
        # NB: Line above needs to be added in right context, i.e after any lines
        #     beginning with % along with any others that start with #
        # append at end the name of the MatrixElement file to be written

        file, fname = tempfile.mkstemp(suffix=".mat")
        os.close(file)

        cfg = GaussianDriver._augment_config(fname, cfg)
        logger.debug("Augmented control information:\n%s", cfg)

        run_g16(cfg)

        q_mol = GaussianDriver._parse_matrix_file(fname)
        try:
            os.remove(fname)
        except Exception:  # pylint: disable=broad-except
            logger.warning("Failed to remove MatrixElement file %s", fname)

        q_mol.origin_driver_name = "GAUSSIAN"
        q_mol.origin_driver_config = cfg
        return ElectronicStructureDriverResult.from_legacy_driver_result(q_mol)
Пример #3
0
    def convert(self, replace: bool = False) -> None:
        """Converts a legacy QMolecule HDF5 file into the new Property-framework.

        Args:
            replace: if True, will replace the original HDF5 file. Otherwise `_new.hdf5` will be
                used as a suffix.

        Raises:
            LookupError: file not found.
        """
        hdf5_file = self._get_path()

        warnings.filterwarnings("ignore", category=DeprecationWarning)
        q_mol = QMolecule(hdf5_file)
        warnings.filterwarnings("default", category=DeprecationWarning)
        q_mol.load()

        new_hdf5_file = hdf5_file
        if not replace:
            new_hdf5_file = hdf5_file.with_name(
                str(hdf5_file.stem) + "_new.hdf5")

        warnings.filterwarnings("ignore", category=DeprecationWarning)
        driver_result = ElectronicStructureDriverResult.from_legacy_driver_result(
            q_mol)
        warnings.filterwarnings("default", category=DeprecationWarning)
        save_to_hdf5(driver_result, str(new_hdf5_file), replace=replace)
    def second_q_ops(self) -> ListOrDictType[SecondQuantizedOp]:
        """Returns the second quantized operators associated with this Property.

        If the arguments are returned as a `list`, the operators are in the following order: the
        Hamiltonian operator, total particle number operator, total angular momentum operator, total
        magnetization operator, and (if available) x, y, z dipole operators.

        The actual return-type is determined by `qiskit_nature.settings.dict_aux_operators`.

        Returns:
            A `list` or `dict` of `SecondQuantizedOp` objects.
        """
        driver_result = self.driver.run()

        if self._legacy_driver:
            self._molecule_data = cast(QMolecule, driver_result)
            self._grouped_property = ElectronicStructureDriverResult.from_legacy_driver_result(
                self._molecule_data)

            if self._legacy_transform:
                self._molecule_data_transformed = self._transform(
                    self._molecule_data)
                self._grouped_property_transformed = (
                    ElectronicStructureDriverResult.from_legacy_driver_result(
                        self._molecule_data_transformed))

            else:
                if not self.transformers:
                    # if no transformers are supplied, we can still provide
                    # `molecule_data_transformed` as a copy of `molecule_data`
                    self._molecule_data_transformed = self._molecule_data
                self._grouped_property_transformed = self._transform(
                    self._grouped_property)

        else:
            self._grouped_property = driver_result
            self._grouped_property_transformed = self._transform(
                self._grouped_property)

        second_quantized_ops = self._grouped_property_transformed.second_q_ops(
        )

        return second_quantized_ops
Пример #5
0
 def setUp(self):
     super().setUp()
     hdf5_file = self.get_resource_path(
         "test_driver_hdf5_legacy.hdf5",
         "drivers/second_quantization/hdf5d")
     # Using QMolecule directly here to avoid the deprecation on HDF5Driver.run method
     # to be triggered and let it be handled on the method test_convert
     # Those deprecation messages are shown only once and this one could prevent
     # the test_convert one to show if called first.
     molecule = QMolecule(hdf5_file)
     molecule.load()
     warnings.filterwarnings("ignore", category=DeprecationWarning)
     self.driver_result = ElectronicStructureDriverResult.from_legacy_driver_result(
         molecule)
     warnings.filterwarnings("default", category=DeprecationWarning)
 def setUp(self):
     super().setUp()
     self.good_check = GaussianDriver.check_installed
     GaussianDriver.check_installed = _check_installed
     # We can now create a driver without the installed (check valid) test failing
     # and create a qmolecule from the saved output matrix file. This will test the
     # parsing of it into the qmolecule is correct.
     g16 = GaussianDriver()
     matfile = self.get_resource_path(
         "test_driver_gaussian_from_mat.mat",
         "drivers/second_quantization/gaussiand")
     try:
         q_mol = g16._parse_matrix_file(matfile)
         self.driver_result = ElectronicStructureDriverResult.from_legacy_driver_result(
             q_mol)
     except QiskitNatureError:
         self.tearDown()
         self.skipTest("GAUSSIAN qcmatrixio not found")
Пример #7
0
    def run(self) -> GroupedSecondQuantizedProperty:
        """
        Returns:
            GroupedSecondQuantizedProperty re-constructed from the HDF5 file.

        Raises:
            LookupError: file not found.
            QiskitNatureError: if the HDF5 file did not contain a GroupedSecondQuantizedProperty.
        """
        hdf5_file = self._get_path()

        legacy_hdf5_file = False

        with h5py.File(hdf5_file, "r") as file:
            if "origin_driver" in file.keys():
                legacy_hdf5_file = True
                warn_deprecated(
                    "0.4.0",
                    DeprecatedType.METHOD,
                    "HDF5Driver.run with legacy HDF5 file",
                    additional_msg=
                    (". Your HDF5 file contains the legacy QMolecule object! You should consider "
                     "converting it to the new property framework. See also HDF5Driver.convert"
                     ),
                )

        if legacy_hdf5_file:
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            try:
                molecule = QMolecule(hdf5_file)
                molecule.load()
                return ElectronicStructureDriverResult.from_legacy_driver_result(
                    molecule)
            finally:
                warnings.filterwarnings("default", category=DeprecationWarning)

        driver_result = load_from_hdf5(str(hdf5_file))

        if not isinstance(driver_result, GroupedSecondQuantizedProperty):
            raise QiskitNatureError(
                f"Expected a GroupedSecondQuantizedProperty but found a {type(driver_result)} "
                "object instead.")

        return driver_result
Пример #8
0
    def run(self) -> ElectronicStructureDriverResult:
        """
        Returns:
            ElectronicStructureDriverResult re-constructed from the HDF5 file.

        Raises:
            LookupError: file not found.
        """
        hdf5_file = self._hdf5_input
        if self.work_path is not None and not os.path.isabs(hdf5_file):
            hdf5_file = os.path.abspath(os.path.join(self.work_path,
                                                     hdf5_file))

        if not os.path.isfile(hdf5_file):
            raise LookupError(f"HDF5 file not found: {hdf5_file}")

        warnings.filterwarnings("ignore", category=DeprecationWarning)
        molecule = QMolecule(hdf5_file)
        warnings.filterwarnings("default", category=DeprecationWarning)
        molecule.load()
        return ElectronicStructureDriverResult.from_legacy_driver_result(
            molecule)
Пример #9
0
    def run(self) -> ElectronicStructureDriverResult:
        cfg = self._config

        psi4d_directory = Path(__file__).resolve().parent
        template_file = psi4d_directory.joinpath("_template.txt")
        qiskit_nature_directory = psi4d_directory.parent.parent

        warnings.filterwarnings("ignore", category=DeprecationWarning)
        molecule = QMolecule()
        warnings.filterwarnings("default", category=DeprecationWarning)

        input_text = [cfg]
        input_text += ["import sys"]
        syspath = (
            "['"
            + qiskit_nature_directory.as_posix()
            + "','"
            + "','".join(Path(p).as_posix() for p in sys.path)
            + "']"
        )

        input_text += ["sys.path = " + syspath + " + sys.path"]
        input_text += ["import warnings"]
        input_text += ["from qiskit_nature.drivers.qmolecule import QMolecule"]
        input_text += ["warnings.filterwarnings('ignore', category=DeprecationWarning)"]
        input_text += [f'_q_molecule = QMolecule("{Path(molecule.filename).as_posix()}")']
        input_text += ["warnings.filterwarnings('default', category=DeprecationWarning)"]

        with open(template_file, "r", encoding="utf8") as file:
            input_text += [line.strip("\n") for line in file.readlines()]

        file_fd, input_file = tempfile.mkstemp(suffix=".inp")
        os.close(file_fd)
        with open(input_file, "w", encoding="utf8") as stream:
            stream.write("\n".join(input_text))

        file_fd, output_file = tempfile.mkstemp(suffix=".out")
        os.close(file_fd)
        try:
            PSI4Driver._run_psi4(input_file, output_file)
            if logger.isEnabledFor(logging.DEBUG):
                with open(output_file, "r", encoding="utf8") as file:
                    logger.debug("PSI4 output file:\n%s", file.read())
        finally:
            run_directory = os.getcwd()
            for local_file in os.listdir(run_directory):
                if local_file.endswith(".clean"):
                    os.remove(run_directory + "/" + local_file)
            try:
                os.remove("timer.dat")
            except Exception:  # pylint: disable=broad-except
                pass

            try:
                os.remove(input_file)
            except Exception:  # pylint: disable=broad-except
                pass

            try:
                os.remove(output_file)
            except Exception:  # pylint: disable=broad-except
                pass

        warnings.filterwarnings("ignore", category=DeprecationWarning)
        _q_molecule = QMolecule(molecule.filename)
        warnings.filterwarnings("default", category=DeprecationWarning)
        _q_molecule.load()
        # remove internal file
        _q_molecule.remove_file()
        _q_molecule.origin_driver_name = "PSI4"
        _q_molecule.origin_driver_config = cfg
        return ElectronicStructureDriverResult.from_legacy_driver_result(_q_molecule)