<jupyter_start><jupyter_text>HOWTO: Reading alignments<jupyter_code># Generate random FASTA alignment of 3 samples, 9 characters long to use as an example
import random

def generate_random_alignment(num_samples, seq_len, bases='ATCG'):
    sequences = ['' for i in range(num_samples)]
    for i in range(seq_len):
        char1 = random.choice(bases)
        if random.random() > 0.5:  # >0.5 means variable
            # Pick another character
            char2 = random.choice(bases)
            freq1 = random.randint(1, num_samples-1)
            freq2 = num_samples - freq1
        else:
            char2 = ''
            freq1, freq2 = num_samples, 0
        for j1 in range(freq1):
            sequences[j1] += char1
        for j2 in range(freq1, freq1+freq2):
            sequences[j2] += char2
    return sequences

def generate_random_fasta(path, num_samples, seq_len, bases='ATCG'):
    sequences = generate_random_alignment(num_samples, seq_len, bases=bases)
    with open(path, 'w') as f:
        for i, seq in enumerate(sequences):
            if i == 1:
                print('>seq{i}\n{s}'.format(i=i+1, s=seq), file=f)
            else:
                print('>seq{i} description{i}\n{s}'.format(i=i+1, s=seq), file=f)

path = 'test.aln'
generate_random_fasta(path, 3, 9)
# Prints the contents of test.aln
with open('test.aln', 'r') as f:
    for line in f:
        print(line.rstrip())<jupyter_output>>seq1 description1
AACAATCGG
>seq2
TACAATCGG
>seq3 description3
TACAATGGG<jupyter_text>Import the `Alignment` object from `alignmentrs``alignmentrs` is the package containing all the classes and methods for reading and manipulating a multiple sequence alignment.The `Alignment` class is used to create an alignment object that contains the information about a multiple sequence alignment, from its sequences to sample names and related metadata.<jupyter_code>from alignmentrs import Alignment<jupyter_output><empty_output><jupyter_text>Open FASTA file using `Alignment.from_fasta`The `Alignment` class contains methods to import data encoded in various formats. `Alignment` class import method names begin with `from`...- `from_dict` imports data formatted as a dictionary- `from_fasta` imports FASTA-formatted string or a FASTA file- `from_json` imports a JSON-formatted string or a JSON file- `from_pickle` imports a pickled alignment objectIn this example, `from_fasta` is used to import an existing FASTA file as an `Alignment` object.<jupyter_code>aln = Alignment.from_fasta(path)<jupyter_output><empty_output><jupyter_text>Inspecting the contents of the alignment The `Alignment` object encapsulates the alignment sequence matrix, sequence identifiers and descriptions (known as row metadata), site annotations (known as column metadata), and comments and descriptions for the entire alignment (known as alignment metadata. AttributesThese can be readily accessed as attributes of the `Alignment` object:- `.data` shows the underlying sequence matrix as a `SeqMatrix` object- `.row_metadata` shows sequence identifiers and other row-related metadata as a pandas `DataFrame`- `.column_metadata` shows site annotations and other column-related metadata as a pandas `DataFrame`- `.alignment_metadata` shows alignment comments and other alignment-related information as a `dict`<jupyter_code># Sequence matrix
aln.data
# Row metadata
aln.row_metadata
# Column metadata
aln.column_metadata<jupyter_output><empty_output><jupyter_text>PropertiesThe `Alignment` object has several properties used to describe its contents:- `.nrows` shows the number samples are present in the alignment.- `.ncols` shows the number of aligned characters in the alignment.- `.sequences` returns the sequences in the alignment as a list of strings.- `.row_and_metadata` returns a new pandas `DataFrame` that joins row metadata with its corresponding a sequence.- `.column_and_metadata` returns a new pandas `DataFrame` that joins column metadata with the sequence at the particular site.<jupyter_code># Number of samples
aln.nrows
# Number of aligned columns
aln.ncols
# Sequences
aln.sequences
# Combined row metadata and sequence
aln.row_and_metadata
# Combined column metadata and sequence
aln.column_and_metadata<jupyter_output><empty_output><jupyter_text>Accessing rows and columnsA row refers to individual sequence of a sample or record in the sequene alignment. These records may be different gene sequences or sequences from different organisms that were aligned using a multiple sequence alignment software (ClustalX, MAFFT, MrBayes, etc.)A column refers to the vertical list of characters found for each single-character column in the alignment. Concretely, a column is the list of nth character for each sample in the sequence alignment.To access rows and columns, `Alignment` as `.row` and `.col` properties for rows and columns respectively. Rows and columns are indexed by integers starting from 0 and uses Python indexing conventions.  Retrieving rows<jupyter_code># Retrieving the sequence of the first sample in the alignment
aln.row[0]
# Retrieving the sequence of the last sample in the alignment containing 3 samples
aln.row[2]
# Retrieving the sequence of the last sample in the alignment containing 3 samples
# using negative indexing
aln.row[-1]
# Retrieving the first 2 sequences in the alignment using a slice
aln.row[0:2]<jupyter_output><empty_output><jupyter_text>Retrieving columns<jupyter_code># Retrieving the first character of each of the 3 samples in the alignment
aln.col[0]
# Retrieving the last character of each of the 3 samples in the alignment
# where all samples are 9 characters long
aln.col[8]
# Retrieving the last character of all 3 samples in the alignment
# where all samples are 9 characters long using negative indexing
aln.col[-1]
# Retrieving the first 2 characters of each of the 3 sample in the alignment using a slice
aln.col[0:2]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07117497886728656, 'fraction_numerical': 0.009805579036348266, 'mean_word_length': 4.661244019138756, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '522051', 'license': 'MIT', 'n_tokens_mistral': 1677, 'n_tokens_neox': 1611, 'n_words': 688, 'path': 'examples/01_Reading_alignments.ipynb', 'repo_name': 'yamasampo/alignmentrs', 'size': '5915'}