Esempio n. 1
0
def test_opt_orca():
    """Test Orca input generation and run functions."""
    h2o = Molecule(PATH_MOLECULES / "h2o.xyz", 'xyz', charge=0, multiplicity=1)

    h2o_geometry = dftb(templates.geometry, h2o)

    s = Settings()
    # generic keyword "basis" must be present in the generic dictionary
    s.basis = "sto_dzp"
    # s.specific.adf.basis.core = "large"

    r = templates.singlepoint.overlay(s)
    h2o_singlepoint = orca(r, h2o_geometry.molecule)

    dipole = h2o_singlepoint.dipole

    final_result = run(dipole, n_processes=1)

    expected_dipole = [0.82409, 0.1933, -0.08316]
    diff = sqrt(sum((x - y)**2 for x, y in zip(final_result, expected_dipole)))
    logger.info(
        f"Expected dipole computed with Orca 3.0.3 is: {expected_dipole}")
    logger.info(f"Actual dipole is: {final_result}")

    assertion.lt(diff, 1e-2)
Esempio n. 2
0
def test_opt_orca():
    """
    Test Orca input generation and run functions.
    """
    h2o = Molecule('test/test_files/h2o.xyz', 'xyz', charge=0, multiplicity=1)

    h2o_geometry = dftb(templates.geometry, h2o)

    s = Settings()
    # generic keyword "basis" must be present in the generic dictionary
    s.basis = "sto_dzp"
    # "specific" allows the user to apply specific keywords for a
    # package that are not in a generic dictionary
    # s.specific.adf.basis.core = "large"

    r = templates.singlepoint.overlay(s)
    h2o_singlepoint = orca(r, h2o_geometry.molecule)

    dipole = h2o_singlepoint.dipole

    final_result = run(dipole, n_processes=1)

    expected_dipole = [0.82409, 0.1933, -0.08316]
    diff = sqrt(sum((x - y)**2 for x, y in zip(final_result, expected_dipole)))
    print("Expected dipole computed with Orca 3.0.3 is:", expected_dipole)
    print("Actual dipole is:", final_result)

    assert diff < 1e-2
Esempio n. 3
0
def test_opt_orca():
    """
    Test Orca input generation and run functions.
    """
    h2o = Molecule('test/test_files/h2o.xyz', 'xyz', charge=0, multiplicity=1)

    h2o_geometry = dftb(templates.geometry, h2o)

    s = Settings()
    # generic keyword "basis" must be present in the generic dictionary
    s.basis = "sto_dzp"
    # "specific" allows the user to apply specific keywords for a
    # package that are not in a generic dictionary
    # s.specific.adf.basis.core = "large"

    r = templates.singlepoint.overlay(s)
    h2o_singlepoint = orca(r, h2o_geometry.molecule)

    dipole = h2o_singlepoint.dipole

    final_result = run(dipole, n_processes=1)

    expected_dipole = [0.82409, 0.1933, -0.08316]
    diff = sqrt(sum((x - y) ** 2 for x, y in zip(final_result,
                                                 expected_dipole)))
    print("Expected dipole computed with Orca 3.0.3 is:", expected_dipole)
    print("Actual dipole is:", final_result)

    assert diff < 1e-2
Esempio n. 4
0
def test_package_wrapper() -> None:
    """Tests for :class:`PackageWrapper<qmflows.packages.package_wrapper.PackageWrapper>`."""
    s1 = Settings()
    s1.input.ams.Task = 'GeometryOptimization'
    s1.input.ams.GeometryOptimization.Convergence.Gradients = 1.0e-4
    s1.input.ams.Properties.NormalModes = 'true'
    s1.input.DFTB.Model = 'DFTB3'
    s1.input.DFTB.ResourcesDir = 'DFTB.org/3ob-3-1'

    s2 = Settings()
    s2.input.basis.type = 'DZP'
    s2.input.basis.core = 'None'
    s2.input.basis.createoutput = 'None'

    mol = from_smiles('O')  # H2O

    job1 = PackageWrapper(AMSJob)(s1, mol, name='amsjob')
    result1 = _get_result(job1, AMSJob)
    assertion.isinstance(result1, ResultWrapper)
    assertion.eq(result1.results.job.status, 'successful')

    job2 = PackageWrapper(ADFJob)(s2, mol, name='adfjob')
    result2 = _get_result(job2, ADFJob)
    assertion.isinstance(result2, ADF_Result)
    assertion.eq(result2.results.job.status, 'successful')
Esempio n. 5
0
def test_linear_ts():
    """
    compute a first approximation to the TS.
    """
    # Read the Molecule from file
    cnc = Molecule('test/test_files/C-N-C.mol', 'mol')

    # User define Settings
    settings = Settings()
    settings.functional = "pbe"
    settings.basis = "SZ"
    settings.specific.dftb.dftb.scc

    constraint1 = Distance(1, 5)
    constraint2 = Distance(3, 4)

    # scan input
    pes = PES(cnc, constraints=[constraint1, constraint2],
              offset=[2.3, 2.3], get_current_values=False,
              nsteps=2, stepsize=[0.1, 0.1])

    # returns a set of results object containing the output of
    # each point in the scan
    lt = pes.scan([dftb, adf], settings)

    # Gets the object presenting the molecule
    # with the maximum energy calculated from the scan
    apprTS = select_max(lt, "energy")

    # Run the TS optimization, using the default TS template
    ts = run(apprTS)

    expected_energy = -3.219708290363864

    assert abs(ts.energy - expected_energy) < 0.02
Esempio n. 6
0
def prepare_cp2k_settings(geometry, work_dir):
    """
    Fills in the parameters for running a single job in CP2K.

    :param geometry: Molecular geometry stored as String
    :type geometry: plams.Molecule
    :param files: Tuple containing the IO files to run the calculations
    :type files: nameTuple
    :parameter settings: Dictionary contaning the data to
    fill in the template
    :type  settings: ~qmflows.Settings
    :parameter work_dir: Name of the Working folder
    :type      work_dir: String
    :param wfn_restart_job: Path to *.wfn cp2k file use as restart file.
    :type wfn_restart_job: String
    :param cp2k_config:  Parameters required by cp2k.
    :type cp2k_config: Dict
   :returns: ~qmflows.Settings
    """
    # Input/Output Files
    file_MO = join(work_dir, 'mo_coeffs.out')

    # create Settings for the Cp2K Jobs
    cp2k_args = Settings()
    cp2k_args.basis = "DZVP-MOLOPT-SR-GTH"
    cp2k_args.potential = "GTH-PBE"
    cp2k_args.cell_parameters = [12.74] * 3
    dft = cp2k_args.specific.cp2k.force_eval.dft
    dft.scf.added_mos = 20
    dft.scf.eps_scf = 1e-3
    dft["print"]["mo"]["mo_index_range"] = "7 46"
    dft.scf.diagonalization.jacobi_threshold = 1e-5

    # Atom basis
    cp2k_args.specific.cp2k.force_eval.subsys.kind["C"]["BASIS_SET"] = "DZVP-MOLOPT-SR-GTH-q4"
    cp2k_args.specific.cp2k.force_eval.subsys.kind["C"]["POTENTIAL"] = "GTH-PBE-q4"
    cp2k_args.specific.cp2k.force_eval.subsys.kind["H"]["BASIS_SET"] = "DZVP-MOLOPT-SR-GTH-q1"
    cp2k_args.specific.cp2k.force_eval.subsys.kind["H"]["POTENTIAL"] = "GTH-PBE-q1"

    # Functional
    # cp2k_args.specific.cp2k.force_eval.dft.xc["xc_functional"]["pbe"]["scale_x"] = 0.75
    # cp2k_args.specific.cp2k.force_eval.dft.xc["xc_functional"]["pbe"]["scale_c"] = 1.0

    # copy the basis and potential to a tmp file
    for f in ['BASIS_MOLOPT', 'GTH_POTENTIALS', 'BASIS_ADMM_MOLOPT']:
        shutil.copy(join('test/test_files', f), work_dir)
    # Cp2k configuration files

    force = cp2k_args.specific.cp2k.force_eval
    force.dft.basis_set_file_name = join(work_dir, 'BASIS_MOLOPT')
    force.dft.Basis_set_file_name = join(work_dir, 'BASIS_ADMM_MOLOPT')
    force.dft.potential_file_name = join(work_dir, 'GTH_POTENTIALS')
    force.dft['print']['mo']['filename'] = file_MO
    cp2k_args.specific.cp2k['global']['project'] = 'ethylene'

    return templates.singlepoint.overlay(cp2k_args)
Esempio n. 7
0
def test_selected_atoms_with_dftb():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.selected_atoms = ["H"]
    expected_settings = Settings(
        {'selected_atoms': ['H'], 'specific': dftb_const})
    assert dftb.generic2specific(s, mol) == expected_settings
    s.selected_atoms = indices
    expected_settings = Settings(
        {'selected_atoms': indices, 'specific': dftb_const})
    assert str(dftb.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 8
0
def test_freeze_with_dftb():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings(
        {'freeze': ['C', 'O'], 'specific': dftb_const})
    assert str(dftb.generic2specific(s, mol)) == str(expected_settings)
    s.freeze = [1, 2]
    expected_settings = Settings(
        {'freeze': [1, 2], 'specific': dftb_const})
    assert str(dftb.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 9
0
def test_freeze_with_adf():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings(
        {'freeze': ["C", "O"], 'specific': adf_const})
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
    s.freeze = [1, 2]
    expected_settings = Settings(
        {'freeze': [1, 2], 'specific': adf_const})
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 10
0
def test_selected_atoms_with_gamess():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.selected_atoms = ["H"]
    expected_settings = Settings(
        {'selected_atoms': ['H'], 'specific': gamess_sett})
    assert str(gamess.generic2specific(s, mol)) == str(expected_settings)
    s = Settings()
    s.selected_atoms = indices
    expected_settings = Settings(
        {'selected_atoms': indices, 'specific': gamess_sett})
    assert str(gamess.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 11
0
def example_FDE_fragments():
    # For the purpose of the example, define xyz files here:
    xyz1 = io.StringIO('''3

    O         0.00000000000000     -2.29819386240000      1.63037963360000
    H        -0.76925379540000     -2.28223123190000      2.22684542850000
    H         0.76925379540000     -2.28223123190000      2.22684542850000''')

    xyz2 = io.StringIO('''3

    O         0.00000000000000      2.29819386240000      1.63037963360000
    H        -0.76925379540000      2.28223123190000      2.22684542850000
    H         0.76925379540000      2.28223123190000      2.22684542850000''')

    xyz3 = io.StringIO('''3

    O         0.00000000000000      0.00000000000000     -0.26192472620000
    H         0.00000000000000      0.77162768440000      0.34261631290000
    H         0.00000000000000     -0.77162768440000      0.34261631290000''')

    # Read the Molecule from file
    m_h2o_1 = Molecule()
    m_h2o_1.readxyz(xyz1, 1)
    m_h2o_2 = Molecule()
    m_h2o_2.readxyz(xyz2, 1)
    m_mol = Molecule()
    m_mol.readxyz(xyz3, 1)

    settings = Settings()
    settings.basis = 'SZ'
    settings.specific.adf.nosymfit = ''

    # Prepare first water fragment
    r_h2o_1 = adf(templates.singlepoint.overlay(settings), m_h2o_1, job_name="h2o_1")

    # Prepare second water fragment
    r_h2o_2 = adf(templates.singlepoint.overlay(settings), m_h2o_2, job_name="h2o_2")

    frags = gather(schedule(Fragment)(r_h2o_1, m_h2o_1, isfrozen=True),
                   schedule(Fragment)(r_h2o_2, m_h2o_2, isfrozen=True),
                   Fragment(None, m_mol))

    job_fde = adf_fragmentsjob(templates.singlepoint. overlay(settings), frags,
                               job_name="test_fde_fragments")

    # Perform FDE job and get dipole
    # This gets the dipole moment of the active subsystem only
    dipole_fde = run(job_fde.dipole)

    print('FDE dipole:', dipole_fde)

    return dipole_fde
Esempio n. 12
0
def main():

    # Current Work Directory
    cwd = os.getcwd()

    # ========== Fill in the following variables
    # Varaible to define the Path ehere the Cp2K jobs will be computed
    scratch = "/path/to/scratch"
    project_name = 'My_awesome_project'  # name use to create folders

    # Path to the basis set used by Cp2k
    basisCP2K = "/Path/to/CP2K/BASIS_MOLOPT"
    potCP2K = "/Path/to/CP2K/GTH_POTENTIALS"

    path_to_trajectory = 'Path/to/trajectory/in/XYZ'

    # Number of MO used to compute the coupling
    nHOMO = None
    couplings_range = None

    # Basis
    basis = "DZVP-MOLOPT-SR-GTH"

    # Algorithm to compute the NAC
    algorithm = 'levine'

    # Integation step used for the dynamics (femtoseconds)
    dt = 1

    # ============== End of User definitions ===================================

    cp2k_args = Settings()
    cp2k_args.basis = basis

    # Results folder
    results_dir = join(cwd, 'total_results')
    if not os.path.exists(results_dir):
        os.mkdir(results_dir)

    # Merge all the HDF5 files
    file_hdf5 = merge_hdf5(scratch, project_name, cwd, results_dir)

    # compute missing couplings
    script_name = "merge_data.py"

    write_python_script(scratch, 'total_results', path_to_trajectory,
                        project_name, basisCP2K, potCP2K, cp2k_args,
                        Settings(), 0, script_name, file_hdf5, nHOMO,
                        couplings_range, algorithm, dt)

    # Script using SLURM
    write_slurm_script(scratch, results_dir, script_name)
Esempio n. 13
0
def write_input(folder_path: PathLike, original_config: DictConfig) -> None:
    """Write the python script to compute the PYXAID hamiltonians."""
    file_path = join(folder_path, "input.yml")

    # transform settings to standard dictionary
    config = Settings(original_config).as_dict()

    # basis and potential
    config["cp2k_general_settings"]["path_basis"] = os.path.abspath(
        config["cp2k_general_settings"]["path_basis"])

    # remove unused keys from input
    for k in ['blocks', 'job_scheduler', 'mo_index_range', 'workdir']:
        del config[k]

    # rename the workflow to execute
    dict_distribute = {
        "distribute_derivative_couplings": "derivative_couplings",
        "distribute_absorption_spectrum": "absorption_spectrum",
        "distribute_single_points": "single_points"
    }
    workflow_type = config["workflow"].lower()
    config['workflow'] = dict_distribute[workflow_type]
    with open(file_path, "w") as f:
        yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
Esempio n. 14
0
def create_job(name, mol, basis='dyall.cv2z'):

    s = Settings()

    s.specific.dirac.dirac['WAVE FUNCTION']
    s.specific.dirac.dirac["4INDEX"]

    s.specific.dirac.HAMILTONIAN.X2Cmmf
    s.specific.dirac.HAMILTONIAN.GAUNT

    s.specific.dirac.INTEGRALS.READIN["UNCONT"]

    s.specific.dirac['WAVE FUNCTION']["relccsd"]
    s.specific.dirac['WAVE FUNCTION']["scf"]
    s.specific.dirac["WAVE FUNCTION"]["SCF"]["_en"] = True
    s.specific.dirac["WAVE FUNCTION"]["SCF"]["CLOSED SHELL"] = 64
    s.specific.dirac["WAVE FUNCTION"]["SCF"]["MAXITR"] = 50
    s.specific.dirac["WAVE FUNCTION"]["SCF"]["EVCCNV"] = "1.0D-9 5.0D-8"

    s.specific.dirac.moltra.active  = 'energy -3.0 30.0 0.01'

    s.specific.dirac.molecule.basis.default = basis
    s.specific.dirac.molecule.basis.special = 'F BASIS cc-pVDZ'

    s.specific.dirac.relccsd.FOCKSPACE
    s.specific.dirac.relccsd.CCSORT.NORECM
    s.specific.dirac.relccsd.CCFSPC.DOEA
    s.specific.dirac.relccsd.CCFSPC.NACTP = '6 6'

    return dirac(s, mol, job_name=name)
Esempio n. 15
0
def test_opt_gamess():
    """
    Test Optimization in Gamess using methanol in water.
    """
    methanol = Molecule('test/test_files/ion_methanol.xyz')
    methanol.properties['symmetry'] = 'Cs'

    s = Settings()
    s.specific.gamess.contrl.nzvar = 12
    s.specific.gamess.system.timlim = 2
    s.specific.gamess.system.mwords = 2
    s.specific.gamess.pcm.solvnt = 'water'
    s.specific.gamess.basis.gbasis = 'sto'
    s.specific.gamess.basis.ngauss = 3
    s.specific.gamess.guess.guess = 'huckel'
    s.specific.gamess.stapt.optol = '1d-5'
    s.specific.gamess.zmat["izmat(1)"] = "1,1,2,  1,2,3,  1,3,4,  1,3,5,  1,3,6, \n"\
                                         "2,1,2,3,  2,2,3,4,  2,2,3,5,  2,2,3,6, \n"\
                                         "3,1,2,3,4,  3,1,2,3,5,  3,1,2,3,6"

    inp = templates.geometry.overlay(s)
    methanol_geometry = gamess(inp, methanol, work_dir='/tmp')

    mol_opt = run(methanol_geometry.molecule)

    coords = concat([a.coords for a in mol_opt.atoms])

    expected_coords = [
        -0.9956983464, 0.9204754677, -0.0002616586, -0.72585581, -0.0802380791,
        2.18166e-05, 0.741292161, 0.0371204735, -1.69738e-05, 1.1448441964,
        0.5632291664, -0.9026112278, 1.1448447102, 0.562978981, 0.9027182521,
        1.1454516521, -0.9993402516, 1.04943e-05
    ]

    assert abs(sum(zipWith(operator.sub)(coords)(expected_coords))) < 1e-7
Esempio n. 16
0
def create_job(name, mol):
    """
    Create a minimal optimization Job
    """
    s = Settings()

    s.specific.dirac.dirac['WAVE FUNCTION']
    s.specific.dirac.dirac.OPTIMIZE
    s.specific.dirac.dirac.OPTIMIZE["_en"] = True
    s.specific.dirac.dirac.OPTIMIZE.NUMGRA
    s.specific.dirac.HAMILTONIAN["LEVY-LEBLOND"]
    s.specific.dirac.HAMILTONIAN.DFT = "LDA"

    s.specific.dirac.GRID.RADINT = "1.0D-9"
    s.specific.dirac.GRID.ANGINT = 15

    s.specific.dirac.INTEGRALS.READIN["UNCONT"]

    s.specific.dirac['WAVE FUNCTION']["scf"]

    s.specific.dirac.molecule.basis.default = "cc-pVDZ"

    s.specific.dirac.molecule.coordinates.units = "AU"

    return dirac(s, mol, job_name=name)
Esempio n. 17
0
def test_fail_dirac():
    """ Dirac package should return ``None`` if it fails """
    mol = Molecule("test/test_files/h2.xyz")
    s = Settings()
    job = dirac(s, mol, job_name="fail_dirac")
    result = run(job.energy)

    assert isNone(result)
Esempio n. 18
0
def test_cp2k_angle_and_period_keywords():
    """Test the translation from settings to CP2K specific angle and periodic keywords."""
    angles = [81.25, 86.56, 89.80]
    ETHYLENE = Molecule(PATH_MOLECULES / "ethylene.xyz")

    s = Settings()
    s.cell_angles = angles
    s.periodic = None

    # apply transformations
    CP2K.handle_special_keywords(s, "cell_angles", angles, ETHYLENE)
    CP2K.handle_special_keywords(s, "periodic", None, ETHYLENE)

    # compare with the reference
    ref = Settings()
    ref.specific.cp2k.force_eval.subsys.cell.ALPHA_BETA_GAMMA = "81.25 86.56 89.8"
    ref.specific.cp2k.force_eval.subsys.cell.periodic = None
    assertion.eq(s.specific, ref.specific)
Esempio n. 19
0
def test_orca_init_hessian():
    """Test the translation from settings to CP2K specific keywords."""
    # Read Hessian from DFTB
    PATH_RKF = PATH / "output_dftb" / "dftb_freq" / "dftb.rkf"
    assertion.truth(PATH_RKF.exists())
    hess = kfreader(PATH_RKF, section="AMSResults", prop="Hessian")
    water = molkit.from_smiles('[OH2]', forcefield='mmff')

    # Tess Hessian initialization
    s = Settings()
    hess = np.array(hess).reshape(9, 9)
    s.inithess = hess
    ORCA.handle_special_keywords(s, "inithess", hess, water)

    # Test that the hessian is readable
    new_hess = parse_hessian(s.specific.orca.geom.InHessName)
    new_hess = np.array(new_hess, dtype=np.float64)
    assertion.truth(np.allclose(hess, new_hess, atol=1e-5))
Esempio n. 20
0
def test_hessian_transfer():
    """Test DFTB -> Orca hessian transfer."""
    h2o = molkit.from_smiles('O')
    h2o.properties.symmetry = 'C1'

    h2o_freq = dftb(templates.freq, h2o, job_name="freq").hessian

    s = Settings()
    s.inithess = h2o_freq

    h2o_opt = orca(templates.geometry.overlay(s), h2o, job_name="opt")

    energy = h2o_opt.energy
    dipole = h2o_opt.dipole

    wf = gather(energy, dipole)

    logger.info(run(wf))
Esempio n. 21
0
def test_c2pk_npt_mock(mocker: MockFixture) -> None:
    """Mock a call to CP2K."""
    s = Settings()
    job = cp2k_mm(s, None)
    run_mocked = mock_runner(mocker, settings=s, jobname="cp2k_mm_npt")
    result = run_mocked(job)

    ref_pressure = np.load(PATH / 'pressure.npy')
    np.testing.assert_allclose(result.pressure, ref_pressure)
Esempio n. 22
0
def test_prm_to_df() -> None:
    """Tests for :func:`prm_to_df`."""
    s = Settings()
    s.lennard_jones = {
        'param': ('epsilon', 'sigma'),
        'unit': ('kcalmol', 'angstrom'),
        'Cs': (1, 1),
        'Cd': (2, 2),
        'O': (3, 3),
        'H': (4, 4)
    }

    ref = {
        'param': {
            'epsilon': 'epsilon',
            'sigma': 'sigma'
        },
        'unit': {
            'epsilon': 'kcalmol',
            'sigma': 'angstrom'
        },
        'Cs': {
            'epsilon': 1.0,
            'sigma': 1.0
        },
        'Cd': {
            'epsilon': 2.0,
            'sigma': 2.0
        },
        'O': {
            'epsilon': 3.0,
            'sigma': 3.0
        },
        'H': {
            'epsilon': 4.0,
            'sigma': 4.0
        }
    }
    prm_to_df(s)
    assertion.eq(s['lennard_jones'].to_dict(), ref)

    # The 'param' key is missing
    s2 = {'lennard-jones': {'Cs': (1, 2)}}
    assertion.assert_(prm_to_df, s2, exception=KeyError)
Esempio n. 23
0
def example_partial_geometry_opt():
    """
    Performa partial optimization freezing the Hydrogen atoms
    """
    methanol = molkit.from_smiles('CO')

    # optimize only H atoms
    s = Settings()
    s.freeze = [1, 2]
    geom_job1 = adf(templates.geometry.overlay(s), methanol, job_name='geom_job1').molecule

    # optimize only H atoms
    s = Settings()
    s.selected_atoms = ['H']
    geom_job2 = adf(templates.geometry.overlay(s), methanol, job_name='geom_job2').molecule

    geom1, geom2 = run(gather(geom_job1, geom_job2), n_processes=1)

    return geom1, geom2
Esempio n. 24
0
def example_generic_constraints():
    """
    This examples illustrates that, by using generic keywords, it is possible
    to call different packages interchangeably with the same Settings
    """

    # build hydrogen fluoride molecule
    hydrogen_fluoride = molkit.from_smiles('F[H]')

    # loop over distances
    jobs = []
    for distance in [1.0, 1.1, 1.2]:
        s = Settings()
        s.constraint['dist 1 2'] = distance
        # loop over packages
        for package in [dftb, adf, orca]:
            job_name = package.pkg_name + '_' + str(distance)
            constraint_opt = package(templates.geometry.overlay(s),
                                     hydrogen_fluoride, job_name)
            jobs.append(constraint_opt)

    # run the jobs
    results = run(gather(*jobs))
    energies = [r.energy for r in results]
    names = [r.job_name for r in results]

    # put resulting energies into a dictionary
    table = {'dftb': {}, 'adf': {}, 'orca': {}}
    for r in results:
        package, distance = r.job_name.split('_')
        table[package][distance] = round(r.energy, 6)

    # print table
    hartree_to_kcalpermol = 627.094
    for package in ['dftb', 'adf', 'orca']:
        row = [package]
        for distance in ['1.0', '1.1', '1.2']:
            val = table[package][distance] - table[package]['1.0']
            row.append(round(val * hartree_to_kcalpermol, 2))
        print('{:10s} {:10.2f} {:10.2f} {:10.2f}'.format(*row))

    return names, energies
Esempio n. 25
0
def _multi_ligand_job(mol: Molecule, psf: PSFContainer, settings: QmSettings,
                      workdir: str, db_file: str,
                      **kwargs: Any) -> CP2KMM_Result:
    """Helper function for :func:`multi_ligand_job`."""
    # Run MATCH on all unique ligands
    lig_dict = _lig_from_psf(mol, psf)
    ff: str = kwargs.pop('forcefield', 'top_all36_cgenff_new')
    rtf_list, prm = _run_match(lig_dict.values(), forcefield=ff)

    # Update the .psf file with all MATCH results
    initial_charge = psf.charge.sum()
    for id_range, rtf_file in zip(lig_dict.keys(), rtf_list):
        overlay_rtf_file(psf, rtf_file, id_range)

    # Update the charge
    _constrain_charge(psf, settings, initial_charge)

    # Fill in all missing core/ligand lennard-jones parameters with those from UFF
    # TODO: Connect this with the newly improved Auto-FOX 0.8 parameter guessing schemes
    prm_to_df(settings)
    if settings.get('lennard_jones') is not None:
        _fill_uff(psf, settings['lennard_jones'])
    elif settings.get('lennard-jones') is not None:
        _fill_uff(psf, settings['lennard-jones'])

    # Write the new .prm and .psf files and update the CP2K settings
    prm_name = join(workdir, 'mol.prm')
    psf_name = join(workdir, 'mol.psf')
    prm.write(prm_name)
    psf.write(psf_name)
    settings.prm = prm_name
    settings.psf = psf_name

    # Run the actual CP2K job
    with SET_CONFIG_STDOUT:
        job = cp2k_mm(mol=mol, settings=settings, **kwargs)
        return run_parallel(job,
                            db_file=db_file,
                            n_threads=1,
                            always_cache=True,
                            registry=registry,
                            echo_log=False)
Esempio n. 26
0
def test_freeze_with_gamess():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings({
        'freeze': ['C', 'O'],
        'specific': gamess_sett
    })
    assert str(gamess.generic2specific(s, mol)) == str(expected_settings)
    s = Settings()
    s.freeze = [1, 2]
    expected_settings = Settings({'freeze': [1, 2], 'specific': gamess_sett})
    assert str(gamess.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 27
0
def test_fail_orca(tmpdir):
    """Orca package should returns ``None`` if the computation fails."""
    methanol = Molecule(PATH_MOLECULES / 'methanol.xyz')

    s = Settings()
    s.specific.orca.main = "RKS The_Cow_Functional SVP Opt TightSCF SmallPrint"

    opt = orca(s, methanol, job_name='fail_orca')

    result = run(opt.molecule, path=tmpdir)
    assertion.eq(result, None)
Esempio n. 28
0
def test_fail_dirac():
    """ Dirac package should return ``None`` if it fails """
    folder = tempfile.mkdtemp(prefix="qmflows_")
    mol = Molecule("test/test_files/h2.xyz")
    s = Settings()
    job = dirac(s, mol, job_name="fail_dirac")
    try:
        result = run(job.energy, path=folder)
        assert isNone(result)
    finally:
        remove(folder)
Esempio n. 29
0
def test_hessian_transfer():
    """
    Test DFTB -> Orca hessian transfer
    """
    h2o = molkit.from_smiles('O')
    h2o.properties.symmetry = 'C1'

    h2o_freq = dftb(templates.freq, h2o, job_name="freq").hessian

    s = Settings()
    s.inithess = h2o_freq

    h2o_opt = orca(templates.geometry.overlay(s), h2o, job_name="opt")

    energy = h2o_opt.energy
    dipole = h2o_opt.dipole

    wf = gather(energy, dipole)

    print(run(wf))
Esempio n. 30
0
def test_fail_orca():
    """ Orca package should returns ``None`` if the computation fails"""
    methanol = Molecule('test/test_files/methanol.xyz')

    s = Settings()
    s.specific.orca.main = "RKS The_Cow_Functional SVP Opt TightSCF SmallPrint"

    opt = orca(s, methanol, job_name='fail_orca')
    result = run(opt.molecule)

    assert isNone(result)
Esempio n. 31
0
def example_freqs():
    """
    This examples illustrates the possibility to use different packages interchangeably.
    Analytical frequencies are not available for B3LYP in ADF
    This workflow captures the resulting error and submits the same job to ORCA.
    """
    # Generate water molecule
    water = molkit.from_smiles('[OH2]', forcefield='mmff')

    # Pre-optimize the water molecule
    opt_water = dftb(templates.geometry, water, job_name="dftb_geometry")

    jobs = []

    # Generate freq jobs for 3 functionals
    for functional in ['pbe', 'b3lyp', 'blyp']:
        s = Settings()
        s.basis = 'DZ'
        s.functional = functional
        # Try to perform the jobs with adf or orca, take result from  first successful calculation
        freqjob = find_first_job(is_successful, [adf, orca],
                                 templates.freq.overlay(s),
                                 opt_water.molecule,
                                 job_name=functional)
        jobs.append(freqjob)

    # Run workflow
    results = run(gather(*jobs), n_processes=1)

    # extrac results
    freqs = [r.frequencies[-3:] for r in results]
    functionals = ['pbe', 'b3lyp', 'blyp']

    # Print the result
    table = [
        "{:10s}{:10.3f}{:10.3f}{:10.3f}\n".format(fun, *fs)
        for fun, fs in zip(functionals, freqs)
    ]
    print(table)

    return freqs
Esempio n. 32
0
def test_c2pk_cell_opt() -> None:
    """Test CP2K cell optimization calculations with the :class:`CP2K_MM` class."""
    mol = Molecule(PATH / 'cspbbr3_3d.xyz')

    s = Settings()
    s.specific.cp2k += cell_opt.specific.cp2k_mm.copy()
    s.specific.cp2k.motion.cell_opt.max_iter = 10
    s.specific.cp2k.motion.print['forces low'].filename = ''

    s.gmax = [22, 22, 22]
    s.cell_parameters = [25.452, 35.995, 24.452]
    s.charge = {
        'param': 'charge',
        'Cs': 0.2,
        'Pb': 0.4,
        'Br': -0.2,
    }
    s.lennard_jones = {
        'param': ('sigma', 'epsilon'),
        'unit': ('nm', 'kjmol'),
        'Cs Cs': (0.585, 1),
        'Cs Pb': (0.510, 1),
        'Br Se': (0.385, 1),
        'Pb Pb': (0.598, 1),
        'Br Pb': (0.290, 1),
        'Br Br': (0.426, 1),
    }

    job = cp2k_mm(settings=s, mol=mol, job_name='cp2k_mm_cell_opt')
    result = run(job, path=PATH)
    assertion.eq(result.status, 'successful')
Esempio n. 33
0
def test_selected_atoms_with_adf():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.selected_atoms = ["H"]
    expected_settings = Settings({
        'selected_atoms': ['H'],
        'specific': {
            'adf': {
                'constraints': {
                    'atom 1': '',
                    'atom 2': ''
                },
                'geometry': {
                    'optim': 'cartesian'
                }
            }
        }
    })
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
    s.selected_atoms = [3, 4, 5, 6]
    expected_settings = Settings({
        'selected_atoms': [3, 4, 5, 6],
        'specific': {
            'adf': {
                'constraints': {
                    'atom 1': '',
                    'atom 2': ''
                },
                'geometry': {
                    'optim': 'cartesian'
                }
            }
        }
    })
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 34
0
def test_freeze_with_adf():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings({
        'freeze': ["C", "O"],
        'specific': {
            'adf': {
                'constraints': {
                    'atom 1': '',
                    'atom 2': ''
                },
                'geometry': {
                    'optim': 'cartesian'
                }
            }
        }
    })
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
    s.freeze = [1, 2]
    expected_settings = Settings({
        'freeze': [1, 2],
        'specific': {
            'adf': {
                'constraints': {
                    'atom 1': '',
                    'atom 2': ''
                },
                'geometry': {
                    'optim': 'cartesian'
                }
            }
        }
    })
    assert str(adf.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 35
0
def test_selected_atoms_with_orca():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.selected_atoms = ["H"]
    expected_settings = Settings({
        'selected_atoms': ['H'],
        'specific': {
            'orca': {
                'geom': {
                    'Constraints': {
                        '_end': '{ C 0 C }{ C 1 C }'
                    }
                }
            }
        }
    })
    assert str(orca.generic2specific(s, mol)) == str(expected_settings)
    s.selected_atoms = [3, 4, 5, 6]
    expected_settings = Settings({
        'selected_atoms': [3, 4, 5, 6],
        'specific': {
            'orca': {
                'geom': {
                    'Constraints': {
                        '_end': '{ C 0 C }{ C 1 C }'
                    }
                }
            }
        }
    })
    assert str(orca.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 36
0
def create_cp2k_settings(mol: Molecule) -> Settings:
    """Create CP2K general settings."""
    # Set path for basis set
    path_basis = pkg_resources.resource_filename("nanoqm",
                                                 "basis/BASIS_MOLOPT")
    path_potential = pkg_resources.resource_filename("nanoqm",
                                                     "basis/GTH_POTENTIALS")

    # Settings specifics
    s = Settings()
    s.basis = "DZVP-MOLOPT-SR-GTH"
    s.potential = "GTH-PBE"
    s.cell_parameters = 25
    s.specific.cp2k.force_eval.subsys.cell.periodic = 'none'
    s.specific.cp2k.force_eval.dft.basis_set_file_name = path_basis
    s.specific.cp2k.force_eval.dft.potential_file_name = path_potential

    # functional
    s.specific.cp2k.force_eval.dft.xc["xc_functional pbe"] = {}

    # Generate kinds for the atom types
    elements = [x.symbol for x in mol.atoms]
    kinds = generate_kinds(elements, s.basis, s.potential)

    # Update the setting with the kinds
    s.specific = s.specific + kinds

    return s
Esempio n. 37
0
def test_freeze_with_orca():
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings({
        'freeze': ['C', 'O'],
        'specific': {
            'orca': {
                'geom': {
                    'Constraints': {
                        '_end': '{ C 0 C }{ C 1 C }'
                    }
                }
            }
        }
    })
    assert str(orca.generic2specific(s, mol)) == str(expected_settings)
    s.freeze = [1, 2]
    expected_settings = Settings({
        'freeze': [1, 2],
        'specific': {
            'orca': {
                'geom': {
                    'Constraints': {
                        '_end': '{ C 0 C }{ C 1 C }'
                    }
                }
            }
        }
    })
    assert str(orca.generic2specific(s, mol)) == str(expected_settings)
Esempio n. 38
0
def example_freqs():
    """
    This examples illustrates the possibility to use different packages interchangeably.
    Analytical frequencies are not available for B3LYP in ADF
    This workflow captures the resulting error and submits the same job to ORCA.
    """
    # Generate water molecule
    water = molkit.from_smiles('[OH2]', forcefield='mmff')

    # Pre-optimize the water molecule
    opt_water = dftb(templates.geometry, water, job_name="dftb_geometry")

    jobs = []

    # Generate freq jobs for 3 functionals
    for functional in ['pbe', 'b3lyp', 'blyp']:
        s = Settings()
        s.basis = 'DZ'
        s.functional = functional
        # Try to perform the jobs with adf or orca, take result from  first successful calculation
        freqjob = find_first_job(is_successful, [adf, orca], templates.freq.overlay(s),
                                 opt_water.molecule, job_name=functional)
        jobs.append(freqjob)

    # Run workflow
    results = run(gather(*jobs), n_processes=1)

    # extrac results
    freqs = [r.frequencies[-3:] for r in results]
    functionals = ['pbe', 'b3lyp', 'blyp']

    # Print the result
    table = ["{:10s}{:10.3f}{:10.3f}{:10.3f}\n".format(fun, *fs)
             for fun, fs in zip(functionals, freqs)]
    print(table)

    return freqs