Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 201 additions & 9 deletions polychrom/hdf5_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,16 +115,34 @@
Files are written with ``libver="v110"``, which reduces HDF5 metadata overhead
(~4 KB -> ~0.8 KB per conformation) and requires HDF5 >= 1.10 to read.


Thinning existing trajectories
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:py:func:`thin_trajectory` shrinks a saved trajectory: it keeps every n-th block (and the last one) and
re-saves positions with the encoding above. Kept blocks keep their original numbers, so a thinned file
``blocks_0-990.h5`` holds blocks 0, 10, ..., 990. :py:func:`list_URIs` lists the blocks actually present in
each file, so thinned folders are read like any other. Code that selects blocks by position in the list
(e.g. ``list_URIs(folder)[1500:]`` to skip equilibration) should select by block number instead.
For example, keeping every 10th block at ``pos_precision=0.1`` reduced a set of loop extrusion
trajectories ~40 times, and changed contact maps (cutoff 7.5) by ~0.02% beyond the effect of using fewer
conformations.

"""

import glob
import json
import os
import shutil
import time
import warnings
from typing import Any, Dict, List, Literal, Optional, Tuple, Union, overload

import h5py
import numpy as np

from polychrom import __version__

DEFAULT_OPTS: Dict[str, Union[int, str]] = {"compression_opts": 5, "compression": "gzip"}


Expand Down Expand Up @@ -369,7 +387,9 @@ def list_URIs(
generally treated like a filename.

This function checks that the HDF5 file is openable (if read_error==True),
but does not check if individual datasets (blocks) exist in a file.
and lists the blocks (groups) that are actually present in each file, so files that do not hold
every block of their filename range (e.g. thinned with :py:func:`thin_trajectory`) are listed
correctly. It does not check that the data inside each block is readable.
If read_error==False, a non-openable file is fully ignored.
NOTE: This covers the most typical case of corruption due to a terminated write,
because an HDF5 file becomes invalid in that case.
Expand All @@ -378,8 +398,6 @@ def list_URIs(
But it does error if one block is listed twice
(e.g. blocks_1-10.h5; blocks_5-15.h5 is invalid)

TODO: think about the above checks, and check for readable datasets as well

Parameters
----------

Expand All @@ -402,8 +420,8 @@ def list_URIs(
filenames = {}
for file in files:
try:
with h5py.File(file, "r"):
pass
with h5py.File(file, "r") as f:
keys = list(f.keys())
except Exception:
if read_error:
raise ValueError(f"Cannot read file {file}")
Expand All @@ -412,10 +430,7 @@ def list_URIs(
RuntimeWarning,
)
continue
# Extract start and end block numbers from filename like "blocks_1-50.h5"
filename_parts = os.path.basename(file).split("_")[1].split(".h5")[0]
st, end = [int(i) for i in filename_parts.split("-")]
for i in range(st, end + 1):
for i in sorted(int(k) for k in keys):
if i in filenames:
raise ValueError(f"Block {i} exists more than once")
filenames[i] = file + f"::{i}"
Expand Down Expand Up @@ -490,6 +505,183 @@ def load_hdf5_file(fname: str) -> Dict[str, Any]:
return _read_h5_group(myfile)


THINNED_MARKER = "THINNED.json"
_THIN_TMP = ".thin_tmp"


def _finish_thinning(folder: str, info: Dict[str, Any]) -> None:
"""Last step of in-place thinning: replace old block files with the new ones. Idempotent."""
tmp = os.path.join(folder, _THIN_TMP)
for f in info["old_files"]:
path = os.path.join(folder, f)
if f not in info["new_files"] and os.path.exists(path):
os.remove(path)
for f in info["new_files"]:
if os.path.exists(os.path.join(tmp, f)):
os.replace(os.path.join(tmp, f), os.path.join(folder, f))
missing = [f for f in info["new_files"] if not os.path.exists(os.path.join(folder, f))]
if missing:
raise RuntimeError(f"Thinned files missing from {folder}: {missing}")
with open(os.path.join(folder, THINNED_MARKER), "w") as fh:
json.dump(info, fh, indent=1)
os.remove(os.path.join(tmp, "READY"))
os.rmdir(tmp)


def _verify_thinned(filename: str, datas: Dict[int, Dict[str, Any]], pos_precision: Optional[float]) -> None:
"""Checks that a written file holds exactly the given blocks, with pos within the rounding error."""
with h5py.File(filename, "r") as f:
if sorted(int(i) for i in f.keys()) != sorted(datas):
raise RuntimeError(f"{filename}: block set differs from what was written")
for block, old in datas.items():
new = _read_h5_group(f[str(block)]) # type: ignore
for name, value in old.items():
if name == "pos_precision":
continue
if name not in new:
raise RuntimeError(f"{filename}::{block}: record {name} is missing")
if name == "pos":
oldpos = np.asarray(value, dtype=np.float64)
err = np.abs(np.asarray(new["pos"], dtype=np.float64) - oldpos).max(initial=0)
scale = np.abs(oldpos).max(initial=1)
tol = (pos_precision / 2 if pos_precision else 0) + 4 * np.finfo(np.float32).eps * scale
if not err <= tol:
raise RuntimeError(f"{filename}::{block}: position error {err} exceeds {tol}")
elif not np.array_equal(np.asarray(new[name]), np.asarray(value)):
raise RuntimeError(f"{filename}::{block}: record {name} differs")


def thin_trajectory(
folder: str,
out_folder: Optional[str] = None,
stride: int = 10,
keep_last: bool = True,
pos_precision: Optional[float] = 0.1,
blocks_per_file: int = 100,
dset_opts: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""
Thins a trajectory to save space: keeps every ``stride``-th block (and the last block), and re-saves
positions with the "chain_delta_v1" encoding at ``pos_precision``.

Kept blocks keep their original block numbers, so URIs stay meaningful
(e.g. ``blocks_0-990.h5::990`` is still block 990). Kept blocks are grouped into files of
``blocks_per_file`` blocks, named after the first and last block they contain.
Only the kept blocks are read from the original files.

Every written file is read back and compared with the original blocks (same blocks, positions within
``pos_precision / 2``, all other records identical) before anything is deleted or moved.
A ``THINNED.json`` file describing what was done is written to the output folder. If it is already
there, nothing is done and its contents are returned, so this function can be run repeatedly
over many folders.

Only ``blocks_*.h5`` files are written. Other files of a trajectory (``initArgs_0.h5``,
``applied_forces_0.h5``...) are left where they are, and are not copied to ``out_folder``.

Parameters
----------
folder : str
Trajectory folder to thin
out_folder : str or None, optional
Folder to write the thinned blocks to; it must not contain block files already.
None (default) thins ``folder`` in place: new files are written and verified in
``folder/.thin_tmp/``, then the original block files are deleted and the new ones moved in.
If this is interrupted after verification, the next call finishes it; if it is interrupted
before, the next call starts over.
stride : int, optional
Keep blocks whose block number is divisible by ``stride`` (default 10)
keep_last : bool, optional
Also keep the last block of the trajectory (default True)
pos_precision : float or None, optional
Grid step for storing positions (default 0.1; maximum error is half of it, see
"Compressed storage of conformations" above). 0.1 is enough for contact maps with typical
cutoffs; choose a smaller value if you need finer geometry. None keeps positions as they are stored.
blocks_per_file : int, optional
Number of kept blocks per output file (default 100); files cover ``stride * blocks_per_file``
original block numbers each
dset_opts : dict or None, optional
Options for dataset creation, by default DEFAULT_OPTS

Returns
-------
Dict[str, Any]
What was done (the contents of THINNED.json): numbers of blocks, file names, sizes, parameters
"""
if stride < 1 or blocks_per_file < 1:
raise ValueError("stride and blocks_per_file must be positive")
in_place = out_folder is None or os.path.abspath(out_folder) == os.path.abspath(folder)
dest = folder if in_place else str(out_folder)
tmp = os.path.join(dest, _THIN_TMP)

if os.path.exists(os.path.join(dest, THINNED_MARKER)):
with open(os.path.join(dest, THINNED_MARKER)) as fh:
return json.load(fh)
if in_place and os.path.exists(os.path.join(tmp, "READY")):
with open(os.path.join(tmp, "READY")) as fh:
info = json.load(fh)
_finish_thinning(folder, info)
return info
if not in_place:
os.makedirs(dest, exist_ok=True)
if glob.glob(os.path.join(dest, "blocks_*-*.h5")):
raise RuntimeError(f"Output folder {dest} already contains block files")
if os.path.exists(tmp):
shutil.rmtree(tmp) # an interrupted attempt that did not finish writing
os.makedirs(tmp)

uris = list_URIs(folder, return_dict=True)
kept = [i for i in uris if i % stride == 0]
last = max(uris)
if keep_last and last not in kept:
kept.append(last)
groups: Dict[int, List[int]] = {}
for i in kept:
groups.setdefault(i // (stride * blocks_per_file), []).append(i)

new_files = []
for group in groups.values():
datas = {}
for i in group:
data = load_URI(uris[i])
if pos_precision is not None and "pos" in data:
data["pos_precision"] = pos_precision
datas[i] = data
filename = f"blocks_{min(group)}-{max(group)}.h5"
with h5py.File(os.path.join(tmp, filename), mode="w", libver="v110") as file:
for i, data in datas.items():
_write_group(data, file.create_group(str(i)), dset_opts=dset_opts)
_verify_thinned(os.path.join(tmp, filename), datas, pos_precision)
new_files.append(filename)

old_files = sorted({os.path.basename(uri.split("::")[0]) for uri in uris.values()})
info: Dict[str, Any] = {
"date": time.strftime("%Y-%m-%d %H:%M:%S"),
"polychrom_version": __version__,
"stride": stride,
"kept_last_block": keep_last,
"pos_precision": pos_precision,
"pos_encoding": POS_ENCODING if pos_precision is not None else None,
"orig_blocks": len(uris),
"kept_blocks": len(kept),
"orig_bytes": sum(os.path.getsize(os.path.join(folder, f)) for f in old_files),
"new_bytes": sum(os.path.getsize(os.path.join(tmp, f)) for f in new_files),
"source_folder": os.path.abspath(folder),
"old_files": old_files,
"new_files": new_files,
}
if in_place:
with open(os.path.join(tmp, "READY"), "w") as fh:
json.dump(info, fh)
_finish_thinning(folder, info)
else:
for f in new_files:
os.replace(os.path.join(tmp, f), os.path.join(dest, f))
with open(os.path.join(dest, THINNED_MARKER), "w") as fh:
json.dump(info, fh, indent=1)
os.rmdir(tmp)
return info


class HDF5Reporter:
def __init__(
self,
Expand Down
93 changes: 93 additions & 0 deletions tests/test_hdf5_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Comprehensive tests for hdf5_format module
"""

import json
import os
import shutil
import tempfile
Expand All @@ -11,6 +12,7 @@
import numpy as np
import pytest

from polychrom import hdf5_format
from polychrom.hdf5_format import (
HDF5Reporter,
_convert_to_hdf5_array,
Expand All @@ -20,6 +22,7 @@
load_hdf5_file,
load_URI,
save_hdf5_file,
thin_trajectory,
)


Expand Down Expand Up @@ -492,3 +495,93 @@ def test_continue_trajectory_gapped_blocks(tmp_path):

for i in [20, 23, 25]:
assert load_URI(uris[i])["pos"][0][0] == float(i)


def test_list_URIs_sparse_files(tmp_path):
"""list_URIs lists the blocks present in a file, not the whole range in its name"""
with h5py.File(tmp_path / "blocks_0-90.h5", "w") as f:
for i in range(0, 100, 10):
f.create_group(str(i))
with h5py.File(tmp_path / "blocks_100-195.h5", "w") as f:
for i in [100, 110, 195]:
f.create_group(str(i))
uris = list_URIs(str(tmp_path), return_dict=True)
assert list(uris) == list(range(0, 120, 10)) + [195]
assert uris[195].endswith("blocks_100-195.h5::195")


def _make_trajectory(folder, nblocks=55, n=200, seed=0):
rng = np.random.default_rng(seed)
rep = HDF5Reporter(folder=str(folder), max_data_length=10)
datas = {}
for i in range(nblocks):
pos = np.cumsum(rng.normal(size=(n, 3)), axis=0).round(2).astype(np.float32)
datas[i] = {"pos": pos, "block": i, "time": 0.5 * i, "kineticEnergy": rng.random()}
rep.report("data", datas[i])
rep.dump_data()
rep.report("initArgs", {"N": n})
return datas


def _check_thinned(folder, datas, kept, precision=0.1):
uris = list_URIs(str(folder), return_dict=True)
assert list(uris) == kept
for i in kept:
new = load_URI(uris[i])
assert np.abs(new["pos"] - datas[i]["pos"]).max() <= precision / 2 + 1e-5
assert new["block"] == i and new["time"] == datas[i]["time"]
assert new["kineticEnergy"] == datas[i]["kineticEnergy"]


def test_thin_trajectory_out_folder(tmp_path):
src, dst = tmp_path / "src", tmp_path / "dst"
datas = _make_trajectory(src)
before = sorted(os.listdir(src))
info = thin_trajectory(str(src), str(dst), stride=10, blocks_per_file=2)
kept = [0, 10, 20, 30, 40, 50, 54]
assert info["orig_blocks"] == 55 and info["kept_blocks"] == 7
assert sorted(os.listdir(src)) == before # source untouched
assert sorted(os.listdir(dst)) == ["THINNED.json", "blocks_0-10.h5", "blocks_20-30.h5", "blocks_40-54.h5"]
_check_thinned(dst, datas, kept)
assert len(list_URIs(str(src))) == 55
# second call does nothing and returns the recorded info
assert thin_trajectory(str(src), str(dst), stride=10, blocks_per_file=2) == info


def test_thin_trajectory_in_place(tmp_path):
datas = _make_trajectory(tmp_path)
info = thin_trajectory(str(tmp_path), stride=10, keep_last=False)
_check_thinned(tmp_path, datas, [0, 10, 20, 30, 40, 50])
assert sorted(os.listdir(tmp_path)) == ["THINNED.json", "blocks_0-50.h5", "initArgs_0.h5"]
assert info["new_bytes"] < info["orig_bytes"]
with open(tmp_path / "THINNED.json") as fh:
assert json.load(fh) == info
assert thin_trajectory(str(tmp_path), stride=10) == info # not thinned twice


def test_thin_trajectory_resume(tmp_path, monkeypatch):
"""An in-place run interrupted after verification is finished by the next call"""
datas = _make_trajectory(tmp_path)

def interrupted(folder, info):
raise KeyboardInterrupt

monkeypatch.setattr(hdf5_format, "_finish_thinning", interrupted)
with pytest.raises(KeyboardInterrupt):
thin_trajectory(str(tmp_path), stride=5)
assert os.path.exists(tmp_path / ".thin_tmp" / "READY")
assert len(list_URIs(str(tmp_path))) == 55 # originals still in place
monkeypatch.undo()
thin_trajectory(str(tmp_path), stride=5)
assert not os.path.exists(tmp_path / ".thin_tmp")
_check_thinned(tmp_path, datas, list(range(0, 55, 5)) + [54])


def test_thin_trajectory_keep_positions(tmp_path):
"""pos_precision=None keeps positions exactly as stored"""
datas = _make_trajectory(tmp_path / "src", nblocks=12)
thin_trajectory(str(tmp_path / "src"), str(tmp_path / "dst"), stride=3, pos_precision=None)
uris = list_URIs(str(tmp_path / "dst"), return_dict=True)
assert list(uris) == [0, 3, 6, 9, 11]
for i, uri in uris.items():
assert np.array_equal(load_URI(uri)["pos"], datas[i]["pos"])
Loading