示例#1
0
def run(job, runner=None, path=None, folder=None, **kwargs):
    """
    Pickup a runner and initialize it.

    :params job: computation to run
    :type job: Promise Object
    :param runner: Type of runner to use
    :type runner: String
    """

    initialize = False
    try:
        config = builtins.config
        if path and os.path.abspath(path) != config.jm.path or \
                folder and folder != config.jm.folder:
            msg = "Reinitializing Plams with new path and/or folder name.\n"
            warn(msg)
            plams.finish()
            plams.init(path=path, folder=folder)
    except AttributeError:
        plams.init(path=path, folder=folder)
        initialize = True
    builtins.config.log.stdout = 0
    builtins.config.jobmanager.jobfolder_exists = 'rename'
    if runner is None:
        ret = call_default(job, **kwargs)
    # elif runner.lower() == 'xenon':
    #     ret = call_xenon(job, **kwargs)
    else:
        raise "Don't know runner: {}".format(runner)
    if initialize:
        plams.finish()
    return ret
示例#2
0
文件: utils.py 项目: mrauha/qmflows
 def wrapper(*args, **kwargs):
     if not plams.config:
         plams.init()
     plams.config.log.stdout = 0
     result = fun(*args, **kwargs)
     plams.finish()
     return result
示例#3
0
 def wrapper(*args, **kwargs):
     try:
         builtins.config
     except AttributeError:
         plams.init()
     builtins.config.log.stdout = 0
     result = fun(*args, **kwargs)
     plams.finish()
     return result
示例#4
0
    def run(self):
        folder = time.strftime("[%H:%M](%d-%m-%Y)", time.localtime())

        plams.init(path=self.run_path, folder=folder)

        kffiles = []
        for job in self.jobs:
            res = job.run(False)
            kffiles.append(res.KFPATH)

        plams.finish()

        return kffiles
示例#5
0
def run(job, runner=None, path=None, folder=None, **kwargs):
    """
    Pickup a runner and initialize it.

    :params job: computation to run
    :type job: Promise Object
    :param runner: Type of runner to use
    :type runner: String
    """
    plams.init(path=path, folder=folder)
    plams.config.log.stdout = 0

    if runner is None:
        ret = call_default(job, kwargs.get('n_processes', 1))
    else:
        raise "Don't know runner: {}".format(runner)

    plams.finish()

    return ret
示例#6
0
def test_restart_init() -> None:
    """Tests for :func:`restart_init` and :class:`RestartInit`."""
    workdir = PATH / 'plams_workdir'
    try:
        init(PATH)
        finish()
        assertion.isdir(workdir)

        init_restart(PATH)
        assertion.isdir(workdir)
        assertion.isdir(f'{workdir}.002', invert=True)
        finish()

        with InitRestart(PATH):
            assertion.isdir(workdir)
            assertion.isdir(f'{workdir}.002', invert=True)

    finally:
        shutil.rmtree(workdir) if isdir(workdir) else None
        shutil.rmtree(f'{workdir}.002') if isdir(f'{workdir}.002') else None
示例#7
0
def run(job, runner=None, path=None, folder=None, **kwargs):
    """
    Pickup a runner and initialize it.

    :params job: computation to run
    :type job: Promise Object
    :param runner: Type of runner to use
    :type runner: String
    """
    plams.init(path=path, folder=folder)
    plams.config.log.stdout = 0

    if runner is None:
        ret = call_default(job, kwargs.get('n_processes', 1),
                           kwargs.get('always_cache', True))
    else:
        raise "Don't know runner: {}".format(runner)

    plams.finish()

    return ret
示例#8
0
    def run(self, init=True, path=None):
        '''
		Method that runs this job
		'''
        if init:
            if path is None:
                plams.init(path=os.getcwd() + r'\RUNS',
                           folder=time.strftime("[%H:%M](%d-%m-%Y)",
                                                time.localtime()))
            else:
                plams.init(path=path)

        s = self.settings
        job = plams.ADFJob(molecule=self.mol, name=self.job_name, settings=s)
        results = job.run()
        results.dir = '\\'.join(results._kfpath().split('\\')[:-2])
        results.KFPATH = results._kfpath()

        if init: plams.finish()

        return results._kfpath()
示例#9
0
def run(job, runner=None, path=None, folder=None, **kwargs):
    """
    Pickup a runner and initialize it.

    :params job: computation to run
    :type job: Promise Object
    :param runner: Type of runner to use
    :type runner: String
    """
    plams.init(path=path, folder=folder)
    plams.config.log.stdout = 0

    if runner is None:
        ret = call_default(job, **kwargs)
    # elif runner.lower() == 'xenon':
    #     ret = call_xenon(job, **kwargs)
    else:
        raise "Don't know runner: {}".format(runner)

    plams.finish()

    return ret
示例#10
0
def main():
    """
        Main interface that reads the file and retrieve all useful geoms etc.
        Then rewrite geometries in a usable formatter_class
        Prep all NBO computations
        Run ADF on each computation
    """
    # Retrieve command line values
    args = get_input_arguments()
    input_file = args['input_file']
    output_file = args['output_file']

    # Init PLAMS, Setting up a plams.$PID directory in the working dir
    init()

    # Retrieve settings from input file
    settings = get_settings(args)

    geometries = IRC_coordinates_from_t21(input_file)
    natoms = number_of_atoms(input_file)

    # Prep a bunch of NBO computations
    NBO_jobs = [prepare_NBO_computation(geom, settings) for geom in geometries]
    # Run each job in parallel as managed by plams
    for job in NBO_jobs:
        job.run()
    # NBO_values is a list of list of charges
    NBO_values = [
        extract_NBO_charges(job._filenames.get('out'), natoms)
        for job in NBO_jobs
    ]
    # Write NBO data
    print_NBO_charges_to_file(NBO_values, output_file)

    # Close plams session
    finish()
示例#11
0
 def __exit__(self, exc_type, exc_value, traceback) -> None:
     """Exit the context manager, call :func:`finish<scm.plams.core.functions.finish>`."""
     finish(self.otherJM)
示例#12
0
 def __exit__(self, exc_type, exc_value, traceback) -> None:
     """Exit the context manager; call |plams.finish|."""
     finish()
        # Retrieve the gradients and dipoles
        grad_less = np.asarray(jobres.readkf('GeoOpt', 'Gradients_InputOrder'))
        pol_less = np.asarray(jobres.readkf('Properties', 'Polarizability'))

        ### CONVERSIONS ###
        bohr_to_ang = 0.529177

        # Saves derivative of gradients in numHess
        polTens[:, mode] = (
            (pol_plus - pol_less) /
            (2 * scaling)) * bohr_to_ang  #bohr to ang conv included
        numHess[:, mode] = (
            (grad_plus - grad_less) /
            (2 * scaling)) * bohr_to_ang  #bohr to ang conv included

        plams.finish()
        ################## END OF PLAMS ########################

    # Same as in change of basis for a range of spectral region
    smallHess = (np.dot(np.transpose(V), (numHess)))
    numFreq, numMode = CalcNormalModes(smallHess)

    smallPol = np.dot(numMode, np.transpose(polTens))
    newNumMode = np.transpose(np.dot(V, np.transpose(numMode)))
    print("smallPol_before transpose", smallPol)
    smallPol = np.transpose(smallPol)
    print("smallPol_after transpose", smallPol)
#    rotStrengths[1], dipStrengths[1] = rotatStr(numFreq, newNumMode, rkfFiles[0].get_APTs(), rkfFiles[0].get_AATs())
#    dipStrengths[1] = dipoleStrength(numFreq,newNumMode,smallPol)
#    export_peaks("modeselection",rotStrengths[1], dipStrengths[1])
示例#14
0
def get_lig_charge(ligand: Molecule,
                   desired_charge: float,
                   ligand_idx: Union[None, int, Iterable[int], slice] = None,
                   invert_idx: bool = False,
                   settings: Optional[Settings] = None,
                   path: Union[None, str, PathLike] = None,
                   folder: Union[None, str, PathLike] = None) -> pd.Series:
    """Calculate and rescale the **ligand** charges using MATCH_.

    The atomic charges in **ligand_idx** wil be altered such that the molecular
    charge of **ligand** is equal to **desired_charge**.

    .. _MATCH: http://brooks.chem.lsa.umich.edu/index.php?page=match&subdir=articles/resources/software

    Examples
    --------
    .. code:: python

        >>> import pandas as pd
        >>> from scm.plams import Molecule

        >>> from CAT.recipes import get_lig_charge

        >>> ligand = Molecule(...)
        >>> desired_charge = 0.66
        >>> ligand_idx = 0, 1, 2, 3, 4

        >>> charge_series: pd.Series = get_lig_charge(
        ...     ligand, desired_charge, ligand_idx
        ... )

        >>> charge_series.sum() == desired_charge
        True


    Parameters
    ----------
    ligand : :class:`~scm.plams.core.mol.molecule.Molecule`
        The input ligand.

    desired_charge : :class:`float`
        The desired molecular charge of the ligand.

    ligand_idx : :class:`int` or :class:`~collections.abc.Iterable` [:class:`int`], optional
        An integer or iterable of integers representing atomic indices.
        The charges of these atoms will be rescaled;
        all others will be frozen with respect to the MATCH output.
        Setting this value to ``None`` means that *all* atomic charges are considered variable.
        Indices should be 0-based.

    invert_idx : :class:`bool`
        If ``True`` invert **ligand_idx**, *i.e.* all atoms specified therein are
        now threated as constants and the rest as variables,
        rather than the other way around.

    settings : :class:`~scm.plams.core.settings.Settings`, optional
        The input settings for :class:`~nanoCAT.ff.match_job.MatchJob`.
        Will default to the ``"top_all36_cgenff_new"`` forcefield if not specified.

    path : :class:`str` or :class:`~os.PathLike`, optional
        The path to the PLAMS workdir as passed to :func:`~scm.plams.core.functions.init`.
        Will default to the current working directory if ``None``.

    folder : :class:`str` or :class:`~os.PathLike`, optional
        The name of the to-be created to the PLAMS working directory
        as passed to :func:`~scm.plams.core.functions.init`.
        Will default to ``"plams_workdir"`` if ``None``.

    Returns
    -------
    :class:`pd.Series` [:class:`str`, :class:`float`]
        A Series with the atom types of **ligand** as keys and atomic charges as values.

    See Also
    --------
    :class:`MatchJob`
        A :class:`~scm.plams.core.basejob.Job` subclass for interfacing with MATCH_:
        Multipurpose Atom-Typer for CHARMM.

    """  # noqa
    if settings is None:
        settings = Settings()
        settings.input.forcefield = 'top_all36_cgenff_new'

    # Run the MATCH Job
    init(path, folder)
    ligand = ligand.copy()
    run_match_job(ligand, settings, action='raise')
    finish()

    # Extract the charges and new atom types
    count = len(ligand)
    charge = np.fromiter((at.properties.charge_float for at in ligand), count=count, dtype=float)
    symbol = np.fromiter((at.properties.symbol for at in ligand), count=count, dtype='<U4')

    # Identify the atom subset
    idx = _parse_ligand_idx(ligand_idx)
    if invert_idx:
        idx = _invert_idx(idx, count)
    try:
        idx_len = len(idx)  # type: ignore
    except TypeError:  # idx is a slice object
        idx_len = len(charge[idx])

    # Correct the charges and return
    charge[idx] -= (charge.sum() - desired_charge) / idx_len
    return pd.Series(charge, index=symbol, name='charge')