biolm.io

Convert between biological file formats (FASTA, CSV, PDB, JSON) and BioLM API request/response structures. For writing API results to disk from clients, see Disk output in Client interfaces.

Primary functions

biolm.io.load_fasta(file_path: str | Path | IO) List[Dict[str, Any]]

Load sequences from a FASTA file.

Parses a FASTA file and returns a list of dictionaries suitable for use with BioLM API requests. Each dictionary contains: - “sequence”: The sequence string - “id”: Sequence identifier from header (if available) - “metadata”: Additional metadata from header (if available)

Supports multi-line sequences (wrapped sequences).

Args:

file_path: Path to FASTA file (str, Path) or file-like object

Returns:

List of dictionaries, each containing sequence data

Raises:

FileNotFoundError: If file path doesn’t exist ValueError: If file is empty or malformed

Example:
default
>>> items = load_fasta("sequences.fasta")
>>> items[0]
{'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'metadata': {}}
biolm.io.to_fasta(data: List[Dict[str, Any]], file_path: str | Path | IO, sequence_key: str = 'sequence') None

Write sequences to a FASTA file.

Converts a list of dictionaries (API response format) to FASTA format. Each dictionary should contain a sequence field (default: “sequence”).

Args:

data: List of dictionaries containing sequence data file_path: Output file path (str, Path) or file-like object sequence_key: Key to use for sequence data (default: “sequence”)

Raises:

ValueError: If sequence_key is missing from any item KeyError: If required keys are missing

Example:
default
>>> data = [{"sequence": "ACDEFGHIKLMNPQRSTVWY", "id": "seq1"}]
>>> to_fasta(data, "output.fasta")
biolm.io.load_csv(file_path: str | Path | IO, sequence_key: str | None = None) List[Dict[str, Any]]

Load data from a CSV file.

Parses a CSV file and returns a list of dictionaries suitable for use with BioLM API requests. Each row becomes a dictionary with column headers as keys. All values are kept as strings (no type inference).

Args:

file_path: Path to CSV file (str, Path) or file-like object. sequence_key: Optional key name to validate exists in CSV; if provided, raises ValueError if column is missing.

Returns:

List of dictionaries, one per row.

Raises:

FileNotFoundError: If file path doesn’t exist. ValueError: If file is empty or sequence_key column is missing.

Example:
default
>>> items = load_csv("data.csv", sequence_key="sequence")
>>> items[0]
{'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'score': '0.95'}
biolm.io.to_csv(data: List[Dict[str, Any]], file_path: str | Path | IO, fieldnames: List[str] | None = None) None

Write data to a CSV file.

Converts a list of dictionaries (API response format) to CSV format.

Args:

data: List of dictionaries to write. file_path: Output file path (str, Path) or file-like object. fieldnames: Optional list of column names; if not provided, inferred from the first item’s keys (missing keys filled with empty strings).

Raises:

ValueError: If data is empty.

Example:
default
>>> data = [{"sequence": "ACDEFGHIKLMNPQRSTVWY", "score": 0.95}]
>>> to_csv(data, "output.csv")
biolm.io.load_pdb(file_path: str | Path | IO) List[Dict[str, Any]]

Load PDB structure(s) from a PDB file.

Reads a PDB file and returns a list of dictionaries suitable for use with BioLM API requests. For single-model PDBs, returns one item. For multi-model PDBs (with MODEL/ENDMDL records), returns one item per model.

Args:

file_path: Path to PDB file (str, Path) or file-like object

Returns:

List of dictionaries, each containing “pdb” key with PDB content. Single-model files return [{“pdb”: “…”}]. Multi-model files return [{“pdb”: “…”}, {“pdb”: “…”}, …].

Raises:

FileNotFoundError: If file path doesn’t exist ValueError: If file is empty

Example:
default
>>> items = load_pdb("structure.pdb")
>>> items[0]
{'pdb': 'ATOM      1  N   MET A   1      20.154  16.967  19.502...'}
biolm.io.to_pdb(data: List[Dict[str, Any]], file_path: str | Path | IO, pdb_key: str = 'pdb') None

Write PDB structure(s) to a PDB file.

Converts a list of dictionaries (API response format) to PDB format. Each dictionary should contain a PDB content field (default: “pdb”). If multiple items are provided, they are concatenated.

Args:

data: List of dictionaries containing PDB data file_path: Output file path (str, Path) or file-like object pdb_key: Key to use for PDB content (default: “pdb”)

Raises:

ValueError: If data is empty or pdb_key is missing from any item

Example:
default
>>> data = [{"pdb": "ATOM      1  N   MET A   1..."}]
>>> to_pdb(data, "output.pdb")

FASTA Format

Loading FASTA Files

The load_fasta() function parses FASTA files and returns a list of dictionaries suitable for API requests:

python
from biolm.io import load_fasta

# Load sequences from file
items = load_fasta("sequences.fasta")

# Each item contains:
# - "sequence": The sequence string
# - "id": Sequence identifier from header
# - "metadata": Additional metadata (if present)

print(items[0])
# {'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'metadata': {}}

FASTA files support: - Multi-line sequences (wrapped sequences are automatically concatenated) - Headers with metadata (pipe-separated or space-separated) - Multiple sequences in a single file

Example FASTA file:

text
>seq1|protein|test
ACDEFGHIKLMNPQRSTVWY
>seq2 description here
MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQAPILSRVGDGTQDNLSGAEKAVQVKVKALPDAQFEVVHSLAKWKRQTLGQHDFSAGEGLYTHMKALRPDEDRLSPLHSVYVDQWDWERVMGDGERQFSTLKSTVEAIWAGIKATEAAVSEEFGLAPFLPDQIHFVHSQELLSRYPDLDAKGRERAIAKDLGAVFLVGIGGKLSDGHRHDVRAPDYDDWSTPSELGHAGLNGDILVWNPVLEDAFELSSMGIRVDADTLKHQLALTGDEDRLELEWHQALLRGEMPQTIGGGIGQSRLTMLLLQLPHIGQVQAGVWPAAVRESVPSLL

Writing FASTA Files

The to_fasta() function writes sequences to FASTA format:

python
from biolm.io import to_fasta

# Data from API response
data = [
    {"sequence": "ACDEFGHIKLMNPQRSTVWY", "id": "seq1"},
    {"sequence": "MKTAYIAKQRQISFVKSHFSRQ", "id": "seq2"},
]

# Write to file
to_fasta(data, "output.fasta")

# With metadata
data_with_metadata = [
    {
        "sequence": "ACDEFGHIKLMNPQRSTVWY",
        "id": "seq1",
        "metadata": {"description": "Test sequence", "type": "protein"},
    }
]
to_fasta(data_with_metadata, "output.fasta")

You can also use a custom sequence key:

python
data = [{"seq": "ACDEFGHIKLMNPQRSTVWY", "id": "seq1"}]
to_fasta(data, "output.fasta", sequence_key="seq")

CSV Format

Loading CSV Files

The load_csv() function parses CSV files with headers:

python
from biolm.io import load_csv

# Load CSV file
items = load_csv("data.csv")

# Each row becomes a dictionary with column headers as keys
print(items[0])
# {'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'score': '0.95'}

You can validate that a specific column exists:

python
# Raises ValueError if "sequence" column is missing
items = load_csv("data.csv", sequence_key="sequence")

Example CSV file:

text
sequence,id,score,description
ACDEFGHIKLMNPQRSTVWY,seq1,0.95,Test sequence 1
MKTAYIAKQRQISFVKSHFSRQ,seq2,0.87,Test sequence 2

Writing CSV Files

The to_csv() function writes data to CSV format:

python
from biolm.io import to_csv

# Data from API response
data = [
    {"sequence": "ACDEFGHIKLMNPQRSTVWY", "id": "seq1", "score": 0.95},
    {"sequence": "MKTAYIAKQRQISFVKSHFSRQ", "id": "seq2", "score": 0.87},
]

# Write to file
to_csv(data, "output.csv")

# With custom fieldnames
to_csv(data, "output.csv", fieldnames=["sequence", "id"])

Missing keys are automatically filled with empty strings.

PDB Format

Loading PDB Files

The load_pdb() function reads PDB structure files:

python
from biolm.io import load_pdb

# Load single-model PDB
items = load_pdb("structure.pdb")

# Returns: [{"pdb": "HEADER    TEST\nATOM      1  N   MET A   1\n..."}]

# For multi-model PDBs, returns one item per model
items = load_pdb("multi_model.pdb")
# Returns: [{"pdb": "MODEL 1..."}, {"pdb": "MODEL 2..."}]

Writing PDB Files

The to_pdb() function writes PDB structures:

python
from biolm.io import to_pdb

# Data from API response
data = [{"pdb": "HEADER    TEST\nATOM      1  N   MET A   1\nEND\n"}]

# Write to file
to_pdb(data, "output.pdb")

# Multiple structures are concatenated
data = [
    {"pdb": "MODEL 1\nATOM...\nENDMDL\n"},
    {"pdb": "MODEL 2\nATOM...\nENDMDL\n"},
]
to_pdb(data, "output.pdb")

Integration with Model Class

The io module is designed to work seamlessly with the Model class:

python
from biolm.io import load_fasta, to_csv
from biolm import Model

# Load sequences from FASTA
items = load_fasta("sequences.fasta")

# Use with model
model = Model("esm2-8m")
results = model.encode(items=items)

# Export results to CSV
to_csv(results, "results.csv")

Complete workflow example:

python
from biolm.io import load_fasta, to_csv
from biolm import Model

# 1. Load input sequences
sequences = load_fasta("input.fasta")

# 2. Process with model
model = Model("esmfold")
structures = model.predict(items=sequences)

# 3. Export results
to_csv(structures, "output.csv")

File-like Objects

All functions support both file paths and file-like objects:

python
import io
from biolm.io import load_fasta, to_fasta

# Load from file-like object
file_obj = io.StringIO(">seq1\nACDEFGHIKLMNPQRSTVWY\n")
items = load_fasta(file_obj)

# Write to file-like object
output = io.StringIO()
to_fasta(items, output)
content = output.getvalue()

Error Handling

The io module raises clear exceptions for common errors:

python
from biolm.io import load_fasta

try:
    items = load_fasta("nonexistent.fasta")
except FileNotFoundError:
    print("File not found")

try:
    items = load_fasta("empty.fasta")
except ValueError as e:
    print(f"Invalid file: {e}")

Common error types: - FileNotFoundError: File path doesn’t exist - ValueError: File is empty, malformed, or missing required fields - KeyError: Missing required keys in data dictionaries

Best Practices

  • Validate input files before processing; use try/except for FileNotFoundError and ValueError

  • Preserve metadata in FASTA headers when exporting

  • Test round-trips: load → process → save → load

See also

We speak the language of bio-AI

© 2022 - 2026 BioLM. All Rights Reserved.