Skip to content

Commit 742f461

Browse files
committed
simplify: structure.sites -> structure
1 parent 958ce75 commit 742f461

File tree

19 files changed

+85
-102
lines changed

19 files changed

+85
-102
lines changed

docs_rst/conf-normal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def find_source():
348348
filename = f"pymatgen/core/{rel_path}#L{line_start}-L{line_end}"
349349
except Exception:
350350
# no need to be relative to core here as module includes full path.
351-
filename = info["module"].replace(".", "/") + ".py"
351+
filename = f"{info['module'].replace('.', '/')}.py"
352352

353353
tag = "v" + __version__
354354
return f"https://github.com/materialsproject/pymatgen/blob/{tag}/{filename}"

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -254,57 +254,52 @@ def equivalent_site_index_and_transform(self, psite):
254254
isite = isite2
255255
break
256256
# Get the translation between psite and its corresponding site in the unit cell (Translation I)
257-
thissite = self.structure_environments.structure[isite]
258-
dthissite = psite.frac_coords - thissite.frac_coords
257+
this_site = self.structure_environments.structure[isite]
258+
dthis_site = psite.frac_coords - this_site.frac_coords
259259
# Get the translation between the equivalent site for which the neighbors have been computed and the site in
260260
# the unit cell that corresponds to psite (Translation II)
261-
equivsite = self.structure_environments.structure[self.structure_environments.sites_map[isite]].to_unit_cell()
261+
equiv_site = self.structure_environments.structure[self.structure_environments.sites_map[isite]].to_unit_cell()
262262
# equivsite = self.structure_environments.structure[self.structure_environments.sites_map[isite]]
263263
dequivsite = (
264264
self.structure_environments.structure[self.structure_environments.sites_map[isite]].frac_coords
265-
- equivsite.frac_coords
265+
- equiv_site.frac_coords
266266
)
267267
found = False
268268
# Find the symmetry that applies the site in the unit cell to the equivalent site, as well as the translation
269269
# that gets back the site to the unit cell (Translation III)
270270
# TODO: check that these tolerances are needed, now that the structures are refined before analyzing envs
271271
tolerances = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4]
272272
for tolerance in tolerances:
273-
for symop in self.symops:
274-
newsite = PeriodicSite(
275-
equivsite._species,
276-
symop.operate(equivsite.frac_coords),
277-
equivsite._lattice,
273+
for sym_op in self.symops:
274+
new_site = PeriodicSite(
275+
equiv_site._species,
276+
sym_op.operate(equiv_site.frac_coords),
277+
equiv_site._lattice,
278278
)
279-
if newsite.is_periodic_image(thissite, tolerance=tolerance):
280-
mysym = symop
281-
dthissite2 = thissite.frac_coords - newsite.frac_coords
279+
if new_site.is_periodic_image(this_site, tolerance=tolerance):
280+
my_sym = sym_op
281+
dthissite2 = this_site.frac_coords - new_site.frac_coords
282282
found = True
283283
break
284284
if not found:
285-
symops = [SymmOp.from_rotation_and_translation()]
286-
for symop in symops:
287-
newsite = PeriodicSite(
288-
equivsite._species,
289-
symop.operate(equivsite.frac_coords),
290-
equivsite._lattice,
285+
sym_ops = [SymmOp.from_rotation_and_translation()]
286+
for sym_op in sym_ops:
287+
new_site = PeriodicSite(
288+
equiv_site._species,
289+
sym_op.operate(equiv_site.frac_coords),
290+
equiv_site._lattice,
291291
)
292292
# if newsite.is_periodic_image(thissite):
293-
if newsite.is_periodic_image(thissite, tolerance=tolerance):
294-
mysym = symop
295-
dthissite2 = thissite.frac_coords - newsite.frac_coords
293+
if new_site.is_periodic_image(this_site, tolerance=tolerance):
294+
my_sym = sym_op
295+
dthissite2 = this_site.frac_coords - new_site.frac_coords
296296
found = True
297297
break
298298
if found:
299299
break
300300
if not found:
301301
raise EquivalentSiteSearchError(psite)
302-
return [
303-
self.structure_environments.sites_map[isite],
304-
dequivsite,
305-
dthissite + dthissite2,
306-
mysym,
307-
]
302+
return [self.structure_environments.sites_map[isite], dequivsite, dthis_site + dthissite2, my_sym]
308303

309304
@abc.abstractmethod
310305
def get_site_neighbors(self, site):

pymatgen/analysis/interfaces/substrate_analyzer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def from_zsl(
5252
if elasticity_tensor is not None:
5353
energy_density = elasticity_tensor.energy_density(strain)
5454

55-
elastic_energy = film.volume * energy_density / len(film.sites)
55+
elastic_energy = film.volume * energy_density / len(film)
5656
else:
5757
elastic_energy = 0
5858

pymatgen/analysis/magnetism/analyzer.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -609,11 +609,7 @@ def __init__(
609609
self,
610610
structure: Structure,
611611
default_magmoms: dict[str, float] | None = None,
612-
strategies: list[str]
613-
| tuple[str, ...] = (
614-
"ferromagnetic",
615-
"antiferromagnetic",
616-
),
612+
strategies: list[str] | tuple[str, ...] = ("ferromagnetic", "antiferromagnetic"),
617613
automatic: bool = True,
618614
truncate_by_symmetry: bool = True,
619615
transformation_kwargs: dict | None = None,
@@ -706,7 +702,11 @@ def __init__(
706702
# we will first create a set of transformations
707703
# and then apply them to our input structure
708704
self.transformations = self._generate_transformations(self.sanitized_structure)
709-
self._generate_ordered_structures(self.sanitized_structure, self.transformations)
705+
ordered_structures, ordered_structures_origins = self._generate_ordered_structures(
706+
self.sanitized_structure, self.transformations
707+
)
708+
self.ordered_structures = ordered_structures
709+
self.ordered_structure_origins = ordered_structures_origins
710710

711711
@staticmethod
712712
def _sanitize_input_structure(input_structure: Structure) -> Structure:
@@ -934,7 +934,7 @@ def _generate_ordered_structures(
934934
self,
935935
sanitized_input_structure: Structure,
936936
transformations: dict[str, MagOrderingTransformation],
937-
):
937+
) -> tuple[list[Structure], list[str]]:
938938
"""Apply our input structure to our list of transformations and output a list
939939
of ordered structures that have been pruned for duplicates and for those
940940
with low symmetry (optional).
@@ -1056,9 +1056,7 @@ def _add_structures(ordered_structures, ordered_structures_origins, structures_t
10561056
self.logger.info(f"Input structure was found in enumerated structures at index {matches.index(True)}")
10571057
self.input_index = matches.index(True)
10581058
self.input_origin = ordered_structures_origins[self.input_index]
1059-
1060-
self.ordered_structures = ordered_structures
1061-
self.ordered_structure_origins = ordered_structures_origins
1059+
return ordered_structures, ordered_structures_origins
10621060

10631061

10641062
MagneticDeformation = namedtuple("MagneticDeformation", "type deformation")

pymatgen/analysis/tests/test_adsorption.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,15 +105,15 @@ def test_generate_adsorption_structures(self):
105105
# Check translation
106106
sites = self.asf_211.find_adsorption_sites()
107107
ads_site_coords = sites["all"][0]
108-
c_site = structures[0].sites[-2]
108+
c_site = structures[0][-2]
109109
assert str(c_site.specie) == "C"
110110
self.assertArrayAlmostEqual(c_site.coords, sites["all"][0])
111111
# Check no translation
112112
structures = self.asf_111.generate_adsorption_structures(co, translate=False)
113113
assert co == Molecule("CO", [[1.0, -0.5, 3], [0.8, 0.46, 3.75]])
114114
sites = self.asf_111.find_adsorption_sites()
115115
ads_site_coords = sites["all"][0]
116-
c_site = structures[0].sites[-2]
116+
c_site = structures[0][-2]
117117
self.assertArrayAlmostEqual(c_site.coords, ads_site_coords + np.array([1.0, -0.5, 3]))
118118

119119
def test_adsorb_both_surfaces(self):

pymatgen/command_line/enumlib_caller.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def get_sg_info(ss):
205205
finder = SpacegroupAnalyzer(Structure.from_sites(ss), self.symm_prec)
206206
return finder.get_space_group_number()
207207

208-
target_sgnum = get_sg_info(symmetrized_structure.sites)
208+
target_sgnum = get_sg_info(list(symmetrized_structure))
209209
curr_sites = list(itertools.chain.from_iterable(disordered_sites))
210210
sgnum = get_sg_info(curr_sites)
211211
ordered_sites = sorted(ordered_sites, key=lambda sites: len(sites))
@@ -250,12 +250,12 @@ def get_sg_info(ss):
250250
output.append(str(self.enum_precision_parameter))
251251
output.append("full")
252252

253-
ndisordered = sum(len(s) for s in disordered_sites)
253+
n_disordered = sum(len(s) for s in disordered_sites)
254254
base = int(
255-
ndisordered
255+
n_disordered
256256
* lcm(
257257
*(
258-
f.limit_denominator(ndisordered * self.max_cell_size).denominator
258+
f.limit_denominator(n_disordered * self.max_cell_size).denominator
259259
for f in map(fractions.Fraction, index_amounts)
260260
)
261261
)
@@ -268,7 +268,7 @@ def get_sg_info(ss):
268268
# enumeration. See Cu7Te5.cif test file.
269269
base *= 10
270270

271-
# base = ndisordered #10 ** int(math.ceil(math.log10(ndisordered)))
271+
# base = ndisordered # 10 ** int(math.ceil(math.log10(ndisordered)))
272272
# To get a reasonable number of structures, we fix concentrations to the
273273
# range expected in the original structure.
274274
total_amounts = sum(index_amounts)

pymatgen/command_line/tests/test_gulp_caller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def test_get_energy_relax_structure_buckingham(self):
306306
assert isinstance(energy, float)
307307
assert isinstance(struct, Structure)
308308
site_len = len(struct)
309-
assert site_len == len(self.mgo_uc.sites)
309+
assert site_len == len(self.mgo_uc)
310310

311311

312312
@unittest.skipIf(not gulp_present, "gulp not present.")

pymatgen/core/structure.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
436436
(bool) True if SiteCollection does not contain atoms that are too
437437
close together.
438438
"""
439-
if len(self.sites) == 1:
439+
if len(self) == 1:
440440
return True
441441
all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]
442442
return bool(np.min(all_dists) > tol)
@@ -480,7 +480,7 @@ def add_site_property(self, property_name: str, values: list):
480480
values (list): A sequence of values. Must be same length as
481481
number of sites.
482482
"""
483-
if len(values) != len(self.sites):
483+
if len(values) != len(self):
484484
raise ValueError("Values must be same length as sites.")
485485
for site, val in zip(self.sites, values):
486486
site.properties[property_name] = val
@@ -551,8 +551,11 @@ def add_oxidation_state_by_site(self, oxidation_states: list[float]):
551551
oxidation_states (list): List of oxidation states.
552552
E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2]
553553
"""
554-
if len(oxidation_states) != len(self.sites):
555-
raise ValueError("Oxidation states of all sites must be specified.")
554+
if len(oxidation_states) != len(self):
555+
raise ValueError(
556+
f"Oxidation states of all sites must be specified, expected {len(self)} values, "
557+
f"got {len(oxidation_states)}"
558+
)
556559
for site, ox in zip(self.sites, oxidation_states):
557560
new_sp = {}
558561
for el, occu in site.species.items():
@@ -613,8 +616,8 @@ def add_spin_by_site(self, spins: list[float]):
613616
spins (list): List of spins
614617
E.g., [+5, -5, 0, 0]
615618
"""
616-
if len(spins) != len(self.sites):
617-
raise ValueError("Spin of all sites must be specified in the dictionary.")
619+
if len(spins) != len(self):
620+
raise ValueError(f"Spins for all sites must be specified, expected {len(self)} spins, got {len(spins)}")
618621

619622
for site, spin in zip(self.sites, spins):
620623
new_sp = {}

pymatgen/core/tests/test_structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -998,14 +998,14 @@ def test_rotate_sites(self):
998998
self.structure.rotate_sites(
999999
indices=[1],
10001000
theta=2.0 * np.pi / 3.0,
1001-
anchor=self.structure.sites[0].coords,
1001+
anchor=self.structure[0].coords,
10021002
to_unit_cell=False,
10031003
)
10041004
self.assertArrayAlmostEqual(self.structure.frac_coords[1], [-1.25, 1.5, 0.75], decimal=6)
10051005
self.structure.rotate_sites(
10061006
indices=[1],
10071007
theta=2.0 * np.pi / 3.0,
1008-
anchor=self.structure.sites[0].coords,
1008+
anchor=self.structure[0].coords,
10091009
to_unit_cell=True,
10101010
)
10111011
self.assertArrayAlmostEqual(self.structure.frac_coords[1], [0.75, 0.5, 0.75], decimal=6)

pymatgen/electronic_structure/boltztrap.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,14 +1639,15 @@ def get_complete_dos(self, structure: Structure, analyzer_for_second_spin=None):
16391639
raise BoltztrapError("Dos merging error: spin component are the same")
16401640

16411641
for s in self._dos_partial:
1642-
if structure.sites[int(s)] not in pdoss:
1643-
pdoss[structure.sites[int(s)]] = {}
1642+
idx = int(s)
1643+
if structure[idx] not in pdoss:
1644+
pdoss[structure[idx]] = {}
16441645
for o in self._dos_partial[s]:
1645-
if Orbital[o] not in pdoss[structure.sites[int(s)]]:
1646-
pdoss[structure.sites[int(s)]][Orbital[o]] = {}
1647-
pdoss[structure.sites[int(s)]][Orbital[o]][spin_1] = self._dos_partial[s][o]
1646+
if Orbital[o] not in pdoss[structure[idx]]:
1647+
pdoss[structure[idx]][Orbital[o]] = {}
1648+
pdoss[structure[idx]][Orbital[o]][spin_1] = self._dos_partial[s][o]
16481649
if analyzer_for_second_spin:
1649-
pdoss[structure.sites[int(s)]][Orbital[o]][spin_2] = analyzer_for_second_spin._dos_partial[s][o]
1650+
pdoss[structure[idx]][Orbital[o]][spin_2] = analyzer_for_second_spin._dos_partial[s][o]
16501651
if analyzer_for_second_spin:
16511652
tdos = Dos(
16521653
self.dos.efermi,

pymatgen/electronic_structure/cohp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,7 @@ def from_file(cls, fmt, filename=None, structure_file=None, are_coops=False, are
796796
bond_dict = {
797797
label: {
798798
"length": v["length"],
799-
"sites": [structure.sites[site] for site in v["sites"]],
799+
"sites": [structure[site] for site in v["sites"]],
800800
}
801801
for label, v in cohp_data.items()
802802
}

pymatgen/io/lammps/data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -783,10 +783,10 @@ def from_ff_and_topologies(cls, box, ff, topologies, atom_style="full"):
783783
topo_labels[k].extend([tuple(topo.type_by_sites[j] for j in t) for t in v])
784784
if isinstance(v_collector, list):
785785
v_collector.append(topo.velocities)
786-
mol_ids.extend([i + 1] * len(topo.sites))
786+
mol_ids.extend([i + 1] * len(topo))
787787
labels.extend(topo.type_by_sites)
788788
coords.append(topo.sites.cart_coords)
789-
q = [0.0] * len(topo.sites) if not topo.charges else topo.charges
789+
q = [0.0] * len(topo) if not topo.charges else topo.charges
790790
charges.extend(q)
791791

792792
atoms = pd.DataFrame(np.concatenate(coords), columns=["x", "y", "z"])

pymatgen/io/lobster/lobsterenv.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -822,10 +822,10 @@ def _find_environments(self, additional_condition, lowerlimit, upperlimit, only_
822822
list_icohps = []
823823
list_lengths = []
824824
list_keys = []
825-
for isite in range(len(self.structure)):
825+
for idx in range(len(self.structure)):
826826
icohps = self._get_icohps(
827827
icohpcollection=self.Icohpcollection,
828-
isite=isite,
828+
isite=idx,
829829
lowerlimit=lowerlimit,
830830
upperlimit=upperlimit,
831831
only_bonds_to=only_bonds_to,
@@ -836,10 +836,10 @@ def _find_environments(self, additional_condition, lowerlimit, upperlimit, only_
836836
lengths_from_ICOHPs,
837837
neighbors_from_ICOHPs,
838838
selected_ICOHPs,
839-
) = self._find_relevant_atoms_additional_condition(isite, icohps, additional_condition)
839+
) = self._find_relevant_atoms_additional_condition(idx, icohps, additional_condition)
840840

841841
if len(neighbors_from_ICOHPs) > 0:
842-
centralsite = self.structure.sites[isite]
842+
centralsite = self.structure[idx]
843843

844844
neighbors_by_distance_start = self.structure.get_sites_in_sphere(
845845
pt=centralsite.coords,

pymatgen/io/res.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def _sfac_from_sites(cls, sites: list[PeriodicSite]) -> ResSFAC:
290290
@classmethod
291291
def _res_from_structure(cls, structure: Structure) -> Res:
292292
"""Produce a res file structure from a pymatgen Structure."""
293-
return Res(None, [], cls._cell_from_lattice(structure.lattice), cls._sfac_from_sites(list(structure.sites)))
293+
return Res(None, [], cls._cell_from_lattice(structure.lattice), cls._sfac_from_sites(list(structure)))
294294

295295
@classmethod
296296
def _res_from_entry(cls, entry: ComputedStructureEntry) -> Res:
@@ -305,7 +305,7 @@ def _res_from_entry(cls, entry: ComputedStructureEntry) -> Res:
305305
AirssTITL(seed, pres, entry.structure.volume, entry.energy, isd, iasd, spg, 1),
306306
rems,
307307
cls._cell_from_lattice(entry.structure.lattice),
308-
cls._sfac_from_sites(list(entry.structure.sites)),
308+
cls._sfac_from_sites(list(entry.structure)),
309309
)
310310

311311
def __init__(self, entry: Structure | ComputedStructureEntry):

pymatgen/io/tests/test_babel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def add_hydrogen(self):
9595
assert len(pb.Molecule(mol_0d).atoms) == 2
9696
adaptor = BabelMolAdaptor(mol_0d)
9797
adaptor.add_hydrogen()
98-
assert len(adaptor.pymatgen_mol.sites) == 14
98+
assert len(adaptor.pymatgen_mol) == 14
9999

100100
def test_rotor_search_wrs(self):
101101
mol = copy.deepcopy(self.mol)

0 commit comments

Comments
 (0)