Sequence Analysis (Functional Workflow)
Use this workflow when you want direct functions and analysis objects in scripts
or pipelines without routing every operation through Protein methods.
When to Prefer Functional APIs
You are processing many sequences in a pipeline with explicit intermediate data.
You want to call lower-level utility functions directly.
You need module-level control over alignment and scoring settings.
Minimal End-to-End Alignment Example
from sparrow import Protein
from sparrow.sequence_analysis.alignment import SequenceAlignment
proteins = {
"seq1": Protein("MGSQSSRSSSQQQ"),
"seq2": Protein("MGSQSSRNNNQQQ"),
"seq3": Protein("MGSQSSRSSSAAA"),
}
msa = SequenceAlignment(proteins, scoring_matrix="BLOSUM62")
alignment = msa.alignment
msa.save_msa("example_alignment.fasta")
Direct Parameter Calculations
from sparrow import calculate_parameters
seq = "MGSQSSRSSSQQQ"
aa = calculate_parameters.calculate_aa_fractions(seq)
complexity = calculate_parameters.calculate_seg_complexity(seq)
hydro = calculate_parameters.calculate_hydrophobicity(seq, mode="KD")
Grammar Feature Vectors
Use sparrow.sequence_analysis.grammar when you want a single-sequence
feature-vector workflow with optional scramble-based z-scores.
from sparrow.sequence_analysis.grammar import compute_feature_vector
# Default output is a float32 NumPy array.
vec = compute_feature_vector(
"MEEEKKKKSSSTTTDDD",
num_scrambles=200,
seed=1,
)
# Only request names when needed.
vec, names = compute_feature_vector(
"MEEEKKKKSSSTTTDDD",
num_scrambles=200,
seed=1,
return_feature_names=True,
)
Patch Primitives
Patch metrics used by grammar are available directly as reusable primitives:
from sparrow.sequence_analysis.patching import patch_fraction, rg_patch_fraction
seq = "AAAAQQRGRGTTTAAAQQ"
a_patch = patch_fraction(seq, "A")
rg_patch = rg_patch_fraction(seq)
Protein vs Functional API
Prefer
Proteinfor interactive analysis and memoized repeated queries.Prefer functional modules for explicit data flow and pipeline composition.
Mix both styles when needed: create
Proteinonly where accessor behavior or object-level caching adds value.
Reference: Alignment Module
Reference: Parameter Functions
Key function entry points:
sparrow.calculate_parameters.calculate_aa_fractions()sparrow.calculate_parameters.calculate_seg_complexity()sparrow.calculate_parameters.calculate_hydrophobicity()sparrow.calculate_parameters.calculate_linear_hydrophobicity()sparrow.sequence_analysis.grammar.compute_feature_vector()sparrow.sequence_analysis.patching.patch_fraction()sparrow.sequence_analysis.patching.rg_patch_fraction()
Utility functions for computing sequence-derived parameters.
This module contains lightweight, dependency-minimal helpers for amino acid composition, sequence complexity, and hydrophobicity calculations.
- calculate_aa_fractions(s)[source]
Compute per-amino-acid fractional composition.
- Parameters:
s (str) – Amino acid sequence (uppercase one-letter codes expected).
- Returns:
Mapping from each standard amino acid to its fractional occurrence (counts divided by total sequence length).
- Return type:
Examples
>>> calculate_aa_fractions("ACAA")['A'] 0.75
- calculate_seg_complexity(s, alphabet=['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'])[source]
Calculate Wootton-Federhen (SEG) compositional complexity.
This is the Shannon-like compositional complexity used by the classic SEG algorithm. Larger negative summed probabilities (before the sign inversion) indicate more diverse composition; the returned value is positive.
- calculate_hydrophobicity(s, mode='KD', normalize=False)[source]
Compute mean hydrophobicity for a sequence.
- Parameters:
- Returns:
Mean per-residue hydrophobicity under the selected scale.
- Return type:
- Raises:
sparrow_exceptions.CalculationException – If an invalid residue or unknown mode is encountered.
- calculate_linear_hydrophobicity(s, mode='KD', normalize=False)[source]
Return per-residue hydrophobicity values.
- Parameters:
- Returns:
Hydrophobicity value for each residue in
s.- Return type:
- Raises:
sparrow_exceptions.CalculationException – If an invalid residue or unknown mode is encountered.
Examples
>>> calculate_linear_hydrophobicity('AA', mode='KD') [6.3, 6.3]
Core grammar-style feature extraction for a single sequence.
This module implements sequence-to-feature-vector workflows using Sparrow-native primitives and optional scramble/statistics-based z-scoring.
- exception GrammarException[source]
Bases:
RuntimeErrorRaised when grammar feature computation fails.
- add_note()
Exception.add_note(note) – add a note to the exception
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class GrammarCompositionStats(feature_names: Sequence[str], mean: numpy.ndarray, std: numpy.ndarray)[source]
Bases:
object- mean: ndarray
- std: ndarray
- class GrammarPatterningConfig(backend: str = 'kappa_cython', num_scrambles: int = 10000, blob_size: int = 5, min_fraction: float = 0.1, seed: int | None = None, fit_method: str = 'gamma_mle')[source]
Bases:
object- Parameters:
- backend: str = 'kappa_cython'
- num_scrambles: int = 10000
- blob_size: int = 5
- min_fraction: float = 0.1
- fit_method: str = 'gamma_mle'
- rng()[source]
- pattern_feature_names(backend)[source]
Return ordered patterning feature names for the selected backend.
- composition_feature_names()[source]
Return ordered composition feature names.
- patch_feature_names()[source]
Return ordered patch feature names.
- compute_composition_raw(sequence_or_protein)[source]
Compute Sparrow-native composition + patch features.
- compute_composition_zscores(raw_composition, composition_stats)[source]
Compute z-scores for selected composition/patch features.
- compute_patterning_raw(sequence_or_protein, config)[source]
Compute ordered patterning features for a sequence.
- compute_patterning_scramble_distribution(sequence_or_protein, config)[source]
Compute scramble distributions for each patterning feature.
- compute_patterning_zscores(raw_patterning, scramble_distribution, config)[source]
Compute patterning z-scores from raw values and scramble distributions.
- merge_feature_blocks(raw_blocks=None, z_blocks=None)[source]
Merge raw and z-score blocks into a single ordered feature vector.
- compute_feature_vector(sequence_or_protein, patterning_config=None, composition_stats=None, use_default_composition_stats=True, include_raw=False, return_array=True, return_feature_names=False, backend=None, num_scrambles=None, blob_size=None, min_fraction=None, seed=None, fit_method=None)[source]
Compute an ordered grammar feature vector for one sequence.
If
use_default_composition_statsis True andcomposition_statsis None, composition z-scores use Sparrow’s built-in human-IDR background. Z-score features are always included. Setinclude_raw=Trueto append the raw feature block. By default this returns anp.float32array.patterning_configis optional. Users can override config fields directly via keyword arguments likenum_scramblesandbackend.
- compute_composition_background_stats(sequences_or_proteins, dtype=<class 'numpy.float32'>)[source]
Compute composition/patch background stats with low memory use.
- Parameters:
- Returns:
Feature names plus background mean/std arrays.
- Return type:
GrammarCompositionStats
- save_composition_stats_npz(output_filename, composition_stats, dtype=<class 'numpy.float32'>, compressed=True)[source]
Save grammar composition background stats to a compact NumPy archive.
- load_composition_stats_npz(input_filename)[source]
Load grammar composition background stats from NumPy archive.
- load_default_composition_stats()[source]
Load built-in human-IDR composition background stats (cached).
Sequence patching primitives.
This module contains reusable primitives for estimating patch coverage in protein sequences using NARDINI-style semantics.
- patch_fraction(sequence, residue_selector, interruption=2, min_target_count=4, adjacent_pair_pattern=None, min_adjacent_pair_count=0)[source]
Compute the sequence fraction covered by residue patches.
- Parameters:
sequence (str) – Amino acid sequence.
residue_selector (str or iterable[str]) – One or more residues that define patch membership.
interruption (int, default 2) – Maximum number of non-target residues that can be bridged inside a patch.
min_target_count (int or None, default 4) – Minimum number of target residues required for a bridged region to count. If
None, no minimum target-count filter is applied.adjacent_pair_pattern (str or iterable[str] or None, default None) – Optional adjacent two-residue motif required inside each bridged region (for example
"RG").min_adjacent_pair_count (int, default 0) – Minimum number of occurrences of
adjacent_pair_patternrequired for a bridged region to count. Ignored whenadjacent_pair_patternisNone.
- Returns:
Fraction of sequence positions covered by valid patch spans.
- Return type:
- rg_patch_fraction(sequence, interruption=2, min_adjacent_rg_pairs=2)[source]
Compute NARDINI-style RG patch span fraction.
- Parameters:
- Returns:
Fraction of sequence positions covered by valid RG patch spans.
- Return type: