예제 #1
0
def run_json(json_data, clean=True):

    warnings.warn(
        "Using `psi4.schema_wrapper.run_json` or `psi4.json_wrapper.run_json` instead of `psi4.schema_wrapper.run_qcschema` is deprecated, and in 1.7 it will stop working\n",
        category=FutureWarning)

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(),
                           str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        p4util.set_memory(json_data["memory"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False
    json_data["provenance"] = {
        "creator": "Psi4",
        "version": __version__,
        "routine": "psi4.json_wrapper.run_json"
    }

    # Attempt to run the computer
    try:
        # qcschema should be copied
        json_data = run_json_qcschema(copy.deepcopy(json_data), clean, True)

    except Exception as exc:
        json_data["error"] = {
            'error_type': type(exc).__name__,
            'error_message':
            ''.join(traceback.format_exception(*sys.exc_info())),
        }
        json_data["success"] = False

        json_data["raw_output"] = _read_output(outfile)

    if return_output:
        json_data["raw_output"] = _read_output(outfile)

    atexit.register(_quiet_remove, outfile)

    return json_data
예제 #2
0
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(),
                           str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        # qcschema should be copied
        json_data = run_json_qcschema(copy.deepcopy(json_data), clean)

    except Exception as exc:
        json_data["error"] = {
            'error_type': type(exc).__name__,
            'error_message':
            ''.join(traceback.format_exception(*sys.exc_info())),
        }
        json_data["success"] = False

        json_data["raw_output"] = _read_output(outfile)

    if return_output:
        json_data["raw_output"] = _read_output(outfile)

    # Destroy the created file at exit
    def _quiet_remove(filename):
        try:
            os.unlink(filename)
        except OSError:
            pass

    atexit.register(_quiet_remove, outfile)

    return json_data
예제 #3
0
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        # qcschema should be copied
        json_data = run_json_qcschema(copy.deepcopy(json_data), clean)

    except Exception as exc:
        json_data["error"] = {
            'error_type': type(exc).__name__,
            'error_message': ''.join(traceback.format_exception(*sys.exc_info())),
        }
        json_data["success"] = False

        json_data["raw_output"] = _read_output(outfile)


    if return_output:
        json_data["raw_output"] = _read_output(outfile)

    # Destroy the created file at exit
    def _quiet_remove(filename):
        try:
            os.unlink(filename)
        except OSError:
            pass

    atexit.register(_quiet_remove, outfile)

    return json_data
예제 #4
0
def run_qcschema(input_data, clean=True):

    outfile = os.path.join(core.IOManager.shared_object().get_default_path(),
                           str(uuid.uuid4()) + ".qcschema_tmpout")
    core.set_output_file(outfile, False)
    print_header()
    start_time = datetime.datetime.now()

    try:
        input_model = qcng.util.model_wrapper(input_data,
                                              qcel.models.AtomicInput)

        keep_wfn = input_model.protocols.wavefunction != 'none'

        # qcschema should be copied
        ret_data = run_json_qcschema(input_model.dict(),
                                     clean,
                                     False,
                                     keep_wfn=keep_wfn)
        ret_data["provenance"] = {
            "creator": "Psi4",
            "version": __version__,
            "routine": "psi4.schema_runner.run_qcschema"
        }

        exit_printing(start_time=start_time, success=True)

        ret = qcel.models.AtomicResult(**ret_data,
                                       stdout=_read_output(outfile))

    except Exception as exc:

        if not isinstance(input_data, dict):
            input_data = input_data.dict()

        input_data = input_data.copy()
        input_data["stdout"] = _read_output(outfile)
        ret = qcel.models.FailedOperation(
            input_data=input_data,
            success=False,
            error={
                'error_type':
                type(exc).__name__,
                'error_message':
                ''.join(traceback.format_exception(*sys.exc_info())),
            })

    atexit.register(_quiet_remove, outfile)

    return ret
예제 #5
0
파일: json_wrapper.py 프로젝트: wdong5/psi4
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])


    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        if json_data.get("schema_name", "").startswith("qc_schema"):
            # qc_schema should be copied
            json_data = run_json_qc_schema(copy.deepcopy(json_data), clean)
        else:
            # Original run updates inplace
            run_json_original_v1_1(json_data, clean)

    except Exception as error:
        json_data["error"] = repr(error)
        json_data["success"] = False

    if return_output:
        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()
        atexit.register(os.unlink, outfile)

    return json_data
예제 #6
0
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        # qc_schema should be copied
        json_data = run_json_qc_schema(copy.deepcopy(json_data), clean)

    except Exception as error:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        json_data["error"] = repr(traceback.format_exception(exc_type, exc_value,
                                          exc_traceback))
        json_data["success"] = False

        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()

    if return_output:
        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()
        atexit.register(os.unlink, outfile)

    return json_data
예제 #7
0
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Direct output
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out")
    core.set_output_file(outfile, False)

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])


    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        if json_data.get("schema_name", "").startswith("qc_schema"):
            # qc_schema should be copied
            json_data = run_json_qc_schema(copy.deepcopy(json_data), clean)
        else:
            # Original run updates inplace
            run_json_original_v1_1(json_data, clean)

    except Exception as error:
        json_data["error"] = repr(error)
        json_data["success"] = False

    if return_output:
        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()
        os.unlink(outfile)

    return json_data
예제 #8
0
def run_json(json_data, clean=True):

    # Set scratch
    if "scratch_location" in json_data:
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Set memory
    if "memory" in json_data:
        psi4.set_memory(json_data["memory"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        outfile = os.path.join(
            core.IOManager.shared_object().get_default_path(),
            str(uuid.uuid4()) + ".json_out")
        core.set_output_file(outfile, False)
        json_data["raw_output"] = "Not yet run."

    # Set a few flags
    json_data["raw_output"] = None
    json_data["success"] = False

    # Attempt to run the computer
    try:
        if ("schema_name" in json_data) and (json_data["schema_name"]
                                             == "QC_JSON"):
            run_json_qc_schema(json_data, clean)
        else:
            run_json_original_v1_1(json_data, clean)

    except Exception as error:
        json_data["error"] = repr(error)
        json_data["success"] = False

    if return_output:
        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()
        os.unlink(outfile)

    return json_data
예제 #9
0
def run_qcschema(
    input_data: Union[Dict[str, Any], qcel.models.AtomicInput],
    clean: bool = True,
    postclean: bool = True
) -> Union[qcel.models.AtomicResult, qcel.models.FailedOperation]:
    """Run a quantum chemistry job specified by :py:class:`qcelemental.models.AtomicInput` **input_data** in |PSIfour|.

    Parameters
    ----------
    input_data
        Quantum chemistry job in either AtomicInput class or dictionary form.
    clean
        Reset global QCVariables, options, and scratch files to default state.
    postclean
        When ``False``, *remove* the output file since absorbed into AtomicResult.
        When ``True``, simply *close* the output file. True is useful when calling
        from a Psi4 session to avoid removing the parent Psi4's output file.

    Returns
    -------
    qcelemental.models.AtomicResult
        Full record of quantum chemistry calculation, including output text. Returned upon job success.
    qcelemental.models.FailedOperation
        Record to diagnose calculation failure, including output text and input specification. Returned upon job failure.

    """
    outfile = os.path.join(core.IOManager.shared_object().get_default_path(),
                           str(uuid.uuid4()) + ".qcschema_tmpout")
    core.set_output_file(outfile, False)
    print_header()

    start_time = datetime.datetime.now()

    try:
        input_model = qcng.util.model_wrapper(input_data,
                                              qcel.models.AtomicInput)

        # Echo the infile on the outfile
        core.print_out("\n  ==> Input QCSchema <==\n")
        core.print_out(
            "\n--------------------------------------------------------------------------\n"
        )
        core.print_out(pp.pformat(json.loads(input_model.json())))
        core.print_out(
            "\n--------------------------------------------------------------------------\n"
        )

        keep_wfn = input_model.protocols.wavefunction != 'none'

        # qcschema should be copied
        ret_data = run_json_qcschema(input_model.dict(),
                                     clean,
                                     False,
                                     keep_wfn=keep_wfn)
        ret_data["provenance"].update({
            "creator":
            "Psi4",
            "version":
            __version__,
            "routine":
            "psi4.schema_runner.run_qcschema"
        })
        ret_data["native_files"]["input"] = json.dumps(json.loads(
            input_model.json()),
                                                       indent=1)

        exit_printing(start_time=start_time, success=True)

        ret = qcel.models.AtomicResult(**ret_data,
                                       stdout=_read_output(outfile))

    except Exception as exc:

        if not isinstance(input_data, dict):
            input_data = input_data.dict()

        input_data = input_data.copy()
        input_data["stdout"] = _read_output(outfile)
        ret = qcel.models.FailedOperation(
            input_data=input_data,
            success=False,
            error={
                'error_type':
                type(exc).__name__,
                'error_message':
                ''.join(traceback.format_exception(*sys.exc_info())),
            })

    _clean_psi_output(postclean, outfile)

    return ret
예제 #10
0
def run_json(json_data):
    """
    Runs and updates the input JSON data.

    Parameters
    ----------
    json_data : JSON input
        Required input fields:
            - molecule : str
                A string representation of the molecule. Any valid psi4 synatx is valid.
            - driver : str
                The driver method to use valid arguments are "energy", "gradient", "property"
            - args : str
                Input arguments to the driver function
            - kwargs : dict
                Input dictionary to the driver function

        Optional input fields:
            - kwargs : dict
                Additional kwargs to be passed to the driver.
            - options : dict
                Global options to set in the Psi4 run.
            - scratch_location : str
                Overide the default scratch location.
            - return_output : bool
                Return the full string reprsentation of the output or not.

        Output fields:
            - return_value : float, psi4.core.Vector, psi4.core.Matrix
                The return value of the input function.
            - variables : dict
                The list of Psi4 variables generated from the run.
            - success : bool
                Indicates if the run was successful or not.
            - error : str
                If an error is raised the result is returned here.
            - raw_output : str
                The full Psi4 output if requested.


    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/psi4/psi4.

    Examples
    --------

    # CP corrected Helium dimer energy in the STO-3G basis.
    >>> json_data = {}

    >>> json_data["molecule"] = "He 0 0 0\n--\nHe 0 0 1"
    >>> json_data["driver"] = "energy"
    >>> json_data["method"] = 'SCF'
    >>> json_data["kwargs"] = {"bsse_type": "cp"}
    >>> json_data["options"] = {"BASIS": "STO-3G"}

    >>> run_json(json_data)
    {
        "raw_output": "Output storing was not requested.",
        "options": {
            "BASIS": "STO-3G"
        },
        "driver": "energy",
        "molecule": "He 0 0 0\n--\nHe 0 0 1",
        "method": "SCF",
        "variables": {
            "SCF N ITERS": 2.0,
            "SCF DIPOLE Y": 0.0,
            "CURRENT DIPOLE Y": 0.0,
            "CP-CORRECTED 2-BODY INTERACTION ENERGY": 0.1839360538612116,
            "HF TOTAL ENERGY": -5.433191881443323,
            "SCF TOTAL ENERGY": -5.433191881443323,
            "TWO-ELECTRON ENERGY": 4.124089347186247,
            "SCF ITERATION ENERGY": -5.433191881443323,
            "CURRENT DIPOLE X": 0.0,
            "CURRENT DIPOLE Z": 0.0,
            "CURRENT REFERENCE ENERGY": -5.433191881443323,
            "CURRENT ENERGY": 0.1839360538612116,
            "COUNTERPOISE CORRECTED TOTAL ENERGY": -5.433191881443323,
            "SCF DIPOLE Z": 0.0,
            "COUNTERPOISE CORRECTED INTERACTION ENERGY": 0.1839360538612116,
            "NUCLEAR REPULSION ENERGY": 2.11670883436,
            "SCF DIPOLE X": 0.0,
            "ONE-ELECTRON ENERGY": -11.67399006298957
        },
        "return_value": 0.1839360538612116,
        "error": "",
        "success": true,
        "provenance": {
            "creator": "Psi4",
            "routine": "psi4.run_json",
            "version": "1.1a1"
        },
        "kwargs": {
            "bsse_type": "cp"
        }
    }
    """

    # Set a few variables
    json_data["error"] = ""
    json_data["raw_output"] = "Output storing was not requested."
    json_data["success"] = False
    json_data["raw_output"] = None

    # Check input
    for check in ["driver", "method", "molecule"]:
        if check not in list(json_data):
            json_data["error"] = "Minimum input requires the %s field." % check
            return json_data

    # Check driver call
    if json_data["driver"] not in list(methods_dict):
        json_data["error"] = "Driver parameters '%s' not recognized" % str(json_data["driver"])
        return json_data


    # Set scratch
    if "scratch_location" in list(json_data):
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Set memory
    if "memory" in list(json_data):
        psi4.core.set_memory(int(json_data["memory"]))

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        outfile = str(uuid.uuid4()) + ".json_out"
        core.set_output_file(outfile, False)
        json_data["raw_output"] = "Not yet run."

    try:
        # Set options
        if "options" in json_data.keys() and (json_data["options"] is not None):
            for k, v in json_data["options"].items():
                core.set_global_option(k, v)

        # Rework args
        args = json_data["method"]
        if not isinstance(args, (list, tuple)):
            args = [args]

        # Deep copy kwargs
        if "kwargs" in list(json_data):
            kwargs = copy.deepcopy(json_data["kwargs"])
        else:
            kwargs = {}

        kwargs["molecule"] = molutil.geometry(json_data["molecule"])

        # Full driver call
        kwargs["return_wfn"] = True

        val, wfn = methods_dict[json_data["driver"]](*args, **kwargs)

        if isinstance(val, (float)):
            json_data["return_value"] = val
        elif isinstance(val, (core.Matrix, core.Vector)):
            json_data["return_value"] = val.to_serial()
        else:
            json_data["error"] += "Unrecognized return value of type %s\n" % type(val)
            json_data["return_value"] = val

        json_data["variables"] = core.get_variables()
        json_data["success"] = True

        prov = {}
        prov["version"] = psi4.__version__
        prov["routine"] = "psi4.run_json"
        prov["creator"] = "Psi4"
        json_data["provenance"] = prov

    except Exception as error:
        json_data["error"] += repr(error)
        json_data["success"] = False

    if return_output:
        with open(outfile, 'r') as f:
            json_data["raw_output"] = f.read()
        os.unlink(outfile)

    return json_data
예제 #11
0
    def compute(self, client: Optional["FractalClient"] = None):
        """Run quantum chemistry."""
        from psi4.driver import pp

        if self.computed:
            return

        if client:
            self.computed = True
            from qcportal.models import KeywordSet, Molecule

            # Build the keywords
            keyword_id = client.add_keywords(
                [KeywordSet(values=self.keywords)])[0]

            # Build the molecule
            mol = Molecule(**self.molecule.to_schema(dtype=2))

            r = client.add_compute("psi4", self.method, self.basis,
                                   self.driver, keyword_id, [mol])
            self.result_id = r.ids[0]
            # NOTE: The following will re-run errored jobs by default
            if self.result_id in r.existing:
                ret = client.query_tasks(base_result=self.result_id)
                if ret:
                    if ret[0].status == "ERROR":
                        client.modify_tasks("restart",
                                            base_result=self.result_id)
                        logger.info("Resubmitting Errored Job {}".format(
                            self.result_id))
                    elif ret[0].status == "COMPLETE":
                        logger.debug("Job already completed {}".format(
                            self.result_id))
                else:
                    logger.debug("Job already completed {}".format(
                        self.result_id))
            else:
                logger.debug("Submitting AtomicResult {}".format(
                    self.result_id))

            return

        logger.info(
            f'<<< JSON launch ... {self.molecule.schoenflies_symbol()} {self.molecule.nuclear_repulsion_energy()}'
        )
        gof = core.get_output_file()

        # EITHER ...
        # from psi4.driver import schema_wrapper
        # self.result = schema_wrapper.run_qcschema(self.plan())
        # ... OR ...
        self.result = qcng.compute(
            self.plan(),
            "psi4",
            raise_error=True,
            # local_options below suitable for serial mode where each job takes all the resources of the parent Psi4 job.
            #   distributed runs through QCFractal will likely need a different setup.
            local_options={
                # B -> GiB
                "memory": core.get_memory() / (2**30),
                "ncores": core.get_num_threads(),
            },
        )
        # ... END

        #pp.pprint(self.result.dict())
        #print("... JSON returns >>>")
        core.set_output_file(gof, True)
        core.reopen_outfile()
        logger.debug(pp.pformat(self.result.dict()))
        core.print_out(_drink_filter(self.result.dict()["stdout"]))
        self.computed = True
예제 #12
0
def run_json(json_data):
    """
    Runs and updates the input JSON data.

    Parameters
    ----------
    json_data : JSON input
        Required input fields:
            - molecule : str
                A string representation of the molecule. Any valid psi4 synatx is valid.
            - driver : str
                The driver method to use valid arguments are "energy", "gradient", "property"
            - args : str
                Input arguments to the driver function
            - kwargs : dict
                Input dictionary to the driver function

        Optional input fields:
            - kwargs : dict
                Additional kwargs to be passed to the driver.
            - options : dict
                Global options to set in the Psi4 run.
            - scratch_location : str
                Overide the default scratch location.
            - return_output : bool
                Return the full string reprsentation of the output or not.

        Output fields:
            - return_value : float, psi4.core.Vector, psi4.core.Matrix
                The return value of the input function.
            - variables : dict
                The list of Psi4 variables generated from the run.
            - success : bool
                Indicates if the run was successful or not.
            - error : str
                If an error is raised the result is returned here.
            - output : str
                The full Psi4 output if requested.


    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/psi4/psi4.

    Examples
    --------

    # CP corrected Helium dimer energy in the STO-3G basis.
    >>> json_data = {}

    >>> json_data["molecule"] = "He 0 0 0\n--\nHe 0 0 1"
    >>> json_data["driver"] = "energy"
    >>> json_data["args"] = 'SCF'
    >>> json_data["kwargs"] = {"bsse_type": "cp"}
    >>> json_data["options"] = {"BASIS": "STO-3G"}

    >>> run_json(json_data)
    {'status': 'finished', 'success': True, 'kwargs': {'bsse_type': 'cp'},
     'molecule': 'He 0 0 0\n--\nHe 0 0 1', 'variables': {u'CURRENT REFERENCE
     ENERGY': -5.433191881443323, u'HF TOTAL ENERGY': -5.433191881443323, u'CURRENT
     DIPOLE Z': 0.0, u'COUNTERPOISE CORRECTED INTERACTION ENERGY':
     0.1839360538612116, u'CURRENT DIPOLE X': 0.0, u'CURRENT DIPOLE Y': 0.0,
     u'NUCLEAR REPULSION ENERGY': 2.11670883436, u'TWO-ELECTRON ENERGY':
     4.124089347186247, u'SCF ITERATION ENERGY': -5.433191881443323, u'CP-CORRECTED
     2-BODY INTERACTION ENERGY': 0.1839360538612116, u'SCF DIPOLE Y': 0.0,
     u'COUNTERPOISE CORRECTED TOTAL ENERGY': -5.433191881443323, u'CURRENT ENERGY':
     0.1839360538612116, u'SCF TOTAL ENERGY': -5.433191881443323, u'SCF DIPOLE Z':
     0.0, u'ONE-ELECTRON ENERGY': -11.67399006298957, u'SCF DIPOLE X': 0.0}, 'args':
     'SCF', 'driver': 'energy', 'return_value': 0.1839360538612116, 'error': '',
     'output': '', 'options': {'BASIS': 'STO-3G'}}
    """

    # Set a few variables
    json_data["error"] = ""
    json_data["output"] = ""

    # Check input
    for check in ["driver", "args", "molecule"]:
        if check not in list(json_data):
            json_data["error"] = "Minimum input requires the %s field." % check
            return False

    if json_data["driver"] not in list(methods_dict):
        json_data["error"] = "Driver parameters '%s' not recognized" % str(
            json_data["driver"])
        return False

    if "scratch_location" in list(json_data):
        psi4_io = core.IOManager.shared_object()
        psi4_io.set_default_path(json_data["scratch_location"])

    # Do we return the output?
    return_output = json_data.pop("return_output", False)
    if return_output:
        outfile = str(uuid.uuid4()) + ".json_out"
        core.set_output_file(outfile, False)
        json_data["output"] = "Not yet run."

    try:
        # Set options
        if "options" in json_data.keys() and (json_data["options"]
                                              is not None):
            for k, v in json_data["options"].items():
                core.set_global_option(k, v)

        # Rework args
        args = json_data["args"]
        if not isinstance(args, (list, tuple)):
            args = [args]

        # Deep copy kwargs
        if "kwargs" in list(json_data):
            kwargs = copy.deepcopy(json_data["kwargs"])
            kwargs["molecule"] = molutil.geometry(json_data["molecule"])
        else:
            kwargs = {}

        # Full driver call
        kwargs["return_wfn"] = True

        val, wfn = methods_dict[json_data["driver"]](*args, **kwargs)

        if isinstance(val, (float)):
            json_data["return_value"] = val
        elif isinstance(val, (core.Matrix, core.Vector)):
            json_data["return_value"] = val.to_serial()
        else:
            json_data[
                "error"] += "Unrecognized return value of type %s\n" % type(
                    val)
            json_data["return_value"] = val

        json_data["variables"] = core.get_variables()
        json_data["success"] = True

    except Exception as error:
        json_data["error"] += repr(error)
        json_data["success"] = False

    if return_output:
        with open(outfile, 'r') as f:
            json_data["output"] = f.read()
        os.unlink(outfile)

    return json_data
예제 #13
0
파일: core.py 프로젝트: hrgrimsl/spock
    def run_psi4(self):
        core.set_output_file(self.output + '.dat')
        import psi4
        psi4.set_memory('1 GB')
        psi_molecule = psi4.geometry(self.psi_geom)
        psi4.set_options({
            'basis': self.basis,
            'molden_write': False,
            'WRITER_FILE_LABEL': str(self.output) + '.dat',
            'maxiter': 500,
            'fail_on_maxiter': False
        })
        if self.multiplicity != 1:
            psi4.set_options({'reference': 'ROHF'})

        e, wfn = psi4.energy('scf', return_wfn=True)
        self.molecule.hf_energy = e
        if os.path.exists('./scr.molden'):
            os.system('rm scr.molden')
        if self.active != None:
            cb = wfn.Cb().to_array()
            ca = wfn.Ca().to_array()
            self.molecule.n_orbitals = len(ca)
            ca[:, self.active + self.reorder] = ca[:,
                                                   self.reorder + self.active]
            cb[:, self.active + self.reorder] = cb[:,
                                                   self.reorder + self.active]
            if self.loc == 'True':
                acs = psi4.core.Matrix('null')
                acs = acs.from_array(ca[:, self.active])
                Local = psi4.core.Localizer.build("BOYS", wfn.basisset(), acs)
                Local.localize()
                acs = Local.L
                ca[:, self.active] = acs
                acs2 = psi4.core.Matrix('null2')
                acs2 = acs2.from_array(cb[:, self.active])
                Local = psi4.core.Localizer.build("BOYS", wfn.basisset(), acs2)
                Local.localize()
                acs2 = Local.L
                cb[:, self.active] = acs2
            ca = psi4.core.Matrix.from_array(ca)
            cb = psi4.core.Matrix.from_array(cb)
            wfn.Cb().copy(cb)
            wfn.Ca().copy(ca)
            psi4.molden(wfn, 'scr.molden')
            psi4.set_options({'frozen_docc': [self.n_fdoccs]})
            self.n_fnoccs = self.molecule.n_orbitals - self.n_fdoccs - len(
                self.active)
            psi4.set_options({'frozen_uocc': [self.n_fnoccs]})
            self.CASCI = psi4.energy('fci', ref_wfn=wfn)
            self.molecule.CASCI = self.CASCI
            self.fci_energy = self.CASCI
            self.molecule.fci_energy = self.CASCI
        else:
            self.CASCI = psi4.energy('fci', ref_wfn=wfn)
            self.molecule.CASCI = self.CASCI
            self.fci_energy = self.CASCI
            self.molecule.fci_energy = self.CASCI
            self.molecule.n_orbitals = len(wfn.Ca().to_array())
            psi4.molden(wfn, 'scr.molden')
        self.molecule.nuclear_repulsion = psi_molecule.nuclear_repulsion_energy(
        )
        self.molecule.canonical_orbitals = np.asarray(wfn.Ca())
        if self.active == None:
            self.active = [i for i in range(0, self.molecule.n_orbitals)]
        self.molecule.overlap_integrals = np.asarray(wfn.S())
        self.molecule.n_qubits = 2 * self.molecule.n_orbitals
        self.molecule.orbital_energies = np.asarray(wfn.epsilon_a())
        self.molecule.fock_matrix = np.asarray(wfn.Fa())
        mints = psi4.core.MintsHelper(wfn.basisset())
        self.molecule.one_body_integrals = general_basis_change(
            np.asarray(mints.ao_kinetic()), self.molecule.canonical_orbitals,
            (1, 0))
        self.molecule.one_body_integrals += general_basis_change(
            np.asarray(mints.ao_potential()), self.molecule.canonical_orbitals,
            (1, 0))
        two_body_integrals = np.asarray(mints.ao_eri())
        two_body_integrals.reshape(
            (self.molecule.n_orbitals, self.molecule.n_orbitals,
             self.molecule.n_orbitals, self.molecule.n_orbitals))
        two_body_integrals = np.einsum('psqr', two_body_integrals)
        two_body_integrals = general_basis_change(
            two_body_integrals, self.molecule.canonical_orbitals, (1, 1, 0, 0))
        self.molecule.two_body_integrals = two_body_integrals
        doccs = [i for i in range(0, self.n_fdoccs)]

        if self.active != None:
            self.molecule.n_orbitals = len(self.active)
            self.molecule.n_qubits = 2 * self.molecule.n_orbitals
        else:
            self.molecule.n_orbitals = len(self.molecule.canonical_orbitals)
            self.molecule.n_qubits = 2 * self.molecule.n_orbitals
        self.molecule.n_fdoccs = self.n_fdoccs
        self.molecule.hamiltonian = self.molecule.get_molecular_hamiltonian(
            occupied_indices=doccs, active_indices=self.active)
        self.molecule.save()
        return self.molecule
    def pre_processing(self):
        """
        Process local run dictionary to create the input directory and identify
        the command to be passed

        Returns:
            :py:class:`dict`: dictionary containing the command to be passed to
            :meth:`process_run`
        """
        from psi4 import set_options, energy, optimize, frequency
        from psi4.core import set_output_file
        from BigDFT.Systems import System
        from os.path import join

        # Check Arguments
        try:
            self.sys = self.run_options["sys"]
        except KeyError:
            raise ValueError("sys= must be provided as an argument")

        try:
            action = self.run_options["action"]
        except KeyError:
            raise ValueError("You must specify a valid action=(energy,"
                             " optimize, frequency")

        try:
            method = self.run_options["method"]
        except KeyError:
            raise ValueError("You must specify an ab initio method=")

        try:
            basis = self.run_options["basis"]
        except KeyError:
            raise ValueError("You must specify a basis=")

        # Run directory
        self._ensure_run_directory()

        # Check skip
        if self.run_options["skip"]:
            try:
                log = PSI4Logfile(self.sys, self._get_logname(True),
                                  action, method)
                return {"command": None}
            except ValueError:  # invalid logfile, so we can't skip.
                pass
            except IOError:  # no logfile, so we can't skip.
                pass

        # Convert system
        if "sapt" in method:
            keys = list(self.sys)
            if len(keys) != 2:
                raise ValueError("For SAPT method, your system must be"
                                 " composed of exactly two fragments.")
            sysA = System()
            sysA[keys[0]] = self.sys[keys[0]]
            sysB = System()
            sysB[keys[1]] = self.sys[keys[1]]
            mol = bigdft_to_psi4(sysA=sysA, sysB=sysB)
        else:
            mol = bigdft_to_psi4(sysA=self.sys)

        # Set extra options.
        if "psi4_options" in self.run_options:
            set_options(self.run_options["psi4_options"])
        set_output_file(self._get_logname(True), False)

        # Instead of a command, we return a closure.
        if action == "energy":
            def cmd(method, mol):
                energy(method, molecule=mol)
        elif action == "optimize":
            def cmd(method, mol):
                optimize(method, molecule=mol)
        elif action == "frequency":
            def cmd(method, mol):
                frequency(method, molecule=mol)

        return {"command": cmd(join(method, basis), mol)}