The Protein Object

sparrow.protein.Protein is the one object you need. Create it from a sequence and read everything off it – parameters, properties, deep-learning predictions, polymer dimensions, and visualizations. Values are computed lazily on first access and cached, so you only pay for what you use.

This page lists everything you can do with a protein, organized by what you want to compute. The deep-learning predictors and polymer-model properties are reached through the predictor and polymeric accessors, but they are documented here alongside everything else so you never have to hunt across pages.

from sparrow import Protein

p = Protein("MGSQSSRSSSQQQQQQQ")
p.FCR                      # a property
p.compute_kappa_x("ED", "KR")        # a method
p.predictor.disorder()     # a prediction
p.polymeric.predicted_nu   # a polymer-model property

Creating a protein

from sparrow import Protein

p = Protein("MGSQSSRSSSQQQQQQQ")
p = Protein("MGSQXU--", validate=True)   # convert non-standard residues

len(p)            # sequence length
p.sequence        # the (upper-cased) sequence string

Sequence & composition

sparrow.protein.Protein.sequence

Returns a string representation of the protein sequence.

sparrow.protein.Protein.molecular_weight

Molecular weight of the protein in Daltons.

sparrow.protein.Protein.amino_acid_fractions

Per-amino-acid fractional composition of the sequence.

sparrow.protein.Protein.compute_residue_fractions

Compute the total fraction of specified residue types in the protein sequence.

sparrow.protein.Protein.fraction_aromatic

Returns the fraction of aromatic residues in the sequence.

sparrow.protein.Protein.fraction_aliphatic

Returns the fraction of aliphatic residues in the sequence.

sparrow.protein.Protein.fraction_polar

Returns the fraction of polar residues in the sequence.

sparrow.protein.Protein.fraction_proline

Returns the fraction of proline residues.

p.amino_acid_fractions["Q"]
p.fraction_aromatic
p.compute_residue_fractions(["S", "T"])

Charge & charge patterning

sparrow.protein.Protein.FCR

Returns the fraction of charged residues (FCR) in the sequence.

sparrow.protein.Protein.NCPR

Returns the net charge per residue of the sequence.

sparrow.protein.Protein.fraction_positive

Returns the fraction of positively charged residues in the sequence.

sparrow.protein.Protein.fraction_negative

Returns the fraction of negatively charged residues in the sequence.

sparrow.protein.Protein.kappa

Charge segregation parameter (kappa) for the sequence.

sparrow.protein.Protein.compute_kappa_x

User-facing high-performance implementation for generic calculation of kappa_x.

sparrow.protein.Protein.SCD

Returns the default sequence charge decoration (SCD) parameter, a charge-patterning metric defined by Sawle and Ghosh (2015).

sparrow.protein.Protein.compute_SCD_x

Function that computes the sequence charge decoration (SCD) parameter of Sawle and Ghosh.

p.FCR, p.NCPR
p.kappa                                   # charge segregation (0-1, or -1)
p.compute_kappa_x("ED", "KR", window_size=6)
p.SCD                                     # sequence charge decoration

Hydrophobicity

sparrow.protein.Protein.hydrophobicity

Mean hydrophobicity of the sequence on the Kyte-Doolittle scale.

sparrow.protein.Protein.SHD

Returns the default sequence hydropathy decoration (SHD) parameter, a hydrophobicity-patterning metric defined by Zheng et al. (2020).

sparrow.protein.Protein.compute_SHD_custom

Sequence Hydropathy Decoration (SHD) using a custom hydrophobicity scale.

Complexity, clustering & patches

sparrow.protein.Protein.complexity

Wootton-Federhen (SEG) compositional complexity of the sequence.

sparrow.protein.Protein.compute_iwd

Returns the inverse weighted distance (IWD), a metric for residue clustering

sparrow.protein.Protein.compute_iwd_charged_weighted

Charge-weighted inverse weighted distance (IWD) for one charge sign.

sparrow.protein.Protein.compute_bivariate_iwd_charged_weighted

Charge-weighted bivariate inverse weighted distance (IWD).

sparrow.protein.Protein.compute_patch_fraction

Returns the sequence fraction covered by residue patches.

sparrow.protein.Protein.compute_rg_patch_fraction

Returns the sequence fraction covered by RG motif-enriched patches.

p.compute_iwd(["D", "E"])                 # clustering of acidic residues
p.compute_patch_fraction("Q")            # fraction in Q-rich patches

Linear (per-residue) profiles

Windowed tracks with one value per residue – ideal for plotting (see Worked Examples).

sparrow.protein.Protein.linear_sequence_profile

Function that returns a vectorized representation of local composition/sequence properties, as defined by the passed 'mode', which acts as a selector toggle for a large set of pre-defined analyses types.

sparrow.protein.Protein.linear_composition_profile

Function that returns a vectorized representation of local composition/sequence properties, as defined by the set of one or more residues passed in composition_list.

sparrow.protein.Protein.linear_property_profile

Returns a vectorized representation of a numerical amino-acid property averaged over a sliding window.

p.linear_sequence_profile(mode="NCPR", window_size=7)
p.linear_composition_profile(["Q", "N"], window_size=8)
p.linear_property_profile("hydropathy-kyte-1982", window_size=9)  # AAindex

The 500+ AAindex scales usable with linear_property_profile are catalogued in Amino-Acid Property Profiles (AAindex).

Domains, motifs & isoforms

sparrow.protein.Protein.low_complexity_domains

Extract low complexity domains (LCDs) from the sequence.

sparrow.protein.Protein.plaac_prion_like_domains

Extract prion-like domains (PLDs) from the sequence using the PLAAC algorithm.

sparrow.protein.Protein.elms

Returns a list of NamedTuples containing each of the elm annotations for the given sequence.

sparrow.protein.Protein.generate_phosphoisoforms

Generate possible phosphoisoform sequences for the protein.

Predictions – disorder & secondary structure

Reached via protein.predictor; networks load lazily and results are cached.

p.predictor.disorder()
p.predictor.dssp_helicity()

Predictions – polymer dimensions

Single-value predictions via protein.predictor; richer polymer-model properties and distance distributions via protein.polymeric.

p.predictor.radius_of_gyration()
p.polymeric.predicted_nu
re_distance, probability = p.polymeric.get_afrc_end_to_end_distribution()

(The full polymer-model surface is documented in the Polymeric reference at the bottom of this page.)

Predictions – modification, localization & phase behavior

p.predictor.serine_phosphorylation()
p.predictor.transmembrane_regions()
p.predictor.pscore()

Machine-learning feature vectors

sparrow.protein.Protein.extract_feature_vector

Returns a grammar feature vector for the current sequence.

vec = p.extract_feature_vector(num_scrambles=256, seed=1)

Visualization

sparrow.protein.Protein.show_sequence

Function that generates an HTML colored string that either renders in the browser or returns the html string.

p.show_sequence(bold_residues=["E", "D"])   # coloured HTML (e.g. in a notebook)

Good to know

  • kappa / compute_kappa_x return -1 when undefined (sequence shorter than the window, or missing a required residue group).

  • hydrophobicity returns the mean value; for a per-residue track use linear_sequence_profile(mode='hydrophobicity').

  • Accessor objects (predictor, polymeric, plugin) are created on first access and reused; predictor networks load on first use.


Full reference

Protein

class Protein(s, validate=False)[source]

Bases: object

__init__(s, validate=False)[source]

Construct a Protein object from a single amino acid sequence.

The sequence is stored upper-cased. Construction is lazy: no sequence parameters are computed here, and each property/method calculates (and caches) its value on first access.

Parameters:
  • s (str) – Amino acid sequence. Stored upper-cased.

  • validate (bool, optional) –

    If True, the sequence is checked for non-standard residues and any that are found are converted to standard amino acids according to the rules below. If a residue cannot be converted, a SparrowException is raised. Default is False.

    • B -> N

    • U -> C

    • X -> G

    • Z -> Q

    • * -> <empty string>

    • - -> <empty string>

Raises:

sparrow.sparrow_exceptions.SparrowException – If validate is True and the sequence still contains an invalid residue after attempted conversion.

See also

sparrow.sequence_analysis.plugins.PluginManager

Plugin interface.

sparrow.predictors.Predictor

Sequence-based predictors.

sparrow.polymer.Polymeric

Polymer property calculations.

property molecular_weight

Molecular weight of the protein in Daltons.

Computed as the sum of the standard residue molecular weights minus one water molecule per peptide bond. Calculated on first access and cached.

Returns:

Molecular weight in Daltons (Da).

Return type:

float

property amino_acid_fractions

Per-amino-acid fractional composition of the sequence.

Calculated on first access and cached.

Returns:

Dictionary with the 20 standard single-letter amino acid codes as keys and the fraction of the sequence made up by each residue as values (each between 0 and 1; the values sum to 1).

Return type:

dict

property FCR

Returns the fraction of charged residues (FCR) in the sequence. Charged residues are Asp, Glu, Lys and Arg.

Returns:

Float between 0 and 1

Return type:

float

property fraction_positive

Returns the fraction of positively charged residues in the sequence. Positive residues are Arg and Lys (not His at physiological pH).

Returns:

Float between 0 and 1

Return type:

float

property fraction_negative

Returns the fraction of negatively charged residues in the sequence. Negative residues are Asp and Glu.

Returns:

Float between 0 and 1

Return type:

float

property NCPR

Returns the net charge per residue of the sequence. Net charge is defined as (fraction positive) - (fraction negative)

Returns:

Float between -1 and +1

Return type:

float

property kappa

Charge segregation parameter (kappa) for the sequence.

Kappa measures how the positive (Arg, Lys) and negative (Asp, Glu) residues are patterned along the sequence: values near 0 indicate well-mixed charges and values near 1 indicate segregated (blocky) charges. It is computed as the average of kappa evaluated with window sizes 5 and 6, with values above 1 flattened to 1.

Returns -1 when kappa is undefined, i.e. the sequence is shorter than 6 residues or it lacks residues from one of the charge groups. Calculated on first access and cached.

Returns:

Kappa value between 0 and 1, or -1 if undefined.

Return type:

float

See also

compute_kappa_x

Generic kappa for arbitrary residue groups / windows.

property SCD

Returns the default sequence charge decoration (SCD) parameter, a charge-patterning metric defined by Sawle and Ghosh (2015).

Charge groups are fixed to the acidic (E, D) and basic (R, K) residues; use compute_SCD_x() for arbitrary groups. Calculated on first access and cached.

Returns:

The sequence charge decoration.

Return type:

float

References

Sawle, L. & Ghosh, K. A theoretical method to compute sequence-dependent configurational properties in charged polymers and proteins. J. Chem. Phys. 143, 085101 (2015).

property SHD

Returns the default sequence hydropathy decoration (SHD) parameter, a hydrophobicity-patterning metric defined by Zheng et al. (2020).

Hydrophobicity values use the default (normalized Kyte-Doolittle) scale; use compute_SHD_custom() to supply your own. Calculated on first access and cached.

Returns:

The sequence hydropathy decoration.

Return type:

float

References

Zheng, W. et al. Hydropathy Patterning Complements Charge Patterning to Describe Conformational Preferences of Disordered Proteins. J. Phys. Chem. Lett. 11, 3408-3415 (2020).

property fraction_aromatic

Returns the fraction of aromatic residues in the sequence. Aromatic residues are Tyr, Phe, Trp.

Returns:

Float between 0 and 1

Return type:

float

property fraction_aliphatic

Returns the fraction of aliphatic residues in the sequence. Aliphatic residues are Ala, Leu, Ile, Met, Val.

Returns:

Float between 0 and 1

Return type:

float

property fraction_polar

Returns the fraction of polar residues in the sequence. Polar residues are Gln, Asn, Ser, Thr, His and Gly.

Returns:

Float between 0 and 1

Return type:

float

property fraction_proline

Returns the fraction of proline residues.

Returns:

Float between 0 and 1

Return type:

float

property hydrophobicity

Mean hydrophobicity of the sequence on the Kyte-Doolittle scale.

Returns the sequence-averaged per-residue hydrophobicity (the mean over all residues). Calculated on first access and cached. For a per-residue hydrophobicity track, use linear_sequence_profile() with mode='hydrophobicity'.

Returns:

Mean per-residue Kyte-Doolittle hydrophobicity.

Return type:

float

property complexity

Wootton-Federhen (SEG) compositional complexity of the sequence.

This is the Shannon-style compositional complexity used by the classic SEG algorithm; higher values indicate more compositionally diverse sequences. Calculated on first access and cached.

Returns:

Compositional complexity of the sequence (>= 0).

Return type:

float

compute_residue_fractions(residue_selector)[source]

Compute the total fraction of specified residue types in the protein sequence.

Parameters:

residue_selector (list) – A list of one or more residue types (amino acid codes) to query in the sequence.

Returns:

The sum of fractions for all specified residue types. Returns 0.0 if none of the specified residues are found in the sequence.

Return type:

float

Examples

>>> protein.compute_residue_fractions(['A', 'G'])
0.15
>>> protein.compute_residue_fractions(['X', 'Z'])
0.0
compute_kappa_x(group1, group2=None, window_size=6, flatten=True)[source]

User-facing high-performance implementation for generic calculation of kappa_x. We use this for calculating real kappa (where group1 and group2 are [‘E’,’D’] and [‘R’,’K’], respectively but the function can be used to calculate arbitrary kappa-based patterning.

NB1: kappa will return as -1 if

  1. the sequence is shorter than the window size

  2. There are no residues from either group1 or group2

The function will raise an exception if the windowsize is < 2

NB2: kappa is defined as comparing the ratio of delta with deltamax, where in this implementation deltamax refers to the delta associated with the most segregated sequence; e.g:

(AAA)n-(XXX)m-(BBB)p

Sometimes, when the charge asymmetry is VERY highly skewed, this most highly segregated sequence does not give the highest delta value, such that we can get a kappa greater than 1. This only occurs in situations where kappa is probably not a useful metric anyway (i.e 100x excess of one group residue vs. another). We recommend setting the ‘flatten’ keyword to True, which means kappa values over 1 will be flattened to 1.

NB3: this implementation differs very slightly from the canonical kappa reference implementation; it adds non-contributing ‘wings’ of the windowsize onto the N- and C-termini of the sequence. This means residue clusters at the end contribute to the overall sequence patterning as much as those in the middle, and also ensures we can analytically determine the deltamax sequence for arbitrary windowsizes.

This both addresses a previous (subtle) limitation in kappa, but also buys a ~100x speedup compared to previous reference implementations. As a final note, I (Alex) wrote the original reference implementation in localCIDER, so feel comfortable criticising its flaws!

NB4: If no residues are provided in group2 then the function assumes all residues not defined in group1 are in group2 and the function becomes a binary patterning function instead of a ternary patterning function.

Parameters:
  • group1 (str or list) – One or more valid amino acid one-letter codes defining the first residue set that patterning is computed for. If group2 is not provided, patterning is computed for group1 vs. all other residues.

  • group2 (str or list, optional) – If provided, defines the SECOND residue set, so patterning is computed for group1 vs. group2 against the background of all other residues. Default is None.

  • window_size (int, optional) – Window size over which local sequence patterning is calculated. Default is 6.

  • flatten (bool, optional) – If True, kappa values above 1 are flattened to 1. Default is True.

Returns:

The generalized kappa value. If flatten is True this is guaranteed to be between 0 and 1 (unless it is -1; see above). If flatten is False values above 1 are possible but indicate kappa is not a useful metric for the sequence.

Return type:

float

compute_iwd(target_residues)[source]

Returns the inverse weighted distance (IWD), a metric for residue clustering

Parameters:

target_residues (str or list) – One or more valid amino acid one-letter residue codes that define the target set for IWD clustering. This can be passed either as a joined string (for example "ILVAM") or as an iterable of residues (for example ["I", "L", "V", "A", "M"]).

Returns:

Float that is positive

Return type:

float

compute_patch_fraction(residue_selector, interruption=2, min_target_count=4, adjacent_pair_pattern=None, min_adjacent_pair_count=0)[source]

Returns the sequence fraction covered by residue patches.

Parameters:
  • residue_selector (str or list) – One or more amino acid one-letter residue codes defining patch hits.

  • interruption (int, optional) – Maximum number of non-target residues bridged inside a candidate patch. Default is 2.

  • min_target_count (int or None, optional) – Minimum number of target residues required for a bridged region to count as a patch. Default is 4. If set to None this filter is disabled.

  • adjacent_pair_pattern (str or list, optional) – Optional adjacent residue motif that must occur in a bridged region (for example "RG"). Default is None.

  • min_adjacent_pair_count (int, optional) – Minimum number of occurrences of adjacent_pair_pattern required for a bridged region to count. Default is 0.

Returns:

Fraction of sequence positions covered by valid patch spans.

Return type:

float

compute_rg_patch_fraction(interruption=2, min_adjacent_rg_pairs=2)[source]

Returns the sequence fraction covered by RG motif-enriched patches.

Parameters:
  • interruption (int, optional) – Maximum number of non-R/G residues bridged inside a candidate RG patch. Default is 2.

  • min_adjacent_rg_pairs (int, optional) – Minimum number of adjacent RG pairs required for a bridged region to count. Default is 2.

Returns:

Fraction of sequence positions covered by valid RG patch spans.

Return type:

float

extract_feature_vector(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]

Returns a grammar feature vector for the current sequence.

This is a convenience wrapper over sparrow.sequence_analysis.grammar.compute_feature_vector().

This feature extraction interface is currently alpha. Breaking changes to arguments, defaults, and returned feature schemas may occur in future releases.

This implementation is inspired by grammar-style analyses but is not an exact replica of the original NARDINI analysis pipeline.

Parameters:
  • patterning_config (GrammarPatterningConfig, optional) – Full patterning config for advanced control.

  • backend (str, optional) – Override patterning backend ("kappa_cython" or "iwd_combined").

  • num_scrambles (int, optional) – Number of sequence scrambles used for patterning z-score estimation.

  • blob_size (int, optional) – Patterning window size for kappa-style calculations.

  • min_fraction (float, optional) – Minimum group fraction required to evaluate a patterning feature.

  • seed (int, optional) – Random seed used for scramble generation.

  • fit_method (str, optional) – Distribution fit mode ("gamma_mle" or "moments").

  • composition_stats (GrammarCompositionStats, optional) – Optional composition/patch background statistics used to add composition z-scores. The default uses sparrow’s built-in human IDR composition background stats.

  • use_default_composition_stats (bool, optional) – If True and composition_stats is None, use Sparrow’s built-in human-IDR composition background stats. Default True.

  • include_raw (bool, optional) – Include raw feature block (raw:: keys). Default False.

  • return_array (bool, optional) – If True, return a NumPy array (np.float32) instead of an OrderedDict. Default True.

  • return_feature_names (bool, optional) – If True and return_array=True, also return an ordered tuple of feature names.

Returns:

Feature vector. Returns an array by default.

Return type:

numpy.ndarray or collections.OrderedDict

compute_SCD_x(group1, group2)[source]

Function that computes the sequence charge decoration (SCD) parameter of Sawle and Ghosh. This is an alternative sequence patterning parameter which we provide here generalized such that it determines the patterning between any two groups of residues.

Parameters:
  • group1 (str or list) – Collection of amino acids to be used for defining “negatively charged” residues.

  • group2 (str or list) – Collection of amino acids to be used for defining “positively charged” residues.

Returns:

The custom sequence charge decoration.

Return type:

float

See also

SCD

SCD computed with the default charge groups (E/D vs R/K).

References

Sawle, L. & Ghosh, K. A theoretical method to compute sequence-dependent configurational properties in charged polymers and proteins. J. Chem. Phys. 143, 085101 (2015).

compute_SHD_custom(hydro_dict)[source]

Sequence Hydropathy Decoration (SHD) using a custom hydrophobicity scale.

SHD quantifies the patterning of hydrophobic residues along the sequence, as defined by Zheng et al. (2020). The hydrophobicity values are supplied by the caller via hydro_dict.

Parameters:

hydro_dict (dict) – Dictionary mapping each amino acid one-letter code to a hydrophobicity score. Every residue present in the sequence must be a key in this dictionary or an exception is raised.

Returns:

The custom sequence hydropathy decoration.

Return type:

float

See also

SHD

SHD computed with the default (normalized Kyte-Doolittle) scale.

References

Zheng, W. et al. Hydropathy Patterning Complements Charge Patterning to Describe Conformational Preferences of Disordered Proteins. J. Phys. Chem. Lett. 11, 3408-3415 (2020).

compute_iwd_charged_weighted(charge=None)[source]

Charge-weighted inverse weighted distance (IWD) for one charge sign.

Quantifies the clustering of either the positive or the negative residues, with each residue’s contribution weighted by the local net charge per residue (NCPR, computed over a window of 8 with extended ends).

Parameters:

charge ({'-', '+'}) – Pass '-' to quantify clustering of negative residues, or '+' to quantify clustering of positive residues.

Returns:

A non-negative clustering value.

Return type:

float

Raises:

sparrow.sparrow_exceptions.ProteinException – If charge is not '-' or '+'.

compute_bivariate_iwd_charged_weighted()[source]

Charge-weighted bivariate inverse weighted distance (IWD).

Quantifies the spatial inter-mixing of positive and negative residues in the sequence, with each pair’s contribution weighted by the difference in local net charge per residue (NCPR, computed over a window of 8 with extended ends).

Returns:

A non-negative clustering value.

Return type:

float

generate_phosphoisoforms(mode='all', phospho_rate=1, phosphosites=None)[source]

Generate possible phosphoisoform sequences for the protein.

Each candidate phosphosite is replaced with the phosphomimetic 'E', enabling approximate calculation of charge-based sequence features in the presence of phosphorylated residues. See the sparrow.sequence_analysis.phospho_isoforms module for details.

Parameters:
  • mode (str, optional) –

    How candidate phosphosites are determined. Default is "all".

    • 'all' : Treats all S/T/Y residues as potential phosphosites.

    • 'predict' : Uses the PARROT-trained phosphorylation predictors to predict phosphosites from sequence.

    • 'custom' : Uses the phosphosites argument as the phosphosite indices.

  • phospho_rate (float, optional) – Value between 0 and 1 setting the maximum fraction of phosphosites that may be phosphorylated in each generated isoform. Default is 1 (all sites may be phosphorylated).

  • phosphosites (list, optional) – Custom list of phosphosite indices, used only when mode='custom'. Default is None.

Returns:

List of phosphoisoform sequences for the selected mode, with phosphorylated residues replaced by 'E'.

Return type:

list

linear_sequence_profile(mode, window_size=8, end_mode='extend-ends', smooth=None)[source]

Function that returns a vectorized representation of local composition/sequence properties, as defined by the passed ‘mode’, which acts as a selector toggle for a large set of pre-defined analyses types.

Parameters:
  • mode (str) –

    Selector for the type of analysis to perform:

    • 'FCR' : Fraction of charged residues

    • 'NCPR' : Net charge per residue

    • 'aromatic' : Fraction of aromatic residues

    • 'aliphatic' : Fraction of aliphatic residues

    • 'polar' : Fraction of polar residues

    • 'proline' : Fraction of proline residues

    • 'positive' : Fraction of positive residues

    • 'negative' : Fraction of negative residues

    • 'hydrophobicity' : Linear hydrophobicity (Kyte-Doolittle)

    • 'seg-complexity' : Linear complexity

    • 'kappa' : Linear charge patterning

  • window_size (int) – Number of residues over which local sequence properties are calculated. A window stepsize of 1 is always used.

  • end_mode (str) –

    Selector that defines how ends are dealt with. Default is 'extend-ends'.

    • 'extend-ends' : The leading/lagging track values are copied from the first and last values.

    • '' : Empty string means they’re ignored.

    • 'zero-ends' : Leading/lagging track values are set to zero.

  • smooth (int or None) – Selector which allows you to smooth the data over a windowsize. Note window must be an odd number (applies a savgol_filter with a 3rd order polynomial which requires an odd number).

Returns:

Per-position track values corresponding to the requested mode.

Return type:

numpy.ndarray

linear_composition_profile(composition_list, window_size=8, end_mode='extend-ends', smooth=None)[source]

Function that returns a vectorized representation of local composition/sequence properties, as defined by the set of one or more residues passed in composition_list.

Parameters:
  • composition_list (list) – List where each element should be a valid amino acid

  • window_size (int) – Number of residues over which local sequence properties are calculated. A window stepsize of 1 is always used

  • end_mode (str) –

    Selector that defines how ends are dealt with. Empty string means nothing is done, but extend-ends and zero-ends ensure the track length equals the sequence length which can often be useful. Default is ‘extend-ends’.

    ’extend-ends’ | The leading/lagging track values are copied from

    the first and last and values.

    ’’ | Empty string means they’re ignored,

    ’zero-ends’ | Means leading/lagging track values are set to zero.

  • smooth (int or None) – Selector which allows you to smooth the data over a windowsize. Note window must be an odd number (applies a savgol_filter with a 3rd order polynomial which requires an odd number).

Returns:

Per-position local density of the residues in composition_list.

Return type:

numpy.ndarray

linear_property_profile(mode, window_size=8, end_mode='extend-ends', smooth=None)[source]

Returns a vectorized representation of a numerical amino-acid property averaged over a sliding window. Each residue is mapped to a value taken from the AAindex1 database (see sparrow.data.aaindex) and the track reports the mean value within each window_size window.

This is the property-based analogue of linear_sequence_profile() and takes the same arguments; only mode differs, selecting an AAindex property instead of a built-in analysis.

Parameters:
  • mode (str) – Identifier of the AAindex property to use. This is either a slug of the form <meaning>-<first-author>-<year> (for example 'hydropathy-kyte-1982') or a raw AAindex accession (for example 'KYTJ820101'). Use sparrow.data.aaindex.list_property_indices() to enumerate the 500+ available indices, and see the property index reference in the documentation for a description of each.

  • window_size (int) – Number of residues over which the local mean is calculated. A window stepsize of 1 is always used. Default is 8.

  • end_mode (str) –

    Selector that defines how ends are handled. Default is 'extend-ends'.

    • 'extend-ends' : leading/lagging values copied from the first and last window values.

    • '' : ends are ignored (track is shorter than the sequence).

    • 'zero-ends' : leading/lagging values set to zero.

  • smooth (int or None) – Optional smoothing window. Must be an odd number (applies a savgol_filter with a 3rd order polynomial). Default is None.

Returns:

Per-position window-averaged property values.

Return type:

numpy.ndarray

Raises:
  • sparrow.sparrow_exceptions.ProteinException – If the selected index has no value for a residue present in the sequence.

  • sparrow.sparrow_exceptions.SparrowException – If mode matches no known property identifier or accession.

Examples

>>> p.linear_property_profile("hydropathy-kyte-1982", window_size=9)
array([...])
low_complexity_domains(mode='holt', **kwargs)[source]

Extract low complexity domains (LCDs) from the sequence.

Parameters:
  • mode ({'holt', 'holt-permissive'}) – Extraction method (both based on the Gutierrez et al. approach). 'holt' counts only target residues toward an LCD; in 'holt-permissive' bridged interruption residues also count toward the LCD length and fraction. Default is 'holt'.

  • **kwargs

    Passed through to the underlying extractor (sparrow.sequence_analysis.sequence_complexity.low_complexity_domains_holt() or its _permissive variant). Common options:

    residue_selectorstr

    One or more one-letter amino acid codes (e.g. 'Q' or 'ED').

    minimum_lengthint, default 15

    Minimum allowed LCD length.

    max_interruptionint, default 5

    Maximum number of consecutive residues NOT in residue_selector permitted inside an LCD (Gutierrez et al. used 17).

    fractional_thresholdfloat, default 0.25

    Minimum fraction (0-1) of residues from residue_selector required in the LCD.

Returns:

Each LCD represented as [sequence, start, end] where start is 0-indexed and end is exclusive (sequence[start:end] equals the LCD substring).

Return type:

list[list]

Examples

>>> p.low_complexity_domains(mode='holt', residue_selector='Q', minimum_length=10)
[['QQQQQQQQQQ', 5, 15]]
plaac_prion_like_domains(simple=True, **kwargs)[source]

Extract prion-like domains (PLDs) from the sequence using the PLAAC algorithm.

NB: We have re-implemented the PLAAC algorithm in pure Python, and this function provides a convenient wrapper for running PLAAC on the sequence. PLEASE CITE the original PLAAC paper (Lancaster et al. 2014) if you use this function in your work.

Parameters:
  • simple (bool, default True) – If True, returns a simplified output format (list of [sequence, start, end] for each PLD). If False, returns the full PLAAC output including scores and other metadata for each PLD.

  • **kwargs

    Passed through to sparrow.sequence_analysis.plaac.plaac.score_sequence(). Common options:

    alphafloat, default 1.0

    Mixing weight for S. cerevisiae vs. custom background frequencies. 1.0 uses pure S. cerevisiae background; 0.0 uses only the frequencies supplied via bg_freqs.

    core_lengthint, default 60

    Minimum contiguous prion-like domain length.

    window_fiint, default 41

    Window size for FoldIndex disorder smoothing.

    window_papaint, default 41

    Window size for PAPA propensity smoothing.

    adjust_prolinesbool, default True

    Apply PAPA proline-adjustment (skip PP / PXP repeats).

    bg_freqsdict[str, float], optional

    Background amino-acid frequency dictionary. Keys are one-letter amino acid codes (e.g. "A", "N", "Q"), values are the corresponding frequencies. Only the 20 standard residues (A C D E F G H I K L M N P Q R S T V W Y) should be provided; any missing residues default to 0.0.

    Example:

    bg_freqs={"A": 0.05, "N": 0.04, "Q": 0.04, ...}
    

    Defaults to S. cerevisiae proteome frequencies when None.

    fg_freqsdict[str, float], optional

    Foreground (prion-like) amino-acid frequency dictionary, same format as bg_freqs. Defaults to the Alberti et al. 28-domain S. cerevisiae prion frequencies when None.

Returns:

If simple is True, a list where each PLD is [sequence, start, end] with start 0-indexed and end exclusive (sequence[start:end] equals the PLD substring). If simple is False, the full PLAAC result object (scores and per-region metadata).

Return type:

list[list] or PLAAC result object

Examples

>>> p.plaac_prion_like_domains(core_length=60)
[['QQQQQQQQQQ', 5, 15]]
show_sequence(blocksize=10, newline=50, fontsize=14, font_family='Courier', colors={}, header=None, bold_positions=[], bold_residues=[], opaque_positions=[], return_raw_string=False, warnings=True)[source]

Function that generates an HTML colored string that either renders in the browser or returns the html string. Contains various customizable components.

Parameters:
  • blocksize (int) – Defines how big blocks of residues are. Blocks are equal to blocksize or the newline parameter, whicever is smaller. Default=10. If set to -1 uses length of the sequence.

  • newline (int) – Defines how many residues are shown before a newline is printed. Default is 50. If set to -1 uses the length of the sequence.

  • fontsize (int) – Fontsize used. Default is 14

  • font_family (str) – Which font family (from HTML fonts) is used. Using a non-monospace font makes no sense as columns will be unaligned. Default is Courier.

  • colors (dict) – Dictionary that allows overiding of default color scheme. Should be of format key-value as ‘residue’-‘color’ where residue is a residue in the string and color is a valid HTML color (which can be a Hexcode, standard HTML color name). Note that this also lets you define colors for non-standard amino acids should these be useful. Default is an empty dictionary. Note also that the standard amino acid colorings are defined at sparrow.data.amino_acids.AA_COLOR

  • header (str) – If provided, a string giving a FASTA-style header (include the leading caret yourself). Default None.

  • bold_positions (list) – List of positions (indexing from 1 onwards) which will be bolded. Useful for highlighting specific regions. Note that this defines individual residues so (for example) to bold residues 10 to 15 would require bold_positions=[10,11,12,13,14,15]. Default is an empty list.

  • bold_residues (list) – List of residue types that can be bolded. Useful for highlighting specific residue groups. Default is an empty list.

  • opaque_positions (list) – List of positions (indexing from 1 onwards) which will be greyed out and slightly opaque. Useful for de-emphasizing specific regions. Note that this defines individual residues so (for example) to grey out residues 10 to 15 would require opaque_positions=[10,11,12,13,14,15]. Default is an empty list.

  • return_raw_string (bool) – If set to true, the function returns the actual raw HTML string, as opposed to an in-notebook rendering. Default is False

  • warnings (bool) – If set to True, will print warnings if an invalid amino acid is encountered. Default is True.

Returns:

If return_raw_string is set to True then an HTML-compatible string is returned.

Return type:

None or str

Raises:

sparrow.sparrow_exceptions.SparrowException – Raises a sparrow exception if invalid input is provided (within reason).

property plugin

Access to sparrow’s sequence-analysis plugins.

The manager is created on first access and cached.

Returns:

Object providing programmatic access to the plugins implemented in sparrow.

Return type:

sparrow.sequence_analysis.plugins.PluginManager

property predictor

Access to sparrow’s sequence-based (PARROT/ALBATROSS) predictors.

The predictor object is created on first access and cached, and each underlying network is loaded lazily on its first use.

Currently available predictors include:

  • disorder : per-residue disorder prediction

  • dssp : per-residue DSSP secondary-structure class

  • nes : nuclear export signal

  • nls : nuclear import signal

  • phosphorylation : serine / threonine / tyrosine

  • pscore : phase-separation propensity

  • tad : transactivation domains

  • mitochondrial_targeting

  • transmembrane_regions

  • rg / re : radius of gyration / end-to-end distance

  • asphericity, prefactor, scaling_exponent

Returns:

Object providing programmatic access to the predictors.

Return type:

sparrow.predictors.Predictor

property polymeric

Access to predicted polymer properties for the sequence.

Many of these properties are only meaningful if the sequence behaves as an intrinsically disordered or unfolded polypeptide. The object is created on first access and cached.

Returns:

Object providing programmatic access to the predicted polymer properties.

Return type:

sparrow.polymer.Polymeric

property elms

Returns a list of NamedTuples containing each of the elm annotations for the given sequence.

Returns:

A list of NamedTuples containing all possible elms in a given sequence.

Return type:

List[NamedTuple]

property sequence

Returns a string representation of the protein sequence.

Returns:

The protein sequence.

Return type:

str

The predictor accessor

Reached as protein.predictor. See also the developer guide for adding a predictor.

The polymeric accessor

Reached as protein.polymeric.