コード例 #1
0
ファイル: cli.py プロジェクト: digideskio/shiv
def copy_bootstrap(bootstrap_target: Path) -> None:
    """Copy bootstrap code from shiv into the pyz.

    :param bootstrap_target: The temporary directory where we are staging pyz contents.
    """
    for bootstrap_file in importlib_resources.contents(bootstrap):
        if importlib_resources.is_resource(bootstrap, bootstrap_file):
            with importlib_resources.path(bootstrap, bootstrap_file) as f:
                shutil.copyfile(f.absolute(), bootstrap_target / f.name)
コード例 #2
0
ファイル: helpers.py プロジェクト: Polyconseil/grocker
def copy_resources(package, destination):
    makedirs(destination, exist_ok=True)

    for entry in resources.contents(package):
        if not resources.is_resource(package, entry):
            continue

        with resources.path(package, entry) as resource_path:
            shutil.copy2(str(resource_path), destination)
コード例 #3
0
def configure_run(scanner, plate_type, plates, orientation, parse_dates):
    config = dict()
    config["parse_dates"] = parse_dates
    if parse_dates:
        config["index_name"] = "time"
    else:
        config["index_name"] = "source"
    if plates is None:
        config["plate_names"] = PLATES[scanner]
    else:
        allowed = frozenset(PLATES[scanner])
        for p in plates:
            if p not in allowed:
                raise ValueError(
                    "Specified tray '{}' does not exist or only on the other "
                    "scanner.".format(p))
        config["plate_names"] = plates

    plate_index = {p: i for i, p in enumerate(PLATES[scanner])}
    config["plate_indexes"] = [plate_index[p] for p in config["plate_names"]]

    with open_binary(gp_align.data, "plate_specs.json") as file_handle:
        plate_specs = json.load(file_handle)
    rows, columns = plate_specs["rows_and_columns"][str(plate_type)]
    config["rows"] = rows
    config["columns"] = columns
    LOGGER.debug("Plate type %d has %d rows and %d columns.", plate_type,
                 rows, columns)

    calibration_name_left = "calibration_type_{:d}_left".format(plate_type)
    with path(gp_align.data, calibration_name_left + ".png") as file_path:
        config["left_image"] = detect_edges(file_path)

    calibration_name_right = "calibration_type_{:d}_right".format(plate_type)
    with path(gp_align.data, calibration_name_right + ".png") as file_path:
        config["right_image"] = detect_edges(file_path)

    config["well_names"] = well_names(rows, columns, orientation)
    config["plate_size"] = plate_specs["plate_size"]
    config["left_positions"] = plate_specs[
        "plate_positions"][calibration_name_left]
    config["right_positions"] = plate_specs[
        "plate_positions"][calibration_name_right]
    return config
コード例 #4
0
ファイル: test_zip.py プロジェクト: SerhatG/nzbToMedia
 def setUp(self):
     # Find the path to the example.*.whl so we can add it to the front of
     # sys.path, where we'll then try to find the metadata thereof.
     self.resources = ExitStack()
     self.addCleanup(self.resources.close)
     wheel = self.resources.enter_context(
         path('importlib_metadata.tests.data',
              'example-21.12-py3-none-any.whl'))
     sys.path.insert(0, str(wheel))
     self.resources.callback(sys.path.pop, 0)
コード例 #5
0
def test_global_linear_from_molecule_fmo_h2o_fchk():
    # FMO: ip = -E(H**O) & ea = -E(LUMO)
    ip, ea, energy = -(
        -3.09871604E-01), -2.48704636E-02, -7.645980351270224E+01
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as fname:
        molecule = Molecule.from_file(fname)
    # check from_molecule
    model = GlobalConceptualDFT.from_molecule(molecule, "linear")
    check_global_reactivity_linear(model, ip, ea, energy, 10)
    # check from_molecule given as a list
    model = GlobalConceptualDFT.from_molecule([molecule], "linear")
    check_global_reactivity_linear(model, ip, ea, energy, 10)
コード例 #6
0
def test_global_linear_from_molecule_fmo_ch4_wfn():
    # FMO: ip = -E(H**O) & ea = -E(LUMO)
    ip, ea, energy = -(
        -5.43101269E-01), -1.93295185E-01, -4.019868797400735E+01
    with path('chemtools.data', 'ch4_uhf_ccpvdz.wfn') as fname:
        molecule = Molecule.from_file(fname)
    # check from_molecule
    model = GlobalConceptualDFT.from_molecule(molecule, "linear")
    check_global_reactivity_linear(model, ip, ea, energy, 10)
    # check from_molecule given as a list
    model = GlobalConceptualDFT.from_molecule([molecule], "linear")
    check_global_reactivity_linear(model, ip, ea, energy, 10)
コード例 #7
0
ファイル: test_fchk.py プロジェクト: the-grayson-group/iodata
def test_load_nbasis_indep(tmpdir):
    # Normal case
    mol1 = load_fchk_helper('li2_g09_nbasis_indep.fchk')
    assert mol1.mo.coeffs.shape == (38, 37)
    # Fake an old g03 fchk file by rewriting one line
    with path('iodata.test.data', 'li2_g09_nbasis_indep.fchk') as fnin:
        fnout = os.path.join(tmpdir, 'tmpg03.fchk')
        with open(fnin) as fin, open(fnout, "w") as fout:
            for line in fin:
                fout.write(line.replace("independent", "independant"))
    mol2 = load_one(fnout)
    assert mol2.mo.coeffs.shape == (38, 37)
コード例 #8
0
ファイル: test_utils.py プロジェクト: kimt33/chemtools-1
def test_get_dict_population_raises():
    # check molecule
    assert_raises(ValueError, get_dict_population, "gibberish", "RMF", "hi")
    # check number of molecules
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as file1:
        with path('chemtools.data', 'h2o_q+1_ub3lyp_ccpvtz.fchk') as file2:
            molecule = [
                Molecule.from_file(file1),
                Molecule.from_file(file2),
            ]
    assert_raises(ValueError, get_dict_population, molecule, "RMF", "esp")
    # check condensing approach
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as fname:
        molecule = Molecule.from_file(fname)
    assert_raises(ValueError, get_dict_population, molecule, "fm", "h")
    assert_raises(ValueError, get_dict_population, molecule, "rm", "hi")
    assert_raises(ValueError, get_dict_population, molecule, "gibberish",
                  "esp")
    # check scheme
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as file1:
        with path('chemtools.data', 'h2o_q+1_ub3lyp_ccpvtz.fchk') as file2:
            with path('chemtools.data', 'h2o_q-1_ub3lyp_ccpvtz.fchk') as file3:
                molecule = [
                    Molecule.from_file(file1),
                    Molecule.from_file(file2),
                    Molecule.from_file(file3),
                ]
    assert_raises(ValueError, get_dict_population, molecule, "rmf",
                  "gibberish")
コード例 #9
0
def test_kinetic_h2o_nuclei():
    # test against multiwfn 3.6 dev src
    with path('chemtools.data', 'data_multiwfn36_fchk_h2o_q+0_ub3lyp_ccpvtz.npz') as fname:
        data = np.load(str(fname))
    tool = KED(data['nuc_dens'], data['nuc_grad'], data['nuc_lap'], data['nuc_ked_pd'])
    # check attributes
    assert_allclose(tool.density, data['nuc_dens'], rtol=1.e-6, atol=0.)
    assert_allclose(tool.gradient, data['nuc_grad'], rtol=1.e-6, atol=0.)
    assert_allclose(tool.laplacian, data['nuc_lap'], rtol=1.e-6, atol=0.)
    # check ked at the position of nuclei
    assert_allclose(tool.ked_positive_definite, data['nuc_ked_pd'], rtol=1.e-5, atol=0.)
    assert_allclose(tool.ked_hamiltonian, data['nuc_ked_ham'], rtol=1.e-5, atol=0.)
    assert_allclose(tool.ked_general(alpha=0.), data['nuc_ked_ham'], rtol=1.e-5, atol=0.)
コード例 #10
0
ファイル: test_opt_loop.py プロジェクト: theochem/gopt
    def test_one_complete_opt_loop(self):
        opt = self.setup_opt()
        opt.calculate_trust_step()

        new_p = opt.next_step_structure()
        with path("saddle.optimizer.test.data", "new_step_water.fchk") as fchk_file:
            result = opt.verify_new_point(new_p, debug_fchk=fchk_file)
        assert result is True
        opt.add_new_point(new_p)
        opt.update_trust_radius()
        # hessian update and modify
        opt.update_hessian()
        opt.modify_hessian()
        opt.calculate_trust_step()
        ref_step = -np.dot(np.linalg.pinv(opt.new.v_hessian), opt.new.v_gradient)
        assert np.allclose(ref_step, opt.new.step)
        opt.calculate_trust_step()
        new_point = opt.next_step_structure()
        with path("saddle.optimizer.test.data", "final_water.fchk") as fchk_file:
            opt.verify_new_point(new_point, debug_fchk=fchk_file)
        opt.add_new_point(new_point)
        assert opt.check_converge() is True
コード例 #11
0
def _check_convert_many(myconvert, tmpdir):
    outfn = os.path.join(tmpdir, 'tmp.xyz')
    with path('iodata.test.data', 'peroxide_relaxed_scan.fchk') as infn:
        myconvert(infn, outfn)
    trj = list(load_many(outfn))
    assert len(trj) == 13
    for iodata in trj:
        assert iodata.natom == 4
        assert_equal(iodata.atnums, [8, 8, 1, 1])
    assert_allclose(trj[1].atcoords[3],
                    [-1.85942837, -1.70565735, 0.0], atol=1e-5)
    assert_allclose(trj[5].atcoords[0],
                    [0.0, 1.32466211, 0.0], atol=1e-5)
コード例 #12
0
ファイル: test_json.py プロジェクト: wilhadams/iodata
def test_qcschema_input(filename, explicit_basis, lot, obasis_name, run_type, geometry):
    with path('iodata.test.data', filename) as qcschema_input:
        try:
            mol = load_one(str(qcschema_input))
            assert mol.lot == lot
            if obasis_name:
                assert mol.obasis_name == obasis_name
            if run_type:
                assert mol.run_type == run_type
            np.testing.assert_allclose(mol.atcoords, geometry)
        # This will change if QCSchema Basis gets supported
        except NotImplementedError:
            assert explicit_basis
コード例 #13
0
def test_load_many(case):
    with path('iodata.test.data', f"water_{case}.pdb") as fn_pdb:
        mols = list(load_many(str(fn_pdb)))
    assert len(mols) == 5
    for mol in mols:
        assert_equal(mol.atnums, [8, 1, 1])
        assert mol.atcoords.shape == (3, 3)
        assert mol.extra.get('chainids') is None
        assert_allclose(mol.extra.get('occupancies'), np.ones(3))
        assert_allclose(mol.extra.get('bfactors'), np.zeros(3))
    assert_allclose(mols[0].atcoords[2] / angstrom, [2.864, 0.114, 3.364])
    assert_allclose(mols[2].atcoords[0] / angstrom, [-0.233, -0.790, -3.248])
    assert_allclose(mols[-1].atcoords[1] / angstrom, [-2.123, -3.355, -3.354])
コード例 #14
0
ファイル: test_inputs.py プロジェクト: wilhadams/iodata
def test_input_gaussian_from_xyz(tmpdir):
    # load geometry from xyz file & add level of theory & basis set
    with path('iodata.test.data', 'water_number.xyz') as fn:
        mol = load_one(fn)
    mol.nelec = 10
    mol.lot = 'ub3lyp'
    mol.obasis_name = '6-31g*'
    # write input in a temporary folder using the user-template
    fname = os.path.join(tmpdir, 'input_from_xyz.com')
    template = """\
%chk=gaussian.chk
%mem=3500MB
%nprocs=4
#p {lot}/{obasis_name} opt scf(tight,xqc,fermi) integral(grid=ultrafine) {extra_cmd}

{title} {lot}/{obasis_name} opt-force

0 1
{geometry}

--Link1--
%chk=gaussian.chk
%mem=3500MB
%nprocs=4
#p {lot}/{obasis_name} force guess=read geom=allcheck integral(grid=ultrafine) output=wfn

gaussian.wfn


"""
    write_input(mol,
                fname,
                fmt='gaussian',
                template=template,
                extra_cmd="nosymmetry")
    # compare saved input to expected input
    with path('iodata.test.data',
              'input_gaussian_h2o_opt_ub3lyp.txt') as fname_expected:
        check_load_input_and_compare(fname, fname_expected)
コード例 #15
0
 def test_select_key_ic(self):
     with path("saddle.test.data", "water.xyz") as mol_path:
         mol = Utils.load_file(mol_path)
     mol_1 = ReducedInternal(mol.coordinates, mol.numbers, 0, 1)
     mol_1.add_bond(1, 0)
     mol_1.add_bond(1, 2)
     mol_1.add_angle(0, 1, 2)
     mol_1.select_key_ic(0)
     assert mol_1.key_ic_number == 1
     mol_1.select_key_ic(2)
     assert mol_1.key_ic_number == 1
     mol_1.select_key_ic(0, 1, 2)
     assert mol_1.key_ic_number == 3
コード例 #16
0
def get_prevent_sync_pattern(prevent_sync_pattern_path: Optional[Path] = None) -> Pattern:
    pattern = None
    # Get the pattern from the path defined in the core config
    if prevent_sync_pattern_path is not None:
        pattern = _get_prevent_sync_pattern(prevent_sync_pattern_path)
    # Default to the pattern from the ignore file in the core resources
    if pattern is None:
        with importlib_resources.path(core_resources, "default_pattern.ignore") as path:
            pattern = _get_prevent_sync_pattern(path)
    # As a last resort use the failsafe
    if pattern is None:
        return FAILSAFE_PATTERN_FILTER
    return pattern
コード例 #17
0
ファイル: test_internal.py プロジェクト: theochem/gopt
 def test_scipy_opt_tfm(self):
     with path("saddle.test.data", "h2o2.xyz") as mol_path:
         mol = Internal.from_file(mol_path)
     mol.auto_select_ic()
     target_ic = mol.ic_values
     target_ic[0] = 2
     target_ic[3] = 2
     target_ic[5] = 2
     mol.set_target_ic(target_ic)
     mol.converge_to_target_ic()
     np.allclose(mol.ic_values[0], 2, atol=1e-4)
     np.allclose(mol.ic_values[3], 2, atol=1e-4)
     np.allclose(mol.ic_values[5], 2, atol=1e-4)
コード例 #18
0
def test_condense_from_file_fd_rmf_esp_h2o_fchk():
    # expected populations of H2O from fchk file
    expected_m = np.array([8, 1, 1]) - np.array(
        [4.14233893E-02, 4.79288419E-01, 4.79288192E-01])
    expected_0 = np.array([8, 1, 1]) - np.array(
        [-7.00779373E-01, 3.50389629E-01, 3.50389744E-01])
    expected_p = np.array([8, 1, 1]) - np.array(
        [-5.81613550E-01, -2.09193820E-01, -2.09192630E-01])
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as file1:
        with path('chemtools.data', 'h2o_q-1_ub3lyp_ccpvtz.fchk') as file2:
            with path('chemtools.data', 'h2o_q+1_ub3lyp_ccpvtz.fchk') as file3:
                fname = [file1, file2, file3]
                # check from_file linear
                model1 = CondensedConceptualDFT.from_file(
                    fname, "linear", "RMF", "esp")
                model2 = CondensedConceptualDFT.from_file(
                    fname, "quadratic", "RMF", "esp")
    check_condensed_reactivity(model1, "linear", expected_0, expected_p,
                               expected_m, 10, 0.572546)
    # check from_file quadratic
    check_condensed_reactivity(model2, "quadratic", expected_0, expected_p,
                               expected_m, 10, 0.572546)
コード例 #19
0
ファイル: application.py プロジェクト: schwartzman/portfolio
def sites():
    g.curr = 'sites'
    with path('resources', 'db.sqlite') as db:
        con = sqlite3.connect(str(db))
    con.row_factory = sqlite3.Row
    cur = con.execute('''
        SELECT slug, title, ssl, link, source, blurb
        FROM sites
        WHERE display=1
        ORDER BY sort
    ''')
    folios = cur.fetchall()
    return render_template('sites.j2', folios=folios)
コード例 #20
0
def test_condense_from_file_fd_rmf_npa_h2o_fchk():
    # expected populations of H2O from fchk file
    expected_m = np.array([8, 1, 1]) - np.array(
        [-3.64452391E-02, 5.18222784E-01, 5.18222455E-01])
    expected_0 = np.array([8, 1, 1]) - np.array(
        [-9.00876494E-01, 4.50438267E-01, 4.50438227E-01])
    expected_p = np.array([8, 1, 1]) - np.array(
        [-1.11332869E+00, 5.66635486E-02, 5.66651430E-02])
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as file1:
        with path('chemtools.data', 'h2o_q-1_ub3lyp_ccpvtz.fchk') as file2:
            with path('chemtools.data', 'h2o_q+1_ub3lyp_ccpvtz.fchk') as file3:
                fname = [file1, file2, file3]
                # check from_file linear
                model1 = CondensedConceptualDFT.from_file(
                    fname, "linear", "RMF", "npa")
                model2 = CondensedConceptualDFT.from_file(
                    fname, "quadratic", "RMF", "npa")
    check_condensed_reactivity(model1, "linear", expected_0, expected_p,
                               expected_m, 10, 0.572546)
    # check from_file quadratic
    check_condensed_reactivity(model2, "quadratic", expected_0, expected_p,
                               expected_m, 10, 0.572546)
コード例 #21
0
def to_html(data, template_filename, fp):
    # Template with Jinja2
    with _resources.path("crawler_book_info", "templates") as _path:
        template_path = str(_path)
        loader = FileSystemLoader(searchpath=template_path)
        env = Environment(loader=loader)
        template = env.get_template(template_filename)

        # Mapping the parser data to template.
        result = template.render(**data)

        # Write to HTML file.
        fp.write(pangu.spacing_text(result))
コード例 #22
0
ファイル: test_internal.py プロジェクト: theochem/gopt
    def test_mini_dihed(self):
        with path("saddle.test.data", "methanol.xyz") as mol_path:
            mol = Internal.from_file(mol_path)
        mol._auto_select_cov_bond()
        mol._auto_select_h_bond()
        mol._auto_select_fragment_bond()
        mol._auto_select_angle()
        # start real parts
        ref = len(mol.ic)
        mol._auto_select_minimum_dihed_normal()
        assert len(mol.ic) - ref == 1

        with path("saddle.test.data", "ethane.xyz") as mol2_path:
            mol2 = Internal.from_file(mol2_path)
        mol2._auto_select_cov_bond()
        mol2._auto_select_h_bond()
        mol2._auto_select_fragment_bond()
        mol2._auto_select_angle()
        # start real parts
        ref = len(mol2.ic)
        mol2._auto_select_minimum_dihed_normal()
        assert len(mol2.ic) - ref == 1
コード例 #23
0
 def test_find_pluggable_components_by_plugin_name(self):
     with ExitStack() as resources:
         testing_path = resources.enter_context(
             path('mailman.plugins.testing', ''))
         resources.enter_context(hack_syspath(0, str(testing_path)))
         resources.enter_context(
             configuration(
                 'plugin.example', **{
                     'class': 'example.hooks.ExamplePlugin',
                     'enabled': 'yes',
                 }))
         components = list(find_pluggable_components('rules', IRule))
     self.assertIn('example-rule', {rule.name for rule in components})
コード例 #24
0
ファイル: test_internal.py プロジェクト: theochem/gopt
 def test_new_dihed_converge(self):
     with path("saddle.test.data", "h2o2.xyz") as mol_path:
         mol = Utils.load_file(mol_path)
     mol = Utils.load_file(mol_path)
     h2o2 = Internal(mol.coordinates, mol.numbers, 0, 1)
     h2o2.auto_select_ic(dihed_special=True)
     assert len(h2o2.ic) == 7
     # print(h2o2.ic_values)
     target_ic = [2.4, 1.8, 1.8, 1.6, 1.6, 0.8, 0.6]
     h2o2.set_target_ic(target_ic)
     h2o2.converge_to_target_ic()
     # print(h2o2.ic_values)
     assert_allclose(h2o2.ic_values, target_ic, atol=1e-2)
コード例 #25
0
def parsec_drive_icon_context(letter):
    # Winreg is not available for some reasons
    if platform.system() != "Windows" or not try_winreg():
        yield
        return

    # Safe context for removing the key after usage
    with importlib_resources.path(resources, DRIVE_ICON_NAME) as drive_icon_path:
        set_parsec_drive_icon(letter, drive_icon_path)
        try:
            yield
        finally:
            del_parsec_drive_icon(letter)
コード例 #26
0
def test_lol_h2o_nuclei():
    # test against multiwfn 3.6 dev src
    with path('chemtools.data', 'data_multiwfn36_fchk_h2o_q+0_ub3lyp_ccpvtz.npz') as fname:
        data = np.load(str(fname))
    lol = LOL(data['nuc_dens'], data['nuc_grad'], data['nuc_ked_pd'])
    assert_allclose(lol.value, data['nuc_lol'], rtol=1.e-6, atol=1.e-6)
    # check raises
    dens, grad, ked = data['nuc_dens'], data['nuc_grad'], data['nuc_ked_pd']
    assert_raises(ValueError, LOL, dens, grad, ked, trans_k=-1)
    assert_raises(ValueError, LOL, dens, grad, ked, trans_a=2, trans_k=-1)
    assert_raises(ValueError, LOL, dens, grad, ked, trans_k=0)
    assert_raises(ValueError, LOL, dens, grad, ked, trans_a=0)
    assert_raises(ValueError, LOL, dens, grad, ked, trans='rational')
コード例 #27
0
def test_condense_from_file_fd_rmf_mulliken_h2o_fchk():
    # expected populations of H2O from fchk file
    expected_m = np.array([8, 1, 1]) - np.array(
        [3.49417097E-01, 3.25291762E-01, 3.25291141E-01])
    expected_0 = np.array([8, 1, 1]) - np.array(
        [-4.32227787E-01, 2.16114060E-01, 2.16113727E-01])
    expected_p = np.array([8, 1, 1]) - np.array(
        [-2.64833827E-01, -3.67583325E-01, -3.67582849E-01])
    with path('chemtools.data', 'h2o_q+0_ub3lyp_ccpvtz.fchk') as file1:
        with path('chemtools.data', 'h2o_q-1_ub3lyp_ccpvtz.fchk') as file2:
            with path('chemtools.data', 'h2o_q+1_ub3lyp_ccpvtz.fchk') as file3:
                fname = [file1, file2, file3]
                model1 = CondensedConceptualDFT.from_file(
                    fname, "linear", "RMF", "mulliken")
                model2 = CondensedConceptualDFT.from_file(
                    fname, "quadratic", "RMF", "mulliken")
    # check from_file linear
    check_condensed_reactivity(model1, "linear", expected_0, expected_p,
                               expected_m, 10, 0.572546)
    # check from_file quadratic
    check_condensed_reactivity(model2, "quadratic", expected_0, expected_p,
                               expected_m, 10, 0.572546)
コード例 #28
0
def test_load_molden_high_am_orca(case):
    # The file tested here is created with ORCA.
    # This is a special case because it contains higher angular momenta than
    # officially supported by the Molden format. Most virtual orbitals were removed.
    with path('iodata.test.data', f'orca_{case}_cc_pvqz_pure.molden') as fn_molden:
        with pytest.warns(FileFormatWarning) as record:
            mol = load_one(str(fn_molden))
    assert len(record) == 1
    assert "ORCA" in record[0].message.args[0]
    # Check normalization
    olp = compute_overlap(mol.obasis, mol.atcoords)
    assert mol.mo.kind == "restricted"
    check_orthonormal(mol.mo.coeffs, olp)
コード例 #29
0
ファイル: test_mol2.py プロジェクト: wilhadams/iodata
def test_load_dump_many_consistency(tmpdir):
    with path('iodata.test.data', 'caffeine.mol2') as fn_mol2:
        mols0 = list(load_many(str(fn_mol2)))
    # write mol2 file in a temporary folder & then read it
    fn_tmp = os.path.join(tmpdir, 'test')
    dump_many(mols0, fn_tmp, fmt='mol2')
    mols1 = list(load_many(fn_tmp, fmt='mol2'))
    assert len(mols0) == len(mols1)
    for mol0, mol1 in zip(mols0, mols1):
        assert mol0.title == mol1.title
        assert_equal(mol0.atnums, mol1.atnums)
        assert_allclose(mol0.atcoords, mol1.atcoords, atol=1.e-5)
        assert_equal(mol0.bonds, mol1.bonds)
コード例 #30
0
ファイル: test_nci.py プロジェクト: tovrstra/chemtools
def test_analyze_nci_assert_errors():
    with path('chemtools.data', 'h2o_dimer_pbe_sto3g.fchk') as file_path:
        mol = Molecule.from_file(file_path)
        cube = UniformGrid.from_file(file_path, spacing=2., extension=0.0)

    dens = np.array([
        2.10160232e-04, 1.11307672e-05, 3.01244062e-04, 2.31768360e-05,
        6.56282686e-03, 2.62815892e-04, 2.46559574e-02, 1.82760928e-03,
        1.89299475e-02, 1.39689069e-03, 1.10257641e+00, 3.63942662e-02,
        8.01150391e-03, 2.79542971e-04, 1.98278511e-02, 1.89336116e-03
    ])

    rdg = np.array([
        6.434055294420, 19.330749118092, 5.927230664196, 13.593077700571,
        2.411123457672, 5.203993648485, 1.482717816902, 3.136335572700,
        1.779261001623, 3.395839461280, 0.226436405120, 0.912678557191,
        2.223911275208, 4.990189542067, 1.676113282597, 3.171756800841
    ])

    assert_raises(ValueError, NCI, np.array([0.]), rdg, cube)
    assert_raises(ValueError, NCI, dens, np.array([0.]), cube)
    assert_raises(ValueError, NCI, dens, rdg, cube, hessian=np.array([0.]))
    assert_raises(ValueError, NCI.from_file, file_path, grid=1)

    desp = NCI(dens, rdg, cube)
    assert desp.signed_density is None
    assert desp.eigvalues is None

    with tmpdir(
            'chemtools.analysis.test.test_base.test_analyze_nci_assert_errors'
    ) as dn:
        test = '%s/%s' % (dn, 'test')
        desp.generate_scripts(test)
        test = '%s/%s' % (dn, 'test-dens.cube')
        assert os.path.isfile(test) and os.access(test, os.R_OK)
        test = '%s/%s' % (dn, 'test-grad.cube')
        assert os.path.isfile(test) and os.access(test, os.R_OK)
        test = '%s/%s' % (dn, 'test.vmd')
        assert os.path.isfile(test) and os.access(test, os.R_OK)

    desp = NCI.from_molecule(mol)
    assert desp.signed_density.shape == desp._density.shape

    desp = NCI.from_file(file_path, grid=cube)

    with tmpdir(
            'chemtools.analysis.test.test_base.test_analyze_nci_assert_errors'
    ) as dn:
        test = '%s/%s' % (dn, 'test.png')
        desp.generate_plot(test)
        assert os.path.isfile(test) and os.access(test, os.R_OK)
コード例 #31
0
ファイル: atomgrid.py プロジェクト: theochem/grid
    def from_preset(
        cls,
        rgrid: OneDGrid = None,
        *,
        atnum: int,
        preset: str,
        center: np.ndarray = None,
        rotate: int = 0,
    ):
        """High level api to construct an atomic grid with preset arguments.

        Examples
        --------
        # construct an atomic grid for H with fine grid setting
        >>> atgrid = AtomGrid.from_preset(rgrid, atnum=1, preset="fine")

        Parameters
        ----------
        rgrid : OneDGrid, optional
            The (1-dimensional) radial grid representing the radius of spherical grids.
        atnum : int, keyword-only argument
            The atomic number specifying the predefined grid.
        preset : str, keyword-only argument
            The name of predefined grid specifying the radial sectors and their corresponding
            number of Lebedev grid points. Supported preset options include:
            'coarse', 'medium', 'fine', 'veryfine', 'ultrafine', and 'insane'.
        center : ndarray(3,), optional, keyword-only argument
            Cartesian coordinates of the grid center. If `None`, the origin is used.
        rotate : int, optional
            Integer used as a seed for generating random rotation matrices to rotate the Lebedev
            spherical grids at each radial grid point. If the integer is zero, then no rotate
            is used.

        """
        if rgrid is None:
            # TODO: generate a default rgrid, currently raise an error instead
            raise ValueError("A default OneDGrid will be generated")
        center = (np.zeros(3, dtype=float)
                  if center is None else np.asarray(center, dtype=float))
        cls._input_type_check(rgrid, center)
        # load radial points and
        with path("grid.data.prune_grid",
                  f"prune_grid_{preset}.npz") as npz_file:
            data = np.load(npz_file)
            # load predefined_radial sectors and num_of_points in each sectors
            rad = data[f"{atnum}_rad"]
            npt = data[f"{atnum}_npt"]

        degs = AngularGrid.convert_lebedev_sizes_to_degrees(npt)
        rad_degs = AtomGrid._find_l_for_rad_list(rgrid.points, rad, degs)
        return cls(rgrid, degrees=rad_degs, center=center, rotate=rotate)
コード例 #32
0
def test_local_conceptual_raises():
    # check invalid densities
    values = {
        1.0: np.array([0.0, 0.5]),
        2.0: np.array([1.0]),
        3.0: np.array([[2.0]])
    }
    assert_raises(ValueError, LocalConceptualDFT, values)
    # check in valid model
    values = {
        1.0: np.array([0.0, 0.5]),
        2.0: np.array([1.0, 1.2]),
        3.0: np.array([2.0, 2.2])
    }
    assert_raises(ValueError, LocalConceptualDFT, values, "rational")
    assert_raises(ValueError, LocalConceptualDFT, values, "Rational")
    # check in valid points
    with path('chemtools.data', 'ch4_uhf_ccpvdz.fchk') as fn:
        assert_raises(ValueError, LocalConceptualDFT.from_file, fn, "linear",
                      np.array([0., 0., 0.]))
        assert_raises(ValueError, LocalConceptualDFT.from_file, fn, "linear",
                      np.array([[0., 0.]]))
        assert_raises(ValueError, LocalConceptualDFT.from_file, fn,
                      "quadratic", np.array([[0., 0.]]))
    # check molecule file inconsistency
    points = np.array([[0., 0., 0.]])
    with path('chemtools.data', 'ch4_uhf_ccpvdz.fchk') as file1:
        with path('chemtools.data', 'o2_uhf.fchk') as file2:
            fns = [file1, file2]
            assert_raises(ValueError, LocalConceptualDFT.from_file, fns,
                          "linear", points)
            assert_raises(ValueError, LocalConceptualDFT.from_file, fns,
                          "quadratic", points)
    with path('chemtools.data', 'ch4_uhf_ccpvdz.fchk') as fn:
        assert_raises(ValueError, LocalConceptualDFT.from_file, [fn, fn],
                      "linear", points)
        assert_raises(ValueError, LocalConceptualDFT.from_file, [fn, fn],
                      "quadratic", points)
コード例 #33
0
def test_mulliken_populations_newbasis():
    """Test orbstools.partition.OrbitalPartitionTools.mulliken_populations with a new basis."""
    # pylint: disable=C0103
    with path("chemtools.data", "naclo4_coeff_ab_mo.npy") as fname:
        coeff_ab_mo = np.load(str(fname))
    with path("chemtools.data", "naclo4_olp_ab_ab.npy") as fname:
        olp_ab_ab = np.load(str(fname))
    with path("chemtools.data", "naclo4_occupations.npy") as fname:
        occupations = np.load(str(fname))
    with path("chemtools.data", "naclo4_ab_atom_indices.npy") as fname:
        ab_atom_indices = np.load(str(fname))

    orbpart = OrbitalPartitionTools(coeff_ab_mo, occupations, olp_ab_ab, 6,
                                    ab_atom_indices)
    assert np.allclose(
        orbpart.transform_orbitals(np.identity(124),
                                   ab_atom_indices).mulliken_populations(),
        orbpart.mulliken_populations(),
    )

    coeff_ab_rand = np.linalg.svd(np.random.rand(124, 124))[0].T
    rand_atom_indices = (np.random.rand(124) * 6 // 1).astype(int)
    # normalize
    olp_rand_rand = coeff_ab_rand.T.dot(olp_ab_ab).dot(coeff_ab_rand)
    coeff_ab_rand *= np.diag(olp_rand_rand)**(-0.5)
    olp_rand_rand = coeff_ab_rand.T.dot(olp_ab_ab).dot(coeff_ab_rand)
    coeff_rand_mo = project(olp_rand_rand,
                            coeff_ab_rand.T.dot(olp_ab_ab).dot(coeff_ab_mo))

    orbpart = OrbitalPartitionTools(coeff_ab_mo, occupations, olp_ab_ab, 6,
                                    rand_atom_indices)
    assert np.allclose(coeff_ab_rand.dot(coeff_rand_mo), coeff_ab_mo)
    assert np.allclose(
        orbpart.transform_orbitals(coeff_ab_rand,
                                   rand_atom_indices).mulliken_populations(),
        OrbitalPartitionTools(coeff_rand_mo, occupations, olp_rand_rand, 6,
                              rand_atom_indices).mulliken_populations(),
    )
コード例 #34
0
ファイル: test_wfx.py プロジェクト: Ali-Tehrani/iodata
def test_load_one_lih_cation_uhf():
    with path('iodata.test.data', 'lih_cation_uhf.wfx') as file_wfx:
        mol = load_one(str(file_wfx))
    # check number of orbitals and occupation numbers
    assert mol.mo.kind == 'unrestricted'
    assert mol.mo.norba == 2
    assert mol.mo.norbb == 1
    assert mol.mo.norb == 3
    assert_allclose(mol.mo.occsa, [1.0, 1.0])
    assert_allclose(mol.mo.occsb, [1.0])
    # check orthonormal mo
    olp = compute_overlap(mol.obasis, mol.atcoords)
    check_orthonormal(mol.mo.coeffsa, olp, 1e-5)
    check_orthonormal(mol.mo.coeffsb, olp, 1e-5)
コード例 #35
0
def test_load_molden_nh3_molpro2012():
    # The file tested here is created with MOLPRO2012.
    with path('iodata.test.data', 'nh3_molpro2012.molden') as fn_molden:
        mol = load_one(str(fn_molden))

    # Check normalization
    olp = compute_overlap(mol.obasis, mol.atcoords)
    check_orthonormal(mol.mo.coeffs, olp)

    # Check Mulliken charges.
    # Comparison with numbers from the Molden program output.
    charges = compute_mulliken_charges(mol)
    molden_charges = np.array([0.0381, -0.2742, 0.0121, 0.2242])
    assert_allclose(charges, molden_charges, atol=1.e-3)
コード例 #36
0
ファイル: helpers.py プロジェクト: Polyconseil/grocker
def load_yaml_resource(package, name):
    with resources.path(package, name) as resource_path:
        return load_yaml(str(resource_path))