本文整理汇总了Python中pymatgen.analysis.structure_matcher.StructureMatcher.group_structures方法的典型用法代码示例。如果您正苦于以下问题:Python StructureMatcher.group_structures方法的具体用法?Python StructureMatcher.group_structures怎么用?Python StructureMatcher.group_structures使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymatgen.analysis.structure_matcher.StructureMatcher
的用法示例。
在下文中一共展示了StructureMatcher.group_structures方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_class
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_class(self):
# Tests entire class as single working unit
sm = StructureMatcher()
# Test group_structures and find_indices
out = sm.group_structures(self.struct_list)
self.assertEqual(list(map(len, out)), [4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1])
self.assertEqual(sum(map(len, out)), len(self.struct_list))
for s in self.struct_list[::2]:
s.replace_species({'Ti': 'Zr', 'O':'Ti'})
out = sm.group_structures(self.struct_list, anonymous=True)
self.assertEqual(list(map(len, out)), [4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1])
示例2: test_class
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_class(self):
# Tests entire class as single working unit
sm = StructureMatcher()
# Test group_structures and find_indices
out = sm.group_structures(self.struct_list)
self.assertEqual(map(len, out), [4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1])
self.assertEqual(sum(map(len, out)), len(self.struct_list))
示例3: test_previous_reconstructions
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_previous_reconstructions(self):
# Test to see if we generated all reconstruction
# types correctly and nothing changes
m = StructureMatcher()
for n in self.rec_archive.keys():
if "base_reconstruction" in self.rec_archive[n].keys():
arch = self.rec_archive[
self.rec_archive[n]["base_reconstruction"]]
sg = arch["spacegroup"]["symbol"]
else:
sg = self.rec_archive[n]["spacegroup"]["symbol"]
if sg == "Fm-3m":
rec = ReconstructionGenerator(self.Ni, 20, 20, n)
el = self.Ni[0].species_string
elif sg == "Im-3m":
rec = ReconstructionGenerator(self.Fe, 20, 20, n)
el = self.Fe[0].species_string
elif sg == "Fd-3m":
rec = ReconstructionGenerator(self.Si, 20, 20, n)
el = self.Si[0].species_string
slabs = rec.build_slabs()
s = Structure.from_file(get_path(os.path.join("reconstructions",
el + "_" + n + ".cif")))
self.assertTrue(any(
[len(m.group_structures([s, slab])) == 1 for slab in slabs]))
示例4: compare_structures
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def compare_structures(options):
"""Inspired to a similar function in pmg_structure."""
paths = options.paths
if len(paths) < 2:
print("You need more than one structure to compare!")
return 1
try:
structures = [abilab.Structure.from_file(p) for p in paths]
except Exception as ex:
print("Error reading structures from files. Are they in the right format?")
print(str(ex))
return 1
from pymatgen.analysis.structure_matcher import StructureMatcher, ElementComparator
compareby = "species" if options.anonymous else "element"
m = StructureMatcher() if compareby == "species" else StructureMatcher(comparator=ElementComparator())
print("Grouping %s structures by `%s` with `anonymous: %s`" % (len(structures), compareby, options.anonymous))
for i, grp in enumerate(m.group_structures(structures, anonymous=options.anonymous)):
print("Group {}: ".format(i))
for s in grp:
spg_symbol, international_number = s.get_space_group_info()
print("\t- {} ({}), vol: {:.2f} A^3, {} ({})".format(
paths[structures.index(s)], s.formula, s.volume, spg_symbol, international_number))
print()
if options.verbose:
pprint(m.as_dict())
示例5: test_class
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_class(self):
# Tests entire class as single working unit
sm = StructureMatcher()
# Test group_structures and find_indices
out = sm.group_structures(self.struct_list)
self.assertEqual(sm.find_indexes(self.struct_list, out), [0, 0, 0, 1, 2, 3, 4, 0, 5, 6, 7, 8, 8, 9, 9, 10])
示例6: apply_transformation
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def apply_transformation(self, structure, return_ranked_list=False):
#Make a mutable structure first
mods = Structure.from_sites(structure)
for sp, spin in self.mag_species_spin.items():
sp = get_el_sp(sp)
oxi_state = getattr(sp, "oxi_state", 0)
if spin:
up = Specie(sp.symbol, oxi_state, {"spin": abs(spin)})
down = Specie(sp.symbol, oxi_state, {"spin": -abs(spin)})
mods.replace_species(
{sp: Composition({up: self.order_parameter,
down: 1 - self.order_parameter})})
else:
mods.replace_species(
{sp: Specie(sp.symbol, oxi_state, {"spin": spin})})
if mods.is_ordered:
return [mods] if return_ranked_list > 1 else mods
enum_args = self.enum_kwargs
enum_args["min_cell_size"] = max(int(
MagOrderingTransformation.determine_min_cell(
structure, self.mag_species_spin,
self.order_parameter)),
enum_args.get("min_cell_size"))
max_cell = self.enum_kwargs.get('max_cell_size')
if max_cell:
if enum_args["min_cell_size"] > max_cell:
raise ValueError('Specified max cell size is smaller'
' than the minimum enumerable cell size')
else:
enum_args["max_cell_size"] = enum_args["min_cell_size"]
t = EnumerateStructureTransformation(**enum_args)
alls = t.apply_transformation(mods,
return_ranked_list=return_ranked_list)
try:
num_to_return = int(return_ranked_list)
except ValueError:
num_to_return = 1
if num_to_return == 1 or not return_ranked_list:
return alls[0]["structure"] if num_to_return else alls
m = StructureMatcher(comparator=SpinComparator())
grouped = m.group_structures([d["structure"] for d in alls])
alls = [{"structure": g[0], "energy": self.emodel.get_energy(g[0])}
for g in grouped]
self._all_structures = sorted(alls, key=lambda d: d["energy"])
return self._all_structures[0:num_to_return]
示例7: test_mix
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_mix(self):
structures = [self.get_structure("Li2O"), self.get_structure("Li2O2"), self.get_structure("LiFePO4")]
for fname in ["POSCAR.Li2O", "POSCAR.LiFePO4"]:
structures.append(Structure.from_file(os.path.join(test_dir, fname)))
sm = StructureMatcher(comparator=ElementComparator())
groups = sm.group_structures(structures)
for g in groups:
formula = g[0].composition.reduced_formula
if formula in ["Li2O", "LiFePO4"]:
self.assertEqual(len(g), 2)
else:
self.assertEqual(len(g), 1)
示例8: test_ignore_species
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def test_ignore_species(self):
s1 = Structure.from_file(os.path.join(test_dir, "LiFePO4.cif"))
s2 = Structure.from_file(os.path.join(test_dir, "POSCAR"))
m = StructureMatcher(ignored_species=["Li"], primitive_cell=False, attempt_supercell=True)
self.assertTrue(m.fit(s1, s2))
self.assertTrue(m.fit_anonymous(s1, s2))
groups = m.group_structures([s1, s2])
self.assertEqual(len(groups), 1)
s2.make_supercell((2, 1, 1))
ss1 = m.get_s2_like_s1(s2, s1, include_ignored_species=True)
self.assertAlmostEqual(ss1.lattice.a, 20.820740000000001)
self.assertEqual(ss1.composition.reduced_formula, "LiFePO4")
self.assertEqual(
{k.symbol: v.symbol for k, v in m.get_best_electronegativity_anonymous_mapping(s1, s2).items()},
{"Fe": "Fe", "P": "P", "O": "O"},
)
示例9: get_slabs
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def get_slabs(self, bonds=None, tol=0.1, max_broken_bonds=0):
"""
This method returns a list of slabs that are generated using the list of
shift values from the method, _calculate_possible_shifts(). Before the
shifts are used to create the slabs however, if the user decides to take
into account whether or not a termination will break any polyhedral
structure (bonds != None), this method will filter out any shift values
that do so.
Args:
bonds ({(specie1, specie2): max_bond_dist}: bonds are
specified as a dict of tuples: float of specie1, specie2
and the max bonding distance. For example, PO4 groups may be
defined as {("P", "O"): 3}.
tol (float): Threshold parameter in fcluster in order to check
if two atoms are lying on the same plane. Default thresh set
to 0.1 Angstrom in the direction of the surface normal.
max_broken_bonds (int): Maximum number of allowable broken bonds
for the slab. Use this to limit # of slabs (some structures
may have a lot of slabs). Defaults to zero, which means no
defined bonds must be broken.
Returns:
([Slab]) List of all possible terminations of a particular surface.
Slabs are sorted by the # of bonds broken.
"""
c_ranges = set() if bonds is None else self._get_c_ranges(bonds)
slabs = []
for shift in self._calculate_possible_shifts(tol=tol):
bonds_broken = 0
for r in c_ranges:
if r[0] <= shift <= r[1]:
bonds_broken += 1
if bonds_broken <= max_broken_bonds:
# For now, set the energy to be equal to no. of broken bonds
# per unit cell.
slab = self.get_slab(shift, tol=tol, energy=bonds_broken)
slabs.append(slab)
# Further filters out any surfaces made that might be the same
m = StructureMatcher(ltol=tol, stol=tol, primitive_cell=False,
scale=False)
slabs = [g[0] for g in m.group_structures(slabs)]
return sorted(slabs, key=lambda s: s.energy)
示例10: compare_structures
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def compare_structures(args):
filenames = args.filenames
if len(filenames) < 2:
print("You need more than one structure to compare!")
sys.exit(-1)
try:
structures = [Structure.from_file(fn) for fn in filenames]
except Exception as ex:
print("Error converting file. Are they in the right format?")
print(str(ex))
sys.exit(-1)
m = StructureMatcher() if args.group == "species" \
else StructureMatcher(comparator=ElementComparator())
for i, grp in enumerate(m.group_structures(structures)):
print("Group {}: ".format(i))
for s in grp:
print("- {} ({})".format(filenames[structures.index(s)],
s.formula))
print()
示例11: RemoveDuplicatesFilterTest
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
class RemoveDuplicatesFilterTest(unittest.TestCase):
def setUp(self):
with open(os.path.join(test_dir, "TiO2_entries.json"), "rb") as fp:
entries = json.load(fp, cls=PMGJSONDecoder)
self._struct_list = [e.structure for e in entries]
self._sm = StructureMatcher()
def test_filter(self):
transmuter = StandardTransmuter.from_structures(self._struct_list)
fil = RemoveDuplicatesFilter()
transmuter.apply_filter(fil)
out = self._sm.group_structures(transmuter.transformed_structures)
self.assertEqual(
self._sm.find_indexes(transmuter.transformed_structures, out), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
)
def test_to_from_dict(self):
fil = RemoveDuplicatesFilter()
d = fil.to_dict
self.assertIsInstance(RemoveDuplicatesFilter().from_dict(d), RemoveDuplicatesFilter)
示例12: compare_structures
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def compare_structures(args):
filenames = args.filenames
if len(filenames) < 2:
print "You need more than one structure to compare!"
sys.exit(-1)
try:
structures = map(read_structure, filenames)
except Exception as ex:
print "Error converting file. Are they in the right format?"
print str(ex)
sys.exit(-1)
from pymatgen.analysis.structure_matcher import StructureMatcher, ElementComparator
m = StructureMatcher() if args.oxi else StructureMatcher(comparator=ElementComparator())
for i, grp in enumerate(m.group_structures(structures)):
print "Group {}: ".format(i)
for s in grp:
print "- {} ({})".format(filenames[structures.index(s)], s.formula)
print
示例13: generate_substitution_structures
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def generate_substitution_structures(self, atom, target_species=[],
sub_both_sides=False, range_tol=1e-2,
dist_from_surf=0):
"""
Function that performs substitution-type doping on the surface and
returns all possible configurations where one dopant is substituted
per surface. Can substitute one surface or both.
Args:
atom (str): atom corresponding to substitutional dopant
sub_both_sides (bool): If true, substitute an equivalent
site on the other surface
target_species (list): List of specific species to substitute
range_tol (float): Find viable substitution sites at a specific
distance from the surface +- this tolerance
dist_from_surf (float): Distance from the surface to find viable
substitution sites, defaults to 0 to substitute at the surface
"""
# Get symmetrized structure in case we want to substitue both sides
sym_slab = SpacegroupAnalyzer(self.slab).get_symmetrized_structure()
# Define a function for substituting a site
def substitute(site, i):
slab = self.slab.copy()
props = self.slab.site_properties
if sub_both_sides:
# Find an equivalent site on the other surface
eq_indices = [indices for indices in
sym_slab.equivalent_indices if i in indices][0]
for ii in eq_indices:
if "%.6f" % (sym_slab[ii].frac_coords[2]) != \
"%.6f" % (site.frac_coords[2]):
props["surface_properties"][ii] = "substitute"
slab.replace(ii, atom)
break
props["surface_properties"][i] = "substitute"
slab.replace(i, atom)
slab.add_site_property("surface_properties",
props["surface_properties"])
return slab
# Get all possible substitution sites
substituted_slabs = []
# Sort sites so that we can define a range relative to the position of the
# surface atoms, i.e. search for sites above (below) the bottom (top) surface
sorted_sites = sorted(sym_slab, key=lambda site: site.frac_coords[2])
if sorted_sites[0].surface_properties == "surface":
d = sorted_sites[0].frac_coords[2] + dist_from_surf
else:
d = sorted_sites[-1].frac_coords[2] - dist_from_surf
for i, site in enumerate(sym_slab):
if d - range_tol < site.frac_coords[2] < d + range_tol:
if target_species and site.species_string in target_species:
substituted_slabs.append(substitute(site, i))
elif not target_species:
substituted_slabs.append(substitute(site, i))
matcher = StructureMatcher()
return [s[0] for s in matcher.group_structures(substituted_slabs)]
示例14: adsorb_both_surfaces
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def adsorb_both_surfaces(self, molecule, repeat=None, min_lw=5.0,
reorient=True, find_args={}, ltol=0.1,
stol=0.1, angle_tol=0.01):
"""
Function that generates all adsorption structures for a given
molecular adsorbate on both surfaces of a slab.
Args:
molecule (Molecule): molecule corresponding to adsorbate
repeat (3-tuple or list): repeat argument for supercell generation
min_lw (float): minimum length and width of the slab, only used
if repeat is None
reorient (bool): flag on whether or not to reorient adsorbate
along the miller index
find_args (dict): dictionary of arguments to be passed to the
call to self.find_adsorption_sites, e.g. {"distance":2.0}
ltol (float): Fractional length tolerance. Default is 0.2.
stol (float): Site tolerance. Defined as the fraction of the
average free length per atom := ( V / Nsites ) ** (1/3)
Default is 0.3.
angle_tol (float): Angle tolerance in degrees. Default is 5 degrees.
"""
# First get all possible adsorption configurations for this surface
adslabs = self.generate_adsorption_structures(molecule, repeat=repeat, min_lw=min_lw,
reorient=reorient, find_args=find_args)
# Now we need to sort the sites by their position along
# c as well as whether or not they are adsorbate
single_ads = []
for i, slab in enumerate(adslabs):
sorted_sites = sorted(slab, key=lambda site: site.frac_coords[2])
ads_indices = [site_index for site_index, site in enumerate(sorted_sites) \
if site.surface_properties == "adsorbate"]
non_ads_indices = [site_index for site_index, site in enumerate(sorted_sites) \
if site.surface_properties != "adsorbate"]
species, fcoords, props = [], [], {"surface_properties": []}
for site in sorted_sites:
species.append(site.specie)
fcoords.append(site.frac_coords)
props["surface_properties"].append(site.surface_properties)
slab_other_side = Structure(slab.lattice, species,
fcoords, site_properties=props)
# For each adsorbate, get its distance from the surface and move it
# to the other side with the same distance from the other surface
for ads_index in ads_indices:
props["surface_properties"].append("adsorbate")
adsite = sorted_sites[ads_index]
diff = abs(adsite.frac_coords[2] - \
sorted_sites[non_ads_indices[-1]].frac_coords[2])
slab_other_side.append(adsite.specie, [adsite.frac_coords[0],
adsite.frac_coords[1],
sorted_sites[0].frac_coords[2] - diff],
properties={"surface_properties": "adsorbate"})
# slab_other_side[-1].add
# Remove the adsorbates on the original side of the slab
# to create a slab with one adsorbate on the other side
slab_other_side.remove_sites(ads_indices)
# Put both slabs with adsorption on one side
# and the other in a list of slabs for grouping
single_ads.extend([slab, slab_other_side])
# Now group the slabs.
matcher = StructureMatcher(ltol=ltol, stol=stol,
angle_tol=angle_tol)
groups = matcher.group_structures(single_ads)
# Each group should be a pair with adsorbate on one side and the other.
# If a slab has no equivalent adsorbed slab on the other side, skip.
adsorb_both_sides = []
for i, group in enumerate(groups):
if len(group) != 2:
continue
ads1 = [site for site in group[0] if \
site.surface_properties == "adsorbate"][0]
group[1].append(ads1.specie, ads1.frac_coords,
properties={"surface_properties": "adsorbate"})
# Build the slab object
species, fcoords, props = [], [], {"surface_properties": []}
for site in group[1]:
species.append(site.specie)
fcoords.append(site.frac_coords)
props["surface_properties"].append(site.surface_properties)
s = Structure(group[1].lattice, species, fcoords, site_properties=props)
adsorb_both_sides.append(s)
return adsorb_both_sides
示例15: get_tasker2_slabs
# 需要导入模块: from pymatgen.analysis.structure_matcher import StructureMatcher [as 别名]
# 或者: from pymatgen.analysis.structure_matcher.StructureMatcher import group_structures [as 别名]
def get_tasker2_slabs(self, tol=0.01, same_species_only=True):
"""
Get a list of slabs that have been Tasker 2 corrected.
Args:
tol (float): Tolerance to determine if atoms are within same plane.
This is a fractional tolerance, not an absolute one.
same_species_only (bool): If True, only that are of the exact same
species as the atom at the outermost surface are considered for
moving. Otherwise, all atoms regardless of species that is
within tol are considered for moving. Default is True (usually
the desired behavior).
Returns:
([Slab]) List of tasker 2 corrected slabs.
"""
sites = list(self.sites)
slabs = []
sortedcsites = sorted(sites, key=lambda site: site.c)
# Determine what fraction the slab is of the total cell size in the
# c direction. Round to nearest rational number.
nlayers_total = int(round(self.lattice.c /
self.oriented_unit_cell.lattice.c))
nlayers_slab = int(round((sortedcsites[-1].c - sortedcsites[0].c)
* nlayers_total))
slab_ratio = nlayers_slab / nlayers_total
a = SpacegroupAnalyzer(self)
symm_structure = a.get_symmetrized_structure()
def equi_index(site):
for i, equi_sites in enumerate(symm_structure.equivalent_sites):
if site in equi_sites:
return i
raise ValueError("Cannot determine equi index!")
for surface_site, shift in [(sortedcsites[0], slab_ratio),
(sortedcsites[-1], -slab_ratio)]:
tomove = []
fixed = []
for site in sites:
if abs(site.c - surface_site.c) < tol and (
(not same_species_only) or
site.species_and_occu == surface_site.species_and_occu):
tomove.append(site)
else:
fixed.append(site)
# Sort and group the sites by the species and symmetry equivalence
tomove = sorted(tomove, key=lambda s: equi_index(s))
grouped = [list(sites) for k, sites in itertools.groupby(
tomove, key=lambda s: equi_index(s))]
if len(tomove) == 0 or any([len(g) % 2 != 0 for g in grouped]):
warnings.warn("Odd number of sites to divide! Try changing "
"the tolerance to ensure even division of "
"sites or create supercells in a or b directions "
"to allow for atoms to be moved!")
continue
combinations = []
for g in grouped:
combinations.append(
[c for c in itertools.combinations(g, int(len(g) / 2))])
for selection in itertools.product(*combinations):
species = [site.species_and_occu for site in fixed]
fcoords = [site.frac_coords for site in fixed]
for s in tomove:
species.append(s.species_and_occu)
for group in selection:
if s in group:
fcoords.append(s.frac_coords)
break
else:
# Move unselected atom to the opposite surface.
fcoords.append(s.frac_coords + [0, 0, shift])
# sort by species to put all similar species together.
sp_fcoord = sorted(zip(species, fcoords), key=lambda x: x[0])
species = [x[0] for x in sp_fcoord]
fcoords = [x[1] for x in sp_fcoord]
slab = Slab(self.lattice, species, fcoords, self.miller_index,
self.oriented_unit_cell, self.shift,
self.scale_factor, energy=self.energy)
slabs.append(slab)
s = StructureMatcher()
unique = [ss[0] for ss in s.group_structures(slabs)]
return unique