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)[source]#
Bases:
objectConfiguration for CIF/BCIF writing operations.
Consolidates options used when writing structures to CIF/BCIF format.
- id#
Entry ID for the data block. Defaults to “unknown_id”.
- Type:
str
- author#
Author name for metadata. Defaults to current user.
- Type:
str
- date#
Date string (YYYY-MM-DD format). Auto-generated if None.
- Type:
str | None
- time#
Time string (HH:MM:SS format). Auto-generated if None.
- Type:
str | None
- include_entity_categories#
Write entity categories (_entity, _entity_poly, etc.). Defaults to False for buffer/string operations, True for file operations.
- Type:
bool
- include_chem_comp#
Write _chem_comp CIF category. Defaults to True.
- Type:
bool
- include_nan_coords#
Include atoms with NaN coordinates. Defaults to True.
- Type:
bool
- extra_fields#
Additional AtomArray annotations to write. Use “all” to include all non-standard annotations. Defaults to empty list.
- Type:
list[str] | Literal[‘all’]
- extra_categories#
Additional CIF categories as dict of {category_name: {column_name: value}}. Defaults to None.
- Type:
dict[str, dict[str, float | int | str | list | numpy.ndarray]] | None
- chain_disambiguation#
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.
- Type:
Literal[‘transformation_id’, ‘chain_iid’] | None
- save_standard_annotations#
Whether to serialize registered
StandardAnnotationBaseannotations (conditions,atomize, etc.) present on the structure into custom CIF categories. Defaults to True.- Type:
bool
- ccd_entries#
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.- Type:
dict[str, biotite.structure.AtomArray] | None
- chem_comp_source#
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.- Type:
Literal[‘array’, ‘ccd’, ‘ccd_non_canonicals’]
- warn_on_ccd_without_registry#
Warn on CCD write from a plain
AtomArray(no parse-time CCD snapshot). SetFalseto silence. Defaults toTrue.- Type:
bool
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'#
- 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.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) 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.- 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.
- Returns:
The loaded structure with bonds from the CIF file.
- Reference:
- atomworks.io.utils.io_utils.load_any(file_or_buffer: PathLike | StringIO | BytesIO, file_type: Literal['cif', 'mmcif', 'pdbx', 'pdb', 'pdb1', 'bcif', 'catcif'] | None = None, *, extra_fields: list[str] | set[str] | frozenset[str] | dict[str, dict[str, Any] | None] | Literal['all'] | None = None, include_bonds: bool = True, model: int | None = None, altloc: Literal['first', 'random_per_chain', 'random_clash_aware'] | str = 'first', altloc_seed: int | None = None, infer_dtypes: bool = True) AtomArrayStack | AtomArrayPlusStack | AtomArray | AtomArrayPlus[source]#
Convenience function for loading a structure from a file or buffer.
NOTE: This function is deprecated! Please use
atomworks.io.parse()with config=”minimal”By default, bonds are NOT loaded here - they are added later in
parse_atom_array()using CCD templates for consistency.- Parameters:
file_or_buffer – Path to the file or buffer to load the structure from.
file_type – Type of the file to load. If None, it will be inferred.
extra_fields –
Extra fields to include as AtomArray annotations. Can be:
List of field names:
["annot1", "annot2"]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 from biotite’s parser. Defaults to False. Bonds are typically added later in parse_atom_array() using CCD templates for consistency.
model – The model number to use for loading the structure. If None, all models will be loaded.
altloc – The altloc ID to use for loading the structure.
altloc_seed – Seed for the random number generator when
altloc="random_per_chain"oraltloc="random_clash_aware".infer_dtypes – Whether to automatically infer dtypes for extra fields from their values. For example, fields containing “1”, “2”, “3” will be converted to int.
- Returns:
The loaded structure.
References
- 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'] | 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.
file_type (Literal["cif", "pdb", "bcif", "sdf", "catcif"], optional) – Type of the file. 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_buffer(structure: AtomArray | list[AtomArray], *, model_ids: list[int] | None = None, config: CIFWriteConfig | None = None, as_bcif: bool = False) StringIO | BytesIO[source]#
Convert an AtomArray (or list thereof) to a CIF formatted buffer.
- Parameters:
structure – The atomic structure to be converted. Pass a list to write each element as a separate model in a multi-model CIF.
model_ids – Model IDs for each element when
structureis a list. Defaults to[1, 2, …].config – Write configuration. If None, uses default CIFWriteConfig().
as_bcif – Return binary CIF format. Defaults to False.
- Returns:
StringIO or BytesIO buffer containing the CIF/BCIF formatted structure.
See also
- atomworks.io.utils.io_utils.to_cif_file(structure: AtomArray | list[AtomArray], path: PathLike, *, model_ids: list[int] | None = None, file_type: Literal['cif', 'bcif', 'cif.gz'] | None = None, id: str | None = None, author: str = 'ncorley', date: str | None = None, time: str | None = None, include_entity_poly: bool | None = None, include_entity_categories: bool = True, include_chem_comp: bool = True, include_nan_coords: bool = True, extra_fields: list[str] | Literal['all'] = [], extra_categories: dict[str, dict[str, float | int | str | list | ndarray]] | None = None, chain_disambiguation: Literal['transformation_id', 'chain_iid'] | None = None, save_standard_annotations: bool = True, include_bonds: bool | None = None, ccd_entries: dict[str, AtomArray] | None = None) PathLike[source]#
Convert an AtomArray structure to a CIF/BCIF formatted file.
- Parameters:
structure – The atomic structure to be converted.
path – The file path where the CIF formatted structure will be saved.
file_type – The file type to save the structure as. If None, the file type will be inferred from the path.
id – The ID of the entry. This will be used as the data block name. If None, the data block name will be inferred from the path.
author – The author of the entry. Defaults to current user.
date – The date of the entry (YYYY-MM-DD). Auto-generated if None.
time – The time of the entry (HH:MM:SS). Auto-generated if None.
include_entity_poly – DEPRECATED. Use
include_entity_categoriesinstead.include_entity_categories – Write entity categories (_entity, _entity_poly, etc.). Defaults to True for file operations.
include_chem_comp – Write _chem_comp CIF category. Defaults to True.
include_nan_coords – Write atoms with NaN coordinates. Defaults to True.
extra_fields – Additional atom_array annotations to include in the CIF file. Use “all” to include all non-standard annotations.
extra_categories – Additional CIF categories to include in data block. Must be dict of form {category_name: {column_name: value}}. Example: {“reflns”: {“d_mean”: 1.0}, “my_metadata”: {“hi”: np.arange(10)}}
chain_disambiguation –
Method for disambiguating chains in multi-transformation assemblies. Defaults to “chain_iid”. - “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.
save_standard_annotations – Whether to serialize registered
StandardAnnotationBaseannotations (conditions,atomize, etc.) present on the structure. Defaults to True.include_bonds – DEPRECATED. This parameter has no effect and will be removed in a future version.
ccd_entries – Optional dict mapping residue name to CCD template AtomArray for
chem_comp_atomandchem_comp_bondemission. Falls back to the structure’s_custom_ccd_registry, then bundled CCD.
- Returns:
The absolute file path where the CIF formatted structure was saved.
- Raises:
IOError – If there’s an issue writing to the specified file path.
See also
- atomworks.io.utils.io_utils.to_cif_string(structure: AtomArray | list[AtomArray], *, model_ids: list[int] | None = None, config: CIFWriteConfig | None = None, as_bcif: bool = False) str | bytes[source]#
Convert an AtomArray (or list thereof) to a CIF formatted string.
- Parameters:
structure – The atomic structure to be converted. Pass a list to write each element as a separate model in a multi-model CIF.
model_ids – Model IDs for each element when
structureis a list. Defaults to[1, 2, …].config – Write configuration. If None, uses default CIFWriteConfig().
as_bcif – Return binary CIF format. Defaults to False.
- Returns:
String or bytes containing the CIF/BCIF formatted structure.