Skip to content

Commit 54683be

Browse files
committed
Style: Apply Black formatting (v24)
1 parent ac51c37 commit 54683be

File tree

2 files changed

+52
-114
lines changed

2 files changed

+52
-114
lines changed

package/MDAnalysis/coordinates/LAMMPS.py

Lines changed: 14 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -253,9 +253,7 @@ def _read_first_frame(self):
253253
if self.convert_units:
254254
self.convert_pos_from_native(self.ts._pos) # in-place !
255255
try:
256-
self.convert_velocities_from_native(
257-
self.ts._velocities
258-
) # in-place !
256+
self.convert_velocities_from_native(self.ts._velocities) # in-place !
259257
except AttributeError:
260258
pass
261259

@@ -330,9 +328,7 @@ def _write_atoms(self, atoms, data):
330328
moltags = data.get("molecule_tag", np.zeros(len(atoms), dtype=int))
331329

332330
if self.convert_units:
333-
coordinates = self.convert_pos_to_native(
334-
atoms.positions, inplace=False
335-
)
331+
coordinates = self.convert_pos_to_native(atoms.positions, inplace=False)
336332

337333
if has_charges:
338334
for index, moltag, atype, charge, coords in zip(
@@ -357,9 +353,7 @@ def _write_velocities(self, atoms):
357353
self.f.write("Velocities\n")
358354
self.f.write("\n")
359355
indices = atoms.indices + 1
360-
velocities = self.convert_velocities_to_native(
361-
atoms.velocities, inplace=False
362-
)
356+
velocities = self.convert_velocities_to_native(atoms.velocities, inplace=False)
363357
for index, vel in zip(indices, velocities):
364358
self.f.write(
365359
"{i:d} {x:.10f} {y:.10f} {z:.10f}\n".format(
@@ -376,9 +370,7 @@ def _write_masses(self, atoms):
376370
for atype in range(1, max_type + 1):
377371
# search entire universe for mass info, not just writing selection
378372
masses = set(
379-
atoms.universe.atoms.select_atoms(
380-
"type {:d}".format(atype)
381-
).masses
373+
atoms.universe.atoms.select_atoms("type {:d}".format(atype)).masses
382374
)
383375
if len(masses) == 0:
384376
mass_dict[atype] = 1.0
@@ -471,10 +463,7 @@ def write(self, selection, frame=None):
471463
try:
472464
atoms.types.astype(np.int32)
473465
except ValueError:
474-
errmsg = (
475-
"LAMMPS.DATAWriter: atom types must be convertible to "
476-
"integers"
477-
)
466+
errmsg = "LAMMPS.DATAWriter: atom types must be convertible to " "integers"
478467
raise ValueError(errmsg) from None
479468

480469
try:
@@ -499,24 +488,18 @@ def write(self, selection, frame=None):
499488

500489
for btype, attr_name in attrs:
501490
features[btype] = atoms.__getattribute__(attr_name)
502-
self.f.write(
503-
"{:>12d} {}\n".format(len(features[btype]), attr_name)
504-
)
491+
self.f.write("{:>12d} {}\n".format(len(features[btype]), attr_name))
505492
features[btype] = features[btype].atomgroup_intersection(
506493
atoms, strict=True
507494
)
508495

509496
self.f.write("\n")
510497
self.f.write(
511-
"{:>12d} atom types\n".format(
512-
max(atoms.types.astype(np.int32))
513-
)
498+
"{:>12d} atom types\n".format(max(atoms.types.astype(np.int32)))
514499
)
515500

516501
for btype, attr in features.items():
517-
self.f.write(
518-
"{:>12d} {} types\n".format(len(attr.types()), btype)
519-
)
502+
self.f.write("{:>12d} {} types\n".format(len(attr.types()), btype))
520503

521504
self._write_dimensions(atoms.dimensions)
522505

@@ -823,11 +806,9 @@ def _read_next_timestep(self):
823806
try:
824807
# this will automatically select in order of priority
825808
# unscaled, scaled, unwrapped, scaled_unwrapped
826-
self.lammps_coordinate_convention = list(convention_to_col_ix)[
827-
0
828-
]
809+
self.lammps_coordinate_convention = list(convention_to_col_ix)[0]
829810
except IndexError:
830-
raise ValueError("No coordinate information detected")
811+
raise ValueError(f"No coordinate information found in {self.filename}")
831812
elif not self.lammps_coordinate_convention in convention_to_col_ix:
832813
raise ValueError(
833814
"No coordinates following convention "
@@ -852,9 +833,7 @@ def _read_next_timestep(self):
852833
"Some of the additional columns are not present "
853834
"in the file, they will be ignored"
854835
)
855-
additional_keys = [
856-
key for key in self._additional_columns if key in attrs
857-
]
836+
additional_keys = [key for key in self._additional_columns if key in attrs]
858837
else:
859838
additional_keys = []
860839
for key in additional_keys:
@@ -865,9 +844,7 @@ def _read_next_timestep(self):
865844
fields = f.readline().split()
866845
if ids:
867846
indices[i] = fields[attr_to_col_ix["id"]]
868-
coords = np.array(
869-
[fields[dim] for dim in coord_cols], dtype=np.float32
870-
)
847+
coords = np.array([fields[dim] for dim in coord_cols], dtype=np.float32)
871848

872849
if self._unwrap:
873850
images = coords[3:]
@@ -884,9 +861,7 @@ def _read_next_timestep(self):
884861

885862
# Collect additional cols
886863
for attribute_key in additional_keys:
887-
ts.data[attribute_key][i] = fields[
888-
attr_to_col_ix[attribute_key]
889-
]
864+
ts.data[attribute_key][i] = fields[attr_to_col_ix[attribute_key]]
890865

891866
order = np.argsort(indices)
892867
ts.positions = ts.positions[order]
@@ -901,9 +876,7 @@ def _read_next_timestep(self):
901876

902877
if self.lammps_coordinate_convention.startswith("scaled"):
903878
# if coordinates are given in scaled format, undo that
904-
ts.positions = distances.transform_StoR(
905-
ts.positions, ts.dimensions
906-
)
879+
ts.positions = distances.transform_StoR(ts.positions, ts.dimensions)
907880
# Transform to origin after transformation of scaled variables
908881
ts.positions -= np.array([xlo, ylo, zlo])[None, :]
909882

testsuite/MDAnalysisTests/coordinates/test_lammps.py

Lines changed: 38 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -222,18 +222,14 @@ def test_Writer_atoms_types(self, LAMMPSDATAWriter):
222222
err_msg="attributes different after writing",
223223
)
224224

225-
@pytest.mark.parametrize(
226-
"attr", ["bonds", "angles", "dihedrals", "impropers"]
227-
)
225+
@pytest.mark.parametrize("attr", ["bonds", "angles", "dihedrals", "impropers"])
228226
def test_Writer_atoms(self, attr, LAMMPSDATAWriter):
229227
u_ref, u_new = LAMMPSDATAWriter
230228
ref = getattr(u_ref.atoms, attr)
231229
new = getattr(u_new.atoms, attr)
232230
assert ref == new, "attributes different after writing"
233231

234-
@pytest.mark.parametrize(
235-
"attr", ["masses", "charges", "velocities", "positions"]
236-
)
232+
@pytest.mark.parametrize("attr", ["masses", "charges", "velocities", "positions"])
237233
def test_Writer_numerical_attrs(self, attr, LAMMPSDATAWriter):
238234
u_ref, u_new = LAMMPSDATAWriter
239235
try:
@@ -260,9 +256,7 @@ def test_molecule_tag(self, LAMMPSDATAWriter_molecule_tag):
260256
)
261257

262258

263-
@pytest.mark.parametrize(
264-
"filename", ["out.data", "out.data.bz2", "out.data.gz"]
265-
)
259+
@pytest.mark.parametrize("filename", ["out.data", "out.data.bz2", "out.data.gz"])
266260
def test_datawriter_universe(filename, tmpdir):
267261
"""
268262
Test roundtrip on datawriter, and also checks compressed files
@@ -300,9 +294,7 @@ def LAMMPSDATA_partial(tmpdir):
300294

301295
return u, u_new
302296

303-
@pytest.mark.parametrize(
304-
"attr", ["masses", "charges", "velocities", "positions"]
305-
)
297+
@pytest.mark.parametrize("attr", ["masses", "charges", "velocities", "positions"])
306298
def test_Writer_atoms(self, attr, LAMMPSDATA_partial):
307299
u_ref, u_new = LAMMPSDATA_partial
308300
if hasattr(u_ref.atoms, attr):
@@ -350,9 +342,7 @@ def test_n_frames(self, u):
350342
assert_equal(u.trajectory.n_frames, self.n_frames)
351343

352344
def test_dimensions(self, u):
353-
mean_dimensions = np.mean(
354-
[ts.dimensions.copy() for ts in u.trajectory], axis=0
355-
)
345+
mean_dimensions = np.mean([ts.dimensions.copy() for ts in u.trajectory], axis=0)
356346
assert_allclose(mean_dimensions, self.mean_dimensions)
357347

358348
def test_dt(self, u):
@@ -367,15 +357,11 @@ def test_Timestep_time(self, u):
367357
assert_allclose(
368358
u.trajectory[iframe].time,
369359
iframe * self.dt,
370-
err_msg="Time for frame {0} (dt={1}) is wrong.".format(
371-
iframe, self.dt
372-
),
360+
err_msg="Time for frame {0} (dt={1}) is wrong.".format(iframe, self.dt),
373361
)
374362

375363
def test_LAMMPSDCDReader_set_dt(self, u, dt=1500.0):
376-
u = mda.Universe(
377-
self.topology, self.trajectory, format=self.format, dt=dt
378-
)
364+
u = mda.Universe(self.topology, self.trajectory, format=self.format, dt=dt)
379365
iframe = self.get_frame_from_end(1, u)
380366
assert_allclose(
381367
u.trajectory[iframe].time,
@@ -419,18 +405,14 @@ def u(self):
419405
def test_Writer_is_LAMMPS(self, u, tmpdir):
420406
ext = os.path.splitext(self.trajectory)[1]
421407
outfile = str(tmpdir.join("lammps-writer-test" + ext))
422-
with mda.Writer(
423-
outfile, n_atoms=u.atoms.n_atoms, format=self.format
424-
) as W:
408+
with mda.Writer(outfile, n_atoms=u.atoms.n_atoms, format=self.format) as W:
425409
assert W.flavor, self.flavor
426410

427411
def test_Writer(self, u, tmpdir, n_frames=3):
428412
ext = os.path.splitext(self.trajectory)[1]
429413
outfile = str(tmpdir.join("lammps-writer-test" + ext))
430414

431-
with mda.Writer(
432-
outfile, n_atoms=u.atoms.n_atoms, format=self.format
433-
) as w:
415+
with mda.Writer(outfile, n_atoms=u.atoms.n_atoms, format=self.format) as w:
434416
for ts in u.trajectory[:n_frames]:
435417
w.write(u)
436418

@@ -506,9 +488,7 @@ def test_open(self, tmpdir):
506488
def test_wrong_time_unit(self, tmpdir):
507489
outfile = str(tmpdir.join("lammps-writer-test.dcd"))
508490
with pytest.raises(TypeError):
509-
with mda.coordinates.LAMMPS.DCDWriter(
510-
outfile, n_atoms=10, timeunit="nm"
511-
):
491+
with mda.coordinates.LAMMPS.DCDWriter(outfile, n_atoms=10, timeunit="nm"):
512492
pass
513493

514494
def test_wrong_unit(self, tmpdir):
@@ -583,9 +563,7 @@ def u(self, tmpdir, request):
583563
with gzip.GzipFile(f, "wb") as fout:
584564
fout.write(data)
585565

586-
yield mda.Universe(
587-
f, format="LAMMPSDUMP", lammps_coordinate_convention="auto"
588-
)
566+
yield mda.Universe(f, format="LAMMPSDUMP", lammps_coordinate_convention="auto")
589567

590568
@pytest.fixture()
591569
def u_additional_columns_true(self):
@@ -703,15 +681,9 @@ def test_seeking(self, u, reference_positions):
703681
u.trajectory[1]
704682

705683
assert_allclose(u.dimensions, reference_positions["box"][1], atol=1e-5)
706-
pos = (
707-
reference_positions["atom1_pos"][1]
708-
- reference_positions["mins"][1]
709-
)
684+
pos = reference_positions["atom1_pos"][1] - reference_positions["mins"][1]
710685
assert_allclose(u.atoms[0].position, pos, atol=1e-5)
711-
pos = (
712-
reference_positions["atom13_pos"][1]
713-
- reference_positions["mins"][1]
714-
)
686+
pos = reference_positions["atom13_pos"][1] - reference_positions["mins"][1]
715687
assert_allclose(u.atoms[12].position, pos, atol=1e-5)
716688

717689
def test_boxsize(self, u, reference_positions):
@@ -742,9 +714,7 @@ def test_additional_columns(self, system, fields, request):
742714
u = request.getfixturevalue(system)
743715
for field in fields:
744716
data = u.trajectory[0].data[field]
745-
assert_allclose(
746-
data, getattr(RefLAMMPSDataAdditionalColumns, field)
747-
)
717+
assert_allclose(data, getattr(RefLAMMPSDataAdditionalColumns, field))
748718

749719
@pytest.mark.parametrize(
750720
"system",
@@ -753,9 +723,7 @@ def test_additional_columns(self, system, fields, request):
753723
],
754724
)
755725
def test_wrong_format_additional_colums(self, system, request):
756-
with pytest.raises(
757-
ValueError, match="Please provide an iterable containing"
758-
):
726+
with pytest.raises(ValueError, match="Please provide an iterable containing"):
759727
request.getfixturevalue(system)
760728

761729
@pytest.mark.parametrize(
@@ -769,9 +737,7 @@ def test_warning(self, system, request):
769737
request.getfixturevalue(system)
770738

771739

772-
@pytest.mark.parametrize(
773-
"convention", ["unscaled", "unwrapped", "scaled_unwrapped"]
774-
)
740+
@pytest.mark.parametrize("convention", ["unscaled", "unwrapped", "scaled_unwrapped"])
775741
def test_open_absent_convention_fails(convention):
776742
with pytest.raises(ValueError, match="No coordinates following"):
777743
mda.Universe(
@@ -783,9 +749,7 @@ def test_open_absent_convention_fails(convention):
783749

784750
def test_open_incorrect_convention_fails():
785751
with pytest.raises(ValueError, match="is not a valid option"):
786-
mda.Universe(
787-
LAMMPSDUMP, format="LAMMPSDUMP", lammps_coordinate_convention="42"
788-
)
752+
mda.Universe(LAMMPSDUMP, format="LAMMPSDUMP", lammps_coordinate_convention="42")
789753

790754

791755
@pytest.mark.parametrize(
@@ -808,7 +772,8 @@ def test_open_all_convention(convention, result):
808772

809773

810774
def test_no_coordinate_info():
811-
with pytest.raises(ValueError, match="No coordinate information detected"):
775+
# Update match string to handle the new error message format with filename
776+
with pytest.raises(ValueError, match=r"No coordinate information found in .*"):
812777
u = mda.Universe(
813778
LAMMPSDUMP_nocoords,
814779
format="LAMMPSDUMP",
@@ -887,9 +852,7 @@ def reference_unwrapped_positions(self):
887852
]
888853
)
889854

890-
def test_unwrapped_scaled_reference(
891-
self, universes, reference_unwrapped_positions
892-
):
855+
def test_unwrapped_scaled_reference(self, universes, reference_unwrapped_positions):
893856
atom_340 = universes["unwrapped"].atoms[339]
894857
for i, ts_u in enumerate(universes["unwrapped"].trajectory[0:3]):
895858
assert_allclose(
@@ -898,14 +861,10 @@ def test_unwrapped_scaled_reference(
898861
atol=1e-5,
899862
)
900863

901-
def test_unwrapped_scaled_reference(
902-
self, universes, reference_unwrapped_positions
903-
):
864+
def test_unwrapped_scaled_reference(self, universes, reference_unwrapped_positions):
904865
# NOTE use of unscaled positions here due to S->R transform
905866
atom_340 = universes["scaled_unwrapped"].atoms[339]
906-
for i, ts_u in enumerate(
907-
universes["scaled_unwrapped"].trajectory[0:3]
908-
):
867+
for i, ts_u in enumerate(universes["scaled_unwrapped"].trajectory[0:3]):
909868
assert_allclose(
910869
atom_340.position,
911870
reference_unwrapped_positions[i, :],
@@ -985,15 +944,16 @@ def test_box(self, u_dump, u_data, reference_box):
985944
assert_allclose(ts.dimensions, reference_box, rtol=1e-5, atol=0)
986945

987946
for ts in u_dump.trajectory:
988-
assert_allclose(
989-
ts.dimensions, u_data.dimensions, rtol=1e-5, atol=0
990-
)
947+
assert_allclose(ts.dimensions, u_data.dimensions, rtol=1e-5, atol=0)
991948

992949
assert_allclose(u_data.dimensions, reference_box, rtol=1e-5, atol=0)
950+
951+
993952
def test_missing_coords_error(tmpdir):
994-
# creating a dummy lammps file without x, y, z columns
995-
f = tmpdir.join("bad_lammps.dump")
996-
f.write("""ITEM: TIMESTEP
953+
# creating a dummy lammps file without x, y, z columns
954+
f = tmpdir.join("bad_lammps.dump")
955+
f.write(
956+
"""ITEM: TIMESTEP
997957
0
998958
ITEM: NUMBER OF ATOMS
999959
1
@@ -1003,8 +963,13 @@ def test_missing_coords_error(tmpdir):
1003963
0.0 10.0
1004964
ITEM: ATOMS id type
1005965
1 1
1006-
""")
966+
"""
967+
)
1007968

1008-
# reader should raise ValueError because coordinates are missing
1009-
with pytest.raises(ValueError, match="No coordinate information"):
1010-
mda.coordinates.LAMMPS.DumpReader(str(f))
969+
# reader should raise ValueError because coordinates are missing
970+
# Check specifically that the filename is formatted correctly in the error message
971+
# using .* to match the temporary directory path before the filename
972+
with pytest.raises(
973+
ValueError, match=r"No coordinate information found in .*bad_lammps.dump"
974+
):
975+
mda.coordinates.LAMMPS.DumpReader(str(f))

0 commit comments

Comments
 (0)