本文整理汇总了Python中pymatgen.core.composition.Composition.from_dict方法的典型用法代码示例。如果您正苦于以下问题:Python Composition.from_dict方法的具体用法?Python Composition.from_dict怎么用?Python Composition.from_dict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymatgen.core.composition.Composition
的用法示例。
在下文中一共展示了Composition.from_dict方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_from_dict
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def test_from_dict(self):
sym_dict = {"Fe": 6, "O": 8}
self.assertEqual(
Composition.from_dict(sym_dict).reduced_formula, "Fe3O4", "Creation form sym_amount dictionary failed!"
)
comp = Composition({"Fe2+": 2, "Fe3+": 4, "O2-": 8})
comp2 = Composition.from_dict(comp.as_dict())
self.assertEqual(comp, comp2)
示例2: test_Metallofullerene
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def test_Metallofullerene(self):
# Test: Parse Metallofullerene formula (e.g. [email protected])
formula = "[email protected]"
sym_dict = {"Y": 3, "N": 1, "C": 80}
cmp = Composition(formula)
cmp2 = Composition.from_dict(sym_dict)
self.assertEqual(cmp, cmp2)
示例3: test_as_dict
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def test_as_dict(self):
c = Composition.from_dict({"Fe": 4, "O": 6})
d = c.as_dict()
correct_dict = {"Fe": 4.0, "O": 6.0}
self.assertEqual(d["Fe"], correct_dict["Fe"])
self.assertEqual(d["O"], correct_dict["O"])
correct_dict = {"Fe": 2.0, "O": 3.0}
d = c.to_reduced_dict
self.assertEqual(d["Fe"], correct_dict["Fe"])
self.assertEqual(d["O"], correct_dict["O"])
示例4: disordered_formula
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def disordered_formula(disordered_struct, symbols=('x', 'y', 'z'), fmt='plain'):
"""
Returns a formula of a form like AxB1-x (x=0.5)
for disordered structures. Will only return a
formula for disordered structures with one
kind of disordered site at present.
Args:
disordered_struct: a disordered structure
symbols: a tuple of characters to use for
subscripts, by default this is ('x', 'y', 'z')
but if you have more than three disordered
species more symbols will need to be added
fmt (str): 'plain', 'HTML' or 'LaTeX'
Returns (str): a disordered formula string
"""
# this is in string utils and not in
# Composition because we need to have access
# to site occupancies to calculate this, so
# have to pass the full structure as an argument
# (alternatively this could be made a method on
# Structure)
from pymatgen.core.composition import Composition
from pymatgen.core.periodic_table import get_el_sp
if disordered_struct.is_ordered:
raise ValueError("Structure is not disordered, "
"so disordered formula not defined.")
disordered_site_compositions = {site.species_and_occu
for site in disordered_struct if not site.is_ordered}
if len(disordered_site_compositions) > 1:
# this probably won't happen too often
raise ValueError("Ambiguous how to define disordered "
"formula when more than one type of disordered "
"site is present.")
disordered_site_composition = disordered_site_compositions.pop()
disordered_species = {str(sp) for sp, occu in disordered_site_composition.items()}
if len(disordered_species) > len(symbols):
# this probably won't happen too often either
raise ValueError("Not enough symbols to describe disordered composition: "
"{}".format(symbols))
symbols = list(symbols)[0:len(disordered_species) - 1]
comp = disordered_struct.composition.get_el_amt_dict().items()
# sort by electronegativity, as per composition
comp = sorted(comp, key=lambda x: get_el_sp(x[0]).X)
disordered_comp = []
variable_map = {}
total_disordered_occu = sum([occu for sp, occu in comp
if str(sp) in disordered_species])
# composition to get common factor
factor_comp = disordered_struct.composition.as_dict()
factor_comp['X'] = total_disordered_occu
for sp in disordered_species:
del factor_comp[str(sp)]
factor_comp = Composition.from_dict(factor_comp)
factor = factor_comp.get_reduced_formula_and_factor()[1]
total_disordered_occu /= factor
remainder = "{}-{}".format(formula_double_format(total_disordered_occu, ignore_ones=False),
'-'.join(symbols))
for sp, occu in comp:
sp = str(sp)
if sp not in disordered_species:
disordered_comp.append((sp, formula_double_format(occu/factor)))
else:
if len(symbols) > 0:
symbol = symbols.pop(0)
disordered_comp.append((sp, symbol))
variable_map[symbol] = occu / total_disordered_occu / factor
else:
disordered_comp.append((sp, remainder))
if fmt == 'LaTeX':
sub_start = "_{"
sub_end = "}"
elif fmt == 'HTML':
sub_start = "<sub>"
sub_end = "</sub>"
elif fmt != 'plain':
raise ValueError("Unsupported output format, "
"choose from: LaTeX, HTML, plain")
disordered_formula = []
for sp, occu in disordered_comp:
disordered_formula.append(sp)
if occu: # can be empty string if 1
if fmt != 'plain':
disordered_formula.append(sub_start)
disordered_formula.append(occu)
#.........这里部分代码省略.........
示例5: get_structure_type
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def get_structure_type(structure, tol=0.1, seed_index=0,
write_poscar_from_cluster=False):
"""
This is a topology-scaling algorithm used to describe the
periodicity of bonded clusters in a bulk structure.
Args:
structure (structure): Pymatgen structure object to classify.
tol (float): Additional percent of atomic radii to allow
for overlap, thereby defining bonds
(0.1 = +10%, -0.1 = -10%)
seed_index (int): Atom number to start the cluster.
write_poscar_from_cluster (bool): Set to True to write a
POSCAR file from the sites in the cluster.
Returns:
string. "molecular" (0D), "chain" (1D), "layered" (2D), or
"conventional" (3D). Also includes " heterogeneous"
if the cluster's composition is not equal to that
of the overal structure.
"""
# Get conventional structure to orthogonalize the lattice as
# much as possible. A tolerance of 0.1 Angst. was suggested by
# pymatgen developers.
s = SpacegroupAnalyzer(structure, 0.1).get_conventional_standard_structure()
heterogeneous = False
noble_gases = ["He", "Ne", "Ar", "Kr", "Xe", "Rn"]
if len([e for e in structure.composition if e.symbol in noble_gases]) != 0:
type = "noble gas"
else:
# make 2x2x2 supercell to ensure sufficient number of atoms
# for cluster building.
s.make_supercell(2)
# Distance matrix (rowA, columnB) shows distance between
# atoms A and B, taking PBCs into account.
distance_matrix = s.distance_matrix
# Fill diagonal with a large number, so the code knows that
# each atom is not bonded to itself.
np.fill_diagonal(distance_matrix, 100)
# Rows (`radii`) and columns (`radiiT`) of radii.
radii = [ELEMENT_RADII[site.species_string] for site in s.sites]
radiiT = np.array(radii)[np.newaxis].T
radii_matrix = radii + radiiT*(1+tol)
# elements of temp that have value less than 0 are bonded.
temp = distance_matrix - radii_matrix
# True (1) is placed where temp < 0, and False (0) where
# it is not.
binary_matrix = (temp < 0).astype(int)
# list of atoms bonded to the seed atom of a cluster
seed = set((np.where(binary_matrix[seed_index]==1))[0])
cluster = seed
NEW = seed
while True:
temp_set = set()
for n in NEW:
# temp_set will have all atoms, without duplicates,
# that are connected to all atoms in NEW.
temp_set.update(set(np.where(binary_matrix[n]==1)[0]))
if temp_set.issubset(cluster):
# if temp_set has no new atoms, the search is done.
break
else:
NEW = temp_set - cluster # List of newly discovered atoms
cluster.update(temp_set) # cluster is updated with new atoms
if len(cluster) == 0: # i.e. the cluster is a single atom.
cluster = [seed_index] # Make sure it's not empty to write POSCAR.
type = "molecular"
elif len(cluster) == len(s.sites): # i.e. all atoms are bonded.
type = "conventional"
else:
cmp = Composition.from_dict(Counter([s[l].specie.name for l in
list(cluster)]))
if cmp.reduced_formula != s.composition.reduced_formula:
# i.e. the cluster does not have the same composition
# as the overall crystal; therefore there are other
# clusters of varying composition.
heterogeneous = True
old_cluster_size = len(cluster)
# Increase structure to determine whether it is
# layered or molecular, then perform the same kind
# of cluster search as before.
s.make_supercell(2)
distance_matrix = s.distance_matrix
np.fill_diagonal(distance_matrix,100)
radii = [ELEMENT_RADII[site.species_string] for site in s.sites]
radiiT = np.array(radii)[np.newaxis].T
radii_matrix = radii + radiiT*(1+tol)
temp = distance_matrix-radii_matrix
binary_matrix = (temp < 0).astype(int)
#.........这里部分代码省略.........
示例6: plot_ion_hull_and_voltages
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def plot_ion_hull_and_voltages(ion, fmt='pdf'):
"""
Plots the phase diagram between the pure material and pure ion,
Connecting the points on the convex hull of the phase diagram.
Args:
ion (str): name of atom that was intercalated, e.g. 'Li'.
fmt (str): matplotlib format style. Check the matplotlib
docs for options.
"""
# Calculated with the relax() function in
# twod_materials.stability.startup. If you are using other input
# parameters, you need to recalculate these values!
ion_ev_fu = {'Li': -1.7540797, 'Mg': -1.31976062, 'Al': -3.19134607}
energy = Vasprun('vasprun.xml').final_energy
composition = Structure.from_file('POSCAR').composition
# Get the formula (with single-digit integers preceded by a '_').
twod_material = list(composition.reduced_formula)
twod_formula = str()
for i in range(len(twod_material)):
try:
int(twod_material[i])
twod_formula += '_{}'.format(twod_material[i])
except:
twod_formula += twod_material[i]
twod_ev_fu = energy / composition.get_reduced_composition_and_factor()[1]
data = [(0, 0, 0, twod_ev_fu)] # (at% ion, n_ions, E_F, abs_energy)
for directory in [
dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)]:
if is_converged(directory):
os.chdir(directory)
energy = Vasprun('vasprun.xml').final_energy
composition = Structure.from_file('POSCAR').composition
ion_fraction = composition.get_atomic_fraction(ion)
no_ion_comp_dict = composition.as_dict()
no_ion_comp_dict.update({ion: 0})
no_ion_comp = Composition.from_dict(no_ion_comp_dict)
n_twod_fu = no_ion_comp.get_reduced_composition_and_factor()[1]
n_ions = composition[ion] / n_twod_fu
E_F = (
(energy - composition[ion] * ion_ev_fu[ion]
- twod_ev_fu * n_twod_fu)
/ composition.num_atoms
)
data.append((ion_fraction, n_ions, E_F, energy / n_twod_fu))
os.chdir('../')
data.append((1, 1, 0, ion_ev_fu[ion])) # Pure ion
sorted_data = sorted(data, key=operator.itemgetter(0))
# Determine which compositions are on the convex hull.
energy_profile = np.array([[item[0], item[2]]
for item in sorted_data if item[2] <= 0])
hull = ConvexHull(energy_profile)
convex_ion_fractions = [
energy_profile[vertex, 0] for vertex in hull.vertices]
convex_formation_energies = [
energy_profile[vertex, 1] for vertex in hull.vertices]
convex_ion_fractions.append(convex_ion_fractions.pop(0))
convex_formation_energies.append(convex_formation_energies.pop(0))
concave_ion_fractions = [
pt[0] for pt in sorted_data if pt[0] not in convex_ion_fractions]
concave_formation_energies = [
pt[2] for pt in sorted_data if pt[0] not in convex_ion_fractions]
voltage_profile = []
j = 0
k = 0
for i in range(1, len(sorted_data) - 1):
if sorted_data[i][0] in convex_ion_fractions:
voltage = -(
((sorted_data[i][3] - sorted_data[k][3])
- (sorted_data[i][1] - sorted_data[k][1]) * ion_ev_fu[ion])
/ (sorted_data[i][1] - sorted_data[k][1])
)
voltage_profile.append((sorted_data[k][0], voltage))
voltage_profile.append((sorted_data[i][0], voltage))
j += 1
k = i
voltage_profile.append((voltage_profile[-1][0], 0))
voltage_profile.append((1, 0))
voltage_profile_x = [tup[0] for tup in voltage_profile]
voltage_profile_y = [tup[1] for tup in voltage_profile]
ax = plt.figure(figsize=(14, 10)).gca()
#.........这里部分代码省略.........
示例7: get_structure_type
# 需要导入模块: from pymatgen.core.composition import Composition [as 别名]
# 或者: from pymatgen.core.composition.Composition import from_dict [as 别名]
def get_structure_type(structure, write_poscar_from_cluster=False):
"""
This is a topology-scaling algorithm used to describe the
periodicity of bonded clusters in a bulk structure.
Args:
structure (structure): Pymatgen structure object to classify.
write_poscar_from_cluster (bool): Set to True to write a
POSCAR from the sites in the cluster.
Returns:
string. 'molecular' (0D), 'chain', 'layered', 'heterogeneous'
(intercalated 3D), or 'conventional' (3D)
"""
# The conventional standard structure is much easier to work
# with.
structure = SpacegroupAnalyzer(
structure).get_conventional_standard_structure()
# Noble gases don't have well-defined bonding radii.
if not len([e for e in structure.composition
if e.symbol in ['He', 'Ne', 'Ar', 'Kr', 'Xe']]) == 0:
type = 'noble gas'
else:
if len(structure.sites) < 45:
structure.make_supercell(2)
# Create a dict of sites as keys and lists of their
# bonded neighbors as values.
sites = structure.sites
bonds = {}
for site in sites:
bonds[site] = []
for i in range(len(sites)):
site_1 = sites[i]
for site_2 in sites[i+1:]:
if (site_1.distance(site_2) <
float(Element(site_1.specie).atomic_radius
+ Element(site_2.specie).atomic_radius) * 1.1):
bonds[site_1].append(site_2)
bonds[site_2].append(site_1)
# Assimilate all bonded atoms in a cluster; terminate
# when it stops growing.
cluster_terminated = False
while not cluster_terminated:
original_cluster_size = len(bonds[sites[0]])
for site in bonds[sites[0]]:
bonds[sites[0]] += [
s for s in bonds[site] if s not in bonds[sites[0]]]
if len(bonds[sites[0]]) == original_cluster_size:
cluster_terminated = True
original_cluster = bonds[sites[0]]
if len(bonds[sites[0]]) == 0: # i.e. the cluster is a single atom.
type = 'molecular'
elif len(bonds[sites[0]]) == len(sites): # i.e. all atoms are bonded.
type = 'conventional'
else:
# If the cluster's composition is not equal to the
# structure's overall composition, it is a heterogeneous
# compound.
cluster_composition_dict = {}
for site in bonds[sites[0]]:
if Element(site.specie) in cluster_composition_dict:
cluster_composition_dict[Element(site.specie)] += 1
else:
cluster_composition_dict[Element(site.specie)] = 1
uniform = True
if len(cluster_composition_dict):
cmp = Composition.from_dict(cluster_composition_dict)
if cmp.reduced_formula != structure.composition.reduced_formula:
uniform = False
if not uniform:
type = 'heterogeneous'
else:
# Make a 2x2x2 supercell and recalculate the
# cluster's new size. If the new cluster size is
# the same as the old size, it is a non-periodic
# molecule. If it is 2x as big, it's a 1D chain.
# If it's 4x as big, it is a layered material.
old_cluster_size = len(bonds[sites[0]])
structure.make_supercell(2)
sites = structure.sites
bonds = {}
for site in sites:
bonds[site] = []
for i in range(len(sites)):
site_1 = sites[i]
for site_2 in sites[i+1:]:
if (site_1.distance(site_2) <
float(Element(site_1.specie).atomic_radius
+ Element(site_2.specie).atomic_radius) * 1.1):
bonds[site_1].append(site_2)
bonds[site_2].append(site_1)
#.........这里部分代码省略.........