Count hydrogen bonds in water#

Start with a pair of waters in a periodic box. Count the hydrogen bond between them, then repeat the same analysis on a trajectory.

python -m pip install 'pydseamslib'

Build and check a two-water frame#

Pass the oxygen positions, box lengths, and hydrogen positions in angstroms. The molecule IDs attach each hydrogen to its parent water. Here one O-H bond points from the second water towards the first.

import pydseams as ds


def water_pairs(frame):
    """Return each unordered hydrogen-bond pair once."""
    return {
        tuple(sorted((row[0], partner)))
        for row in frame.hbonds
        for partner in row[1:]
    }


frame = ds.from_arrays(
    [[5.0, 5.0, 5.0], [7.8, 5.0, 5.0]],
    [20.0, 20.0, 20.0],
    numbers=[8, 8],
    mol_ids=[1, 2],
    hydrogen_positions=[
        [4.0, 5.0, 5.0],
        [5.0, 4.0, 5.0],
        [6.8, 5.0, 5.0],
        [7.8, 6.0, 5.0],
    ],
    hydrogen_mol_ids=[1, 1, 2, 2],
    bonded="hbond",
)
pairs = water_pairs(frame)
assert pairs == {(1, 2)}
if __name__ == "__main__":
    print(f"{len(pairs)} hydrogen-bonded water pair")

Save the block as water_bonds.py and run python water_bonds.py. Expected output:

1 hydrogen-bonded water pair

Each row of frame.hbonds starts with its centre oxygen’s atom ID. The other entries are bonded oxygen IDs. For frames built from arrays, these IDs start at 1 and follow selection order. The molecule IDs passed to from_arrays assign hydrogens to their parent oxygens. Both ends list each bond, so taking a set of sorted pairs gives a single pair for each connection.

Count pairs across a labelled trajectory#

For a GROMACS XTC or TRR, supply the matching GRO topology. Its atom order must match the trajectory. In this example SOL is the water residue name, OW is oxygen, and HW1 and HW2 are hydrogen. Use the corresponding names from your topology.

python -m pip install 'pydseamslib[readcon]'
def water_frames(trajectory_path, topology_path):
    return ds.iter_trajectory(
        trajectory_path,
        topology=topology_path,
        residue_name="SOL",
        atom_name="OW",
        hydrogen_names=("HW1", "HW2"),
        bonded="hbond",
    )


def count_water_bonds(trajectory_path, topology_path):
    for trajectory_frame in water_frames(trajectory_path, topology_path):
        yield trajectory_frame.frame, len(water_pairs(trajectory_frame))

Save the Python blocks together as water_bonds.py. The count_water_bonds function yields the frame number and unique pair count for each saved frame. In a Python prompt, import it with from water_bonds import count_water_bonds and call next(count_water_bonds("water.xtc", "water.gro")) for the first frame.

Measure how long pairs persist#

Save one pair collection per frame, including empty frames. The intermittent curve measures presence at the two ends of a lag. The continuous curve requires presence at every saved frame in between. Here the pair breaks and reforms across three frames saved every 0.5 ps.

from dseams import hbond_lifetime


lifetime = hbond_lifetime([pairs, set(), pairs], dt=0.5, directed=False)
assert lifetime.lag_time.tolist() == [0.0, 0.5, 1.0]
assert lifetime.intermittent.tolist() == [1.0, 0.0, 1.0]
assert lifetime.continuous.tolist() == [1.0, 0.0, 0.0]

At a lag of 1 ps the bond has reformed, while its continuous survival is zero. A break and reunion between consecutive saved frames is invisible to both curves.

Write both lifetime curves for your trajectory#

Append this function to water_bonds.py. It passes one set of unordered pairs per frame, including empty sets, to the lifetime accumulator. Keep the same atom order and water selection across frames so each pair refers to the same two molecules.

import csv


def write_water_lifetimes(
    trajectory_path, topology_path, output_path, *, frame_spacing_ps, max_lag_frames
):
    frames = water_frames(trajectory_path, topology_path)
    curve = hbond_lifetime(
        (water_pairs(trajectory_frame) for trajectory_frame in frames),
        dt=frame_spacing_ps,
        max_lag=max_lag_frames,
        directed=False,
    )
    with open(output_path, "w", newline="") as output:
        writer = csv.writer(output)
        writer.writerow(["lag_ps", "intermittent", "continuous", "n_origins"])
        writer.writerows(
            zip(curve.lag_time, curve.intermittent, curve.continuous, curve.n_origins)
        )

The following command reads water.xtc with its matching water.gro and writes lifetimes.csv. Change frame_spacing_ps to the time between saved frames. With one frame per picosecond and a maximum lag of 20 frames, the output covers lags through 20 ps if the trajectory has at least 21 frames.

python - <<'PYTHON'
from water_bonds import write_water_lifetimes

write_water_lifetimes(
    "water.xtc", "water.gro", "lifetimes.csv",
    frame_spacing_ps=1.0, max_lag_frames=20,
)
PYTHON

The two fractions should both start at 1 if the trajectory contains hydrogen bonds. At each lag, n_origins counts the eligible starting frames, including starts with no bonds. A curve value of nan means that none of those frames contained a starting bond.

For ring sizes on the same H-bond graph, see Primitive rings.