Skip to content

Latest commit

 

History

History
138 lines (111 loc) · 9.35 KB

python.org

File metadata and controls

138 lines (111 loc) · 9.35 KB

Python API

Build the extension (from a checkout next to readcon-core):
cd python
maturin develop --features python
from pathlib import Path
import readcon
from readcon_db import ConCorpus

db = ConCorpus("/tmp/corpus")
ro = ConCorpus("/tmp/corpus", readonly=True)
db.append_trajectory(1, "run.con")
db.append_trajectory_str(2, Path("run.con").read_text(), source="run.con")
db.append_trajectory_frames(3, readcon.read_con("run.con"))
keys = db.select(
    traj_id=1,
    symbol="Cu",
    natoms_min=1,
    natoms_max=10_000,
    energy_min=-50.0,
    energy_max=0.0,
    require_forces=True,
)
h = db.frame_hash(1, 0)          # bytes(16)
assert db.find_by_hash(h) == (1, 0)
db.index_canonical_identity()
hits = db.find_by_atom_order_path("product.con")
# hits[0].permutation[i] is the query index of stored atom i
text = db.get_frame_text(1, 0)
raw = ConCorpus.xxh3_128(b"blob")
h = ConCorpus.hash_con_text(Path("run.con").read_text())  # == db.frame_hash(1, 0)
frame = db.get_frame(1, 0)       # StoredFrame, not a readcon.ConFrame

get_frame returns a StoredFrame. frame.xyz is the coordinate rows, frame.atoms[i] builds that atom only, and frame.cell and frame.angles are the box. append_trajectory_frames commits 64 frames at a time. Both are specified in @@rst::doc:`/howto/migration`@@ and exercised in @@rst::doc:`/howto/streaming`@@.

The generated page is @@rst::doc:`/reference/python-api`@@.

Optional select kwargs: exact_hash= (16-byte LE xxh3-128), energy_min / energy_max, fmax_min / fmax_max, mass_min / mass_max, volume_min / volume_max, frame_index_min / frame_index_max, charge_min / charge_max, element_exact, element_min, formula, require_forces, require_velocities, require_energy, limit.

Observation archives

An observation archive is a corpus directory, observations.rdb, that a consumer such as a GP surrogate fills with the oracle evaluations it made. The C writer is rkrdb_archive_open / rkrdb_archive_append. ObservationArchive is the same writer in Python. ArchiveReader opens any corpus read-only and returns each stored frame as a readcon.ConFrame, so readcon must be installed.
from readcon_db import ArchiveReader

with ArchiveReader("out/obs-archive") as archive:  # or ".../observations.rdb"
    print(len(archive), archive.n_trajectories)
    for obs in archive:
        print(obs.traj_id, obs.frame_idx, obs.energy, obs.metadata["units"])
        xyz = obs.frame.coords_array()[obs.caller_order]
        forces = obs.frame.forces_array()[obs.caller_order]
    last = archive[-1]
    frame = archive.frame(traj_id=3)            # readcon.ConFrame
    text = archive.text(traj_id=3, frame_idx=0)  # stored CON text
CallReturns
ArchiveReader(path)path is the corpus directory or the archive directory that holds observations.rdb
len(archive), archive.keys()observation count, and the (traj_id, frame_idx) keys in ascending order
archive.n_trajectories, trajectory_ids(), n_frames(t), source(t)trajectory count, ids, frames per trajectory, the source label the writer stored
iter(archive), archive[i]Observation objects in key order, i may be negative
archive.get(t, f=0), trajectory(t)one Observation, or every frame of one trajectory
archive.frame(t, f=0), text(t, f=0)the readcon.ConFrame, or the stored CON text
refresh()takes the key list again and returns the new count
archive.trajectory_metadata(t)the metadata dict the writer set on trajectory t, or None
close(), closedcloses the LMDB environment, and whether it is closed

An Observation has traj_id, frame_idx, key, index (its position in key order), text, frame, natoms, energy and metadata (the JSON metadata line), and caller_order.

The archive writer stores one single-frame trajectory per evaluation, with trajectory ids 0, 1, 2, ... in append order. Other writers can store several frames per trajectory, and the reader keys every frame. frame is in stored CON order, which groups atoms by type. The writer stores caller index i as the atom_id of each atom, and caller_order[i] is the stored row of caller atom i. A frame whose atom ids are not 0..natoms raises ValueError on caller_order.

The key list is taken at open. A writer in another process can keep appending, and refresh() picks up the new rows. LMDB does not support opening one environment twice in the same process. Close an ObservationArchive before an ArchiveReader opens that archive in the same process. Reading takes a reader slot in lock.mdb, so the reader needs write permission on the corpus directory and its files. Without it the open fails with ArchiveError (Permission denied). Copy the archive first when it is not yours to write.

A missing path raises FileNotFoundError. A directory that holds no corpus, or one that LMDB cannot open, raises readcon_db.ArchiveError (a RuntimeError). An absent key or trajectory raises KeyError, a position past the end raises IndexError, and a closed reader raises ValueError.

from readcon_db import ObservationArchive

with ObservationArchive("out/obs-archive", atomic_numbers=[1, 8, 1], cell=[25.0, 25.0, 25.0]) as w:
    w.append(positions, forces, energy)  # (natoms, 3) rows, caller order
    w.flush()
    positions, forces, energy = w.fetch(0)

append queues the row for a background thread and returns. flush waits until every queued row is stored or counted in dropped. committed counts stored rows, including those from earlier runs.

MPI: pack on root, Bcast on the caller communicator

bcast_packed_frame(comm, corpus_dir, traj_id, frame_idx, root=0) takes an mpi4py Comm — LAMMPS lmp.world, COMM_WORLD.Split(...), a Dup. mpi4py already called MPI_Init; the helper never does, and never names the process-wide world handle.
from mpi4py import MPI
from readcon_db import ConCorpus, bcast_packed_frame, bcast_packed_frames

# Host-owned comm. A LAMMPS Python fix passes lmp.world (or a split).
comm = MPI.COMM_WORLD.Dup()
blob = bcast_packed_frame(comm, "/scratch/corpus", traj_id=1, frame_idx=0)
xyz = ConCorpus.unpack_positions(blob)
batch = bcast_packed_frames(comm, "/scratch/corpus", [(1, 0), (1, 1), (1, 2)])
frames = ConCorpus.unpack_batch(batch)
comm.Free()

Cooked H5MD 1.1 interchange (h5py; fixed natoms; CON stays authority):

db.export_h5md(traj_id=1, path="traj.h5")

Dest must not exist. File "x"; a write failure removes the dest.

The file has /h5md version [1,1] with author=/=creator, particles/all/position/value of shape [T][N][3], position/step and position/time of shape [T], box/edges/value of shape [T][3][3], integer-Z species, optional particles/all/velocity [T][N][3] (dest Angstrom ps-1), and unit attributes for one engine system (like metatomic model vs engine): length Angstrom, time ps, force kJ mol-1 Angstrom-1, velocity Angstrom ps-1. Below major 4 the clock and the velocities are the natural unit (amu*angstrom^2/eV)^0.5 from velocity_file_time_unit, with or without units.time. Major 4 uses units.time. A missing major-4 label is an error when the frame has a clock or velocities. export_h5md(traj_id, path, velocity_time_unit=None) passes that override through and does not replace the assigned unit. CON units.length / units.energy convert through unit_conversion_factor (SI). Time is CON header.time(), or i * timestep, else the frame index, all in ps. unit_conversion_factor(from, to) and canonicalize_unit(expr) are on the Python module. Callers write aliases (A, ev, femtosecond); append_trajectory(..., units={...}), extend_trajectory(..., units={...}), ingest_directory(..., units={...}), and set_units(traj_id, {...}) store canonical names (angstrom, eV, fs) in CON metadata. append / extend stamp the incoming numbers; set_units converts stored numbers so the new label is honest. Below major 4 set_units does not rescale the clock or the velocities when the time label changes. Major 4 scales both by units.time. get_units(traj_id, frame_idx) returns the stored units JSON as a string. set_trajectory_metadata(traj_id, {...}) stores one JSON object that describes a trajectory as a whole (a run summary, say) and trajectory_metadata(traj_id) returns it, or None; frames appended later keep it, and an unknown trajectory raises KeyError. Mixed-force trajectories write a full [T][N][3] force dataset (zeros on frames without forces). Mixed-velocity trajectories write a full [T][N][3] velocity dataset the same way. Box boundary follows CON pbc (periodic when absent). author=/=creator=/=boundary attrs are fixed-length ASCII. Physical unit attrs are short H5MD strings (MDAnalysis 2.10 indexes them as dict keys).

Standalone: examples/mpi_bcast_frame.py.

Cooked SoA (RCSO)

See @@rst::doc:`/cooked-soa`@@. Tier is opt-in; the .con text remains authority. Bindings expose cook / delete / has-valid / positions / forces / velocities.