Biotite Documentation

repository·main·Indexed 21 days ago

https://github.com/biotite-dev/biotite

Biotite is a comprehensive Python library for bioinformatics and computational molecular biology. It leverages NumPy for high-performance array-based data manipulation and uses Rust via PyO3 for performance-critical modules. The library provides tools for sequence analysis, 3D biomolecular structure exploration, and Pythonic access to biological databases such as NCBI Entrez, UniProt, PDB, and PubChem.

Tokens
56.2K
Snippets
197
Records
241
Agent score
75%

What's inside Biotite

  1. Overview of Biotite capabilities

    main

    Biotite is a Python library for computational molecular biology that uses NumPy ndarray objects for internal data storage. This allows for fast C-accelerated analysis and intuitive NumPy-like indexing.

    Key capabilities include:

    • Data Fetching: Searching and fetching data from biological databases (e.g., NCBI Entrez).
    • File I/O: Reading and writing popular sequence and structure file formats.
    • Analysis & Editing: Analyzing and editing sequence and structure data.
    • Visualization: Visualizing sequence and structure data.
    • Integration: Interfacing with external applications for further analysis.
  2. Overview of Biotite features

    main

    Biotite is a fast Python library for computational molecular biology. It provides a uniform interface for various bioinformatics tasks, allowing developers to focus on unique analysis rather than basic functionality.

    Key capabilities include:

    • Sequence Analysis: Work with nucleotide, protein, and structural alphabets (like 3Di). Includes rapid, modular alignment tools and Matplotlib-based visualization for alignments and feature maps.
    • 3D Structure Exploration: Handle large biomolecules and small molecules using a NumPy-like interface. Supports filtering, transforming, and analyzing structures (e.g., surface area calculation, superimposition) and interfaces with formats like PDB, CIF/BinaryCIF, and MOL/SDF.
    • Database Access: Query biological databases such as NCBI Entrez, UniProt, PDB, and PubChem using Pythonic logical operators instead of raw REST APIs.
    • Software Integration: Seamlessly interface with external tools for multiple sequence alignment and secondary structure annotation. These interfaces handle file creation and command-line execution internally, allowing you to pass and receive Python objects directly.
  3. Overview of Biotite subpackages

    main

    Biotite is organized into four primary subpackages, each targeting a specific domain of bioinformatics:

    • biotite.sequence: Tools for handling sequence information (nucleotides, proteins, etc.), supporting various file formats, sequence manipulations, and modular sequence alignments.
    • biotite.structure: Tools for handling 3D biomolecular structures. Structures are represented using NumPy arrays for atom coordinates and annotations (residue names, elements, charges), enabling high-performance operations on single models or MD trajectories. Supports formats like PDB and BinaryCIF.
    • biotite.database: Provides a Pythonic interface to search and download data from biological databases via REST APIs.
    • biotite.application: Provides seamless interfaces for external software (e.g., Clustal Omega, NCBI BLAST). These interfaces accept and return Biotite sequence and structure objects, handling file I/O and CLI arguments internally.
  4. Explore Biotite extension packages

    main

    Biotite supports several independent extension packages that build upon its core functionality. These are separate Python packages developed independently. Available extensions include:

    • Gecos: An automatic generator for alignment color schemes based on substitution matrices.
    • Hydride: Prediction of hydrogen positions in arbitrary molecular models.
    • fastpdb: A high-performance drop-in replacement for Biotite's PDBFile.
    • Springcraft: Investigation of molecular dynamics using elastic network models.
    • pepp'r: Evaluation of predicted poses against reference structures.
    • Pocketeer: A suite for detecting and working with protein pockets.
  5. Use the biotite.database subpackage to access online biological databases

    main
    The biotite.database subpackage provides uniform interfaces for interacting with popular online biological databases. It is designed so that the patterns used to search and download data from one database (like NCBI Entrez) can be applied to others (like RCSB PDB or UniProt), minimizing the learning curve when switching between data sources.
  6. Follow Biotite module import and export patterns

    main

    Biotite uses a pattern similar to NumPy where users import packages rather than individual modules. To support this, follow these rules:

    • Subpackage __init__.py: Must import all publicly accessible modules using relative imports. Import statements should be the only statements in the file.
      from .module1 import *
      from .module2 import *
    • Cross-subpackage imports: Use absolute imports targeting the specific module (not the package) to avoid circular imports.
      from biotite.subpackage.module import foo
    • Namespace Protection: Every module must define the __all__ variable containing all publicly accessible attributes to prevent namespace pollution.
  7. Work with sequence Annotations and Features

    main

    An Annotation is a collection of Feature objects corresponding to a sequence. You can obtain an Annotation from a GenBankFile using gb.get_annotation(file).

    Each Feature contains:

    • A key (e.g., CDS, gene, regulatory).
    • A qual dictionary containing feature qualifiers (e.g., regulatory_class).
    • One or more locs (Location objects).

    A Location object defines the start and end positions, the strand, and potential Location.Defect flags.

    import biotite.sequence.io.genbank as gb
    
    annotation = gb.get_annotation(file)
    for feature in annotation:
        # Access feature key and qualifiers
        print(f"Key: {feature.key}")
        if feature.key == "regulatory":
            print(f"Class: {feature.qual['regulatory_class']}")
        
        # Access locations
        for loc in feature.locs:
            print(f"Range: {loc.first} to {loc.last}")
  8. Align custom sequence types with substitution matrices

    main

    If the MSA software supports protein alignment and custom substitution matrices (e.g., MUSCLE and MAFFT), you can align non-standard sequence types (e.g., using a custom Alphabet and GeneralSequence).

    Internally, Biotite converts these sequences and the SubstitutionMatrix into a format the software understands, performs the alignment, and then maps the results back to your original sequence type. Note that for custom alphabets that do not use characters as symbols, you may need to print alignment.trace instead of the alignment itself.

    import numpy as np
    import biotite.application.mafft as mafft
    import biotite.sequence as seq
    import biotite.sequence.align as align
    
    # Define a custom alphabet and sequences
    alphabet = seq.Alphabet(("foo", "bar", 42))
    sequences = [seq.GeneralSequence(alphabet, symbols) for symbols in [...]]
    
    # Define a custom substitution matrix
    matrix = align.SubstitutionMatrix(
        alphabet, alphabet, np.array([
            [ 100, -100, -100],
            [-100,  100, -100],
            [-100, -100,  100]
        ])
    )
    
    # Perform alignment
    alignment = mafft.MafftApp.align(sequences, matrix=matrix)
    print(alignment.trace)
  9. How heuristic sequence alignments work in Biotite

    main

    Heuristic alignment methods (alignment searches) are used instead of optimal alignment methods when dealing with very long sequences (e.g., genomes) or large databases. While optimal alignment scales poorly in terms of time and memory, heuristic methods are significantly faster by using a multi-stage process:

    1. K-mer matching: Rapidly finding short, exact matches (seeds) between sequences.
    2. Seed extension: Expanding these matches using fast, ungapped alignments.
    3. Gapped alignment: Performing more accurate, computationally expensive gapped alignments only on promising regions.
    4. Significance evaluation: Using statistical measures (like E-values) to determine if an alignment is biologically significant or occurred by chance.

    Biotite provides a modular system to build these multi-stage processes by combining different classes and functions.

  10. Use AnnotatedSequence for sequence and feature management

    main

    An AnnotatedSequence combines a Sequence with an Annotation. You can obtain it using gb.get_annotated_sequence(file).

    Key Behaviors:

    • Slicing: Slicing an AnnotatedSequence applies the index to both the Annotation and the Sequence. The sequence_start property shifts to the start of the slice.
    • Feature Indexing: You can index an AnnotatedSequence directly with a Feature object to extract the specific sequence corresponding to that feature (handling multiple locations or reverse strands automatically).

    Warning: AnnotatedSequence uses base position indices (e.g., starting at 1), whereas standard Sequence objects use array position indices (starting at 0). Therefore, annot_seq[n:m].sequence may differ from annot_seq.sequence[n:m].

    import biotite.sequence.io.genbank as gb
    
    annot_seq = gb.get_annotated_sequence(file)
    
    # 1. Slice by range
    sub_seq = annot_seq[100:200]
    
    # 2. Slice by Feature object
    cds_feature = next(f for f in annot_seq.annotation if f.key == "CDS")
    cds_seq = annot_seq[cds_feature]
  11. How Biotite and OpenMM work together

    main

    The biotite.interface.openmm subpackage provides an interface to the OpenMM molecular simulation toolkit. It allows you to expand Biotite's structural capabilities into molecular dynamics.

    Conversion Patterns:

    • To OpenMM: Use to_<x>() functions to convert Biotite objects to OpenMM objects (e.g., to_topology(), to_system()).
    • From OpenMM: Use from_<x>() functions to convert OpenMM objects back to Biotite objects (e.g., from_topology(), from_system(), from_states()).

    Note that when converting from OpenMM states to a Biotite AtomArrayStack, you must provide an AtomArray as a template to define the topology (residues, atoms, and bonds), as the states themselves only contain coordinates and box dimensions.

    import biotite.interface.openmm as openmm_interface
    
    # Convert AtomArray to OpenMM Topology
    topology = openmm_interface.to_topology(molecule)
    
    # Convert OpenMM Topology back to AtomArray template
    template = openmm_interface.from_topology(topology)
    
    # Convert OpenMM states to an AtomArrayStack trajectory using a template
    trajectory = openmm_interface.from_states(template, states)
  12. What are structural alphabets?

    main

    Structural alphabets are representations of protein or nucleic acid structures where each residue is encoded into a single character based on local geometry or contact partners. This allows high-performance sequence-based methods (like alignment searches) to be applied to structural data.

    Biotite provides several alphabets via the biotite.structure.alphabet subpackage. A prominent example is the 3Di alphabet, which is used for fast protein structure comparison (similar to the Foldseek software).