Skip to content

Simplify dict["key"] if "key" in dict else None to dict.get("key") #3038

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -858,11 +858,11 @@ def test_coordination_sequences(self):
"structure_environments_files",
"se_mp-5020.json",
)
with open(BaTiO3_se_fpath) as f:
dd = json.load(f)
se = StructureEnvironments.from_dict(dd)
with open(BaTiO3_se_fpath) as file:
dct = json.load(file)
struct_envs = StructureEnvironments.from_dict(dct)
lse = LightStructureEnvironments.from_structure_environments(
strategy=SimplestChemenvStrategy(), structure_environments=se
strategy=SimplestChemenvStrategy(), structure_environments=struct_envs
)
cf = ConnectivityFinder()
sc = cf.get_structure_connectivity(light_structure_environments=lse)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ def test_serialization(self):
"structure_environments_files",
"se_mp-5020.json",
)
with open(BaTiO3_se_fpath) as f:
dd = json.load(f)
se = StructureEnvironments.from_dict(dd)
with open(BaTiO3_se_fpath) as file:
dd = json.load(file)
struct_envs = StructureEnvironments.from_dict(dd)
lse = LightStructureEnvironments.from_structure_environments(
strategy=SimplestChemenvStrategy(), structure_environments=se
strategy=SimplestChemenvStrategy(), structure_environments=struct_envs
)
cf = ConnectivityFinder()
sc = cf.get_structure_connectivity(light_structure_environments=lse)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, dd):
def from_dict(cls, dct):
"""
Reconstructs the SeparationPlane algorithm from its JSON-serializable dict representation.

Expand All @@ -336,22 +336,18 @@ def from_dict(cls, dd):

Returns: a SeparationPlane algorithm.
"""
eop = (
[np.array(eo_perm) for eo_perm in dd["explicit_optimized_permutations"]]
if ("explicit_optimized_permutations" in dd and dd["explicit_optimized_permutations"] is not None)
else None
)
eop = [np.array(eo_perm) for eo_perm in dct.get("explicit_optimized_permutations", [])] or None
return cls(
plane_points=dd["plane_points"],
mirror_plane=dd["mirror_plane"],
ordered_plane=dd["ordered_plane"],
point_groups=dd["point_groups"],
ordered_point_groups=dd["ordered_point_groups"],
explicit_permutations=[np.array(eperm) for eperm in dd["explicit_permutations"]],
plane_points=dct["plane_points"],
mirror_plane=dct["mirror_plane"],
ordered_plane=dct["ordered_plane"],
point_groups=dct["point_groups"],
ordered_point_groups=dct["ordered_point_groups"],
explicit_permutations=[np.array(eperm) for eperm in dct["explicit_permutations"]],
explicit_optimized_permutations=eop,
multiplicity=dd["multiplicity"] if "multiplicity" in dd else None,
other_plane_points=dd["other_plane_points"] if "other_plane_points" in dd else None,
minimum_number_of_points=dd["minimum_number_of_points"],
multiplicity=dct.get("multiplicity"),
other_plane_points=dct.get("other_plane_points"),
minimum_number_of_points=dct["minimum_number_of_points"],
)

def __str__(self):
Expand Down Expand Up @@ -599,50 +595,52 @@ def as_dict(self):
"IUCr_symbol": self.IUCrsymbol,
"coordination": self.coordination,
"central_site": [float(xx) for xx in self.central_site],
"points": [[float(xx) for xx in pp] for pp in self.points] if self.points is not None else None,
"solid_angles": [float(ang) for ang in self._solid_angles] if self._solid_angles is not None else None,
"points": [[float(xx) for xx in pp] for pp in (self.points or [])] or None,
"solid_angles": [float(ang) for ang in (self._solid_angles or [])] or None,
"deactivate": self.deactivate,
"_faces": self._faces,
"_edges": self._edges,
"_algorithms": [algo.as_dict for algo in self._algorithms] if self._algorithms is not None else None,
"_algorithms": [algo.as_dict for algo in (self._algorithms or [])] or None,
"equivalent_indices": self.equivalent_indices,
"neighbors_sets_hints": [nbsh.as_dict() for nbsh in self.neighbors_sets_hints]
if self.neighbors_sets_hints is not None
else None,
}

@classmethod
def from_dict(cls, dd):
def from_dict(cls, dct):
"""
Reconstructs the CoordinationGeometry from its JSON-serializable dict representation.

Args:
dd: a JSON-serializable dict representation of a CoordinationGeometry.
dct: a JSON-serializable dict representation of a CoordinationGeometry.

Returns: a CoordinationGeometry.
"""
dec = MontyDecoder()
return cls(
mp_symbol=dd["mp_symbol"],
name=dd["name"],
alternative_names=dd["alternative_names"],
IUPAC_symbol=dd["IUPAC_symbol"],
IUCr_symbol=dd["IUCr_symbol"],
coordination=dd["coordination"],
central_site=dd["central_site"],
points=dd["points"],
mp_symbol=dct["mp_symbol"],
name=dct["name"],
alternative_names=dct["alternative_names"],
IUPAC_symbol=dct["IUPAC_symbol"],
IUCr_symbol=dct["IUCr_symbol"],
coordination=dct["coordination"],
central_site=dct["central_site"],
points=dct["points"],
solid_angles=(
dd["solid_angles"] if "solid_angles" in dd else [4.0 * np.pi / dd["coordination"]] * dd["coordination"]
dct["solid_angles"]
if "solid_angles" in dct
else [4.0 * np.pi / dct["coordination"]] * dct["coordination"]
),
deactivate=dd["deactivate"],
faces=dd["_faces"],
edges=dd["_edges"],
algorithms=[dec.process_decoded(algo_d) for algo_d in dd["_algorithms"]]
if dd["_algorithms"] is not None
deactivate=dct["deactivate"],
faces=dct["_faces"],
edges=dct["_edges"],
algorithms=[dec.process_decoded(algo_d) for algo_d in dct["_algorithms"]]
if dct["_algorithms"] is not None
else None,
equivalent_indices=dd["equivalent_indices"] if "equivalent_indices" in dd else None,
neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd) for nbshd in dd["neighbors_sets_hints"]]
if ("neighbors_sets_hints" in dd and dd["neighbors_sets_hints"] is not None)
equivalent_indices=dct.get("equivalent_indices"),
neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd) for nbshd in dct["neighbors_sets_hints"]]
if ("neighbors_sets_hints" in dct and dct["neighbors_sets_hints"] is not None)
else None,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -683,17 +683,17 @@ def compute_structure_environments(

# Initialize the StructureEnvironments object (either from initial_structure_environments or from scratch)
if initial_structure_environments is not None:
se = initial_structure_environments
if se.structure != self.structure:
struct_envs = initial_structure_environments
if struct_envs.structure != self.structure:
raise ValueError("Structure is not the same in initial_structure_environments")
if se.voronoi != self.detailed_voronoi:
if self.detailed_voronoi.is_close_to(se.voronoi):
self.detailed_voronoi = se.voronoi
if struct_envs.voronoi != self.detailed_voronoi:
if self.detailed_voronoi.is_close_to(struct_envs.voronoi):
self.detailed_voronoi = struct_envs.voronoi
else:
raise ValueError("Detailed Voronoi is not the same in initial_structure_environments")
se.info = info
struct_envs.info = info
else:
se = StructureEnvironments(
struct_envs = StructureEnvironments(
voronoi=self.detailed_voronoi,
valences=self.valences,
sites_map=self.sites_map,
Expand Down Expand Up @@ -740,7 +740,7 @@ def compute_structure_environments(
if optimization > 0:
self.detailed_voronoi.local_planes[isite] = {}
self.detailed_voronoi.separations[isite] = {}
se.init_neighbors_sets(
struct_envs.init_neighbors_sets(
isite=isite,
additional_conditions=additional_conditions,
valences=valences,
Expand All @@ -749,14 +749,14 @@ def compute_structure_environments(
to_add_from_hints = []
nb_sets_info = {}

for cn, nb_sets in se.neighbors_sets[isite].items():
for cn, nb_sets in struct_envs.neighbors_sets[isite].items():
if cn not in all_cns:
continue
for inb_set, nb_set in enumerate(nb_sets):
logging.debug(f" ... getting environments for nb_set ({cn:d}, {inb_set:d})")
t_nbset1 = time.process_time()
ce = self.update_nb_set_environments(
se=se,
se=struct_envs,
isite=isite,
cn=cn,
inb_set=inb_set,
Expand Down Expand Up @@ -784,10 +784,10 @@ def compute_structure_environments(
suggested_nb_set_voronoi_indices = nb_sets_hints.hints(hints_info)
for idx_new, new_nb_set_voronoi_indices in enumerate(suggested_nb_set_voronoi_indices):
logging.debug(f" hint # {idx_new:d}")
new_nb_set = se.NeighborsSet(
structure=se.structure,
new_nb_set = struct_envs.NeighborsSet(
structure=struct_envs.structure,
isite=isite,
detailed_voronoi=se.voronoi,
detailed_voronoi=struct_envs.voronoi,
site_voronoi_indices=new_nb_set_voronoi_indices,
sources={
"origin": "nb_set_hints",
Expand All @@ -804,10 +804,10 @@ def compute_structure_environments(
continue
if new_nb_set in [ta["new_nb_set"] for ta in to_add_from_hints]:
has_nb_set = True
elif cn_new_nb_set not in se.neighbors_sets[isite]:
elif cn_new_nb_set not in struct_envs.neighbors_sets[isite]:
has_nb_set = False
else:
has_nb_set = new_nb_set in se.neighbors_sets[isite][cn_new_nb_set]
has_nb_set = new_nb_set in struct_envs.neighbors_sets[isite][cn_new_nb_set]
if not has_nb_set:
to_add_from_hints.append(
{
Expand All @@ -821,16 +821,16 @@ def compute_structure_environments(
logging.debug(" => already present")
logging.debug(" ... getting environments for nb_sets added from hints")
for missing_nb_set_to_add in to_add_from_hints:
se.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add["new_nb_set"])
struct_envs.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add["new_nb_set"])
for missing_nb_set_to_add in to_add_from_hints:
isite_new_nb_set = missing_nb_set_to_add["isite"]
cn_new_nb_set = missing_nb_set_to_add["cn_new_nb_set"]
new_nb_set = missing_nb_set_to_add["new_nb_set"]
inew_nb_set = se.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set)
inew_nb_set = struct_envs.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set)
logging.debug(f" ... getting environments for nb_set ({cn_new_nb_set}, {inew_nb_set}) - from hints")
t_nbset1 = time.process_time()
self.update_nb_set_environments(
se=se,
se=struct_envs,
isite=isite_new_nb_set,
cn=cn_new_nb_set,
inb_set=inew_nb_set,
Expand All @@ -842,7 +842,7 @@ def compute_structure_environments(
nb_sets_info[cn] = {}
nb_sets_info[cn][inew_nb_set] = {"time": t_nbset2 - t_nbset1}
t2 = time.process_time()
se.update_site_info(isite=isite, info_dict={"time": t2 - t1, "nb_sets_info": nb_sets_info})
struct_envs.update_site_info(isite=isite, info_dict={"time": t2 - t1, "nb_sets_info": nb_sets_info})
if timelimit is not None:
time_elapsed = t2 - time_init
time_left = timelimit - time_elapsed
Expand All @@ -852,7 +852,7 @@ def compute_structure_environments(
logging.debug(f" ... computed in {t2 - t1:.2f} seconds")
time_end = time.process_time()
logging.debug(f" ... compute_structure_environments ended in {time_end - time_init:.2f} seconds")
return se
return struct_envs

def update_nb_set_environments(self, se, isite, cn, inb_set, nb_set, recompute=False, optimization=None):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1343,7 +1343,7 @@ def from_dict(cls, d):
neighbors_sets = [
{
int(cn): [
cls.NeighborsSet.from_dict(dd=nb_set_dict, structure=structure, detailed_voronoi=voronoi)
cls.NeighborsSet.from_dict(nb_set_dict, structure=structure, detailed_voronoi=voronoi)
for nb_set_dict in nb_sets
]
for cn, nb_sets in site_nbs_sets_dict.items()
Expand Down Expand Up @@ -2127,7 +2127,7 @@ def from_dict(cls, d):
all_nbs_sites.append({"site": site, "index": nb_site["index"], "image_cell": image_cell})
neighbors_sets = [
[
cls.NeighborsSet.from_dict(dd=nb_set, structure=structure, all_nbs_sites=all_nbs_sites)
cls.NeighborsSet.from_dict(nb_set, structure=structure, all_nbs_sites=all_nbs_sites)
for nb_set in site_nb_sets
]
if site_nb_sets is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ def test_structure_environments_neighbors_sets(self):
with open(f"{se_files_dir}/se_mp-7000.json") as f:
dd = json.load(f)

se = StructureEnvironments.from_dict(dd)
struct_envs = StructureEnvironments.from_dict(dd)

isite = 6
nb_set = se.neighbors_sets[isite][4][0]
nb_set = struct_envs.neighbors_sets[isite][4][0]

nb_set_surface_points = [
[1.0017922780870239, 0.99301365328679292],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ def test_structure_environments(self):
with open(f"{struct_env_files_dir}/se_mp-7000.json") as f:
dd = json.load(f)

se = StructureEnvironments.from_dict(dd)
struct_envs = StructureEnvironments.from_dict(dd)
isite = 6
csm_and_maps_fig, csm_and_maps_subplot = se.get_csm_and_maps(isite=isite)
csm_and_maps_fig, csm_and_maps_subplot = struct_envs.get_csm_and_maps(isite=isite)
assert_array_almost_equal(csm_and_maps_subplot.lines[0].get_xydata().flatten(), [0.0, 0.53499332])
assert_array_almost_equal(csm_and_maps_subplot.lines[1].get_xydata().flatten(), [1.0, 0.47026441])
assert_array_almost_equal(csm_and_maps_subplot.lines[2].get_xydata().flatten(), [2.0, 0.00988778])

environments_figure, environments_subplot = se.get_environments_figure(isite=isite)
environments_figure, environments_subplot = struct_envs.get_environments_figure(isite=isite)
assert_array_almost_equal(
np.array(environments_subplot.patches[0].get_xy()),
[
Expand Down Expand Up @@ -98,14 +98,14 @@ def test_structure_environments(self):
],
)

se.save_environments_figure(isite=isite, imagename="image.png")
struct_envs.save_environments_figure(isite=isite, imagename="image.png")
assert os.path.exists("image.png")

assert len(se.differences_wrt(se)) == 0
assert len(struct_envs.differences_wrt(struct_envs)) == 0

assert se == se
assert struct_envs == struct_envs

ce = se.ce_list[isite][4][0]
ce = struct_envs.ce_list[isite][4][0]

assert len(ce), 4

Expand Down Expand Up @@ -140,7 +140,7 @@ def test_structure_environments(self):
min_geoms = ce.minimum_geometries(n=3)
assert len(min_geoms) == 3

ce2 = se.ce_list[7][4][0]
ce2 = struct_envs.ce_list[7][4][0]

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

se = StructureEnvironments.from_dict(dd)
struct_envs = StructureEnvironments.from_dict(dd)

strategy = SimplestChemenvStrategy()
lse = LightStructureEnvironments.from_structure_environments(
structure_environments=se, strategy=strategy, valences="undefined"
structure_environments=struct_envs, strategy=strategy, valences="undefined"
)
isite = 6
nb_set = lse.neighbors_sets[isite][0]
Expand Down Expand Up @@ -241,7 +241,7 @@ def test_light_structure_environments(self):
multi_strategy = MultiWeightsChemenvStrategy.stats_article_weights_parameters()

lse_multi = LightStructureEnvironments.from_structure_environments(
strategy=multi_strategy, structure_environments=se, valences="undefined"
strategy=multi_strategy, structure_environments=struct_envs, valences="undefined"
)
assert lse_multi.coordination_environments[isite][0]["csm"] == pytest.approx(0.009887784240541068)
assert lse_multi.coordination_environments[isite][0]["ce_fraction"] == pytest.approx(1.0)
Expand Down
Loading