core.alignment.Alignment
core.alignment.Alignment(seqs_data, slice_record=None, **kwargs)A collection of aligned sequences.
Notes
Should be constructed using make_aligned_seqs().
Attributes
| Name | Description |
|---|---|
| annotation_db | the annotation database for the collection |
| array_positions | Returns a numpy array of positions, axis 0 is alignment positions |
| array_seqs | Returns a numpy array of sequences, axis 0 is seqs in order |
| modified | collection is a modification of underlying storage |
| name_map | returns mapping of seq names to parent seq names |
| names | returns the names of the sequences in the collection |
| num_seqs | the number of sequences in the collection |
| seqs | iterable of sequences in the collection |
| storage | the aligned sequence storage instance of the collection |
Methods
| Name | Description |
|---|---|
| add_feature | add feature on named sequence, or on the alignment itself |
| add_seqs | Returns new collection with additional sequences. |
| alignment_quality | Computes the alignment quality using the indicated app |
| apply_scaled_gaps | applies gaps in self to ungapped sequences |
| coevolution | performs pairwise coevolution measurement |
| copy | creates new instance, only mutable attributes are copied |
| copy_annotations | copy annotations into attached annotation db |
| count_ambiguous_per_seq | Return the counts of ambiguous characters per sequence as a DictArray. |
| count_gaps_per_pos | return counts of gaps per position as a DictArray |
| count_gaps_per_seq | return counts of gaps per sequence as a DictArray |
| counts | counts of motifs |
| counts_per_pos | return MotifCountsArray of counts per position |
| counts_per_seq | counts of non-overlapping motifs per sequence |
| deepcopy | returns deep copy of self |
| degap | returns collection sequences without gaps or missing characters. |
| distance_matrix | Returns pairwise distances between sequences. |
| dotplot | make a dotplot between two sequences. |
| drop_duplicated_seqs | returns self without duplicated sequences |
| duplicated_seqs | returns the names of duplicated sequences |
| entropy_per_pos | returns shannon entropy per position |
| entropy_per_seq | Returns the Shannon entropy per sequence. |
| filtered | The alignment positions where predicate(column) is true. |
| get_ambiguous_positions | Returns dict of seq:{position:char} for ambiguous chars. |
| get_degapped_relative_to | Remove all columns with gaps in sequence with given name. |
| get_drawable | make a figure from sequence features |
| get_drawables | returns a dict of drawables, keyed by type |
| get_features | yields Feature instances |
| get_gap_array | returns bool array with gap state True, False otherwise |
| get_gapped_seq | Return a gapped Sequence object for the specified seqname. |
| get_identical_sets | returns sets of names for sequences that are identical |
| get_motif_probs | Return a dictionary of motif probs, calculated as the averaged |
| get_position_indices | Returns list of column indices for which f(col) is True. |
| get_projected_feature | returns an alignment feature projected onto the seqid sequence |
| get_projected_features | projects all features from other sequences onto seqid |
| get_seq | Return a Sequence object for the specified seqname. |
| get_seq_names_if | Returns list of names of seqs where f(seq) is True. |
| get_similar | Returns new SequenceCollection containing sequences similar to target. |
| has_annotation_db | returns True if self has annotation db |
| has_terminal_stop | Returns True if any sequence has a terminal stop codon. |
| information_plot | plot information per position |
| is_ragged | by definition False for an Alignment |
| iter_positions | Iterates over positions in the alignment, in order. |
| iter_seqs | Iterates over sequences in the collection, in order. |
| iupac_consensus | Returns string containing IUPAC consensus sequence of the alignment. |
| majority_consensus | Returns consensus sequence containing most frequent item at each |
| make_feature | create a feature on named sequence, or on the alignment itself |
| matching_ref | Returns new alignment with seqs well aligned with a reference. |
| no_degenerates | returns new alignment without degenerate characters |
| omit_bad_seqs | Returns new alignment without sequences with a number of uniquely |
| omit_gap_pos | Returns new alignment where all cols (motifs) have <= allowed_gap_frac gaps. |
| pad_seqs | Returns copy in which sequences are padded with the gap character to same length. |
| probs_per_pos | returns MotifFreqsArray per position |
| probs_per_seq | return frequency array of motifs per sequence |
| quick_tree | Returns a phylogenetic tree. |
| rc | Returns the reverse complement of all sequences in the alignment. |
| renamed_seqs | Returns new alignment with renamed sequences. |
| replace_annotation_db | public interface to assigning the annotation_db |
| reverse_complement | Returns the reverse complement of all sequences in the collection. |
| sample | Returns random sample of positions from self, e.g. to bootstrap. |
| seqlogo | returns Drawable sequence logo using mutual information |
| sliding_windows | Generator yielding new alignments of given length and interval. |
| strand_symmetry | returns dict of strand symmetry test results per ungapped seq |
| take_positions | Returns new Alignment containing only specified positions. |
| take_positions_if | Returns new Alignment containing cols where f(col) is True. |
| take_seqs | Returns new collection containing only specified seqs. |
| take_seqs_if | Returns new collection containing seqs where f(seq) is True. |
| to_dict | Return a dictionary of sequences. |
| to_dna | returns copy of self as a collection of DNA moltype seqs |
| to_fasta | Return collection in Fasta format. |
| to_html | returns html with embedded styles for sequence colouring |
| to_json | returns json formatted string |
| to_moltype | returns copy of self with changed moltype |
| to_phylip | Return collection in PHYLIP format and mapping to sequence ids |
| to_pretty | returns a string representation of the alignment in pretty print format |
| to_rich_dict | returns a json serialisable dict |
| to_rna | returns copy of self as a collection of RNA moltype seqs |
| variable_positions | Return a list of variable position indexes. |
| with_masked_annotations | returns an alignment with regions replaced by mask_char |
| write | Write the sequences to a file, preserving order of sequences. |
add_feature
core.alignment.Alignment.add_feature(
seqid=None,
biotype,
name,
spans,
parent_id=None,
strand='+',
on_alignment=None,
**kwargs,
)add feature on named sequence, or on the alignment itself
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqid | str | None | sequence name, incompatible with on_alignment | None |
| parent_id | str | None | name of the parent feature | None |
| biotype | str | biological type, e.g. CDS | required |
| name | str | name of the feature | required |
| spans | list[tuple[int, int]] | plus strand coordinates of feature | required |
| strand | str | int | ‘+’ (default) or ‘-’ | '+' |
| on_alignment | bool | None | the feature is in alignment coordinates, incompatible with setting seqid. Set to True if seqid not provided. | None |
Returns
| Name | Type | Description |
|---|---|---|
| Feature |
Raises
| Name | Type | Description |
|---|---|---|
| ValueError if define a seqid not on alignment or use seqid and | ||
| on_alignment. |
add_seqs
core.alignment.Alignment.add_seqs(seqs, **kwargs)Returns new collection with additional sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqs | dict[str, str | bytes | NumpyIntArrayType] | sequences to add | required |
alignment_quality
core.alignment.Alignment.alignment_quality(app_name='ic_score', **kwargs)Computes the alignment quality using the indicated app
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| app_name | str | name of an alignment score calculating app, e.g. ‘ic_score’, ‘cogent3_score’, ‘sp_score’ | 'ic_score' |
| kwargs | Any | keyword arguments to be passed to the app. Use cogent3.app_help(app_name) to see the available options. |
{} |
Returns
| Name | Type | Description |
|---|---|---|
| float or a NotCompleted instance if the score could not be computed |
apply_scaled_gaps
core.alignment.Alignment.apply_scaled_gaps(other, aa_to_codon=True)applies gaps in self to ungapped sequences
coevolution
core.alignment.Alignment.coevolution(
stat='nmi',
segments=None,
drawable=None,
show_progress=False,
parallel=False,
par_kw=None,
)performs pairwise coevolution measurement
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| stat | str | coevolution metric, defaults to ‘nmi’ (Normalized Mutual Information). Valid choices are ‘rmi’ (Resampled Mutual Information) and ‘mi’, mutual information. | 'nmi' |
| segments | list[tuple[int, int]] | None | coordinates of the form [(start, end), …] where all possible pairs of alignment positions within and between segments are examined. | None |
| drawable | str | None | Result object is capable of plotting data specified type. str value must be one of plot type ‘box’, ‘heatmap’, ‘violin’. | None |
| show_progress | bool | Progress | dict[str, Any] | shows a progress bar. | False |
| parallel | bool | run in parallel using numba thread-level parallelism (prange). | False |
| par_kw | dict[str, Any] | None | max_workers sets the number of numba threads. use_mpi=True raises NotImplementedError. Other keys are silently ignored. |
None |
Returns
| Name | Type | Description |
|---|---|---|
| DictArray of results with lower-triangular values. Upper triangular | ||
| elements and estimates that could not be computed for numerical reasons | ||
| are set as nan |
copy
core.alignment.Alignment.copy(copy_annotations=False)creates new instance, only mutable attributes are copied
copy_annotations
core.alignment.Alignment.copy_annotations(seq_db)copy annotations into attached annotation db
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seq_db | AnnotationDbABC | compatible annotation db | required |
Notes
Only copies annotations for records with seqid in self.names
count_ambiguous_per_seq
core.alignment.Alignment.count_ambiguous_per_seq()Return the counts of ambiguous characters per sequence as a DictArray.
count_gaps_per_pos
core.alignment.Alignment.count_gaps_per_pos(include_ambiguity=True)return counts of gaps per position as a DictArray
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| include_ambiguity | bool | if True, ambiguity characters that include the gap state are included | True |
count_gaps_per_seq
core.alignment.Alignment.count_gaps_per_seq(
induced_by=False,
unique=False,
include_ambiguity=True,
drawable=None,
)return counts of gaps per sequence as a DictArray
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| induced_by | bool | a gapped column is considered to be induced by a seq if the seq has a non-gap character in that column. | False |
| unique | bool | count is limited to gaps uniquely induced by each sequence | False |
| include_ambiguity | bool | if True, ambiguity characters that include the gap state are included | True |
| drawable | str | None | if True, resulting object is capable of plotting data via specified plot type ‘bar’, ‘box’ or ‘violin’ | None |
counts
core.alignment.Alignment.counts(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
exclude_unobserved=False,
)counts of motifs
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | number of elements per character. | 1 |
| include_ambiguity | bool | if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. | False |
| allow_gap | bool | if True, motifs containing a gap character are included. | False |
| exclude_unobserved | bool | if True, unobserved motif combinations are excluded. | False |
Notes
only non-overlapping motifs are counted
counts_per_pos
core.alignment.Alignment.counts_per_pos(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
warn=False,
)return MotifCountsArray of counts per position
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | number of elements per character. | 1 |
| include_ambiguity | bool | if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. | False |
| allow_gap | bool | if True, motifs containing a gap character are included. | False |
| warn | bool | warns if motif_length > 1 and alignment trimmed to produce motif columns | False |
counts_per_seq
core.alignment.Alignment.counts_per_seq(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
exclude_unobserved=False,
warn=False,
)counts of non-overlapping motifs per sequence
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | number of elements per character. | 1 |
| include_ambiguity | bool | if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. | False |
| allow_gap | bool | if True, motifs containing a gap character are included. | False |
| exclude_unobserved | bool | if False, all canonical states included | False |
| warn | bool | warns if motif_length > 1 and alignment trimmed to produce motif columns | False |
deepcopy
core.alignment.Alignment.deepcopy(**kwargs)returns deep copy of self
Notes
Reduced to sliced sequences in self, kwargs are ignored. Annotation db is not copied if the alignment has been sliced.
degap
core.alignment.Alignment.degap(storage_backend=None, **kwargs)returns collection sequences without gaps or missing characters.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| storage_backend | str | None | name of the storage backend to use for the SeqsData object, defaults to cogent3 builtin. | None |
| kwargs | Any | keyword arguments for the storage driver | {} |
Notes
The returned collection will not retain an annotation_db if present.
distance_matrix
core.alignment.Alignment.distance_matrix(
calc='pdist',
drop_invalid=False,
parallel=False,
**kwargs,
)Returns pairwise distances between sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| calc | str | a pairwise distance calculator name. Presently only ‘pdist’, ‘jc69’, ‘tn93’, ‘hamming’, ‘paralinear’ are supported. | 'pdist' |
| drop_invalid | bool | If True, sequences for which a pairwise distance could not be calculated are excluded. If False, an ArithmeticError is raised if a distance could not be computed on observed data. | False |
dotplot
core.alignment.Alignment.dotplot(
name1=None,
name2=None,
window=20,
threshold=None,
k=None,
min_gap=0,
width=500,
title=None,
rc=False,
biotype=None,
show_progress=False,
)make a dotplot between two sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| name1 | str | None | names of sequences – if not provided, a random choice is made | None |
| name2 | str | None | names of sequences – if not provided, a random choice is made | None |
| window | int | segment size for comparison between sequences | 20 |
| threshold | int | None | windows where the sequences are identical >= threshold are a match | None |
| k | int | None | size of k-mer to break sequences into. Larger values increase speed but reduce resolution. If not specified, and window == threshold, then k is set to window. Otherwise, it is computed as the maximum of {threshold // (window - threshold), 5}. | None |
| min_gap | int | permitted gap for joining adjacent line segments, default is no gap joining | 0 |
| width | int | figure width. Figure height is computed based on the ratio of len(seq1) / len(seq2) | 500 |
| title | str | None | title for the plot | None |
| rc | bool | include dotplot of reverse compliment also. Only applies to Nucleic acids moltypes | False |
| biotype | str | tuple[str] | None | if selected sequences are annotated, display only these biotypes | None |
Returns
| Name | Type | Description |
|---|---|---|
| a Drawable or AnnotatedDrawable |
drop_duplicated_seqs
core.alignment.Alignment.drop_duplicated_seqs()returns self without duplicated sequences
Notes
Retains the first sequence of each duplicte group.
duplicated_seqs
core.alignment.Alignment.duplicated_seqs()returns the names of duplicated sequences
Notes
The gapped sequence is used.
entropy_per_pos
core.alignment.Alignment.entropy_per_pos(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
warn=False,
)returns shannon entropy per position
entropy_per_seq
core.alignment.Alignment.entropy_per_seq(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
exclude_unobserved=True,
warn=False,
)Returns the Shannon entropy per sequence.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | number of characters per tuple. | 1 |
| include_ambiguity | bool | if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. | False |
| allow_gap | bool | if True, motifs containing a gap character are included. | False |
| exclude_unobserved | bool | if True, unobserved motif combinations are excluded. | True |
| warn | bool | warns if motif_length > 1 and alignment trimmed to produce motif columns | False |
Notes
For motif_length > 1, it’s advisable to specify exclude_unobserved=True, this avoids unnecessary calculations.
filtered
core.alignment.Alignment.filtered(
predicate,
motif_length=1,
drop_remainder=True,
**kwargs,
)The alignment positions where predicate(column) is true.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| predicate | Callable[[list[Aligned]], bool] | a callback function that takes an tuple of motifs and returns True/False | required |
| motif_length | int | length of the motifs the sequences should be split into, eg. 3 for filtering aligned codons. | 1 |
| drop_remainder | bool | If length is not modulo motif_length, allow dropping the terminal remaining columns | True |
get_ambiguous_positions
core.alignment.Alignment.get_ambiguous_positions()Returns dict of seq:{position:char} for ambiguous chars.
Used in likelihood calculations.
get_degapped_relative_to
core.alignment.Alignment.get_degapped_relative_to(name)Remove all columns with gaps in sequence with given name.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| name | str | sequence name | required |
Notes
The returned alignment will not retain an annotation_db if present.
get_drawable
core.alignment.Alignment.get_drawable(
biotype=None,
width=600,
vertical=False,
title=None,
)make a figure from sequence features
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| biotype | str | tuple[str, …] | list[str] | set[str] | None | passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included. | None |
| width | float | width in pixels | 600 |
| vertical | int | rotates the drawable | False |
| title | str | None | title for the plot | None |
Returns
| Name | Type | Description |
|---|---|---|
| a Drawable instance |
get_drawables
core.alignment.Alignment.get_drawables(biotype=None)returns a dict of drawables, keyed by type
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| biotype | str | tuple[str, …] | list[str] | set[str] | None | passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included. | None |
get_features
core.alignment.Alignment.get_features(
seqid=None,
biotype=None,
name=None,
allow_partial=False,
on_alignment=None,
limit=None,
**kwargs,
)yields Feature instances
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqid | str | Iterator[str] | None | limit search to features on this named sequence, defaults to search all | None |
| biotype | str | tuple[str, …] | list[str] | set[str] | None | biotype of the feature, e.g. CDS, gene | None |
| name | str | None | name of the feature | None |
| on_alignment | bool | None | limit query to features on Alignment, ignores sequences. Ignored on SequenceCollection instances. | None |
| allow_partial | bool | allow features partially overlaping self | False |
| limit | int | None | maximum total number of features to yield across sequence-level and alignment-level features. If None, all matching features are returned. Must be positive. | None |
Notes
When dealing with a nucleic acid moltype, the returned features will yield a sequence segment that is consistently oriented irrespective of strand of the current instance.
get_gap_array
core.alignment.Alignment.get_gap_array(include_ambiguity=True)returns bool array with gap state True, False otherwise
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| include_ambiguity | bool | if True, ambiguity characters that include the gap state are included | True |
get_gapped_seq
core.alignment.Alignment.get_gapped_seq(seqname, recode_gaps=False)Return a gapped Sequence object for the specified seqname.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqname | str | sequence name | required |
| recode_gaps | bool | if True, gap characters are replaced by the most general ambiguity code, e.g. N for DNA and RNA | False |
Notes
This method breaks the connection to the annotation database.
get_identical_sets
core.alignment.Alignment.get_identical_sets(mask_degen=False)returns sets of names for sequences that are identical
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| mask_degen | bool | if True, degenerate characters are ignored | False |
get_motif_probs
core.alignment.Alignment.get_motif_probs(
alphabet=None,
include_ambiguity=False,
exclude_unobserved=False,
allow_gap=False,
pseudocount=0,
)Return a dictionary of motif probs, calculated as the averaged frequency across sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| alphabet | c3_alphabet.CharAlphabet[Any] | None | alphabet to use for motifs | None |
| include_ambiguity | bool | if True resolved ambiguous codes are included in estimation of frequencies. | False |
| exclude_unobserved | bool | if True, motifs that are not present in the alignment are excluded from the returned dictionary. | False |
| allow_gap | bool | allow gap motif | False |
| pseudocount | int | value to add to each count | 0 |
Notes
only non-overlapping motifs are counted
get_position_indices
core.alignment.Alignment.get_position_indices(f, negate=False)Returns list of column indices for which f(col) is True.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| f | Callable[[PySeq[str]], bool] | function that returns true/false given an alignment position | required |
| negate | bool | if True, not f() is used | False |
get_projected_feature
core.alignment.Alignment.get_projected_feature(seqid, feature)returns an alignment feature projected onto the seqid sequence
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqid | str | name of the sequence to project the feature onto | required |
| feature | Feature[Alignment] | a Feature, bound to self, that will be projected | required |
Returns
| Name | Type | Description |
|---|---|---|
| a new Feature bound to seqid |
Notes
The alignment coordinates of feature are converted into the seqid sequence coordinates and the object is bound to that sequence.
The feature is added to the annotation_db.
get_projected_features
core.alignment.Alignment.get_projected_features(seqid, **kwargs)projects all features from other sequences onto seqid
get_seq
core.alignment.Alignment.get_seq(seqname, copy_annotations=False)Return a Sequence object for the specified seqname.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seqname | str | name of the sequence to return | required |
| copy_annotations | bool | if True, only the annotations for the specified sequence are copied to the annotation database of the Sequence object which is decoupled from this collection. If False, the connection to this collections db is retained. | False |
get_seq_names_if
core.alignment.Alignment.get_seq_names_if(f, negate=False)Returns list of names of seqs where f(seq) is True.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| f | Callable[[TSequenceOrAligned], bool] | function that takes a sequence object and returns True or False | required |
| negate | bool | select all sequences EXCEPT those where f(seq) is True | False |
Notes
Sequence objects can be converted into strings or numpy arrays using str() and numpy.array() respectively.
get_similar
core.alignment.Alignment.get_similar(
target,
min_similarity=0.0,
max_similarity=1.0,
metric=cast('Callable[[Any, Any], float]', c3_sequence.frac_same),
transform=None,
)Returns new SequenceCollection containing sequences similar to target.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| target | c3_sequence.Sequence | Aligned | sequence object to compare to. Can be in the collection. | required |
| min_similarity | float | minimum similarity that will be kept. Default 0.0. | 0.0 |
| max_similarity | float | maximum similarity that will be kept. Default 1.0. | 1.0 |
| metric | Callable[[c3_sequence.Sequence | Aligned, c3_sequence.Sequence | Aligned], float] | a similarity function to use. Must be f(first_seq, second_seq). The default metric is fraction similarity, ranging from 0.0 (0% identical) to 1.0 (100% identical). The Sequence class have lots of methods that can be passed in as unbound methods to act as the metric, e.g. frac_same_gaps. | cast('Callable[[Any, Any], float]', c3_sequence.frac_same) |
| transform | Callable[[c3_sequence.Sequence | Aligned], c3_sequence.Sequence | Aligned] | None | transformation function to use on the sequences before the metric is calculated. If None, uses the whole sequences in each case. A frequent transformation is a function that returns a specified range of a sequence, e.g. eliminating the ends. Note that the transform applies to both the real sequence and the target sequence. | None |
Notes
both min_similarity and max_similarity are inclusive.
Warnings
if the transformation changes the type of the sequence (e.g. extracting a string from an RnaSequence object), distance metrics that depend on instance data of the original class may fail.
has_annotation_db
core.alignment.Alignment.has_annotation_db()returns True if self has annotation db
has_terminal_stop
core.alignment.Alignment.has_terminal_stop(gc=1, strict=False)Returns True if any sequence has a terminal stop codon.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| gc | GeneticCodeTypes | valid input to cogent3.get_code(), a genetic code object, number or name | 1 |
| strict | bool | If True, raises an exception if a seq length not divisible by 3 | False |
information_plot
core.alignment.Alignment.information_plot(
width=None,
height=None,
window=None,
stat='median',
include_gap=True,
)plot information per position
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| width | int | None | figure width in pixels | None |
| height | int | None | figure height in pixels | None |
| window | int | None | used for smoothing line, defaults to sqrt(length) | None |
| stat | str | ‘mean’ or ’median, used as the summary statistic for each window | 'median' |
| include_gap | bool | whether to include gap counts, shown on right y-axis | True |
is_ragged
core.alignment.Alignment.is_ragged()by definition False for an Alignment
iter_positions
core.alignment.Alignment.iter_positions(pos_order=None)Iterates over positions in the alignment, in order.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| pos_order | list[int | slice | FeatureMap] | range | None | list of indices specifying the column order. If None, the positions are iterated in order. | None |
Returns
| Name | Type | Description |
|---|---|---|
| yields lists of elemenets for each position (column) in the alignment |
iter_seqs
core.alignment.Alignment.iter_seqs(seq_order=None)Iterates over sequences in the collection, in order.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| seq_order | Iterable[str | int] | None | list of seqids giving the order in which seqs will be returned. Defaults to self.names | None |
iupac_consensus
core.alignment.Alignment.iupac_consensus(allow_gap=True)Returns string containing IUPAC consensus sequence of the alignment.
majority_consensus
core.alignment.Alignment.majority_consensus()Returns consensus sequence containing most frequent item at each position.
make_feature
core.alignment.Alignment.make_feature(feature, on_alignment=None, **kwargs)create a feature on named sequence, or on the alignment itself
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| feature | FeatureDataType | a dict with all the necessary data rto construct a feature | required |
| on_alignment | bool | None | the feature is in alignment coordinates, incompatible with setting ‘seqid’. Set to True if ‘seqid’ not provided. | None |
Returns
| Name | Type | Description |
|---|---|---|
| Feature |
Raises
| Name | Type | Description |
|---|---|---|
| ValueError if define a 'seqid' not on alignment or use 'seqid' and | ||
| on_alignment. |
Notes
To get a feature AND add it to annotation_db, use add_feature().
matching_ref
core.alignment.Alignment.matching_ref(ref_name, gap_fraction, gap_run)Returns new alignment with seqs well aligned with a reference.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ref_name | str | name of the sequence to use as the reference | required |
| gap_fraction | float | fraction of positions that either have a gap in the template but not in the seq or in the seq but not in the template | required |
| gap_run | int | number of consecutive gaps tolerated in query relative to sequence or sequence relative to query | required |
no_degenerates
core.alignment.Alignment.no_degenerates(motif_length=1, allow_gap=False)returns new alignment without degenerate characters
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | sequences are segmented into units of this size and the segments are excluded if they contain degenerate characters. | 1 |
| allow_gap | bool | whether gaps are allowed or whether they are treated as a degenerate character (latter is default, as most evolutionary modelling treats gaps as N). | False |
omit_bad_seqs
core.alignment.Alignment.omit_bad_seqs(quantile=None)Returns new alignment without sequences with a number of uniquely introduced gaps exceeding quantile
Uses count_gaps_per_seq(unique=True) to obtain the counts of gaps uniquely introduced by a sequence. The cutoff is the quantile of this distribution.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| quantile | float | None | sequences whose unique gap count is in a quantile larger than this cutoff are excluded. The default quantile is (num_seqs - 1) / num_seqs | None |
omit_gap_pos
core.alignment.Alignment.omit_gap_pos(allowed_gap_frac=None, motif_length=1)Returns new alignment where all cols (motifs) have <= allowed_gap_frac gaps.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| allowed_gap_frac | float | None | specifies proportion of gaps is allowed in each column. Set to 0 to exclude columns with any gaps, 1 to include all columns. Default is None which is equivalent to (num_seqs-1)/num_seqs and leads to elimination of columns that are only gaps. | None |
| motif_length | int | set’s the “column” width, e.g. setting to 3 corresponds to codons. A motif that includes a gap at any position is included in the counting. | 1 |
pad_seqs
core.alignment.Alignment.pad_seqs(pad_length=None)Returns copy in which sequences are padded with the gap character to same length.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| pad_length | int | None | Length all sequences are to be padded to. Will pad to max sequence length if pad_length is None or less than max length. | None |
probs_per_pos
core.alignment.Alignment.probs_per_pos(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
warn=False,
)returns MotifFreqsArray per position
probs_per_seq
core.alignment.Alignment.probs_per_seq(
motif_length=1,
include_ambiguity=False,
allow_gap=False,
exclude_unobserved=False,
warn=False,
)return frequency array of motifs per sequence
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| motif_length | int | number of characters per motif | 1 |
| include_ambiguity | bool | if True, include motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. | False |
| allow_gap | bool | if True, include motifs containing a gap character | False |
| exclude_unobserved | bool | if True, exclude motifs not present in the sequences in the resulting array | False |
| warn | bool | warns if motif_length > 1 and collection trimmed to produce motif columns. | False |
quick_tree
core.alignment.Alignment.quick_tree(
calc='pdist',
drop_invalid=False,
parallel=False,
use_hook=None,
)Returns a phylogenetic tree.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| calc | str | a pairwise distance calculator or name of one. For options see cogent3.evolve.fast_distance.available_distances | 'pdist' |
| drop_invalid | bool | If True, sequences for which a pairwise distance could not be calculated are excluded. If False, an ArithmeticError is raised if a distance could not be computed on observed data. | False |
| parallel | bool | parallel execution of distance calculations | False |
| use_hook | str | None | name of a third-party package that implements the quick_tree hook. If not specified, defaults to the first available hook or the cogent3 quick_tree() app. To force default, set use_hook=“cogent3”. | None |
Returns
| Name | Type | Description |
|---|---|---|
| a phylogenetic tree |
rc
core.alignment.Alignment.rc()Returns the reverse complement of all sequences in the alignment. A synonym for reverse_complement.
renamed_seqs
core.alignment.Alignment.renamed_seqs(renamer)Returns new alignment with renamed sequences.
replace_annotation_db
core.alignment.Alignment.replace_annotation_db(value, check=True)public interface to assigning the annotation_db
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| value | AnnotationDbABC | list[AnnotationDbABC] | None | the annotation db instance | required |
| check | bool | whether to check value supports the feature interface | True |
Notes
The check can be very expensive, so if you’re confident set it to False
reverse_complement
core.alignment.Alignment.reverse_complement()Returns the reverse complement of all sequences in the collection. A synonym for rc.
sample
core.alignment.Alignment.sample(
n=None,
with_replacement=False,
motif_length=1,
randint=numpy.random.randint,
permutation=numpy.random.permutation,
)Returns random sample of positions from self, e.g. to bootstrap.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| n | int | None | number of positions to sample. If None, all positions are sampled. | None |
| with_replacement | bool | if True, samples with replacement. | False |
| motif_length | int | number of positions to sample as a single motif. | 1 |
| randint | Callable[[int, int | None, int | None], NumpyIntArrayType] | random number generator, default is numpy.randint | numpy.random.randint |
| permutation | Callable[[int], NumpyIntArrayType] | function to generate a random permutation of positions, default is numpy.permutation | numpy.random.permutation |
Notes
By default (resampling all positions without replacement), generates a permutation of the positions of the alignment.
Setting with_replacement to True and otherwise leaving parameters as defaults generates a standard bootstrap resampling of the alignment.
seqlogo
core.alignment.Alignment.seqlogo(
width=700,
height=100,
wrap=None,
vspace=0.005,
colours=None,
)returns Drawable sequence logo using mutual information
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| width | float | plot dimensions in pixels | 700 |
| height | float | plot dimensions in pixels | 700 |
| wrap | int | None | number of alignment columns per row | None |
| vspace | float | vertical separation between rows, as a proportion of total plot | 0.005 |
| colours | dict[str, str] | None | mapping of characters to colours. If note provided, defaults to custom for everything ecept protein, which uses protein moltype colours. | None |
Notes
Computes MI based on log2 and includes the gap state, so the maximum possible value is -log2(1/num_states)
sliding_windows
core.alignment.Alignment.sliding_windows(window, step, start=None, end=None)Generator yielding new alignments of given length and interval.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| window | int | The length of each returned alignment. | required |
| step | int | The interval between the start of the successive windows. | required |
| start | int | None | first window start position | None |
| end | int | None | last window start position | None |
strand_symmetry
core.alignment.Alignment.strand_symmetry(motif_length=1)returns dict of strand symmetry test results per ungapped seq
take_positions
core.alignment.Alignment.take_positions(cols, negate=False)Returns new Alignment containing only specified positions.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| cols | list[int] | NumpyIntArrayType | list of column indices to keep | required |
| negate | bool | if True, all columns except those in cols are kept | False |
take_positions_if
core.alignment.Alignment.take_positions_if(f, negate=False)Returns new Alignment containing cols where f(col) is True.
take_seqs
core.alignment.Alignment.take_seqs(
names,
negate=False,
copy_annotations=False,
**kwargs,
)Returns new collection containing only specified seqs.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| names | str | PySeq[str] | sequences to select (or exclude if negate=True) | required |
| negate | bool | select all sequences EXCEPT names | False |
| kwargs | Any | keyword arguments to be passed to the constructor of the new collection | {} |
| copy_annotations | bool | if True, only annotations from selected seqs are copied to the annotation_db of the new collection | False |
take_seqs_if
core.alignment.Alignment.take_seqs_if(f, negate=False)Returns new collection containing seqs where f(seq) is True.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| f | Callable[[TSequenceOrAligned], bool] | function that takes a sequence object and returns True or False | required |
| negate | bool | select all sequences EXCEPT those where f(seq) is True | False |
Notes
Sequence objects can be converted into strings or numpy arrays using str() and numpy.array() respectively.
to_dict
core.alignment.Alignment.to_dict(as_array=False)Return a dictionary of sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| as_array | bool | if True, sequences are returned as numpy arrays, otherwise as strings | False |
to_dna
core.alignment.Alignment.to_dna()returns copy of self as a collection of DNA moltype seqs
to_fasta
core.alignment.Alignment.to_fasta(block_size=60)Return collection in Fasta format.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| block_size | int | the sequence length to write to each line, by default 60 | 60 |
Returns
| Name | Type | Description |
|---|---|---|
| The collection in Fasta format. |
to_html
core.alignment.Alignment.to_html(
name_order=None,
wrap=60,
limit=None,
colors=None,
font_size=12,
font_family='Lucida Console',
*,
ref_name='longest',
**kwargs,
)returns html with embedded styles for sequence colouring
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| name_order | PySeq[str] | None | order of names for display. | None |
| wrap | int | number of alignment columns per row | 60 |
| limit | int | None | truncate alignment to this length | None |
| ref_name | str | Name of an existing sequence or ‘longest’. If the latter, the longest sequence (excluding gaps and ambiguities) is selected as the reference. | 'longest' |
| colors | Mapping[str, str] | None | {character moltype. | None |
| font_size | int | in points. Affects labels and sequence and line spacing (proportional to value) | 12 |
| font_family | str | string denoting font family | 'Lucida Console' |
Examples
In a jupyter notebook, this code is used to provide the representation.
.. code-block:: python
aln # is rendered by jupyter
You can directly use the result for display in a notebook as
.. code-block:: python
from IPython.core.display import HTML
HTML(aln.to_html())
to_json
core.alignment.Alignment.to_json()returns json formatted string
to_moltype
core.alignment.Alignment.to_moltype(moltype)returns copy of self with changed moltype
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| moltype | MolTypes | name of the new moltype, e.g, ‘dna’, ‘rna’. | required |
Notes
Cannot convert from nucleic acids to proteins. Use get_translation() for that.
to_phylip
core.alignment.Alignment.to_phylip()Return collection in PHYLIP format and mapping to sequence ids
Notes
raises exception if sequences do not all have the same length
to_pretty
core.alignment.Alignment.to_pretty(name_order=None, wrap=None)returns a string representation of the alignment in pretty print format
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| name_order | list[str] | None | order of names for display. | None |
| wrap | int | None | maximum number of printed bases | None |
to_rich_dict
core.alignment.Alignment.to_rich_dict()returns a json serialisable dict
to_rna
core.alignment.Alignment.to_rna()returns copy of self as a collection of RNA moltype seqs
variable_positions
core.alignment.Alignment.variable_positions(
include_gap_motif=True,
include_ambiguity=False,
motif_length=1,
)Return a list of variable position indexes.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| include_gap_motif | bool | if False, sequences with a gap motif in a column are ignored. | True |
| include_ambiguity | bool | if True, all states are considered. | False |
| motif_length | int | if any position within a motif is variable, the entire motif is considered variable. | 1 |
Returns
| Name | Type | Description |
|---|---|---|
| tuple of integers, if motif_length > 1, the returned positions are | ||
| motif_length long sequential indices. |
Notes
Truncates alignment to be modulo motif_length.
with_masked_annotations
core.alignment.Alignment.with_masked_annotations(
biotypes,
mask_char='?',
shadow=False,
seqid=None,
)returns an alignment with regions replaced by mask_char
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| biotypes | PySeq[str] | annotation type(s) | required |
| mask_char | str | must be a character valid for the moltype. The default value is the most ambiguous character, eg. ‘?’ for DNA | '?' |
| shadow | bool | If True, masks everything but the biotypes | False |
| seqid | str | None | name of sequence to mask, defaults to all | None |
write
core.alignment.Alignment.write(filename, format_name=None, **kwargs)Write the sequences to a file, preserving order of sequences.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| filename | str | name of the sequence file | required |
| format_name | str | None | format of the sequence file | None |
Notes
If format_name is None, will attempt to infer format from the filename suffix.