Skip to content

Commit

Permalink
Minor fix to get_element_profile (#2818)
Browse files Browse the repository at this point in the history
* return type

* remove unnecessary dict.keys()

---------

Co-authored-by: Janosh Riebesell <[email protected]>
  • Loading branch information
jmmshn and janosh authored Jan 30, 2023
1 parent 04b4d1f commit 809685b
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 38 deletions.
3 changes: 1 addition & 2 deletions pymatgen/analysis/diffraction/tem.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,9 @@ def cell_intensity(
dict of hkl plane to cell intensity
"""
csf = self.cell_scattering_factors(structure, bragg_angles)
plane = bragg_angles.keys()
csf_val = np.array(list(csf.values()))
cell_intensity_val = (csf_val * csf_val.conjugate()).real
cell_intensity = dict(zip(plane, cell_intensity_val))
cell_intensity = dict(zip(bragg_angles, cell_intensity_val))
return cell_intensity

def get_pattern(
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/disorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def get_warren_cowley_parameters(structure: Structure, r: float, dr: float) -> d
n_neighbors[site.specie] += 1

alpha_ij = {} # type: ignore
for sp1, sp2 in itertools.product(comp.keys(), comp.keys()):
for sp1, sp2 in itertools.product(comp, comp):
pij = n_ij.get((sp1, sp2), 0) / n_neighbors[sp1]
conc2 = comp.get_atomic_fraction(sp2)
alpha_ij[(sp1, sp2)] = (pij - conc2) / ((1 if sp1 == sp2 else 0) - conc2)
Expand Down
19 changes: 10 additions & 9 deletions pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,25 +1102,26 @@ def get_element_profile(self, element, comp, comp_tol=1e-5):
if element not in self.elements:
raise ValueError("get_transition_chempots can only be called with elements in the phase diagram.")

gccomp = Composition({el: amt for el, amt in comp.items() if el != element})
elref = self.el_refs[element]
elcomp = Composition(element.symbol)
gc_comp = Composition({el: amt for el, amt in comp.items() if el != element})
el_ref = self.el_refs[element]
el_comp = Composition(element.symbol)
evolution = []

for cc in self.get_critical_compositions(elcomp, gccomp)[1:]:
decomp_entries = self.get_decomposition(cc).keys()
for cc in self.get_critical_compositions(el_comp, gc_comp)[1:]:
decomp_entries = list(self.get_decomposition(cc))
decomp = [k.composition for k in decomp_entries]
rxn = Reaction([comp], decomp + [elcomp])
rxn = Reaction([comp], decomp + [el_comp])
rxn.normalize_to(comp)
c = self.get_composition_chempots(cc + elcomp * 1e-5)[element]
amt = -rxn.coeffs[rxn.all_comp.index(elcomp)]
c = self.get_composition_chempots(cc + el_comp * 1e-5)[element]
amt = -rxn.coeffs[rxn.all_comp.index(el_comp)]
evolution.append(
{
"chempot": c,
"evolution": amt,
"element_reference": elref,
"element_reference": el_ref,
"reaction": rxn,
"entries": decomp_entries,
"critical_composition": cc,
}
)
return evolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ class SubstitutionPredictorTest(unittest.TestCase):
def test_prediction(self):
sp = SubstitutionPredictor(threshold=8e-3)
result = sp.list_prediction(["Na+", "Cl-"], to_this_composition=True)[5]
cprob = sp.p.cond_prob_list(result["substitutions"].keys(), result["substitutions"].values())
assert result["probability"] == approx(cprob)
cond_prob = sp.p.cond_prob_list(list(result["substitutions"]), result["substitutions"].values())
assert result["probability"] == approx(cond_prob)
assert set(result["substitutions"].values()) == {"Na+", "Cl-"}

result = sp.list_prediction(["Na+", "Cl-"], to_this_composition=False)[5]
cprob = sp.p.cond_prob_list(result["substitutions"].keys(), result["substitutions"].values())
assert result["probability"] == approx(cprob)
cond_prob = sp.p.cond_prob_list(list(result["substitutions"]), result["substitutions"].values())
assert result["probability"] == approx(cond_prob)
assert set(result["substitutions"].values()) != {"Na+", "Cl-"}

c = Composition({"Ag2+": 1, "Cl-": 2})
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,7 +1296,7 @@ def surface_chempot_range_map(

# Plot the edge along the max x value
pt = v[-1]
delu1, delu2 = pt.keys()
delu1, delu2 = pt
xvals.extend([pt[delu1], pt[delu1]])
yvals.extend(pt[delu2][0])
if not show_unphyiscal_only:
Expand Down Expand Up @@ -1849,7 +1849,7 @@ def scaled_wulff(self, wulffshape, r):
"""
# get the scaling ratio for the energies
r_ratio = r / wulffshape.effective_radius
miller_list = wulffshape.miller_energy_dict.keys()
miller_list = list(wulffshape.miller_energy_dict)
# Normalize the magnitude of the facet normal vectors
# of the Wulff shape by the minimum surface energy.
se_list = np.array(list(wulffshape.miller_energy_dict.values()))
Expand Down
10 changes: 6 additions & 4 deletions pymatgen/apps/battery/battery_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,17 @@ class AbstractVoltagePair(MSONable):
frac_charge: float
frac_discharge: float
working_ion_entry: ComputedEntry
framework_formula: str # should be made into Composition whenever the as_dict and from dict are fixed
framework_formula: str

def __post_init__(self):
# ensure the frame work is a reduced composition
self.framework_formula = self.framework.reduced_formula
fw = Composition(self.framework_formula)
self.framework_formula = fw.reduced_formula

@property
def working_ion(self) -> Element:
"""
working ion as pymatgen Element object
Working ion as pymatgen Element object
"""
return self.working_ion_entry.composition.elements[0]

Expand Down Expand Up @@ -129,6 +130,7 @@ class AbstractElectrode(Sequence, MSONable):
Developers implementing a new battery (other than the two general ones
already implemented) need to implement a VoltagePair and an Electrode.
Attributes:
voltage_pairs: Objects that represent each voltage step
working_ion: Representation of the working ion that only contains element type
Expand Down Expand Up @@ -159,7 +161,7 @@ def __len__(self):
@property
def working_ion(self):
"""
working ion as pymatgen Element object
Working ion as pymatgen Element object
"""
return self.working_ion_entry.composition.elements[0]

Expand Down
26 changes: 15 additions & 11 deletions pymatgen/apps/battery/conversion_battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,11 @@ def from_composition_and_pd(cls, comp, pd, working_ion_symbol="Li", allow_unstab
composition and a phase diagram.
Args:
comp:
Starting composition for ConversionElectrode, e.g.,
comp: Starting composition for ConversionElectrode, e.g.,
Composition("FeF3")
pd:
A PhaseDiagram of the relevant system (e.g., Li-Fe-F)
working_ion_symbol:
Element symbol of working ion. Defaults to Li.
allow_unstable:
Allow compositions that are unstable
pd: A PhaseDiagram of the relevant system (e.g., Li-Fe-F)
working_ion_symbol: Element symbol of working ion. Defaults to Li.
allow_unstable: Allow compositions that are unstable
"""
working_ion = Element(working_ion_symbol)
entry = None
Expand Down Expand Up @@ -274,6 +270,7 @@ class ConversionVoltagePair(AbstractVoltagePair):
"""
A VoltagePair representing a Conversion Reaction with a defined voltage.
Typically not initialized directly but rather used by ConversionElectrode.
Attributes:
rxn (BalancedReaction): BalancedReaction for the step
voltage (float): Voltage for the step
Expand All @@ -284,8 +281,14 @@ class ConversionVoltagePair(AbstractVoltagePair):
mass_discharge (float): Mass of discharged state
frac_charge (float): Fraction of working ion in the charged state
frac_discharge (float): Fraction of working ion in the discharged state
entries_charge ([ComputedEntry]): Entries in the charged state
entries_discharge ([ComputedEntry]): Entries in discharged state
entries_charge ([ComputedEntry]): Entries representing decompositions products
in the charged state. Enumerates the decompositions products at the tieline,
so the number of entries will be one fewer than the dimensions of the phase
diagram
entries_discharge ([ComputedEntry]): Entries representing decompositions products
in the discharged state. Enumerates the decompositions products at the tieline,
so the number of entries will be one fewer than the dimensions of the phase
diagram
working_ion_entry (ComputedEntry): Entry of the working ion.
"""

Expand All @@ -294,7 +297,7 @@ class ConversionVoltagePair(AbstractVoltagePair):
entries_discharge: Iterable[ComputedEntry]

@classmethod
def from_steps(cls, step1, step2, normalization_els, framework_formula=None):
def from_steps(cls, step1, step2, normalization_els, framework_formula):
"""
Creates a ConversionVoltagePair from two steps in the element profile
from a PD analysis.
Expand All @@ -304,6 +307,7 @@ def from_steps(cls, step1, step2, normalization_els, framework_formula=None):
step2: Ending step
normalization_els: Elements to normalize the reaction by. To
ensure correct capacities.
framework_formula: Formula of the framework.
"""
working_ion_entry = step1["element_reference"]
working_ion = working_ion_entry.composition.elements[0].symbol
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/io/cp2k/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,9 +659,9 @@ def parse_dft_params(self):

# Functional
if self.input and self.input.check("FORCE_EVAL/DFT/XC/XC_FUNCTIONAL"):
xcfuncs = list(self.input["force_eval"]["dft"]["xc"]["xc_functional"].subsections.keys())
if xcfuncs:
self.data["dft"]["functional"] = xcfuncs
xc_funcs = list(self.input["force_eval"]["dft"]["xc"]["xc_functional"].subsections)
if xc_funcs:
self.data["dft"]["functional"] = xc_funcs
else:
for v in self.input["force_eval"]["dft"]["xc"].subsections.values():
if v.name.upper() == "XC_FUNCTIONAL":
Expand Down Expand Up @@ -1614,7 +1614,7 @@ def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postpr
terminate_on_match=terminate_on_match,
postprocess=postprocess,
)
for k in patterns.keys():
for k in patterns:
self.data[k] = [i[0] for i in matches.get(k, [])]

def read_table_pattern(
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2014,7 +2014,7 @@ def verify_potcar(self) -> tuple[bool, bool]:
# file with known potcar file hashes.
md5_file_hash = self.file_hash
hash_db = loadfn(os.path.join(cwd, "vasp_potcar_file_hashes.json"))
if md5_file_hash in hash_db.keys():
if md5_file_hash in hash_db:
passed_hash_check = True
else:
passed_hash_check = False
Expand Down

0 comments on commit 809685b

Please sign in to comment.