Skip to content

LAMMPS DATAWriter convert_units=False raises UnboundLocalError #5527

Open

Description

@swf1996120

Summary

MDAnalysis.coordinates.LAMMPS.DATAWriter exposes the convert_units argument, but convert_units=False is not implemented consistently. Writing a system with box dimensions fails because _write_dimensions() only assigns the local variable triv inside if self.convert_units: and then uses it unconditionally. The atom writer has the same issue with its coordinates local, and the velocity writer always performs a unit conversion even when conversion is disabled.

Reproduction

import MDAnalysis as mda
import numpy as np

u = mda.Universe.empty(2, trajectory=True)
u.add_TopologyAttr('types', ['1', '1'])
u.add_TopologyAttr('masses', [12.0, 12.0])
u.add_bonds([(0, 1)], types=[1])
u.add_TopologyAttr('angles', [])
u.add_TopologyAttr('dihedrals', [])
u.add_TopologyAttr('impropers', [])
u.atoms.positions = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
u.dimensions = np.array([10.0, 10.0, 10.0, 90.0, 90.0, 90.0])

with mda.Writer('system.data', n_atoms=2, format='DATA', convert_units=False) as writer:
    writer.write(u.atoms)

With MDAnalysis 2.11.0, this raises:

UnboundLocalError: cannot access local variable 'triv' where it is not associated with a value

The same topology and writer call with convert_units=True succeeds and produces a DATA file. The failure therefore comes from the public option itself, before any unit conversion or LAMMPS parsing.

Expected behavior

convert_units=False should write coordinates, box dimensions, and velocities in the supplied native units, just as the option promises. The implementation should define the unconverted arrays in the false branch and skip velocity conversion when conversion is disabled.

Relevant code

)
def _write_masses(self, atoms):
self.f.write("\n")
self.f.write("Masses\n")
self.f.write("\n")
mass_dict = {}
max_type = max(atoms.types.astype(np.int32))
for atype in range(1, max_type + 1):
# search entire universe for mass info, not just writing selection
masses = set(
atoms.universe.atoms.select_atoms(
"type {:d}".format(atype)
).masses
)

The same flag-dependent uninitialized value appears for atom coordinates:

indices = atoms.indices + 1
types = atoms.types.astype(np.int32)
moltags = data.get("molecule_tag", np.zeros(len(atoms), dtype=int))
if self.convert_units:
coordinates = self.convert_pos_to_native(
atoms.positions, inplace=False
)
if has_charges:
for index, moltag, atype, charge, coords in zip(
indices, moltags, types, charges, coordinates
):
x, y, z = coords
self.f.write(
f"{index:d} {moltag:d} {atype:d} {charge:f}"
f" {x:.10f} {y:.10f} {z:.10f}\n"
)
else:
for index, moltag, atype, coords in zip(
indices, moltags, types, coordinates
):

Velocities are converted unconditionally here:

def _write_velocities(self, atoms):
self.f.write("\n")
self.f.write("Velocities\n")
self.f.write("\n")
indices = atoms.indices + 1
velocities = self.convert_velocities_to_native(
atoms.velocities, inplace=False
)
for index, vel in zip(indices, velocities):
self.f.write(
"{i:d} {x:.10f} {y:.10f} {z:.10f}\n".format(
i=index, x=vel[0], y=vel[1], z=vel[2]
)
)

Activity

  1. IAlibay commented on Oct 27, 2026

    @IAlibay
    Member

    @swf1996120 - I have seen you suspiciously open 4 issues all close to each other across MDAnalysis and OpenMM. Is this some kind of LLM automated report?

  2. swf1996120 commented on Oct 27, 2026

    @swf1996120
    Author

    Thanks for asking. Yes, these reports are part of an LLM-assisted testing study. An LLM helped generate candidate test cases and draft the issue text, while I ran each reproducer locally, verified the behavior against the package, minimized the examples, and searched existing issues before filing. I take responsibility for the reports, and I should have disclosed the AI assistance when opening them.

    I will pause additional reports to MDAnalysis for now and follow the project’s AI policy going forward.

  3. Shreyanshsingh23 commented on Nov 26, 2026

    @Shreyanshsingh23

    hey, can i take this one?

    still there on develop: in DATAWriter (coordinates/LAMMPS.py), coordinates (L332) and triv (L417) only get set inside if self.convert_units:, so convert_units=False hits the UnboundLocalError, and _write_velocities (L360) converts no matter what the flag says.

    plan:

    • add the missing branches so positions and box dimensions are written as given when convert_units=False
    • only convert velocities when convert_units is true
    • add tests in test_lammps.py that write with convert_units=False and check positions, box and velocities in the output are unchanged

    can you assign it to me? will have a PR up soon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions