How-to — CON I/O by language

Note

Diátaxis how-to (goal-oriented recipes). Learning path first: Tutorial — your first CON checkpoint. Conversion tasks: How-to — Chemfiles conversion and selection.

These pages answer how do I … once you already know the shape of a CON file from the :doc:`tutorial`. Pick a language section and copy the block that matches your task. For XYZ/PDB/GRO ingress use the chemfiles how-to, not this page. Pairing atoms across frames by column 5 is :doc:`atom-correspondence`.

Requirement words

The words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY on this page follow RFC 2119.

Querying the spec version

/Added in v0.5.0. Per-frame spec_version added in v0.6.0.

There are two distinct version queries:

  1. Library spec version: the highest spec version the library implements (compile-time constant).

  2. File spec version: the version a particular file was written with, parsed from the JSON metadata on line 2. Legacy files without JSON metadata report version 1.

Rust

use readcon_core::{CON_SPEC_VERSION, VERSION};

// Library version
    assert_eq!(CON_SPEC_VERSION, 3);
println!("readcon-core {} (spec v{})", VERSION, CON_SPEC_VERSION);

// Per-frame version (from parsed file)
use readcon_core::iterators::read_first_frame;
let frame = read_first_frame(std::path::Path::new("input.con")).unwrap();
println!("File spec version: {}", frame.header.spec_version);
println!("Extra metadata: {:?}", frame.header.metadata);

C/C++

#include "readcon-core.h"

// Compile-time library version check
#if RKR_CON_SPEC_VERSION >= 2
    // atom_id semantics available
#endif

// Runtime library version
printf("spec v%u, lib %s\n",
       rkr_con_spec_version(), rkr_library_version());

// Per-frame version (from parsed file)
RKRConFrame *handle = rkr_read_first_frame("input.con");
printf("File spec version: %u\n", rkr_frame_spec_version(handle));

// Full JSON metadata
char *json = rkr_frame_metadata_json(handle);
printf("Metadata: %s\n", json);
rkr_free_string(json);
free_rkr_frame(handle);

Python

import readcon

# Library version
print(readcon.__version__)       # e.g. "0.6.0"
print(readcon.CON_SPEC_VERSION)  # 3

# Per-frame version (from parsed file)
frames = readcon.read_con("input.con")
print(frames[0].spec_version)   # 2 for v2 files, 1 for legacy
print(frames[0].metadata)       # dict of native JSON-compatible values
print(frames[0].energy)         # typed helper for common keys
print(frames[0].frame_index)
print(frames[0].timestep)

Working with JSON metadata

/Added in v0.6.0.

Line 2 of every v2 CON file contains a JSON object. The writer always stamps con_spec_version; additional keys survive round-trips.

Rust: attaching custom metadata

use readcon_core::types::ConFrameBuilder;
use std::collections::BTreeMap;

let mut meta = BTreeMap::new();
meta.insert("generator".to_string(),
            serde_json::Value::String("my-tool 1.0".to_string()));
meta.insert("temperature_K".to_string(),
            serde_json::json!(300.0));

let builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0])
    .metadata(meta);
// ... add atoms, build, write ...
// Line 2 of the output:
// {"con_spec_version":2,"generator":"my-tool 1.0","temperature_K":300.0}

Python: reading and attaching metadata

import readcon

# Reading: metadata comes from the file's JSON line
frames = readcon.read_con("input.con")
print(frames[0].metadata)  # e.g. {"generator": "my-tool 1.0"}
print(frames[0].energy)    # typed accessors for common keys
print(frames[0].frame_index)

# Writing: metadata can be attached via typed setters
frame = readcon.ConFrame(
    cell=[10.0, 10.0, 10.0],
    angles=[90.0, 90.0, 90.0],
    atoms=[readcon.Atom("H", 0.0, 0.0, 0.0, atom_id=1, mass=1.0)],
)
frame.set_energy(-42.5)
frame.set_frame_index(5)
frame.set_time(2.5)
frame.set_timestep(0.5)
frame.set_neb_bead(3)
frame.set_neb_band(1)
frame.set_scalar_metadata("temperature_K", 300.0)
frame.set_string_metadata("generator", "my-tool 1.0")

# Direct item assignment uses the live metadata dict and is validated
# when the frame is written.
frame.metadata["workflow"] = {"name": "neb", "bead": 3}

# Or replace metadata from a raw JSON object
frame.set_metadata_json(
    '{"generator":"my-tool 1.0","temperature_K":300.0}'
)
readcon.write_con("output.con", [frame])

Legacy file detection

import warnings
import readcon

frames = readcon.read_con("old_eon_file.con")
if frames[0].spec_version < 2:
    warnings.warn(
        "Legacy CON file (spec v1): atom_id values may be sequential placeholders",
        stacklevel=2,
    )

Rust

Reading a CON file

use std::fs;
use readcon_core::iterators::ConFrameIterator;

let contents = fs::read_to_string("trajectory.con").unwrap();
let iter = ConFrameIterator::new(&contents);

for result in iter {
    let frame = result.unwrap();
    println!("Cell: {:?}", frame.header.boxl);
    println!("Atoms: {}", frame.atom_data.len());
}

Reading a convel file with velocities

The same iterator handles both .con and .convel files. Velocity data is detected automatically by the parser.

use std::fs;
use readcon_core::iterators::ConFrameIterator;

let contents = fs::read_to_string("trajectory.convel").unwrap();
let iter = ConFrameIterator::new(&contents);

for result in iter {
    let frame = result.unwrap();
    println!("Has velocities: {}", frame.has_velocities());

    for atom in &frame.atom_data {
        print!("{} ({:.4}, {:.4}, {:.4})", atom.symbol, atom.x, atom.y, atom.z);
        if atom.has_velocity() {
            print!(" vel=({:.6}, {:.6}, {:.6})",
                   atom.vx.unwrap(), atom.vy.unwrap(), atom.vz.unwrap());
        }
        println!();
    }
}

Writing frames

use std::fs::File;
use readcon_core::writer::ConFrameWriter;

let file = File::create("output.con").unwrap();
let mut writer = ConFrameWriter::new(file);

for frame in &frames {
    writer.write_frame(frame).unwrap();
}

Velocity data is written automatically when frame.has_velocities() returns true.

Building frames from data

/Added in v0.4.0.

Use ConFrameBuilder to construct frames programmatically. The atom_id parameter (6th argument to add_atom) is the original atom index – the position of this atom in your input before type-based grouping. The builder groups atoms by symbol automatically, but preserves each atom’s atom_id so the original ordering can be reconstructed.

use readcon_core::types::ConFrameBuilder;

let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
// atom_id 0 and 1 for Cu, 2 for H -- these survive type-based reordering
builder.add_atom("Cu", 0.0, 0.0, 0.0, false, 0, 63.546);
builder.add_atom("H",  1.0, 2.0, 3.0, false, 2, 1.008);
builder.add_atom("Cu", 2.55, 2.55, 0.0, false, 1, 63.546);
let frame = builder.build()?;
// Atoms are now grouped: Cu(id=0), Cu(id=1), H(id=2)

Writing with custom precision

/Added in v0.4.0.

Control the number of decimal places in output coordinates:

use std::fs::File;
use readcon_core::writer::ConFrameWriter;

// Default text round-trips every finite binary64 value.
let file = File::create("output.con").unwrap();
let mut writer = ConFrameWriter::new(file);

// Fixed decimals are lossy. Ask for them explicitly.
let file = File::create("fixed.con").unwrap();
let mut writer = ConFrameWriter::with_precision(file, 6);

Reading a single frame efficiently

/Added in v0.4.3.

When only the first frame is needed, read_first_frame stops after parsing it. Files under 64 KiB are read into memory directly; larger files use memory-mapped I/O.

use readcon_core::iterators::read_first_frame;
use std::path::Path;

let frame = read_first_frame(Path::new("single.con")).unwrap();
println!("Atoms: {}", frame.atom_data.len());

Reading all frames from a file

For trajectory files with many frames, read_all_frames applies the same small-file optimization and uses memory-mapped I/O for larger files.

use readcon_core::iterators::read_all_frames;
use std::path::Path;

let frames = read_all_frames(Path::new("large_trajectory.con")).unwrap();
println!("Loaded {} frames", frames.len());

Reading a compressed trajectory in bounded memory

The path readers above decompress a .con.gz or .con.zst file into one buffer before parsing, so memory grows with the decompressed size. ConFrameReader decodes and parses while it reads, and its buffer stays near one frame plus its read size (1 MiB, one mebibyte, by default).

use readcon_core::stream::ConFrameReader;
use std::path::Path;

let mut atoms = 0;
for frame in ConFrameReader::open(Path::new("long_run.con.gz")).unwrap() {
    atoms += frame.unwrap().atom_data.len();
}
println!("Atoms over all frames: {atoms}");

ConFrameReader::new takes any std::io::Read, such as a socket or a decoder you have set up yourself. forward() skips a frame without building it. Frames and parse errors are those of ConFrameIterator::from_bytes over the whole stream. The reader stops after the first error. When the source fails, the reader first returns the frames that from_bytes finds in the bytes read before the failure, then the input or output error. A frame is returned once the stream has ended, or once a line with text and one more line follow it, because the parser looks that far ahead to decide where a frame ends. A frame larger than one read makes the buffer grow to that frame plus one read. For a frame longer than eight reads, an eighth of the frame takes the place of that read.

Parallel parsing

The parallel feature parses many frames on a Rayon pool. Python wheels enable it. read_all_frames, read_con with n_threads omitted, and rkr_read_all_frames stay on the calling thread. There is no file-size cutoff that starts workers for you. A pool helps when the file has many frames and the coordinate parse is the cost. One frame does not pay for workers: starting a pool made that read slower.

None, 0, and 1 are the calling thread. n > 2= is a pool of that size. Equal-length frames, including a whitespace tail, use equal-span boundaries, so the caller does not walk every header. Frames that do not share a length still walk headers on the caller, then parse the spans on the pool. A plain file of 64 KiB or more stays mapped. Smaller files, and gzip or zstd input, are read into one buffer. The unit table is built once and reused by the serial iterator, the C reader, and this pool.

#[cfg(feature = "parallel")]
use readcon_core::iterators::{frames_from_text, parse_frames_parallel};

let contents = std::fs::read_to_string("large_trajectory.con").unwrap();
let sequential = frames_from_text(&contents, Some(1)).unwrap();
let results = parse_frames_parallel(&contents);
let frames: Vec<_> = results.into_iter().filter_map(|r| r.ok()).collect();

Python (wheels enable parallel):

frames = readcon.read_con("large_trajectory.con")
seq = readcon.read_con("large_trajectory.con", n_threads=1)
pinned = readcon.read_con("large_trajectory.con", n_threads=8)
assert readcon.has_parallel_support()

C (published prefix is built with parallel):

uintptr_t n = 0;
RKRConFrame **auto_p = rkr_read_all_frames(path, &n);
RKRConFrame **seq = rkr_read_all_frames_n_threads(path, &n, 1);
RKRConFrame **pool = rkr_read_all_frames_n_threads(path, &n, 8);
if (!rkr_has_parallel_support()) {
    /* seq and pool are the same sequential path */
}

Appending, flushing, and buffering

ConFrameWriter keeps one frame of text in a scratch buffer and writes that buffer through std::io::BufWriter (8 KiB). write_frame does not always reach the file. flush does, and dropping the writer flushes too. After flush returns, a reader sees a complete prefix.

OpenMode::Append and from_path_append extend an uncompressed file. A missing file is created. A non-empty file that does not end in a newline receives one. Gzip and zstd paths are refused. Python write_con(..., append=True) streams one frame at a time and flushes before it returns. C is create_writer_from_path_append_c and rkr_writer_flush.

use readcon_core::writer::ConFrameWriter;
let mut writer = ConFrameWriter::from_path_append("run.con").unwrap();
writer.write_frame(&frame).unwrap();
writer.flush().unwrap();
readcon.write_con("run.con", frames)
readcon.write_con("run.con", more, append=True)
RKRConFrameWriter *writer = create_writer_from_path_append_c("run.con");
rkr_writer_extend(writer, frames, n);
rkr_writer_flush(writer);
free_rkr_writer(writer);

Compression by extension, and stdin

A path ending in .gz is gzip and .zst is zstd, on read and on write. The same choice is the magic bytes at the start of a read. Pass compression”gzip”, ="zstd", or "none" to write_con to override the extension. The PyPI wheels are built with the zstd feature, so a .zst path writes zstd. A source build without that feature raises ValueError and names zstd. append=True is only for an uncompressed file.

ConFrameReader::new takes any std::io::Read. Standard input is that reader. A fifo opened by path is not mapped: the path readers take the buffered branch for anything that is not a regular file of at least 64 KiB. Python read_con_string parses text you already read, including sys.stdin.read().

use readcon_core::stream::ConFrameReader;
use std::io::stdin;
for frame in ConFrameReader::new(stdin().lock()) {
    let frame = frame.unwrap();
    println!("{}", frame.atom_data.len());
}
import sys
import readcon
text = sys.stdin.read()
frames = readcon.read_con_string(text)
readcon.write_con("copy.con.gz", frames)

Units

A CON units object names length, energy, and the other quantities. unit_conversion_factor(from, to) returns the multiplier that takes a value in from into to. The name table is built once per process. Readers share it, including the C reader and a parallel parse. Versions 1, 2, and 3.0 store velocities in the natural time unit (amu*angstrom^2/eV)^0.5 (about 10.18 fs). A units.time label of fs on those versions describes the header. It is not the unit of the numbers (CON-units.8, CON-units.9). A rewrite stamps minor 1. From minor 1, units.time is authoritative (CON-units.10), so the writer replaces fs with that natural-unit spelling. The numbers stay as they were. From minor 1, units.time is the velocity time unit.

use readcon_core::units::unit_conversion_factor;
let meters = unit_conversion_factor("angstrom", "m").unwrap();
frame.metadata["units"] = {"length": "angstrom", "energy": "eV"}
text = readcon.write_con_string([frame])
assert readcon.read_con_string(text)[0].metadata["units"]["length"] == "angstrom"

Extended XYZ

read_extxyz returns a dict. positions has shape (frames, atoms, 3), masses is (frames, atoms), cell is (frames, 6), and species is one symbol sequence per frame. A frame of fewer than 4096 atoms is a tuple. A wider frame is a SpeciesRow in a SpeciesFrames sequence, an immutable view of interned strings, with species.ids() the (frames, atoms) id array. A row supports len, indexing, iteration, slicing, equality with a tuple or a list, pickling, and hash. arrays holds every per-atom column. A repeated symbol is one string, and a frame whose symbols match the previous frame is that same tuple when the frame is under 4096 atoms. arrays["pos"] is positions. write_extxyz writes that dict back. A caller that unpacked a tuple from an older read_extxyz should index the dict. n_threads of 2 or more splits frames, or the atoms of one wide frame. A file whose symbols differ, or whose header changes from frame to frame, uses the general scan. The uniform scan is only for one species and one column layout repeated in every frame.

ASE plugin

The ase-readcon package registers readcon-con and readcon-convel on the ase.ioformats entry point. ASE loads that group when ase.io.read or ase.io.write sees the format name.

pip install readcon
pip install -e ase-readcon
import readcon
from ase.io import read, write

atom = readcon.Atom("H", 0.0, 0.0, 0.0, atom_id=1, mass=1.0)
frame = readcon.ConFrame((10.0, 10.0, 10.0), (90.0, 90.0, 90.0), [atom])
readcon.write_con("ase_roundtrip.con", [frame])
images = read("ase_roundtrip.con", index=":", format="readcon-con")
write("ase_roundtrip_again.con", images, format="readcon-con")
write("ase_roundtrip_again.convel", images, format="readcon-convel")
back = read("ase_roundtrip_again.con", index=0, format="readcon-con")
assert len(images) == 1
assert list(back.arrays["atom_id"]) == [1]

A read walks iter_con(stream=True) unless the slice needs a length, in which case it uses count_frames and ConTrajectory. A geometry file with no per-axis constraint is built from read_coords. Each frame keeps its own element order, so a later frame stored oxygen-first stays oxygen-first and each atom keeps that element’s mass. Velocities, forces, and a per-axis mask use the frame objects.

Column 5 is the per-atom array atom_id. A read sets atoms.arrays["atom_id"]. A write puts that array back into column 5. When the array is absent the atoms are numbered 0 .. n-1. ASE tags are not column 5.

A hold on every axis is FixAtoms. A hold on some axes is FixCartesian with that mask, for example a Pt(100) adatom held in z only. The mask round-trips.

A geometry write of one species and sequential ids uses write_coords. Custom ids, velocities, and append=True go through write_con.

Python

Installation

# From PyPI
pip install readcon

# From source
maturin develop --features python

# Via pixi
pixi r -e python python-build

Reading and inspecting frames

import readcon

# Read from file
frames = readcon.read_con("trajectory.con")
first = readcon.read_first_frame("trajectory.con")

# Iterate over frames
for frame in readcon.iter_con("trajectory.con"):
    print(len(frame))

# Read from string
with open("trajectory.con") as f:
    frames = readcon.read_con_string(f.read())

for frame in frames:
    print(f"Cell: {frame.cell}")
    print(f"Angles: {frame.angles}")
    print(f"Atom count: {len(frame)}")
    print(f"Has velocities: {frame.has_velocities}")
    print(f"Pre-box header: {frame.prebox_header}")

    for atom in frame.atoms:
        print(f"  {atom.symbol}: ({atom.x:.4f}, {atom.y:.4f}, {atom.z:.4f})")
        print(f"    fixed={atom.is_fixed}, id={atom.atom_id}, mass={atom.mass}")

Column arrays

read_con keeps one coordinate slab when every frame has the same atom count. columns() returns that slab as positions with no second copy, so a later call is the same array. masses is (frames, atoms), fixed is (frames, atoms, 3) with 1.0 on a held axis, and cell is (frames, 6). velocities and forces are present when any frame has that section. Indexing a frame takes it out of the list, and columns() then raises OSError. Call columns() first.

write_columns writes that dict. Every atom uses symbol. The arrays are borrowed once. There is no per-atom Python loop.

read_positions is the path form of the same buffer. The returned array views it: base is that buffer and OWNDATA is false.

import readcon

atom = readcon.Atom("H", 1.25, 0.0, 0.0, atom_id=1, mass=1.0)
frame = readcon.ConFrame((10.0, 10.0, 10.0), (90.0, 90.0, 90.0), [atom])
readcon.write_con("column_src.con", [frame, frame])
frames = readcon.read_con("column_src.con")
cols = frames.columns()
assert cols["positions"].shape == (2, 1, 3)
assert frames.columns()["positions"] is cols["positions"]
readcon.write_columns("columns.con", cols, symbol="H")
back = readcon.read_positions("columns.con")
assert back.shape == cols["positions"].shape
assert back.base is not None
assert not back.flags["OWNDATA"]
assert back[0, 0, 0] == 1.25

Streaming a large or compressed trajectory

iter_con(path) reads the whole file into memory before the first frame, and decompresses a gzip file whole. For a long run, ask it to stream:

import readcon

energies = []
for frame in readcon.iter_con("long_run.con.gz", stream=True):
    energies.append(frame.energy)

Memory then stays near one frame plus 1 MiB, whatever the file size. The frames are the same as without stream=True. The loop raises OSError at a damaged frame, after it has processed the frames before it. Without stream=True, invalid UTF-8 (Unicode Transformation Format, 8-bit) is raised by iter_con itself, before any frame.

Working with convel velocity data

import readcon

frames = readcon.read_con("trajectory.convel")
frame = frames[0]

if frame.has_velocities:
    for atom in frame.atoms:
        if atom.has_velocity:
            print(f"{atom.symbol}: vel=({atom.vx:.6f}, {atom.vy:.6f}, {atom.vz:.6f})")
        else:
            print(f"{atom.symbol}: no velocity")

Constructing frames from data

/Added in v0.4.0.

Build frames programmatically using Atom and ConFrame constructors:

import readcon

atoms = [
    readcon.Atom(symbol="Cu", x=0.0, y=0.0, z=0.0,
                 fixed=[False, False, False], atom_id=1),
    readcon.Atom(symbol="Cu", x=2.55, y=2.55, z=0.0,
                 fixed=[False, False, False], atom_id=2),
]
frame = readcon.ConFrame(
    cell=[10.0, 10.0, 10.0],
    angles=[90.0, 90.0, 90.0],
    atoms=atoms,
)
frame.atoms.append(readcon.Atom(symbol="H", x=1.0, y=1.0, z=1.0))
frame.atoms[0].fixed = [True, False, True]

Writing frames

import readcon

# Read, modify, and write back
frames = readcon.read_con("input.con")

# Write to file
readcon.write_con("output.con", frames)

# Write to string
output = readcon.write_con_string(frames)
print(output)

Writing with custom precision

/Added in v0.4.0.

Pass the precision keyword to control decimal places:

import readcon

# Default text round-trips every finite binary64 value.
readcon.write_con("output.con", frames)

# Fixed decimals are lossy. Ask for them explicitly.
readcon.write_con("fixed.con", frames, precision=6)
output = readcon.write_con_string(frames, precision=17)

ASE Atoms conversion

/Added in v0.4.0. atom_id, velocity, mass, forces, and per-axis fixed-mask transfer are preserved.

Convert between ConFrame and ASE Atoms objects. ASE MUST be installed (it is an optional dependency). The conversion preserves atom_id (via a custom per-atom array), velocities, forces, masses, and per-axis fixed masks.

import readcon

# ConFrame -> ase.Atoms
frames = readcon.read_con("input.con")
ase_atoms = frames[0].to_ase()

# ase.Atoms -> ConFrame
frame = readcon.ConFrame.from_ase(ase_atoms)

# Convenience: read a .con file directly as ase.Atoms list
ase_list = readcon.read_con_as_ase("trajectory.con")

atom_id in ASE roundtrips

to_ase() stores each atom’s atom_id as a custom atom_id per-atom array on the ASE Atoms object. Tags are left untouched so they remain available for other uses (slab layers, etc.).

import readcon

frames = readcon.read_con("saddle.con")
ase_atoms = frames[0].to_ase()

# atom_id is stored as a named per-atom array
print(ase_atoms.get_array("atom_id"))  # e.g. [3, 0, 1, 4, 2]

# Roundtrip preserves atom_id
frame_back = readcon.ConFrame.from_ase(ase_atoms)
assert [a.atom_id for a in frame_back.atoms] == [3, 0, 1, 4, 2]

When converting from an ASE Atoms object that was not created by readcon, from_ase() checks for the atom_id array first, then falls back to tags (if any are non-zero), and finally uses sequential indices.

Velocities and masses in ASE roundtrips

Velocities from .convel files are transferred via set_velocities() / get_velocities(). Custom masses (when present on the ConFrame) override ASE’s atomic-number defaults via set_masses().

import readcon

# convel -> ASE preserves velocities
frames = readcon.read_con("trajectory.convel")
ase_atoms = frames[0].to_ase()
print(ase_atoms.get_velocities())  # non-zero velocity array

# Roundtrip back to ConFrame
frame_back = readcon.ConFrame.from_ase(ase_atoms)
assert frame_back.has_velocities
assert frame_back.atoms[0].fixed == frames[0].atoms[0].fixed

Roundtrip test pattern

import readcon

frames = readcon.read_con("input.convel")
output = readcon.write_con_string(frames)
frames2 = readcon.read_con_string(output)

assert len(frames) == len(frames2)
for orig, reread in zip(frames, frames2):
    assert len(orig) == len(reread)
    assert orig.has_velocities == reread.has_velocities

C

Reading and printing frames

#include "readcon-core.h"
#include <stdio.h>

int main(int argc, char *argv[]) {
    CConFrameIterator *iter = read_con_file_iterator(argv[1]);
    if (!iter) return 1;

    RKRConFrame *handle;
    while ((handle = con_frame_iterator_next(iter)) != NULL) {
        CFrame *frame = rkr_frame_to_c_frame(handle);

        printf("Cell: [%.4f, %.4f, %.4f]\n",
               frame->cell[0], frame->cell[1], frame->cell[2]);
        printf("Atoms: %zu, Has velocities: %s\n",
               frame->num_atoms, frame->has_velocities ? "yes" : "no");

        for (size_t i = 0; i < frame->num_atoms; i++) {
            CAtom *a = &frame->atoms[i];
            printf("  Atom %zu: (%.4f, %.4f, %.4f) fixed=%d id=%llu\n",
                   i, a->x, a->y, a->z, a->is_fixed,
                   (unsigned long long)a->atom_id);
            if (a->has_velocity) {
                printf("    vel=(%.6f, %.6f, %.6f)\n", a->vx, a->vy, a->vz);
            }
        }

        free_c_frame(frame);
        free_rkr_frame(handle);
    }
    free_con_frame_iterator(iter);
    return 0;
}

Building frames from data

/Added in v0.4.0.

#include "readcon-core.h"

double cell[3] = {10.0, 10.0, 10.0};
double angles[3] = {90.0, 90.0, 90.0};
RKRConFrameBuilder *builder =
    rkr_frame_new(cell, angles, "", "", "", "");
RKRStatus status = rkr_frame_add_atom(builder, "Cu", 0.0, 0.0, 0.0,
                                      false, 1, 63.546);
if (status != RKR_STATUS_SUCCESS) {
    fprintf(stderr, "%s\n", rkr_status_message(status));
    free_rkr_frame_builder(builder);
    return 1;
}
status = rkr_frame_add_atom_with_velocity_and_forces_fixed_mask(
        builder, "Cu", 2.55, 2.55, 0.0,
        true, false, true,
        2, 63.546,
        0.1, 0.2, 0.3,
        -0.1, -0.2, -0.3);
if (status != RKR_STATUS_SUCCESS) {
    fprintf(stderr, "%s\n", rkr_status_message(status));
    free_rkr_frame_builder(builder);
    return 1;
}
RKRConFrame *frame = rkr_frame_builder_build(builder);
if (!frame) {
    return 1;
}

// Write with custom precision
RKRConFrameWriter *writer =
    create_writer_from_path_with_precision_c("output.con", 17);
if (writer) {
    rkr_writer_extend(writer, (const RKRConFrame **)&frame, 1);
}
free_rkr_writer(writer);
free_rkr_frame(frame);

Reading a single frame

/Added in v0.4.0.

RKRConFrame *frame = rkr_read_first_frame("input.con");
if (frame) {
    CFrame *cf = rkr_frame_to_c_frame(frame);
    printf("Atoms: %zu\n", cf->num_atoms);
    free_c_frame(cf);
    free_rkr_frame(frame);
}

Writing frames

#include "readcon-core.h"

// After collecting handles into an array:
RKRConFrameWriter *writer = create_writer_from_path_c("output.con");
RKRStatus result = rkr_writer_extend(writer,
                                     (const RKRConFrame **)handles,
                                     num_frames);
if (result != RKR_STATUS_SUCCESS) {
    fprintf(stderr, "write failed: %s\n", rkr_status_message(result));
}
free_rkr_writer(writer);

Memory management

The C API uses two ownership patterns:

  1. Opaque handles (RKRConFrame): allocated by Rust, freed with free_rkr_frame(). Used for lossless frame manipulation.

  2. Transparent structs (CFrame): extracted copies freed with free_c_frame(). Used for direct data access.

Always free both the CFrame and the RKRConFrame separately.

C++

RAII iteration with range-based for

#include "readcon-core.hpp"
#include <iostream>

int main(int argc, char *argv[]) {
    readcon::ConFrameIterator frames(argv[1]);

    for (auto&& frame : frames) {
        auto cell = frame.cell();
        auto angles = frame.angles();
        std::cout << "Cell: " << cell[0] << ", " << cell[1] << ", "
                  << cell[2] << "\n";
        std::cout << "Has velocities: " << std::boolalpha
                  << frame.has_velocities() << "\n";

        for (const auto& atom : frame.atoms()) {
            std::cout << "  (" << atom.x << ", " << atom.y << ", "
                      << atom.z << ")";
            if (atom.has_velocity) {
                std::cout << " vel=(" << atom.vx << ", " << atom.vy
                          << ", " << atom.vz << ")";
            }
            std::cout << "\n";
        }
    }
    return 0;
}

Building frames from data

/Added in v0.4.0.

#include "readcon-core.hpp"

readcon::ConFrameBuilder builder(
    {10.0, 10.0, 10.0}, {90.0, 90.0, 90.0});
builder.add_atom("Cu", 0.0, 0.0, 0.0, false, 1, 63.546);
builder.add_atom_with_velocity_and_forces(
    "Cu", 2.55, 2.55, 0.0,
    {true, false, true},
    2, 63.546,
    0.1, 0.2, 0.3,
    -0.1, -0.2, -0.3);
auto frame = builder.build();

Reading a single frame

/Added in v0.4.0.

auto frame = readcon::read_first_frame("input.con");
std::cout << "Atoms: " << frame.atoms().size() << "\n";

Collecting and writing frames

#include "readcon-core.hpp"
#include <vector>

readcon::ConFrameIterator input("input.con");
std::vector<readcon::ConFrame> all_frames;

for (auto&& frame : input) {
    all_frames.push_back(std::move(frame));
}

// Default text round-trips every finite binary64 value.
readcon::ConFrameWriter writer("output.con");
writer.extend(all_frames);

// Fixed decimals are lossy. Ask for them explicitly.
readcon::ConFrameWriter fixed_writer("fixed.con", 6);
fixed_writer.extend(all_frames);

Integration with eOn

The C++ RAII API is used by eOn for all .con and .convel I/O:

// Reading: mmap-based single frame read
auto frame = readcon::read_first_frame(con_path);
// frame.cell(), frame.atoms(), frame.has_velocities(), frame.has_forces()

// Writing: builder with precision control
readcon::ConFrameBuilder builder(lengths, angles);
for (int i = 0; i < nAtoms; i++) {
    builder.add_atom(symbol, x, y, z, fixed_mask, id, mass);
}
auto out_frame = builder.build();
readcon::ConFrameWriter writer(path, 17);  // 17 digits for lossless roundtrip
writer.extend({out_frame});

Julia

Installation and setup

# Point to the shared library
ENV["READCON_CORE_LIB"] = "/path/to/libreadcon_core.so"  # or READCON_LIB_PATH

# Or build from source (library auto-discovered)
using Pkg
Pkg.develop(path="julia/ReadCon")

Reading frames

using ReadCon

frames = read_con("trajectory.con")

for frame in frames
    println("Cell: ", frame.cell)
    println("Angles: ", frame.angles)
    println("Atoms: ", length(frame.atoms))
    println("Has velocities: ", frame.has_velocities)
    println("Has forces: ", frame.has_forces)
    println("Spec version: ", frame.spec_version)
    println("Energy: ", frame.energy)
    println("Header: ", frame.prebox_header)

    for atom in frame.atoms
        @printf("  (%.4f, %.4f, %.4f) fixed=%s id=%d\n",
                atom.x, atom.y, atom.z, atom.is_fixed, atom.atom_id)
    end
end

Writing frames

using ReadCon

frames = read_con("trajectory.con")
write_con("roundtrip.con", frames)
write_con("precise.con", frames; precision=17)

Julia writes through the C FFI builder and writer. The path preserves velocities, forces, per-axis fixed masks, masses, atom ids, and JSON metadata exposed by metadata_json.

Working with convel velocity data

using ReadCon

frames = read_con("trajectory.convel")
frame = frames[1]

if frame.has_velocities
    for atom in frame.atoms
        if atom.has_velocity
            @printf("vel=(%.6f, %.6f, %.6f)\n", atom.vx, atom.vy, atom.vz)
        end
    end
end

Multi-frame trajectory processing

using ReadCon

frames = read_con("neb_trajectory.con")
println("Loaded $(length(frames)) images")

# Process each NEB image
for (i, frame) in enumerate(frames)
    n_free = count(a -> !a.is_fixed, frame.atoms)
    println("Image $i: $n_free free atoms")
end

Compressed input

read_con opens the file with read_con_file_iterator. That iterator decodes .gz, and .zst when the shared library was built with zstd. write_con always writes plain CON text. It does not look at the suffix. Gzip and zstd output is create_writer_gzip_c / create_writer_zstd_c in that same library, or write_con in Python with compression”gzip”= or "zstd".

using ReadCon

frames = read_con("trajectory.con.gz")
println(length(frames), " frames")

CON-bin

CON-bin is a binary column file. The header is one host page. Positions of every frame follow as one little-endian run, then velocities the same way. Every frame must have the same atom count. write_conbin streams a CON text file into that layout. read_conbin returns a writable view of the position run, the velocity run, and the atom count. The arrays are shaped (frames, atoms * 3). A frame with no velocity section is stored as zeros. A binary32 file is read_conbin_f32.

import readcon

atom = readcon.Atom("Cu", 1.0, 2.0, 3.0, atom_id=1, mass=63.546)
frame = readcon.ConFrame((10.0, 10.0, 10.0), (90.0, 90.0, 90.0), [atom])
readcon.write_con("conbin_src.con", [frame])
n_frames, n_atoms = readcon.write_conbin("conbin_src.con", "conbin_out.bin")
positions, velocities, atoms = readcon.read_conbin("conbin_out.bin")
assert (n_frames, n_atoms, atoms) == (1, 1, 1)
assert positions.shape == (1, 3)
assert velocities.shape == (1, 3)
assert positions[0, 0] == 1.0
assert velocities[0, 0] == 0.0

Rust uses conbin::write_from_con and conbin::read_owned_f64. The doctest on write_from_con runs that round trip.

PDB columns

read_pdb scans a PDB file into three arrays and does not build a frame. Positions are (frames, atoms, 3), masses are (frames, atoms), and the cell is (frames, 6) with lengths then angles. CRYST1 fills the cell. ATOM and HETATM lines use the fixed coordinate columns. The element is the two characters at columns 77–78 when they are present. Masses are filled for H and Cu. Any other element is NaN. ``ENDMDL`:doc:` 1e-9

assert list(cell[0][:3]) == [10.0, 12.0, 14.0]

Rust reads the same bytes with pdb_scan::tables_from_pdb_bytes. The doctest on that function checks one copper atom.

Fortran: gzip and zstd writers

open_writer writes plain CON. open_writer_gzip writes gzip. open_writer_zstd writes zstd when the library was built with that feature. A lean library returns a writer whose valid is false. extend_one appends one frame. free releases the writer.

use readcon
type(frame_t) :: frame
type(writer_t) :: gz, zst
integer :: stat
frame = read_first_frame('in.con')
gz = open_writer_gzip('out.con.gz')
stat = gz%extend_one(frame)
call gz%free()
zst = open_writer_zstd('out.con.zst')
if (zst%valid()) then
  stat = zst%extend_one(frame)
  call zst%free()
end if
call frame%free()

Chemfiles — convert other formats into CON

Foreign formats are a separate how-to track:

Exact numeric CON output from C

create_writer_from_path_round_trip_c(path) retains every finite binary64 value, including forces below the precision of fixed decimal output. Use rkr_writer_extend to append frames and rkr_writer_flush to check for write failures before calling free_rkr_writer. Decimal-place formatting is available through create_writer_from_path_with_precision_c. Seventeen decimal places do not preserve every binary64 value.