I/O Utilities#
General utility functions for working with CIF files in Biotite.
- class atomworks.io.utils.io_utils.CIFWriteConfig(id: str = 'unknown_id', author: str = <factory>, date: str | None = None, time: str | None = None, include_entity_categories: bool = False, include_nan_coords: bool = True, include_chem_comp: bool = True, extra_fields: list[str] | ~typing.Literal['all'] = <factory>, extra_categories: dict[str, dict[str, float | int | str | list | ~numpy.ndarray]] | None = None, chain_disambiguation: ~typing.Literal['transformation_id', 'chain_iid'] | None = None, save_standard_annotations: bool = True, ccd_entries: dict[str, ~biotite.structure.AtomArray] | None = None, chem_comp_source: ~typing.Literal['array', 'ccd', 'ccd_non_canonicals'] = 'ccd', warn_on_ccd_without_registry: bool = True, coord_decimals: int | None = 3)[source]#
Bases:
objectConfiguration for CIF/BCIF writing operations.
Consolidates options used when writing structures to CIF/BCIF format.
- Variables:
id (str) – Entry ID for the data block. Defaults to “unknown_id”.
author (str) – Author name for metadata. Defaults to current user.
date (str | None) – Date string (YYYY-MM-DD format). Auto-generated if None.
time (str | None) – Time string (HH:MM:SS format). Auto-generated if None.
include_entity_categories (bool) – Write entity categories (_entity, _entity_poly, etc.). Defaults to False for buffer/string operations, True for file operations.
include_chem_comp (bool) – Write _chem_comp CIF category. Defaults to True.
include_nan_coords (bool) – Include atoms with NaN coordinates. Defaults to True.
extra_fields (list[str] | Literal['all']) – Additional AtomArray annotations to write. Use “all” to include all non-standard annotations. Defaults to empty list.
extra_categories (dict[str, dict[str, float | int | str | list | numpy.ndarray]] | None) – Additional CIF categories as dict of {category_name: {column_name: value}}. Defaults to None.
chain_disambiguation (Literal['transformation_id', 'chain_iid'] | None) –
Method for disambiguating chains in multi-transformation assemblies.
”transformation_id”: Stores transformation_id in struct_conn symmetry fields. Preserves original chain_id. Requires AtomWorks to read.
”chain_iid”: Writes chain_iid as chain_id to make chains unique. Better compatibility with external software.
None: No disambiguation. Raises error if chains are ambiguous.
Defaults to None.
save_standard_annotations (bool) – Whether to serialize registered
StandardAnnotationBaseannotations (conditions,atomize, etc.) present on the structure into custom CIF categories. Defaults to True.ccd_entries (dict[str, biotite.structure.AtomArray] | None) – Optional dict mapping residue name to CCD template AtomArray. When provided, these templates are used for
chem_comp_atomandchem_comp_bondemission. Falls back to the structure’s_custom_ccd_registryattribute (if available, only for AtomArrayPlus types), then bundled CCD.chem_comp_source (Literal['array', 'ccd', 'ccd_non_canonicals']) –
Source of
chem_comp_atom/chem_comp_bondrows:"array"— always the AtomArray itself (regardless of where it came from)"ccd"— always the CCD we have access to (AtomArray fallback if no template)."ccd_non_canonicals"— AtomArray for canonical residues, CCD for the rest.
warn_on_ccd_without_registry (bool) – Warn on CCD write from a plain
AtomArray(no parse-time CCD snapshot). SetFalseto silence. Defaults toTrue.coord_decimals (int | None) – Decimal places coordinates are rounded to before writing.
Nonewrites them unrounded. Defaults to 3, the mmCIF convention.
Note
atom_sitealways includes anatom_array_indexcolumn (0, 1, …, n-1).See also
- author: str#
- ccd_entries: dict[str, AtomArray] | None = None#
- chain_disambiguation: Literal['transformation_id', 'chain_iid'] | None = None#
- chem_comp_source: Literal['array', 'ccd', 'ccd_non_canonicals'] = 'ccd'#
- coord_decimals: int | None = 3#
- date: str | None = None#
- extra_categories: dict[str, dict[str, float | int | str | list | ndarray]] | None = None#
- extra_fields: list[str] | Literal['all']#
- id: str = 'unknown_id'#
- include_chem_comp: bool = True#
- include_entity_categories: bool = False#
- include_nan_coords: bool = True#
- save_standard_annotations: bool = True#
- time: str | None = None#
- warn_on_ccd_without_registry: bool = True#
- atomworks.io.utils.io_utils.apply_sharding_pattern(path: PathLike, sharding_pattern: str | None = None) Path[source]#
Apply a sharding pattern to construct a file path.
- Parameters:
path – The base path or identifier (e.g., PDB ID).
sharding_pattern – Pattern for organizing files in subdirectories. Examples: -
"/0:2/": Use first two characters for first directory level -"/0:2/2:4/": Use chars 0-2 for first dir, then chars 2-4 for second dir -None: No sharding (default)
- Returns:
The constructed file path with sharding applied.
Examples
>>> apply_sharding_pattern("12as", "/0:2/1:3/") Path("12/2a/12as")
- atomworks.io.utils.io_utils.atom_array_to_file(structure: AtomArray | AtomArrayStack | list[AtomArray], dest: PathLike | str | StringIO | BytesIO | None = None, *, file_type: Literal['cif', 'bcif', 'cif.gz', 'bcif.gz', 'cif.gzip', 'bcif.gzip', 'cif.zst', 'bcif.zst'] | None = None, model_ids: list[int] | None = None, config: CIFWriteConfig | None = None) str | bytes | PathLike | None[source]#
Write atoms, bonds, and StandardAnnotations as CIF or BinaryCIF.
- Parameters:
structure – Atoms, or a list of models.
dest – Path, writable buffer, or None to return content.
file_type –
ciforbcif, optionally compressed withgz,gzip, orzst. Inferred from paths; otherwise defaults tocif.model_ids – IDs for list input; defaults to
[1, 2, ...].config – Optional CIF export settings, replacing the defaults.
- Returns:
Absolute path, None for buffers, or content (text for CIF, bytes for binary/compressed output).
- atomworks.io.utils.io_utils.build_sharding_pattern(depth: int, chars_per_dir: int = 2) str[source]#
Build a sharding pattern string from depth and characters per directory.
- Parameters:
depth – Number of directory levels.
chars_per_dir – Number of characters to use for each directory level.
- Returns:
Sharding pattern string.
Examples
>>> build_sharding_pattern(2, 2) '/0:2/2:4/' >>> build_sharding_pattern(3, 1) '/0:1/1:2/2:3/'
- atomworks.io.utils.io_utils.get_structure(file_obj: CIFFile | PDBFile | BinaryCIFFile | CIFBlock, *, extra_fields: list[str] | set[str] | frozenset[str] | dict[str, dict[str, Any] | None] | Literal['all'] | None = None, include_bonds: bool = False, model: int | None = None, altloc: Literal['first', 'random_per_chain', 'random_clash_aware'] | str = 'first', altloc_seed: int | None = None, infer_dtypes: bool = True, preserve_ins_code: bool = False) AtomArrayStack | AtomArray[source]#
Load structure into Biotite’s AtomArray or AtomArrayStack.
By default, bonds are NOT loaded here - they are added later in
parse_atom_array()using CCD templates for consistency.Note
For CIF files,
transformation_idis automatically included. This field is required for assembly processing. Loaded entity identifiers use the string annotationentity_id;label_entity_idis accepted as an extra-field input alias.- Parameters:
file_obj – The file object to load with Biotite.
extra_fields –
Extra fields to include as AtomArray annotations. Can be:
List of field names:
["b_factor", "occupancy"]Dict with specs:
{"my_field": {"default": 0, "dtype": np.int32}}"all": Include all fields from the atom_site category
include_bonds – Whether to include bond information. Passed to biotite’s parser. Defaults to False.
model – The model number to use for loading the structure.
altloc (Literal["first", "random_per_chain", "random_clash_aware"] | str) – The altloc ID to use for loading the structure.
"first"selects the alphabetically-first altloc letter per chain."random_per_chain"selects a random altloc independently for each chain."random_clash_aware"selects one altloc per residue, avoiding steric clashes between nearby residues via constraint satisfaction. A specific altloc ID (e.g.,"A","B") can also be provided. If a specific altloc ID is not present in the file, an error will be raised.altloc_seed – Seed for the random number generator when
altloc="random_per_chain"oraltloc="random_clash_aware". IfNone(default), selection is non-deterministic. Provide an integer for reproducible results.infer_dtypes – Whether to automatically infer dtypes for extra fields from their values.
preserve_ins_code – Keep CIF insertion codes instead of clearing them for processing.
- Returns:
The loaded structure with bonds from the CIF file.
- Reference:
- atomworks.io.utils.io_utils.load_any(file_or_buffer: str | PathLike | StringIO | BytesIO, file_type: str | None = None, *, model: int | None = None, squeeze: bool = True) AtomArray | AtomArrayStack | AtomArrayPlus | AtomArrayPlusStack | list[AtomArray][source]#
Deprecated alias for
atomworks.io.atom_array_from_file(), with the same behavior.
- atomworks.io.utils.io_utils.parse_sharding_pattern(sharding_pattern: str) list[tuple[int, int]][source]#
Parse a sharding pattern string into directory levels.
- Parameters:
sharding_pattern – String like
"/1:2/0:2/"where each/start:end/defines a directory level.start:enddefines the character range to use for that directory level.- Returns:
List of (start, end) tuples for each directory level.
Examples
>>> parse_sharding_pattern("/1:2/0:2/") [(1, 2), (0, 2)]
- atomworks.io.utils.io_utils.read_any(path_or_buffer: PathLike | StringIO | BytesIO, file_type: Literal['cif', 'pdb', 'bcif', 'sdf', 'catcif', 'mmjson'] | None = None) CIFFile | PDBFile | BinaryCIFFile[source]#
Reads any of the allowed file types into the appropriate Biotite file object.
- Parameters:
path_or_buffer (PathLike | io.StringIO | io.BytesIO) – The path to the file or a buffer to read from. If a buffer, it’s highly recommended to specify the file_type. Paths may be plain, gzip-compressed (
.gz/.gzip), or Zstandard-compressed (.zst).file_type – Type of the file, including
"mmjson". If None, it will be inferred from the file extension. When using a buffer, the file type must be specified.
- Returns:
The loaded file object.
- Return type:
pdbx.CIFFile | biotite_pdb.PDBFile | pdbx.BinaryCIFFile
- Raises:
ValueError – If the file type is unsupported or cannot be determined.
- atomworks.io.utils.io_utils.suppress_logging_messages(logger_name: str, message_pattern: str) Generator[None, None, None][source]#
Temporarily suppress logging messages matching a pattern.
- Parameters:
logger_name – Name of the logger to filter.
message_pattern – String pattern to match in log messages (substring match).
Examples
>>> with suppress_logging_messages("atomworks.io", "not found"): ... # Code that generates "not found" warnings ... pass
- atomworks.io.utils.io_utils.to_cif_file(structure: AtomArray | AtomArrayStack | list[AtomArray], dest: PathLike | str | StringIO | BytesIO | None = None, *, file_type: Literal['cif', 'bcif', 'cif.gz', 'bcif.gz', 'cif.gzip', 'bcif.gzip', 'cif.zst', 'bcif.zst'] | None = None, model_ids: list[int] | None = None, config: CIFWriteConfig | None = None) str | bytes | PathLike | None#
Write atoms, bonds, and StandardAnnotations as CIF or BinaryCIF.
- Parameters:
structure – Atoms, or a list of models.
dest – Path, writable buffer, or None to return content.
file_type –
ciforbcif, optionally compressed withgz,gzip, orzst. Inferred from paths; otherwise defaults tocif.model_ids – IDs for list input; defaults to
[1, 2, ...].config – Optional CIF export settings, replacing the defaults.
- Returns:
Absolute path, None for buffers, or content (text for CIF, bytes for binary/compressed output).
- atomworks.io.utils.io_utils.to_pdb_buffer(structure: AtomArray) StringIO[source]#
Convert an AtomArray structure to a PDB formatted StringIO buffer.
NOTE: It’s recommended to use atom_array_to_file instead of this function. That function is more flexible and can handle extra annotations and metadata that PDB does not support.
- Parameters:
structure (-) – The atomic structure to be converted.
- Returns:
The PDB formatted StringIO buffer of the structure.
- Return type:
StringIO
- atomworks.io.utils.io_utils.to_pdb_string(structure: AtomArray) str[source]#
Convert an AtomArray structure to a PDB formatted string.
NOTE: It’s recommended to use atom_array_to_file instead of this function. That function is more flexible and can handle extra annotations and metadata that PDB does not support.
- Parameters:
structure (-) – The atomic structure to be converted.
- Returns:
The PDB formatted string representation of the structure.
- Return type:
str