Skip to content

Commit 958ce75

Browse files
committed
simplify: structure.sites -> structure
1 parent 13f7f5d commit 958ce75

File tree

21 files changed

+84
-85
lines changed

21 files changed

+84
-85
lines changed

pymatgen/analysis/local_env.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -81,17 +81,16 @@ def radii(self):
8181
"""
8282
List of ionic radii of elements in the order of sites.
8383
"""
84-
el = [site.species_string for site in self._structure.sites]
85-
radii_dict = dict(zip(el, self._ionic_radii))
86-
# print radii_dict
84+
elems = [site.species_string for site in self._structure]
85+
radii_dict = dict(zip(elems, self._ionic_radii))
8786
return radii_dict
8887

8988
@property
9089
def valences(self):
9190
"""
9291
List of oxidation states of elements in the order of sites.
9392
"""
94-
el = [site.species_string for site in self._structure.sites]
93+
el = [site.species_string for site in self._structure]
9594
valence_dict = dict(zip(el, self._valences))
9695
return valence_dict
9796

@@ -122,7 +121,7 @@ def nearest_key(sorted_vals, skey):
122121
return after
123122
return before
124123

125-
for i, site in enumerate(self._structure.sites):
124+
for i, site in enumerate(self._structure):
126125
if isinstance(site.specie, Element):
127126
radius = site.specie.atomic_radius
128127
# Handle elements with no atomic_radius
@@ -186,7 +185,7 @@ def _get_valences(self):
186185
valences = bv.get_valences(self._structure)
187186
except Exception:
188187
valences = []
189-
for site in self._structure.sites:
188+
for site in self._structure:
190189
if len(site.specie.common_oxidation_states) > 0:
191190
valences.append(site.specie.common_oxidation_states[0])
192191
# Handle noble gas species
@@ -199,9 +198,9 @@ def _get_valences(self):
199198
self._structure.add_oxidation_state_by_site(valences)
200199
# raise
201200

202-
# el = [site.specie.symbol for site in self._structure.sites]
203-
# el = [site.species_string for site in self._structure.sites]
204-
# el = [site.specie for site in self._structure.sites]
201+
# el = [site.specie.symbol for site in self._structure]
202+
# el = [site.species_string for site in self._structure]
203+
# el = [site.specie for site in self._structure]
205204
# valence_dict = dict(zip(el, valences))
206205
# print valence_dict
207206
return valences
@@ -2093,7 +2092,7 @@ def site_is_of_motif_type(struct, n, approach="min_dist", delta=0.1, cutoff=10,
20932092
ops = LocalStructOrderParams(["cn", "tet", "oct", "bcc", "q6", "sq_pyr", "tri_bipyr"])
20942093

20952094
neighs_cent = get_neighbors_of_site_with_index(struct, n, approach=approach, delta=delta, cutoff=cutoff)
2096-
neighs_cent.append(struct.sites[n])
2095+
neighs_cent.append(struct[n])
20972096
opvals = ops.get_order_parameters(
20982097
neighs_cent,
20992098
len(neighs_cent) - 1,

pymatgen/analysis/magnetism/analyzer.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,12 +219,12 @@ def __init__(
219219
# round magmoms on magnetic ions below threshold to zero
220220
# and on non magnetic ions below threshold_nonmag
221221
magmoms = [
222-
m
223-
if abs(m) > threshold and a.species_string in self.default_magmoms
224-
else m
225-
if abs(m) > threshold_nonmag and a.species_string not in self.default_magmoms
222+
magmom
223+
if abs(magmom) > threshold and site.species_string in self.default_magmoms
224+
else magmom
225+
if abs(magmom) > threshold_nonmag and site.species_string not in self.default_magmoms
226226
else 0
227-
for (m, a) in zip(magmoms, structure.sites)
227+
for magmom, site in zip(magmoms, structure)
228228
]
229229

230230
# overwrite existing magmoms with default_magmoms

pymatgen/analysis/piezo_sensitivity.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,8 @@ def get_unstable_FCM(self, max_force=1):
376376
struct = self.structure
377377
operations = self.FCM_operations
378378
# set max force in reciprocal space
379-
numsites = len(struct.sites)
380-
D = (1 / max_force) * 2 * (np.ones([numsites * 3, numsites * 3]))
379+
n_sites = len(struct)
380+
D = (1 / max_force) * 2 * (np.ones([n_sites * 3, n_sites * 3]))
381381
for op in operations:
382382
same = 0
383383
transpose = 0
@@ -634,30 +634,30 @@ def get_rand_FCM(self, asum=15, force=10):
634634
"""
635635
from pymatgen.io.phonopy import get_phonopy_structure
636636

637-
numsites = len(self.structure.sites)
637+
n_sites = len(self.structure)
638638
structure = get_phonopy_structure(self.structure)
639639
pnstruc = Phonopy(structure, np.eye(3), np.eye(3))
640640

641641
dyn = self.get_unstable_FCM(force)
642642
dyn = self.get_stable_FCM(dyn)
643643

644-
dyn = np.reshape(dyn, (numsites, 3, numsites, 3)).swapaxes(1, 2)
644+
dyn = np.reshape(dyn, (n_sites, 3, n_sites, 3)).swapaxes(1, 2)
645645

646646
dynmass = np.zeros([len(self.structure), len(self.structure), 3, 3])
647647
masses = []
648-
for j in range(numsites):
649-
masses.append(self.structure.sites[j].specie.atomic_mass)
650-
dynmass = np.zeros([numsites, numsites, 3, 3])
651-
for m in range(numsites):
652-
for n in range(numsites):
648+
for idx in range(n_sites):
649+
masses.append(self.structure[idx].specie.atomic_mass)
650+
dynmass = np.zeros([n_sites, n_sites, 3, 3])
651+
for m in range(n_sites):
652+
for n in range(n_sites):
653653
dynmass[m][n] = dyn[m][n] * np.sqrt(masses[m]) * np.sqrt(masses[n])
654654

655655
supercell = pnstruc.get_supercell()
656656
primitive = pnstruc.get_primitive()
657657

658658
converter = dyntofc.DynmatToForceConstants(primitive, supercell)
659659

660-
dyn = np.reshape(np.swapaxes(dynmass, 1, 2), (numsites * 3, numsites * 3))
660+
dyn = np.reshape(np.swapaxes(dynmass, 1, 2), (n_sites * 3, n_sites * 3))
661661

662662
converter.set_dynamical_matrices(dynmat=[dyn])
663663

pymatgen/analysis/structure_prediction/substitutor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def _is_charge_balanced(struct):
160160
"""
161161
Checks if the structure object is charge balanced
162162
"""
163-
return sum(s.specie.oxi_state for s in struct.sites) == 0.0
163+
return sum(site.specie.oxi_state for site in struct) == 0.0
164164

165165
@staticmethod
166166
def _is_from_chemical_system(chemical_system, struct):

pymatgen/command_line/gulp_caller.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -299,12 +299,12 @@ def structure_lines(
299299

300300
if frac_flg:
301301
gin += "frac\n"
302-
coord_attr = "frac_coords"
302+
coords_key = "frac_coords"
303303
else:
304304
gin += "cart\n"
305-
coord_attr = "coords"
306-
for site in structure.sites:
307-
coord = [str(i) for i in getattr(site, coord_attr)]
305+
coords_key = "coords"
306+
for site in structure:
307+
coord = [str(i) for i in getattr(site, coords_key)]
308308
specie = site.specie
309309
core_site_desc = specie.symbol + " core " + " ".join(coord) + "\n"
310310
gin += core_site_desc

pymatgen/command_line/tests/test_gulp_caller.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ def test_get_relaxed_structure(self):
253253
out_str = fp.read()
254254
struct = self.gio.get_relaxed_structure(out_str)
255255
assert isinstance(struct, Structure)
256-
assert len(struct.sites) == 8
256+
assert len(struct) == 8
257257
assert struct.lattice.a == 4.212
258258
assert struct.lattice.alpha == 90
259259

@@ -286,12 +286,12 @@ def setUp(self):
286286
def test_get_energy_tersoff(self):
287287
p = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR.Al12O18"), check_for_POTCAR=False)
288288
structure = p.structure
289-
enrgy = get_energy_tersoff(structure)
290-
assert isinstance(enrgy, float)
289+
energy = get_energy_tersoff(structure)
290+
assert isinstance(energy, float)
291291

292292
def test_get_energy_buckingham(self):
293-
enrgy = get_energy_buckingham(self.mgo_uc)
294-
assert isinstance(enrgy, float)
293+
energy = get_energy_buckingham(self.mgo_uc)
294+
assert isinstance(energy, float)
295295
# test with vacancy structure
296296
del self.mgo_uc[0]
297297
energy = get_energy_buckingham(
@@ -302,10 +302,10 @@ def test_get_energy_buckingham(self):
302302
assert isinstance(energy, float)
303303

304304
def test_get_energy_relax_structure_buckingham(self):
305-
enrgy, struct = get_energy_relax_structure_buckingham(self.mgo_uc)
306-
assert isinstance(enrgy, float)
305+
energy, struct = get_energy_relax_structure_buckingham(self.mgo_uc)
306+
assert isinstance(energy, float)
307307
assert isinstance(struct, Structure)
308-
site_len = len(struct.sites)
308+
site_len = len(struct)
309309
assert site_len == len(self.mgo_uc.sites)
310310

311311

pymatgen/core/structure.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -773,17 +773,17 @@ def from_sites(
773773
prop_keys: list[str] = []
774774
props = {}
775775
lattice = sites[0].lattice
776-
for i, site in enumerate(sites):
776+
for idx, site in enumerate(sites):
777777
if site.lattice != lattice:
778778
raise ValueError("Sites must belong to the same lattice")
779-
for k, v in site.properties.items():
780-
if k not in prop_keys:
781-
prop_keys.append(k)
782-
props[k] = [None] * len(sites)
783-
props[k][i] = v
784-
for k, v in props.items():
785-
if any(vv is None for vv in v):
786-
warnings.warn(f"Not all sites have property {k}. Missing values are set to None.")
779+
for key, val in site.properties.items():
780+
if key not in prop_keys:
781+
prop_keys.append(key)
782+
props[key] = [None] * len(sites)
783+
props[key][idx] = val
784+
for key, val in props.items():
785+
if any(vv is None for vv in val):
786+
warnings.warn(f"Not all sites have property {key}. Missing values are set to None.")
787787
return cls(
788788
lattice,
789789
[site.species for site in sites],

pymatgen/electronic_structure/boltztrap.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ def write_proj(self, output_file_proj, output_file_def):
382382
# This function is useless in std version of BoltzTraP code
383383
# because x_trans script overwrite BoltzTraP.def
384384
for oi, o in enumerate(Orbital):
385-
for site_nb in range(0, len(self._bs.structure.sites)):
385+
for site_nb in range(len(self._bs.structure)):
386386
if oi < len(self._bs.projections[Spin.up][0][0]):
387387
with open(output_file_proj + "_" + str(site_nb) + "_" + str(o), "w") as f:
388388
f.write(self._bs.structure.composition.formula + "\n")
@@ -424,7 +424,7 @@ def write_proj(self, output_file_proj, output_file_def):
424424
)
425425
i = 1000
426426
for oi, o in enumerate(Orbital):
427-
for site_nb in range(0, len(self._bs.structure.sites)):
427+
for site_nb in range(0, len(self._bs.structure)):
428428
if oi < len(self._bs.projections[Spin.up][0][0]):
429429
f.write(f"{i},'boltztrap.proj_{site_nb}_{o.name}old', 'formatted',0\n")
430430
i += 1

pymatgen/electronic_structure/boltztrap2.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ def get_partial_doses(self, tdos, eband_ud, spins, enr, npts_mu, T, progress):
623623
n_iter = np.prod(np.sum([np.array(i.shape)[2:] for i in self.data.proj.values()]))
624624
t = tqdm(total=n_iter * 2)
625625
for spin, eb in zip(spins, eband_ud):
626-
for isite, site in enumerate(self.data.structure.sites):
626+
for idx, site in enumerate(self.data.structure):
627627
if site not in pdoss:
628628
pdoss[site] = {}
629629
for iorb, orb in enumerate(Orbital):
@@ -635,7 +635,7 @@ def get_partial_doses(self, tdos, eband_ud, spins, enr, npts_mu, T, progress):
635635
if orb not in pdoss[site]:
636636
pdoss[site][orb] = {}
637637

638-
self.data.ebands = self.data.proj[spin][:, :, isite, iorb].T
638+
self.data.ebands = self.data.proj[spin][:, :, idx, iorb].T
639639
coeffs = fite.fitde3D(self.data, self.equivalences)
640640
proj, vvproj, cproj = fite.getBTPbands(self.equivalences, coeffs, self.data.lattvec)
641641

pymatgen/io/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ def to_cube(self, filename, comment=None):
354354
f"\t {self.dim[idx]} {lattice_matrix[0]:.6f} {lattice_matrix[1]:.6f} {lattice_matrix[2]:.6f}\n"
355355
)
356356

357-
for site in self.structure.sites:
357+
for site in self.structure:
358358
file.write(
359359
f"\t {Element(site.species_string).Z} 0.000000 "
360360
f"{ang_to_bohr * site.coords[0]} "

pymatgen/io/cssr.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ def __str__(self):
4343
f"{len(self.structure)} 0",
4444
f"0 {self.structure.formula}",
4545
]
46-
for i, site in enumerate(self.structure.sites):
47-
output.append(f"{i + 1} {site.specie} {site.a:.4f} {site.b:.4f} {site.c:.4f}")
46+
for idx, site in enumerate(self.structure):
47+
output.append(f"{idx + 1} {site.specie} {site.a:.4f} {site.b:.4f} {site.c:.4f}")
4848
return "\n".join(output)
4949

5050
def write_file(self, filename):

pymatgen/io/lmto.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,9 @@ def as_dict(self):
126126
sites = []
127127
classes = []
128128
num_atoms = {}
129-
for s, site in enumerate(self.structure.sites):
129+
for idx, site in enumerate(self.structure):
130130
atom = site.specie
131-
label_index = ineq_sites_index.index(eq_atoms[s])
131+
label_index = ineq_sites_index.index(eq_atoms[idx])
132132
if atom.symbol in num_atoms:
133133
if label_index + 1 > sum(num_atoms.values()):
134134
num_atoms[atom.symbol] += 1

pymatgen/io/tests/test_pwscf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ def test_read_str(self):
358358

359359
# generate list of coords
360360
pw_sites = []
361-
for site in pwin.structure.sites:
361+
for site in pwin.structure:
362362
pw_sites.append(list(site.coords))
363363
pw_sites = np.array(pw_sites)
364364

pymatgen/io/tests/test_zeopp.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def setUp(self):
159159
self.structure = p.structure
160160
bv = BVAnalyzer()
161161
valences = bv.get_valences(self.structure)
162-
el = [site.species_string for site in self.structure.sites]
162+
el = [site.species_string for site in self.structure]
163163
valence_dict = dict(zip(el, valences))
164164
self.rad_dict = {}
165165
for k, v in valence_dict.items():
@@ -210,7 +210,7 @@ def setUp(self):
210210
self.structure = p.structure
211211
bv = BVAnalyzer()
212212
valences = bv.get_valences(self.structure)
213-
el = [site.species_string for site in self.structure.sites]
213+
el = [site.species_string for site in self.structure]
214214
valence_dict = dict(zip(el, valences))
215215
self.rad_dict = {}
216216
for k, v in valence_dict.items():
@@ -240,10 +240,10 @@ def setUp(self):
240240
valences = bv.get_valences(self.structure)
241241
radii = []
242242
for idx, valence in enumerate(valences):
243-
el = self.structure.sites[idx].specie.symbol
243+
el = self.structure[idx].specie.symbol
244244
radius = Species(el, valence).ionic_radius
245245
radii.append(radius)
246-
el = [site.species_string for site in self.structure.sites]
246+
el = [site.species_string for site in self.structure]
247247
self.rad_dict = dict(zip(el, radii))
248248
for el in self.rad_dict:
249249
print((el, self.rad_dict[el].real))

pymatgen/io/vasp/sets.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3037,16 +3037,16 @@ def get_valid_magmom_struct(structure, inplace=True, spin_mode="auto"):
30373037
default_values = {"s": 1.0, "v": [1.0, 1.0, 1.0], "n": None}
30383038
if spin_mode[0].lower() == "a":
30393039
mode = "n"
3040-
for isite in structure.sites:
3041-
if "magmom" not in isite.properties or isite.properties["magmom"] is None:
3040+
for site in structure:
3041+
if "magmom" not in site.properties or site.properties["magmom"] is None:
30423042
pass
3043-
elif isinstance(isite.properties["magmom"], (float, int)):
3043+
elif isinstance(site.properties["magmom"], (float, int)):
30443044
if mode == "v":
30453045
raise TypeError("Magmom type conflict")
30463046
mode = "s"
3047-
if isinstance(isite.properties["magmom"], int):
3048-
isite.properties["magmom"] = float(isite.properties["magmom"])
3049-
elif len(isite.properties["magmom"]) == 3:
3047+
if isinstance(site.properties["magmom"], int):
3048+
site.properties["magmom"] = float(site.properties["magmom"])
3049+
elif len(site.properties["magmom"]) == 3:
30503050
if mode == "s":
30513051
raise TypeError("Magmom type conflict")
30523052
mode = "v"
@@ -3056,12 +3056,12 @@ def get_valid_magmom_struct(structure, inplace=True, spin_mode="auto"):
30563056
mode = spin_mode[0].lower()
30573057

30583058
new_struct = structure.copy() if not inplace else structure
3059-
for isite in new_struct.sites:
3059+
for site in new_struct:
30603060
if mode == "n":
3061-
if "magmom" in isite.properties:
3062-
isite.properties.pop("magmom")
3063-
elif "magmom" not in isite.properties or isite.properties["magmom"] is None:
3064-
isite.properties["magmom"] = default_values[mode]
3061+
if "magmom" in site.properties:
3062+
site.properties.pop("magmom")
3063+
elif "magmom" not in site.properties or site.properties["magmom"] is None:
3064+
site.properties["magmom"] = default_values[mode]
30653065

30663066
if not inplace:
30673067
return new_struct

pymatgen/io/vasp/tests/test_sets.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -494,16 +494,16 @@ def test_valid_magmom_struct(self):
494494
# First test the helper function
495495
struct = self.structure.copy()
496496
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="v")
497-
props = [isite.properties for isite in struct.sites]
497+
props = [site.properties for site in struct]
498498
assert props == [{"magmom": [1.0, 1.0, 1.0]}] * len(props)
499499

500500
struct = self.structure.copy()
501501
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="s")
502-
props = [isite.properties for isite in struct.sites]
502+
props = [site.properties for site in struct]
503503
assert props == [{"magmom": 1.0}] * len(props)
504504
struct.insert(0, "Li", [0, 0, 0])
505505
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="a")
506-
props = [isite.properties for isite in struct.sites]
506+
props = [site.properties for site in struct]
507507
assert props == [{"magmom": 1.0}] * len(props)
508508

509509
struct = self.structure.copy()

pymatgen/io/xr.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def __str__(self):
5252
]
5353
# There are actually 10 more fields per site
5454
# in a typical xr file from GULP, for example.
55-
for idx, site in enumerate(self.structure.sites):
55+
for idx, site in enumerate(self.structure):
5656
output.append(f"{idx + 1} {site.specie} {site.x:.4f} {site.y:.4f} {site.z:.4f}")
5757
mat = self.structure.lattice.matrix
5858
for _ in range(2):

0 commit comments

Comments
 (0)