Skip to content

Commit 67ba063

Browse files
authored
simplify dict["key"] if "key" in dict else None to dict.get("key") (#3038)
1 parent 051f853 commit 67ba063

22 files changed

+223
-219
lines changed

pymatgen/analysis/chemenv/connectivity/tests/test_connected_components.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -858,11 +858,11 @@ def test_coordination_sequences(self):
858858
"structure_environments_files",
859859
"se_mp-5020.json",
860860
)
861-
with open(BaTiO3_se_fpath) as f:
862-
dd = json.load(f)
863-
se = StructureEnvironments.from_dict(dd)
861+
with open(BaTiO3_se_fpath) as file:
862+
dct = json.load(file)
863+
struct_envs = StructureEnvironments.from_dict(dct)
864864
lse = LightStructureEnvironments.from_structure_environments(
865-
strategy=SimplestChemenvStrategy(), structure_environments=se
865+
strategy=SimplestChemenvStrategy(), structure_environments=struct_envs
866866
)
867867
cf = ConnectivityFinder()
868868
sc = cf.get_structure_connectivity(light_structure_environments=lse)

pymatgen/analysis/chemenv/connectivity/tests/test_structure_connectivity.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ def test_serialization(self):
2828
"structure_environments_files",
2929
"se_mp-5020.json",
3030
)
31-
with open(BaTiO3_se_fpath) as f:
32-
dd = json.load(f)
33-
se = StructureEnvironments.from_dict(dd)
31+
with open(BaTiO3_se_fpath) as file:
32+
dd = json.load(file)
33+
struct_envs = StructureEnvironments.from_dict(dd)
3434
lse = LightStructureEnvironments.from_structure_environments(
35-
strategy=SimplestChemenvStrategy(), structure_environments=se
35+
strategy=SimplestChemenvStrategy(), structure_environments=struct_envs
3636
)
3737
cf = ConnectivityFinder()
3838
sc = cf.get_structure_connectivity(light_structure_environments=lse)

pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py

Lines changed: 35 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ def as_dict(self):
327327
}
328328

329329
@classmethod
330-
def from_dict(cls, dd):
330+
def from_dict(cls, dct):
331331
"""
332332
Reconstructs the SeparationPlane algorithm from its JSON-serializable dict representation.
333333
@@ -336,22 +336,18 @@ def from_dict(cls, dd):
336336
337337
Returns: a SeparationPlane algorithm.
338338
"""
339-
eop = (
340-
[np.array(eo_perm) for eo_perm in dd["explicit_optimized_permutations"]]
341-
if ("explicit_optimized_permutations" in dd and dd["explicit_optimized_permutations"] is not None)
342-
else None
343-
)
339+
eop = [np.array(eo_perm) for eo_perm in dct.get("explicit_optimized_permutations", [])] or None
344340
return cls(
345-
plane_points=dd["plane_points"],
346-
mirror_plane=dd["mirror_plane"],
347-
ordered_plane=dd["ordered_plane"],
348-
point_groups=dd["point_groups"],
349-
ordered_point_groups=dd["ordered_point_groups"],
350-
explicit_permutations=[np.array(eperm) for eperm in dd["explicit_permutations"]],
341+
plane_points=dct["plane_points"],
342+
mirror_plane=dct["mirror_plane"],
343+
ordered_plane=dct["ordered_plane"],
344+
point_groups=dct["point_groups"],
345+
ordered_point_groups=dct["ordered_point_groups"],
346+
explicit_permutations=[np.array(eperm) for eperm in dct["explicit_permutations"]],
351347
explicit_optimized_permutations=eop,
352-
multiplicity=dd["multiplicity"] if "multiplicity" in dd else None,
353-
other_plane_points=dd["other_plane_points"] if "other_plane_points" in dd else None,
354-
minimum_number_of_points=dd["minimum_number_of_points"],
348+
multiplicity=dct.get("multiplicity"),
349+
other_plane_points=dct.get("other_plane_points"),
350+
minimum_number_of_points=dct["minimum_number_of_points"],
355351
)
356352

357353
def __str__(self):
@@ -599,50 +595,52 @@ def as_dict(self):
599595
"IUCr_symbol": self.IUCrsymbol,
600596
"coordination": self.coordination,
601597
"central_site": [float(xx) for xx in self.central_site],
602-
"points": [[float(xx) for xx in pp] for pp in self.points] if self.points is not None else None,
603-
"solid_angles": [float(ang) for ang in self._solid_angles] if self._solid_angles is not None else None,
598+
"points": [[float(xx) for xx in pp] for pp in (self.points or [])] or None,
599+
"solid_angles": [float(ang) for ang in (self._solid_angles or [])] or None,
604600
"deactivate": self.deactivate,
605601
"_faces": self._faces,
606602
"_edges": self._edges,
607-
"_algorithms": [algo.as_dict for algo in self._algorithms] if self._algorithms is not None else None,
603+
"_algorithms": [algo.as_dict for algo in (self._algorithms or [])] or None,
608604
"equivalent_indices": self.equivalent_indices,
609605
"neighbors_sets_hints": [nbsh.as_dict() for nbsh in self.neighbors_sets_hints]
610606
if self.neighbors_sets_hints is not None
611607
else None,
612608
}
613609

614610
@classmethod
615-
def from_dict(cls, dd):
611+
def from_dict(cls, dct):
616612
"""
617613
Reconstructs the CoordinationGeometry from its JSON-serializable dict representation.
618614
619615
Args:
620-
dd: a JSON-serializable dict representation of a CoordinationGeometry.
616+
dct: a JSON-serializable dict representation of a CoordinationGeometry.
621617
622618
Returns: a CoordinationGeometry.
623619
"""
624620
dec = MontyDecoder()
625621
return cls(
626-
mp_symbol=dd["mp_symbol"],
627-
name=dd["name"],
628-
alternative_names=dd["alternative_names"],
629-
IUPAC_symbol=dd["IUPAC_symbol"],
630-
IUCr_symbol=dd["IUCr_symbol"],
631-
coordination=dd["coordination"],
632-
central_site=dd["central_site"],
633-
points=dd["points"],
622+
mp_symbol=dct["mp_symbol"],
623+
name=dct["name"],
624+
alternative_names=dct["alternative_names"],
625+
IUPAC_symbol=dct["IUPAC_symbol"],
626+
IUCr_symbol=dct["IUCr_symbol"],
627+
coordination=dct["coordination"],
628+
central_site=dct["central_site"],
629+
points=dct["points"],
634630
solid_angles=(
635-
dd["solid_angles"] if "solid_angles" in dd else [4.0 * np.pi / dd["coordination"]] * dd["coordination"]
631+
dct["solid_angles"]
632+
if "solid_angles" in dct
633+
else [4.0 * np.pi / dct["coordination"]] * dct["coordination"]
636634
),
637-
deactivate=dd["deactivate"],
638-
faces=dd["_faces"],
639-
edges=dd["_edges"],
640-
algorithms=[dec.process_decoded(algo_d) for algo_d in dd["_algorithms"]]
641-
if dd["_algorithms"] is not None
635+
deactivate=dct["deactivate"],
636+
faces=dct["_faces"],
637+
edges=dct["_edges"],
638+
algorithms=[dec.process_decoded(algo_d) for algo_d in dct["_algorithms"]]
639+
if dct["_algorithms"] is not None
642640
else None,
643-
equivalent_indices=dd["equivalent_indices"] if "equivalent_indices" in dd else None,
644-
neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd) for nbshd in dd["neighbors_sets_hints"]]
645-
if ("neighbors_sets_hints" in dd and dd["neighbors_sets_hints"] is not None)
641+
equivalent_indices=dct.get("equivalent_indices"),
642+
neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd) for nbshd in dct["neighbors_sets_hints"]]
643+
if ("neighbors_sets_hints" in dct and dct["neighbors_sets_hints"] is not None)
646644
else None,
647645
)
648646

pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -683,17 +683,17 @@ def compute_structure_environments(
683683

684684
# Initialize the StructureEnvironments object (either from initial_structure_environments or from scratch)
685685
if initial_structure_environments is not None:
686-
se = initial_structure_environments
687-
if se.structure != self.structure:
686+
struct_envs = initial_structure_environments
687+
if struct_envs.structure != self.structure:
688688
raise ValueError("Structure is not the same in initial_structure_environments")
689-
if se.voronoi != self.detailed_voronoi:
690-
if self.detailed_voronoi.is_close_to(se.voronoi):
691-
self.detailed_voronoi = se.voronoi
689+
if struct_envs.voronoi != self.detailed_voronoi:
690+
if self.detailed_voronoi.is_close_to(struct_envs.voronoi):
691+
self.detailed_voronoi = struct_envs.voronoi
692692
else:
693693
raise ValueError("Detailed Voronoi is not the same in initial_structure_environments")
694-
se.info = info
694+
struct_envs.info = info
695695
else:
696-
se = StructureEnvironments(
696+
struct_envs = StructureEnvironments(
697697
voronoi=self.detailed_voronoi,
698698
valences=self.valences,
699699
sites_map=self.sites_map,
@@ -740,7 +740,7 @@ def compute_structure_environments(
740740
if optimization > 0:
741741
self.detailed_voronoi.local_planes[isite] = {}
742742
self.detailed_voronoi.separations[isite] = {}
743-
se.init_neighbors_sets(
743+
struct_envs.init_neighbors_sets(
744744
isite=isite,
745745
additional_conditions=additional_conditions,
746746
valences=valences,
@@ -749,14 +749,14 @@ def compute_structure_environments(
749749
to_add_from_hints = []
750750
nb_sets_info = {}
751751

752-
for cn, nb_sets in se.neighbors_sets[isite].items():
752+
for cn, nb_sets in struct_envs.neighbors_sets[isite].items():
753753
if cn not in all_cns:
754754
continue
755755
for inb_set, nb_set in enumerate(nb_sets):
756756
logging.debug(f" ... getting environments for nb_set ({cn:d}, {inb_set:d})")
757757
t_nbset1 = time.process_time()
758758
ce = self.update_nb_set_environments(
759-
se=se,
759+
se=struct_envs,
760760
isite=isite,
761761
cn=cn,
762762
inb_set=inb_set,
@@ -784,10 +784,10 @@ def compute_structure_environments(
784784
suggested_nb_set_voronoi_indices = nb_sets_hints.hints(hints_info)
785785
for idx_new, new_nb_set_voronoi_indices in enumerate(suggested_nb_set_voronoi_indices):
786786
logging.debug(f" hint # {idx_new:d}")
787-
new_nb_set = se.NeighborsSet(
788-
structure=se.structure,
787+
new_nb_set = struct_envs.NeighborsSet(
788+
structure=struct_envs.structure,
789789
isite=isite,
790-
detailed_voronoi=se.voronoi,
790+
detailed_voronoi=struct_envs.voronoi,
791791
site_voronoi_indices=new_nb_set_voronoi_indices,
792792
sources={
793793
"origin": "nb_set_hints",
@@ -804,10 +804,10 @@ def compute_structure_environments(
804804
continue
805805
if new_nb_set in [ta["new_nb_set"] for ta in to_add_from_hints]:
806806
has_nb_set = True
807-
elif cn_new_nb_set not in se.neighbors_sets[isite]:
807+
elif cn_new_nb_set not in struct_envs.neighbors_sets[isite]:
808808
has_nb_set = False
809809
else:
810-
has_nb_set = new_nb_set in se.neighbors_sets[isite][cn_new_nb_set]
810+
has_nb_set = new_nb_set in struct_envs.neighbors_sets[isite][cn_new_nb_set]
811811
if not has_nb_set:
812812
to_add_from_hints.append(
813813
{
@@ -821,16 +821,16 @@ def compute_structure_environments(
821821
logging.debug(" => already present")
822822
logging.debug(" ... getting environments for nb_sets added from hints")
823823
for missing_nb_set_to_add in to_add_from_hints:
824-
se.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add["new_nb_set"])
824+
struct_envs.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add["new_nb_set"])
825825
for missing_nb_set_to_add in to_add_from_hints:
826826
isite_new_nb_set = missing_nb_set_to_add["isite"]
827827
cn_new_nb_set = missing_nb_set_to_add["cn_new_nb_set"]
828828
new_nb_set = missing_nb_set_to_add["new_nb_set"]
829-
inew_nb_set = se.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set)
829+
inew_nb_set = struct_envs.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set)
830830
logging.debug(f" ... getting environments for nb_set ({cn_new_nb_set}, {inew_nb_set}) - from hints")
831831
t_nbset1 = time.process_time()
832832
self.update_nb_set_environments(
833-
se=se,
833+
se=struct_envs,
834834
isite=isite_new_nb_set,
835835
cn=cn_new_nb_set,
836836
inb_set=inew_nb_set,
@@ -842,7 +842,7 @@ def compute_structure_environments(
842842
nb_sets_info[cn] = {}
843843
nb_sets_info[cn][inew_nb_set] = {"time": t_nbset2 - t_nbset1}
844844
t2 = time.process_time()
845-
se.update_site_info(isite=isite, info_dict={"time": t2 - t1, "nb_sets_info": nb_sets_info})
845+
struct_envs.update_site_info(isite=isite, info_dict={"time": t2 - t1, "nb_sets_info": nb_sets_info})
846846
if timelimit is not None:
847847
time_elapsed = t2 - time_init
848848
time_left = timelimit - time_elapsed
@@ -852,7 +852,7 @@ def compute_structure_environments(
852852
logging.debug(f" ... computed in {t2 - t1:.2f} seconds")
853853
time_end = time.process_time()
854854
logging.debug(f" ... compute_structure_environments ended in {time_end - time_init:.2f} seconds")
855-
return se
855+
return struct_envs
856856

857857
def update_nb_set_environments(self, se, isite, cn, inb_set, nb_set, recompute=False, optimization=None):
858858
"""

pymatgen/analysis/chemenv/coordination_environments/structure_environments.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1343,7 +1343,7 @@ def from_dict(cls, d):
13431343
neighbors_sets = [
13441344
{
13451345
int(cn): [
1346-
cls.NeighborsSet.from_dict(dd=nb_set_dict, structure=structure, detailed_voronoi=voronoi)
1346+
cls.NeighborsSet.from_dict(nb_set_dict, structure=structure, detailed_voronoi=voronoi)
13471347
for nb_set_dict in nb_sets
13481348
]
13491349
for cn, nb_sets in site_nbs_sets_dict.items()
@@ -2127,7 +2127,7 @@ def from_dict(cls, d):
21272127
all_nbs_sites.append({"site": site, "index": nb_site["index"], "image_cell": image_cell})
21282128
neighbors_sets = [
21292129
[
2130-
cls.NeighborsSet.from_dict(dd=nb_set, structure=structure, all_nbs_sites=all_nbs_sites)
2130+
cls.NeighborsSet.from_dict(nb_set, structure=structure, all_nbs_sites=all_nbs_sites)
21312131
for nb_set in site_nb_sets
21322132
]
21332133
if site_nb_sets is not None

pymatgen/analysis/chemenv/coordination_environments/tests/test_read_write.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,10 @@ def test_structure_environments_neighbors_sets(self):
8888
with open(f"{se_files_dir}/se_mp-7000.json") as f:
8989
dd = json.load(f)
9090

91-
se = StructureEnvironments.from_dict(dd)
91+
struct_envs = StructureEnvironments.from_dict(dd)
9292

9393
isite = 6
94-
nb_set = se.neighbors_sets[isite][4][0]
94+
nb_set = struct_envs.neighbors_sets[isite][4][0]
9595

9696
nb_set_surface_points = [
9797
[1.0017922780870239, 0.99301365328679292],

pymatgen/analysis/chemenv/coordination_environments/tests/test_structure_environments.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@ def test_structure_environments(self):
3737
with open(f"{struct_env_files_dir}/se_mp-7000.json") as f:
3838
dd = json.load(f)
3939

40-
se = StructureEnvironments.from_dict(dd)
40+
struct_envs = StructureEnvironments.from_dict(dd)
4141
isite = 6
42-
csm_and_maps_fig, csm_and_maps_subplot = se.get_csm_and_maps(isite=isite)
42+
csm_and_maps_fig, csm_and_maps_subplot = struct_envs.get_csm_and_maps(isite=isite)
4343
assert_array_almost_equal(csm_and_maps_subplot.lines[0].get_xydata().flatten(), [0.0, 0.53499332])
4444
assert_array_almost_equal(csm_and_maps_subplot.lines[1].get_xydata().flatten(), [1.0, 0.47026441])
4545
assert_array_almost_equal(csm_and_maps_subplot.lines[2].get_xydata().flatten(), [2.0, 0.00988778])
4646

47-
environments_figure, environments_subplot = se.get_environments_figure(isite=isite)
47+
environments_figure, environments_subplot = struct_envs.get_environments_figure(isite=isite)
4848
assert_array_almost_equal(
4949
np.array(environments_subplot.patches[0].get_xy()),
5050
[
@@ -98,14 +98,14 @@ def test_structure_environments(self):
9898
],
9999
)
100100

101-
se.save_environments_figure(isite=isite, imagename="image.png")
101+
struct_envs.save_environments_figure(isite=isite, imagename="image.png")
102102
assert os.path.exists("image.png")
103103

104-
assert len(se.differences_wrt(se)) == 0
104+
assert len(struct_envs.differences_wrt(struct_envs)) == 0
105105

106-
assert se == se
106+
assert struct_envs == struct_envs
107107

108-
ce = se.ce_list[isite][4][0]
108+
ce = struct_envs.ce_list[isite][4][0]
109109

110110
assert len(ce), 4
111111

@@ -140,7 +140,7 @@ def test_structure_environments(self):
140140
min_geoms = ce.minimum_geometries(n=3)
141141
assert len(min_geoms) == 3
142142

143-
ce2 = se.ce_list[7][4][0]
143+
ce2 = struct_envs.ce_list[7][4][0]
144144

145145
assert ce.is_close_to(ce2, rtol=0.01, atol=1e-4)
146146
assert not ce.is_close_to(ce2, rtol=0.0, atol=1e-8)
@@ -153,11 +153,11 @@ def test_light_structure_environments(self):
153153
with open(f"{struct_env_files_dir}/se_mp-7000.json") as f:
154154
dd = json.load(f)
155155

156-
se = StructureEnvironments.from_dict(dd)
156+
struct_envs = StructureEnvironments.from_dict(dd)
157157

158158
strategy = SimplestChemenvStrategy()
159159
lse = LightStructureEnvironments.from_structure_environments(
160-
structure_environments=se, strategy=strategy, valences="undefined"
160+
structure_environments=struct_envs, strategy=strategy, valences="undefined"
161161
)
162162
isite = 6
163163
nb_set = lse.neighbors_sets[isite][0]
@@ -241,7 +241,7 @@ def test_light_structure_environments(self):
241241
multi_strategy = MultiWeightsChemenvStrategy.stats_article_weights_parameters()
242242

243243
lse_multi = LightStructureEnvironments.from_structure_environments(
244-
strategy=multi_strategy, structure_environments=se, valences="undefined"
244+
strategy=multi_strategy, structure_environments=struct_envs, valences="undefined"
245245
)
246246
assert lse_multi.coordination_environments[isite][0]["csm"] == pytest.approx(0.009887784240541068)
247247
assert lse_multi.coordination_environments[isite][0]["ce_fraction"] == pytest.approx(1.0)

0 commit comments

Comments
 (0)