Пример #1
0
 def test_pdf_primitive_vs_supercell(self):
     test_doc, success = res2dict(REAL_PATH + "data/KP_primitive.res",
                                  db=False)
     test_doc["text_id"] = ["primitive", "cell"]
     test_doc["lattice_cart"] = abc2cart(test_doc["lattice_abc"])
     test_doc["cell_volume"] = cart2volume(test_doc["lattice_cart"])
     supercell_doc, success = res2dict(REAL_PATH + "data/KP_supercell.res",
                                       db=False)
     supercell_doc["text_id"] = ["supercell", "cell"]
     supercell_doc["lattice_cart"] = abc2cart(supercell_doc["lattice_abc"])
     supercell_doc["cell_volume"] = cart2volume(
         supercell_doc["lattice_cart"])
     test_doc["pdf"] = PDF(test_doc,
                           dr=0.01,
                           low_mem=True,
                           rmax=10,
                           num_images="auto",
                           debug=DEBUG)
     supercell_doc["pdf"] = PDF(
         supercell_doc,
         dr=0.01,
         low_mem=True,
         rmax=10,
         num_images="auto",
         debug=DEBUG,
     )
     overlap = PDFOverlap(test_doc["pdf"], supercell_doc["pdf"])
     self.assertLessEqual(overlap.similarity_distance, 1e-3)
     self.assertGreaterEqual(overlap.similarity_distance, 0.0)
Пример #2
0
    def test_convert_positions(self):
        doc = res2dict(REAL_PATH + "data/structures/Li7Sn-Fmmm.res")[0]
        crystal = res2dict(REAL_PATH + "data/structures/Li7Sn-Fmmm.res", as_model=True)[
            0
        ]

        doc["positions_abs"] = frac2cart(doc["lattice_cart"], doc["positions_frac"])

        np.testing.assert_array_equal(doc["positions_abs"], crystal.positions_abs)
        print(crystal.positions_abs)
        for site in crystal:
            print(site, site.get_coords("cartesian"))
Пример #3
0
    def test_pseudoternary_from_fake_query(self):
        cursor, s = res2dict(REAL_PATH + "data/hull-LLZO/*.res")
        print()
        print(80 * "-")
        self.assertEqual(
            len(cursor), 12,
            "Error with test res files, please check installation...")
        hull = QueryConvexHull(cursor=cursor,
                               elements=["La2O3", "ZrO2", "Li2O"],
                               no_plot=True)
        self.assertEqual(len(hull.cursor), 7)

        fake_query = DBQuery.__new__(DBQuery)
        fake_query.cursor = hull.cursor
        for ind, doc in enumerate(fake_query.cursor):
            fake_query.cursor[ind]["_id"] = None
            fake_query.cursor[ind]["text_id"] = [doc["source"][0], "."]
        fake_query._non_elemental = True
        fake_query._create_hull = True
        fake_query.args = dict()
        fake_query.args["intersection"] = True
        fake_query.args["subcmd"] = "hull"
        fake_query.args["composition"] = ["La2O3:ZrO2:Li2O"]
        hull = QueryConvexHull(
            query=fake_query,
            hull_cutoff=0.01,
            chempots=[26200.3194 / 40, -8715.94784 / 12, -3392.59361 / 12],
            no_plot=True,
        )
        self.assertEqual(len(hull.cursor), 10)
        self.assertEqual(len(hull.hull_cursor), 9)
Пример #4
0
    def test_binary_from_fake_query(self):
        cursor, s = res2dict(REAL_PATH + "data/hull-KP-KSnP_pub/*.res")
        print()
        print(80 * "-")
        self.assertEqual(
            len(cursor), 295,
            "Error with test res files, please check installation...")
        hull = QueryConvexHull(cursor=cursor, elements=["KP"], no_plot=True)
        self.assertEqual(len(hull.cursor), 295)
        self.assertEqual(len(hull.hull_cursor), 7)

        fake_query = DBQuery.__new__(DBQuery)
        fake_query.cursor = hull.cursor
        for ind, doc in enumerate(fake_query.cursor):
            fake_query.cursor[ind]["_id"] = None
            fake_query.cursor[ind]["text_id"] = [doc["source"][0], "."]
            del fake_query.cursor[ind]["hull_distance"]
            del fake_query.cursor[ind]["concentration"]

        fake_query._non_elemental = False
        fake_query._create_hull = True
        fake_query.args = dict()
        fake_query.args["intersection"] = False
        fake_query.args["subcmd"] = "hull"
        fake_query.args["composition"] = ["KP"]
        hull = QueryConvexHull(query=fake_query,
                               chempots=[-791.456765, -219.58161025],
                               no_plot=True)
        # now need to include custom chempots in counts
        self.assertEqual(len(hull.cursor), 297)
        self.assertEqual(len(hull.hull_cursor), 9)
Пример #5
0
    def test_pseudoternary_hull_with_custom_chempots(self):
        cursor, s = res2dict(REAL_PATH + "data/hull-LLZO/*.res")
        print()
        print(80 * "-")
        self.assertEqual(
            len(cursor), 12,
            "Error with test res files, please check installation...")
        hull = QueryConvexHull(
            cursor=cursor,
            elements=["La2O3", "ZrO2", "Li2O"],
            chempots=[-3275.040 / 5, -2178.987 / 3, -848.148 / 3],
            no_plot=True,
        )
        self.assertEqual(len(hull.cursor), 10)
        self.assertEqual(len(hull.hull_cursor), 5)

        # cursor, s = res2dict(REAL_PATH + 'data/hull-LLZO/*.res')
        hull = QueryConvexHull(
            cursor=cursor,
            elements=["La2O3", "ZrO2", "Li2O"],
            hull_cutoff=0.20,
            chempots=[26200.3194 / 40, -8715.94784 / 12, -3392.59361 / 12],
            no_plot=True,
        )
        self.assertEqual(len(hull.cursor), 10)
        self.assertEqual(len(hull.hull_cursor), 10)

        for doc in hull.hull_cursor:
            if "cubic-LLZO" in doc["source"][0]:
                self.assertAlmostEqual(doc["formation_enthalpy_per_atom"],
                                       -0.05758265622)
                self.assertAlmostEqual(doc["hull_distance"], 0.008746875)
                break
        else:
            raise RuntimeError("Did not find cubic-LLZO in cursor")
Пример #6
0
    def test_double_uniqueness_hierarchy(self):
        import glob

        files = glob.glob(REAL_PATH + "data/uniqueness_hierarchy/*.res")
        files += glob.glob(REAL_PATH + "data/hull-LLZO/*LLZO*.res")
        cursor = [res2dict(f)[0] for f in files]
        cursor = sorted(cursor, key=lambda x: x["enthalpy_per_atom"])[0:10]
        uniq_inds, _, _, _ = get_uniq_cursor(cursor,
                                             sim_tol=0.1,
                                             energy_tol=1e20,
                                             projected=True,
                                             **{
                                                 "dr": 0.01,
                                                 "gaussian_width": 0.1
                                             })
        filtered_cursor = [cursor[ind] for ind in uniq_inds]
        self.assertEqual(len(uniq_inds), 3)
        self.assertEqual(len(filtered_cursor), 3)
        print([doc["source"] for doc in filtered_cursor])
        self.assertTrue(
            "cubic-LLZO-CollCode999999" in filtered_cursor[0]["source"][0])
        self.assertTrue("KP-NaP-OQMD_2817-CollCode14009" in filtered_cursor[1]
                        ["source"][0])
        self.assertTrue(
            "KP-NaP-CollCode421420" in filtered_cursor[2]["source"][0])
Пример #7
0
    def _scrape_prototypes(self, file_lists, root):
        """ Scrape prototype data, i.e. structures with no DFT data, and push
        to database.

        Parameters:
            file_lists (dict): filenames and filetype counts stored by directory name key.
            root (str): directory name to scrape.

        Returns:
            int: number of successfully structures imported to database.

        """
        import_count = 0
        for _, file in enumerate(file_lists[root]['res']):
            res_dict, success = res2dict(file,
                                         db=False,
                                         verbosity=self.verbosity,
                                         noglob=True)
            if not success:
                self.logfile.write('! {}'.format(res_dict))
            else:
                final_struct = res_dict
                if not self.dryrun:
                    final_struct.update(self.tag_dict)
                    import_count += self._struct2db(final_struct)

        return import_count
Пример #8
0
    def test_k3p_uniq_default(self):
        cursor, _ = res2dict(REAL_PATH + "data/K3P_uniq/*.res")
        cursor = sorted(cursor, key=lambda x: x["enthalpy_per_atom"])
        uniq_inds, _, _, _ = get_uniq_cursor(cursor)
        filtered_cursor = [cursor[ind] for ind in uniq_inds]
        self.assertEqual(len(cursor), 10)
        self.assertEqual(len(filtered_cursor), 5)
        found = []
        correct_structures = [
            "K3P-OQMD_4786-CollCode25550",
            "K3P-mode-follow-swap-Na3N-OQMD_21100-CollCode165992",
            "KP-fvsqdf",
            "PK-NNa3-OQMD_21100-CollCode165992",
            "KP-yzcni8",
        ]
        for struct in correct_structures:
            for doc in filtered_cursor:
                if struct in doc["source"][0]:
                    found.append(True)
                    break
            else:
                found.append(False)

        if not all(found):
            print([doc["source"][0] for doc in filtered_cursor])

        self.assertTrue(all(found))
Пример #9
0
    def test_binary_voltage_mayo(self):
        """ Test binary voltages from cursor for Mayo et al,
        DOI: 10.1021/acs.chemmater.5b04208.

        """
        res_list = glob(REAL_PATH + "data/hull-LiP-mdm_chem_mater/*.res")
        cursor = [res2dict(res)[0] for res in res_list]
        hull = QueryConvexHull(cursor=cursor,
                               elements=["Li", "P"],
                               no_plot=True,
                               voltage=True)
        for profile in hull.voltage_data:
            self.assertEqual(len(profile.voltages), len(profile.capacities))
        LiP_voltage_curve = np.loadtxt(REAL_PATH + "data/LiP_voltage.csv",
                                       delimiter=",")
        self.assertTrue(len(hull.voltage_data) == 1)
        np.testing.assert_allclose(
            hull.voltage_data[0].voltages,
            LiP_voltage_curve[:, 1],
            verbose=True,
            rtol=1e-4,
        )
        np.testing.assert_allclose(hull.voltage_data[0].capacities,
                                   LiP_voltage_curve[:, 0],
                                   verbose=True,
                                   rtol=1e-4)
        self._check_voltages_match_capacities(hull.voltage_data)
Пример #10
0
 def test_ternary_voltage_with_single_phase_region(self):
     """ Test ternary voltages with single-phase regions. """
     # load old hull then rejig it to go through a ternary phase
     cursor = res2dict(REAL_PATH + "data/hull-LiSiP/*.res")[0]
     hull = QueryConvexHull(cursor=cursor,
                            species="LiSiP",
                            no_plot=True,
                            voltage=True)
     np.testing.assert_array_almost_equal(
         np.asarray(hull.voltage_data[0].voltages),
         np.asarray([
             1.1683,
             1.1683,
             1.0759,
             0.7983,
             0.6447,
             0.3726,
             0.3394,
             0.1995,
             0.1570,
             0.1113,
             0.1041,
             0.0000,
         ]),
         decimal=3,
     )
     self.assertEqual(len(hull.voltage_data[0].capacities), 12)
     self.assertEqual(len(hull.voltage_data[1].capacities), 11)
     self._check_voltages_match_capacities(hull.voltage_data)
Пример #11
0
    def test_concurrent_pdf(self):
        import glob
        import numpy as np
        import time
        from copy import deepcopy

        files = glob.glob(REAL_PATH + "data/hull-KPSn-KP/*.res")[0:24]
        cursor = [res2dict(file, db=False)[0] for file in files]
        serial_cursor = deepcopy(cursor)
        pdf_args = {
            "dr": 0.1,
            "num_images": "auto",
            "gaussian_width": 0.1,
            "lazy": False,
            "projected": False,
        }
        start = time.time()
        pdf_factory = PDFFactory(cursor, **pdf_args)
        factory_elapsed = time.time() - start
        start = time.time()
        for doc in serial_cursor:
            doc["pdf"] = PDF(doc, **pdf_args, timing=False)
        serial_elapsed = time.time() - start
        print("{:.2f} s over {} processes vs {:.2f} s in serial".format(
            factory_elapsed, pdf_factory.nprocs, serial_elapsed))
        print("Corresponding to a speedup of {:.1f} vs ideal {:.1f}".format(
            serial_elapsed / factory_elapsed, pdf_factory.nprocs))
        for ind, doc in enumerate(serial_cursor):
            np.testing.assert_array_almost_equal(doc["pdf"].gr,
                                                 cursor[ind]["pdf"].gr,
                                                 decimal=6)
Пример #12
0
    def test_ternary_voltage_with_exclusively_two_phase_regions(self):
        """ Test ternary voltages exclusively awkward two-phase regions. """
        # load old hull then rejig it to go through a ternary phase
        res_list = glob(REAL_PATH + "data/hull-KPSn-KP/*.res")
        self.assertEqual(
            len(res_list),
            87,
            "Could not find test res files, please check installation...",
        )
        cursor = [res2dict(res)[0] for res in res_list]
        cursor = [
            doc for doc in cursor
            if (doc["stoichiometry"] == [["P", 1], ["Sn", 1]]
                or doc["stoichiometry"] == [["K", 1], ["P", 1], ["Sn", 1]]
                or doc["stoichiometry"] == [["P", 1]] or doc["stoichiometry"]
                == [["K", 1]] or doc["stoichiometry"] == [["Sn", 1]])
        ]

        hull = QueryConvexHull(
            cursor=cursor,
            elements=["K", "Sn", "P"],
            no_plot=True,
            pathways=True,
            voltage=True,
        )
        self.assertEqual(len(hull.voltage_data), 1)
        self._check_voltages_match_capacities(hull.voltage_data)
Пример #13
0
    def test_spg_standardize(self):
        from matador.utils.cell_utils import standardize_doc_cell
        from matador.scrapers import cif2dict
        import glob

        doc, s = castep2dict(REAL_PATH +
                             "data/Na3Zn4-swap-ReOs-OQMD_759599.castep")
        std_doc = standardize_doc_cell(doc)
        dist = pdf_sim_dist(doc, std_doc)
        self.assertLess(dist, 0.01)

        fnames = glob.glob(REAL_PATH + "data/bs_test/*.res")
        for fname in fnames:
            doc, s = res2dict(fname, db=False)
            doc["cell_volume"] = cart2volume(doc["lattice_cart"])
            std_doc = standardize_doc_cell(doc)
            dist = pdf_sim_dist(doc, std_doc)
            self.assertLess(dist, 0.01)

        doc = Crystal(
            castep2dict(REAL_PATH +
                        "data/Na3Zn4-swap-ReOs-OQMD_759599.castep")[0])
        std_doc = standardize_doc_cell(doc)
        dist = pdf_sim_dist(doc, std_doc)
        self.assertLess(dist, 0.01)

        doc = Crystal(cif2dict(REAL_PATH + "data/cif_files/AgBiI.cif")[0])
        with self.assertRaises(RuntimeError):
            std_doc = standardize_doc_cell(doc)
Пример #14
0
    def test_ternary_hull_distances(self):
        """ Test computing ternary hull distances. """
        res_list = glob(REAL_PATH + "data/hull-KPSn-KP/*.res")
        self.assertEqual(
            len(res_list),
            87,
            "Could not find test res files, please check installation...",
        )
        cursor = [res2dict(res)[0] for res in res_list]
        hull = QueryConvexHull(cursor=cursor,
                               elements=["K", "Sn", "P"],
                               no_plot=True)
        self.assertEqual(len(hull.hull_cursor), 16)
        self.assertEqual(len(hull.cursor), 87)
        for ind, doc in enumerate(hull.cursor):
            hull.cursor[ind]["filename"] = doc["source"][0].split("/")[-1]

        structures = np.loadtxt(REAL_PATH + "data/test_KSnP.dat")
        hull_dist_test = np.loadtxt(REAL_PATH + "data/test_KSnP_hull_dist.dat")
        precomp_hull_dist = hull.get_hull_distances(structures,
                                                    precompute=True)
        no_precomp_hull_dist = hull.get_hull_distances(structures,
                                                       precompute=False)
        np.testing.assert_array_almost_equal(np.sort(hull_dist_test),
                                             np.sort(hull.hull_dist),
                                             decimal=3)
        np.testing.assert_array_almost_equal(np.sort(hull.hull_dist),
                                             np.sort(precomp_hull_dist),
                                             decimal=3)
        np.testing.assert_array_almost_equal(no_precomp_hull_dist,
                                             precomp_hull_dist,
                                             decimal=5)
        self.assertFalse(np.isnan(hull.hull_dist).any())
Пример #15
0
 def test_pseudoternary_hull(self):
     cursor, s = res2dict(REAL_PATH + "data/hull-LLZO/*.res")
     print()
     print(80 * "-")
     self.assertEqual(
         len(cursor), 12,
         "Error with test res files, please check installation...")
     hull = QueryConvexHull(cursor=cursor,
                            elements=["La2O3", "ZrO2", "Li2O"],
                            no_plot=True)
     self.assertEqual(len(hull.cursor), 7)
     self.assertEqual(len(hull.hull_cursor), 5)
     hull = QueryConvexHull(
         cursor=cursor,
         elements=["La2O3", "ZrO2", "Li2O"],
         hull_cutoff=0.01,
         no_plot=True,
     )
     self.assertEqual(len(hull.cursor), 7)
     self.assertEqual(len(hull.hull_cursor), 6)
     self.assertEqual(len(hull.convex_hull.vertices), 5)
     for doc in hull.hull_cursor:
         if "cubic-LLZO" in doc["source"][0]:
             self.assertAlmostEqual(doc["formation_enthalpy_per_atom"],
                                    -0.05758265622)
             self.assertAlmostEqual(doc["hull_distance"], 0.008746875)
             break
     else:
         raise RuntimeError("Did not find cubic-LLZO in cursor")
Пример #16
0
 def test_hull_from_file_with_extraneous_elements(self):
     """ Loading hull structures from files with too many elements. """
     res_list = glob(REAL_PATH + "data/hull-KPSn-KP/*.res")
     cursor = [res2dict(res)[0] for res in res_list]
     hull = QueryConvexHull(cursor=cursor,
                            elements=["K", "Sn"],
                            no_plot=True,
                            debug=True)
     self.assertEqual(len(hull.hull_cursor), 5)
Пример #17
0
 def test_pseudoternary_hull_failure(self):
     cursor, s = res2dict(REAL_PATH + "data/hull-LLZO/*.res")
     print()
     print(80 * "-")
     self.assertEqual(
         len(cursor), 12,
         "Error with test res files, please check installation...")
     with self.assertRaises(RuntimeError):
         QueryConvexHull(cursor=cursor, no_plot=True)
Пример #18
0
def main():
    """ Run GA. """
    from glob import glob
    from sys import argv
    from matador.hull import QueryConvexHull
    from matador.fingerprints.similarity import get_uniq_cursor
    from matador.utils.chem_utils import get_formula_from_stoich
    from matador.scrapers.castep_scrapers import res2dict
    from ilustrado.ilustrado import ArtificialSelector

    cursor = [res2dict(res)[0] for res in glob('seed/*.res')]
    hull = QueryConvexHull(cursor=cursor,
                           no_plot=True,
                           kpoint_tolerance=0.03,
                           summary=True,
                           hull_cutoff=1e-1)
    print('Filtering down to only ternary phases... {}'.format(
        len(hull.hull_cursor)))
    hull.hull_cursor = [
        doc for doc in hull.hull_cursor if len(doc['stoichiometry']) == 3
    ]
    print('Filtering unique structures... {}'.format(len(hull.hull_cursor)))
    # uniq_list, _, _, _ = list(get_uniq_cursor(hull.hull_cursor[1:-1], debug=False))
    # cursor = [hull.hull_cursor[1:-1][ind] for ind in uniq_list]
    cursor = hull.hull_cursor
    print('Final cursor length... {}'.format(len(cursor)))
    print('over {} stoichiometries...'.format(
        len(
            set([
                get_formula_from_stoich(doc['stoichiometry']) for doc in cursor
            ]))))
    print([doc['stoichiometry'] for doc in cursor])

    def filter_fn(doc):
        """ Filter out any non-ternary phases. """
        return True if len(doc['stoichiometry']) == 3 else False

    ArtificialSelector(gene_pool=cursor,
                       seed='KPSn',
                       compute_mode='slurm',
                       entrypoint=__file__,
                       walltime_hrs=12,
                       slurm_template='template.slurm',
                       max_num_nodes=100,
                       hull=hull,
                       check_dupes=0,
                       structure_filter=filter_fn,
                       best_from_stoich=True,
                       max_num_mutations=3,
                       max_num_atoms=50,
                       mutation_rate=0.4,
                       crossover_rate=0.6,
                       num_generations=20,
                       population=30,
                       num_survivors=20,
                       elitism=0.5,
                       loglevel='debug')
Пример #19
0
 def test_pdf_from_projected(self):
     doc, success = res2dict(REAL_PATH + "data/LiPZn-r57des.res")
     doc["lattice_cart"] = abc2cart(doc["lattice_abc"])
     doc["text_id"] = ["unprojected", "test"]
     doc["pdf_unprojected"] = PDF(doc, dr=0.01, **{"debug": False})
     doc["text_id"] = ["projected", "test"]
     doc["pdf_projected"] = PDF(doc, dr=0.01, **{"debug": False})
     np.testing.assert_array_almost_equal(doc["pdf_unprojected"].gr,
                                          doc["pdf_projected"].gr)
Пример #20
0
    def test_with_skips(self):
        from matador.crystal import Crystal
        from matador.utils.cursor_utils import filter_unique_structures
        import glob

        files = glob.glob(REAL_PATH + "data/uniqueness_hierarchy/*.res")
        cursor = [Crystal(res2dict(f)[0]) for f in files]
        filtered_cursor = filter_unique_structures(cursor, energy_tol=0)
        self.assertEqual(len(filtered_cursor), len(cursor))

        cursor = sorted([res2dict(f)[0] for f in files],
                        key=lambda doc: doc["enthalpy_per_atom"])[0:10]
        for ind, doc in enumerate(cursor):
            doc["enthalpy_per_atom"] = float(-ind)

        cursor[8]["enthalpy_per_atom"] = -5.0
        cursor[9]["enthalpy_per_atom"] = -5.0001

        filtered_cursor = filter_unique_structures(cursor, energy_tol=0.003)
        self.assertEqual(len(filtered_cursor), 8)
Пример #21
0
 def test_binary_volume_curve(self):
     """ Test simple binary volume curve. """
     res_list = glob(REAL_PATH + "data/hull-LiP-mdm_chem_mater/*.res")
     cursor = [res2dict(res)[0] for res in res_list]
     hull = QueryConvexHull(cursor=cursor,
                            elements=["Li", "P"],
                            no_plot=True)
     hull.volume_curve()
     self.assertEqual(len(hull.volume_data["x"][0]),
                      len(hull.hull_cursor) - 1)
     self.assertEqual(len(hull.volume_data["electrode_volume"][0]),
                      len(hull.hull_cursor) - 1)
Пример #22
0
def swaps():
    """ Run swaps, returning data to be checked. """
    sys.argv = [
        "matador",
        "swaps",
        "--db",
        DB_NAME,
        "--res",
        "--cell",
        "-c",
        "NaPZn",
        "-int",
        "-sw",
        "NaLi:PSi:ZnSn",
    ]
    if CONFIG_FNAME is not None:
        sys.argv += ["--config", CONFIG_FNAME]
    matador.cli.cli.main()
    expected_dir = "swaps-NaPZn-ci_test-NaLi:PSi:ZnSn"
    output_folder_exists = os.path.isdir(expected_dir)
    successes = []
    elem_successes = []
    if output_folder_exists:
        os.chdir(expected_dir)
        expected_files = [
            "Li3Si2-swap-NaP_intermediates",
            "Li3Sn4-swap-Na3Zn4-ReOs-OQMD_759599",
            "Li-swap-Na-edgecase-CollCode10101",
        ]
        target_elems = ["Li", "Si", "Sn"]

        for files in expected_files:
            cell, s = cell2dict(files, db=False, positions=True)
            successes.append(s)
            if s:
                elems = set(cell["atom_types"])
                elem_successes.append(
                    any([elem not in target_elems for elem in elems]))
            else:
                elem_successes.append(False)
            res, s = res2dict(files, db=False)
            successes.append(s)
            if s:
                elems = set(res["atom_types"])
                elem_successes.append(
                    any([elem not in target_elems for elem in elems]))
            else:
                elem_successes.append(False)

    os.chdir(OUTPUT_DIR)

    return output_folder_exists, successes, elem_successes
Пример #23
0
 def test_hull_from_file(self):
     """ Loading hull structures from files. """
     res_list = glob(REAL_PATH + "data/hull-KPSn-KP/*.res")
     self.assertEqual(
         len(res_list),
         87,
         "Could not find test res files, please check installation...",
     )
     cursor = [res2dict(res)[0] for res in res_list]
     hull = QueryConvexHull(cursor=cursor,
                            elements=["K", "Sn", "P"],
                            no_plot=True)
     self.assertEqual(len(hull.hull_cursor), 16)
Пример #24
0
    def test_slice(self):

        parents = [
            res2dict(REAL_PATH + "/query-K3P-KP/KP-NaP-CollCode182164.res")[0],
            res2dict(REAL_PATH + "/query-K6P-KP/KP-GA-uynlzz-17x7.res")[0],
        ]
        doc2res(parents[0], "parent1", hash_dupe=False, info=False)
        doc2res(parents[1], "parent2", hash_dupe=False, info=False)
        _iter = 0
        while _iter < 100:
            child = random_slice(
                parents, standardize=True, supercell=True, shift=True, debug=True
            )
            feasible = check_feasible(child, parents, max_num_atoms=50)
            _iter += 1
            if feasible:
                doc2res(child, "feasible", hash_dupe=True, info=False)
            else:
                doc2res(child, "failed", hash_dupe=True, info=False)

        parents[1] = create_simple_supercell(parents[1], [3, 1, 1])
        doc2res(parents[1], "supercell2", hash_dupe=False, info=False)
Пример #25
0
 def test_identity_overlap(self):
     doc, success = res2dict(REAL_PATH + "data/LiPZn-r57des.res")
     doc["lattice_cart"] = abc2cart(doc["lattice_abc"])
     doc["text_id"] = ["pdf", "test"]
     doc["pdf_smear"] = PDF(
         doc,
         num_images=3,
         dr=0.001,
         gaussian_width=0.1,
         style="smear",
         debug=False,
         low_mem=True,
     )
     overlap = PDFOverlap(doc["pdf_smear"], doc["pdf_smear"])
     self.assertEqual(overlap.similarity_distance, 0.0)
Пример #26
0
    def test_convert_positions(self):
        doc = res2dict(REAL_PATH + "data/structures/Li7Sn-Fmmm.res")[0]
        crystal = res2dict(REAL_PATH + "data/structures/Li7Sn-Fmmm.res",
                           as_model=True)[0]

        doc["positions_abs"] = frac2cart(doc["lattice_cart"],
                                         doc["positions_frac"])

        np.testing.assert_array_almost_equal(doc["positions_abs"],
                                             crystal.positions_abs)
        for ind, site in enumerate(crystal):
            np.testing.assert_array_almost_equal(doc["positions_abs"][ind],
                                                 site.coords_cartesian)

        crystal.cell.lengths = np.asarray(crystal.cell.lengths) * 10

        rescaled_pos = frac2cart(
            np.asarray(doc["lattice_cart"]) * 10, doc["positions_frac"])

        for ind, site in enumerate(crystal):
            np.testing.assert_array_almost_equal(doc["positions_frac"][ind],
                                                 site.coords)
            np.testing.assert_array_almost_equal(rescaled_pos[ind],
                                                 site.coords_cartesian)
Пример #27
0
 def test_uniq_filter_with_hierarchy_2(self):
     cursor, f_ = res2dict(REAL_PATH + "data/hull-LLZO/*LLZO*.res")
     cursor = sorted(cursor, key=lambda x: x["enthalpy_per_atom"])[0:10]
     uniq_inds, _, _, _ = get_uniq_cursor(cursor,
                                          sim_tol=0.1,
                                          energy_tol=1e10,
                                          projected=True,
                                          **{
                                              "dr": 0.01,
                                              "gaussian_width": 0.1
                                          })
     filtered_cursor = [cursor[ind] for ind in uniq_inds]
     self.assertEqual(len(uniq_inds), 1)
     self.assertEqual(len(filtered_cursor), 1)
     self.assertTrue(
         "cubic-LLZO-CollCode999999" in filtered_cursor[0]["source"][0])
Пример #28
0
    def test_no_overlap_retains_all_structures(self):
        import glob

        files = glob.glob(REAL_PATH + "data/uniqueness_hierarchy/*.res")
        cursor = [res2dict(f)[0] for f in files]
        uniq_inds, _, _, _ = get_uniq_cursor(cursor,
                                             sim_tol=0,
                                             energy_tol=1e20,
                                             projected=True,
                                             debug=True,
                                             **{
                                                 "dr": 0.1,
                                                 "gaussian_width": 0.1
                                             })
        filtered_cursor = [cursor[ind] for ind in uniq_inds]
        self.assertEqual(len(filtered_cursor), len(cursor))
Пример #29
0
    def test_ternary_voltage_problematic_with_crystal_models(self):
        """ Test for NaSnP voltages which triggered a bug in the capacity
        calculation.

        """
        cursor = res2dict(REAL_PATH + "data/voltage_data/voltage-NaSnP/*.res",
                          as_model=True)[0]
        hull = QueryConvexHull(cursor=cursor,
                               species="NaSnP",
                               no_plot=True,
                               voltage=True,
                               volume=True)
        self._check_voltages_match_capacities(hull.voltage_data)
        self.assertEqual(len(hull.voltage_data), 2)
        self.assertEqual(len(hull.voltage_data[0].capacities), 13)
        self.assertEqual(len(hull.voltage_data[1].capacities), 12)
Пример #30
0
def _match_peaks(res_file, gsas_reflections, **kwargs):
    """ Check if peaks match with HKL between matador and GSAS. """
    doc, s = res2dict(res_file, as_model=True)

    pxrd = PXRD(doc, **kwargs)
    gsas_peaks = np.loadtxt(gsas_reflections)
    hkl_array = {}
    for peak in gsas_peaks:
        hkl_array[(int(peak[0]), int(peak[1]), int(peak[2]))] = peak[3]

    for ind, hkl in enumerate(pxrd.hkls):
        hkl_tuple = (int(hkl[0]), int(hkl[1]), int(hkl[2]))
        if hkl_tuple in hkl_array:
            assert (np.abs(hkl_array[hkl_tuple] - pxrd.peak_positions[ind]) <
                    PEAK_POS_TOL)

    return pxrd