MSA

The MSA module of MIToS has utilities for working with Multiple Sequence Alignments of protein Sequences (MSA).

using MIToS.MSA # to load the MSA module

Features

Contents

MSA IO

Reading MSA files

The main function for reading MSA files in MIToS is read and it is defined in the Utils module. This function takes a filename/path as a first argument followed by other arguments. It opens the file and uses the arguments to call the parse function. read decides how to open the file, using the prefixes (e.g. https) and suffixes (i.e. extensions) of the file name, while parse does the actual parsing of the file. You can readgzipped files if they have the .gz extension and also urls pointing to a web file. The second argument of read and parse is the file FileFormat. The supported MSA formats at the moment are Stockholm, FASTA, PIR (NBRF) and Raw. For example, reading with MIToS the full Stockholm MSA of the family PF07388 using the Pfam RESTful interface will be:

using MIToS.MSA

read("http://pfam.xfam.org/family/PF07388/alignment/full", Stockholm)
AnnotatedMultipleSequenceAlignment with 633 annotations : 610×310 Named Matrix{MIToS.MSA.Residue}
                Seq ╲ Col │  232   233   234   235  …  1150  1151  1152  1153
──────────────────────────┼──────────────────────────────────────────────────
A0A4R4NVL5_9ACTN/20-355   │    Q     I     F     E  …     -     -     -     -
A0A1G9EU47_9GAMM/4-312    │    N     L     F     V        L     -     -     -
A0A2T0MTV3_9ACTN/2-311    │    -     V     F     Y        S     Y     -     -
A0A561TEV1_9ACTN/6-327    │    Q     I     F     Q        -     -     -     -
A0A2S8WMS7_9MICC/3-321    │    -     L     I     A        -     -     -     -
A0A1Y4FDM4_9FIRM/15-307   │    -     -     -     -        -     -     -     -
A1ATF7_PELPD/200-311      │    -     -     -     -        -     -     -     -
A0A2S4XWD6_9ACTN/16-332   │    Q     I     F     F        -     -     -     -
⋮                              ⋮     ⋮     ⋮     ⋮  ⋱     ⋮     ⋮     ⋮     ⋮
A0A2S4YZT7_9ACTN/8-320    │    -     I     F     C        -     -     -     -
A0A2S5T452_9BURK/210-312  │    -     -     -     -        -     -     -     -
A0A0N0TTD0_9ACTN/1-308    │    -     -     -     -        -     -     -     -
A0A657AJS7_9GAMM/5-300    │    -     -     -     -        -     -     -     -
K9TZG0_CHRTP/9-325        │    -     L     V     A        -     -     -     -
A0A0L0K2N6_9ACTN/6-319    │    Q     I     Y     V        -     -     -     -
A0A0F7N7H1_9ACTN/7-329    │    Q     I     F     E        -     -     -     -
A0A2P2GGG4_9ACTN/8-328    │    Q     I     F     Q  …     -     -     -     -

The third (and optional) argument of read and parse is the output MSA type:

  • Matrix{Residue} : It only contains the aligned sequences.
  • MultipleSequenceAlignment : It contains the aligned sequences and their

names/identifiers.

  • AnnotatedMultipleSequenceAlignment : It's the richest MIToS' MSA format and it's the

default. It includes the aligned sequences, their names and the MSA annotations.

Example of Matrix{Residue} output using a Stockholm file as input:

read("http://pfam.xfam.org/family/PF07388/alignment/full", Stockholm, Matrix{Residue})
610×310 Matrix{MIToS.MSA.Residue}:
 Q  I  F  E  V  S  T  L  Y  G  A  A  T  …  A  Y  Y  S  I  P  -  -  -  -  -  -
 N  L  F  V  V  E  S  P  L  Q  A  L  S     V  M  F  D  C  F  S  I  L  -  -  -
 -  V  F  Y  A  S  T  L  F  G  V  M  S     R  Y  F  G  L  P  V  A  S  Y  -  -
 Q  I  F  Q  V  S  T  L  Y  G  A  A  T     A  Y  Y  D  V  P  V  A  -  -  -  -
 -  L  I  A  A  S  T  A  Y  Q  V  A  S     Q  L  F  D  M  P  -  -  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -  …  -  -  -  -  -  -  -  -  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -     Q  I  Y  P  Q  -  -  -  -  -  -  -
 Q  I  F  F  A  S  T  L  Y  G  A  A  T     A  F  Y  G  L  P  A  -  -  -  -  -
 N  I  F  I  F  S  S  P  L  Q  F  L  F     S  L  L  K  I  T  S  Y  E  C  L  -
 -  -  -  -  -  -  -  -  -  -  -  -  -     -  -  -  -  -  -  -  -  -  -  -  -
 ⋮              ⋮              ⋮        ⋱        ⋮              ⋮           
 -  -  Y  F  I  S  S  P  L  H  F  F  I     W  L  R  P  D  I  R  V  E  T  L  -
 -  I  F  C  A  S  T  L  Y  G  A  A  T     A  L  Y  G  L  P  V  A  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -     Q  L  Y  G  E  G  T  -  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -     V  Y  Y  G  V  P  V  A  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -  …  L  I  F  G  D  -  -  -  -  -  -  -
 -  L  V  A  C  Q  G  S  I  Q  L  I  T     -  -  -  -  -  -  -  -  -  -  -  -
 Q  I  Y  V  A  S  T  L  Y  G  V  A  T     E  F  Y  G  I  P  V  A  -  -  -  -
 Q  I  F  E  V  S  T  L  Y  G  A  A  T     T  L  Y  G  I  P  V  A  -  -  -  -
 Q  I  F  Q  V  S  T  L  Y  G  A  A  T     V  Y  Y  G  V  P  V  A  -  -  -  -

Because read calls parse, you should look into the documentation of parse to know the available keyword arguments. The optional keyword arguments of those functions are:

  • generatemapping : If generatemapping is true (default: false), sequences and

columns mappings are generated and saved in the MSA annotations. The default is false to not overwrite mappings by mistake when you read an annotated MSA file saved with MIToS.

  • useidcoordinates : If useidcoordinates is true (default: false) and the names

have the form seqname/start-end, MIToS uses this coordinates to generate sequence mappings. This is safe and useful with unmodified Pfam MSAs. Do not use it when reading an MSA saved with MIToS. MIToS deletes unaligned insert columns, therefore disrupts sequences that have them.

  • deletefullgaps : Given that lowercase characters and dots are converted to gaps,

unaligned insert columns in the MSA (derived from a HMM profile) are converted into full gap columns. deletefullgaps is true by default, deleting full gaps columns and therefore insert columns.

Note

If you want to keep the insert columns... Use the keyword argument keepinserts to true in read/parse. This only works with an AnnotatedMultipleSequenceAlignment output. A column annotation ("Aligned") is stored in the annotations, where insert columns are marked with 0 and aligned columns with 1.

When read returns an AnnotatedMultipleSequenceAlignment, it uses the MSA Annotations to keep track of performed modifications. To access these notes, use printmodifications:

msa = read("http://pfam.xfam.org/family/PF01565/alignment/full", Stockholm)

printmodifications(msa)
-------------------
2021-05-26T22:58:44.264

deletefullgaps!  :  Deletes 898 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
-------------------
2021-05-26T22:58:44.435

filtercolumns! : 898 s have been deleted.

Writing MSA files

Julia REPL shows MSAs as Matrices. If you want to print them in another format, you should use the print function with an MSA object as first argument and the FileFormatFASTA, Stockholm, PIR or Raw as second argument.

using MIToS.MSA

msa = read("http://pfam.xfam.org/family/PF16996/alignment/full", Stockholm) # reads a Stockholm MSA file

print(msa, FASTA) # prints msa in FASTA format
>A0A139NMD7_9STRE/5-59
KDDIFYKDIEGRMDELKRKPPKKEKKTRAERISTFFSVSLGLVILIGLLFTLFRI
>A0A139NPI6_9STRE/5-59
NEDLFYKEVEGRMADLQQKAPEKEKKTGAERLNTLFSLALGLVILLGLLFTLLRM
>A0A0F3HAA3_STRPA/8-62
KKDLFYKEVEGRMESLKRRPAEKEKTTRSEKINVTFNVIIGLVILLGVIFTLFRV
>A0A4Q0VKA2_9LACO/6-62
KKDMLTHDISSRMKQEKRKVPARENETGGKALNITISVAIAIIVLAGILYPLV--
>A0A139NTT2_9STRE/3-57
KKDLFYKDVEQKLDSLKQGQPKKEKASLGEKLNKAFVIALGLVILIGLIFTLIG-
>A8AWV6_STRGC/3-57
KKDLFYKDIEGRLDELKHGRPKKEKASLGEKFNKAFVIALGLMILIGLIFTLIGV
>F9Q2V2_STROR/1-43
------------MEELKQGALKKEKPTRGEKISKTFSILLGMLILLTLIFTLLGI
>A3CM62_STRSV/3-57
KKDLFYKDIEGRLDELKHGKPKKEKASLGENLNKAFVIVLGLMILIGLIFTLIG-

To save an MSA object to a file, use the write function. This function takes a filename as a first argument. If the filename ends with .gz, the output will be a compressed (gzipped) file. The next two arguments of write are passed to print, so write behaves as print.

write("msa.gz", msa, FASTA) # writes msa in FASTA format in a gzipped file

MSA Annotations

MSA annotations are based on the Stockholm format mark-ups. There are four types of annotations stored as dictionaries. All the annotations have a feature name as part of the key, which should be a single "word" (without spaces) and less than 50 characters long.

  • File annotations : The annotations can contain either file or MSA information. They

have feature names as keys and the values are strings (free text). Lines starting with #=GF in Stockholm format.

  • Column annotations : They have feature names as keys and strings with exactly 1 char

per column as values. Lines starting with #=GC in Stockholm format.

  • Sequence annotations : The keys are tuples with the sequence name and the feature

name. The values are free text (strings). Lines starting with #=GS in Stockholm format. Annotations in the PIR/NBRF format are also stored as sequence annotations. In particular, we use the names "Type" and "Title" to name the sequence type in the identifier line and the first comment line before the sequence in PIR files, respectively.

  • Residue annotations : The keys are tuples with the sequence name and the feature

name. The values are strings with exactly 1 char per column/residues. #=GR lines in Stockholm format.

Julia REPL shows the Annotations type as they are represented in the Stockholm format. You can get the Annotations inside an annotated MSA or sequence using the annotations function.

annotations(msa)
#=GF ID	Asp4
#=GF AC	PF16996.7
#=GF DE	Accessory secretory protein Sec Asp4
#=GF AU	Coggill P;0000-0001-5731-1588
#=GF SE	Pfam-B_7603 (release 27.0)
#=GF GA	27.70 27.70;
#=GF TC	29.00 28.80;
#=GF NC	25.50 25.40;
#=GF BM	hmmbuild HMM.ann SEED.ann
#=GF SM	hmmsearch -Z 57096847 -E 1000 --cpu 4 HMM pfamseq
#=GF TP	Family
#=GF RN	[1]
#=GF RM	23000954
#=GF RT	Emerging themes in SecA2-mediated protein export.
#=GF RA	Feltcher ME, Braunstein M;
#=GF RL	Nat Rev Microbiol. 2012;10:779-789.
#=GF DR	INTERPRO; IPR031551;
#=GF DR	SO; 0100021; polypeptide_conserved_region;
#=GF CC	Asp4 and Asp5 are putative accessory components of the SecY2
#=GF CC	channel of the SecA2-SecY2 mediated export system, but they are
#=GF CC	not present in all SecA2-SecY2 systems. This family of Asp4 is
#=GF CC	found in Firmicutes [1].
#=GF SQ	8
#=GF MIToS_2021-05-26T22:58:44.689	deletefullgaps!  :  Deletes 4 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2021-05-26T22:58:44.690	filtercolumns! : 4 s have been deleted.
#=GS A3CM62_STRSV/3-57	AC	A3CM62.1
#=GS A0A139NTT2_9STRE/3-57	AC	A0A139NTT2.1
#=GS A0A139NMD7_9STRE/5-59	AC	A0A139NMD7.1
#=GS F9Q2V2_STROR/1-43	AC	F9Q2V2.1
#=GS A0A4Q0VKA2_9LACO/6-62	AC	A0A4Q0VKA2.1
#=GS A0A139NPI6_9STRE/5-59	AC	A0A139NPI6.1
#=GS A0A0F3HAA3_STRPA/8-62	AC	A0A0F3HAA3.1
#=GS A8AWV6_STRGC/3-57	AC	A8AWV6.1
#=GC seq_cons			KKDLFYKDlEGRM--LK+tsPKKEKsTtGE+lNpsFsluLGLlILlGLIFTLlth

Particular annotations can be accessed using the functions getannot.... These functions take the MSA/sequence as first argument and the feature name of the desired annotation as the last. In the case of getannotsequence and getannotresidue, the second argument should be the sequence name.

getannotsequence(msa, "A0A139NPI6_9STRE/5-59", "AC") # ("A0A139NPI6_9STRE/5-59", "AC") is the key in the dictionary
"A0A139NPI6.1"

If you want to add new annotations, you should use the setannot…! functions. These functions have the same arguments that getannot... functions except for an extra argument used to indicate the new annotation value.

setannotsequence!(msa, "A0A139NPI6_9STRE/5-59", "New_Feature_Name", "New_Annotation")
"New_Annotation"

A getannot... function without the key (last arguments), returns the particular annotation dictionary. As you can see, the new sequence annotation is now part of our MSA annotations.

getannotsequence(msa)
Dict{Tuple{String, String}, String} with 9 entries:
  ("A3CM62_STRSV/3-57", "AC")                   => "A3CM62.1"
  ("A0A139NTT2_9STRE/3-57", "AC")               => "A0A139NTT2.1"
  ("A0A139NMD7_9STRE/5-59", "AC")               => "A0A139NMD7.1"
  ("F9Q2V2_STROR/1-43", "AC")                   => "F9Q2V2.1"
  ("A0A4Q0VKA2_9LACO/6-62", "AC")               => "A0A4Q0VKA2.1"
  ("A0A139NPI6_9STRE/5-59", "AC")               => "A0A139NPI6.1"
  ("A0A0F3HAA3_STRPA/8-62", "AC")               => "A0A0F3HAA3.1"
  ("A8AWV6_STRGC/3-57", "AC")                   => "A8AWV6.1"
  ("A0A139NPI6_9STRE/5-59", "New_Feature_Name") => "New_Annotation"

Editing your MSA

MIToS offers functions to edit your MSA. Because these functions modify the msa, their names end with a bang !, following the Julia convention. Some of these functions have an annotate keyword argument (in general, it's true by default) to indicate if the modification should be recorded in the MSA/sequence annotations.

One common task is to delete sequences or columns of the MSA. This could be done using the functions filtersequences! and filtercolumns!. These functions take the MSA or sequence (if it's possible) as first argument and a BitVector or Vector{Bool} mask as second argument. It deletes all the sequences or columns where the mask is false. These functions are also defined for Annotations, this allows to automatically update (modify) the annotations (and therefore, sequence and column mappings) in the MSA.

This two deleting operations are used in the second and third mutating functions of the following list:

  • setreference! : Sets one of the sequences as the first sequence of the MSA (query or

reference sequence).

  • adjustreference! : Deletes columns with gaps in the first sequence of the MSA

(reference).

  • gapstrip! : This function first calls adjustreference!, then deletes sequences with

low (user defined) MSA coverage and finally, columns with user defined % of gaps.

Also, there are several available funtions shuffle_…!. These functions are useful to generate random alignments. The Information module of MIToS uses them to calculate the Z scores of MI values.

Example: Deleting sequences

For example, if you want to keep only the proteins from Actinobacteria you can delete all the sequences that don't have _9ACTN in their UniProt entry names:

using MIToS.MSA

msa = read("http://pfam.xfam.org/family/PF07388/alignment/full", Stockholm)

sequencenames(msa) # the function sequencenames returns the sequence names in the MSA
610-element Vector{String}:
 "A0A4R4NVL5_9ACTN/20-355"
 "A0A1G9EU47_9GAMM/4-312"
 "A0A2T0MTV3_9ACTN/2-311"
 "A0A561TEV1_9ACTN/6-327"
 "A0A2S8WMS7_9MICC/3-321"
 "A0A1Y4FDM4_9FIRM/15-307"
 "A1ATF7_PELPD/200-311"
 "A0A2S4XWD6_9ACTN/16-332"
 "A0A099Y4C6_9FLAO/4-292"
 "K9TTY0_CHRTP/9-335"
 ⋮
 "A0A657AKB5_9GAMM/3-322"
 "A0A2S4YZT7_9ACTN/8-320"
 "A0A2S5T452_9BURK/210-312"
 "A0A0N0TTD0_9ACTN/1-308"
 "A0A657AJS7_9GAMM/5-300"
 "K9TZG0_CHRTP/9-325"
 "A0A0L0K2N6_9ACTN/6-319"
 "A0A0F7N7H1_9ACTN/7-329"
 "A0A2P2GGG4_9ACTN/8-328"
mask = map(x -> occursin(r"_9ACTN", x), sequencenames(msa)) # an element of mask is true if "_9ACTN" is in the name
610-element Vector{Bool}:
 1
 0
 1
 1
 0
 0
 0
 1
 0
 0
 ⋮
 0
 1
 0
 1
 0
 0
 1
 1
 1
filtersequences!(msa, mask) # deletes all the sequences where mask is false

sequencenames(msa)
308-element Vector{String}:
 "A0A4R4NVL5_9ACTN/20-355"
 "A0A2T0MTV3_9ACTN/2-311"
 "A0A561TEV1_9ACTN/6-327"
 "A0A2S4XWD6_9ACTN/16-332"
 "A0A0N0N9N0_9ACTN/3-323"
 "A0A0B5DET6_9ACTN/6-318"
 "A0A2T7SMV9_9ACTN/17-330"
 "A0A327WAZ1_9ACTN/6-318"
 "A0A1H6EY13_9ACTN/2-310"
 "A0A371PTE8_9ACTN/8-320"
 ⋮
 "A0A384IRZ7_9ACTN/75-335"
 "A0A3N6EG16_9ACTN/8-323"
 "A0A5P0YVM1_9ACTN/6-329"
 "A0A6G4X6U8_9ACTN/10-325"
 "A0A2S4YZT7_9ACTN/8-320"
 "A0A0N0TTD0_9ACTN/1-308"
 "A0A0L0K2N6_9ACTN/6-319"
 "A0A0F7N7H1_9ACTN/7-329"
 "A0A2P2GGG4_9ACTN/8-328"

Example: Exporting a MSA for freecontact (part I)

The most simple input for the command line tool freecontact (if you don't want to set --mincontsep) is a Raw MSA file with a reference sequence without insertions or gaps. This is easy to get with MIToS using read (deletes the insert columns), setreference! (to choose a reference), adjustreference! (to delete columns with gaps in the reference) and write (to save it in Raw format) functions.

julia> using MIToS.MSA

julia> msa = read("http://pfam.xfam.org/family/PF02476/alignment/full", Stockholm)
AnnotatedMultipleSequenceAlignment with 46 annotations : 25×126 Named Matrix{MIToS.MSA.Residue}
               Seq ╲ Col │   9   10   11   12   13  …  195  196  197  198  199
─────────────────────────┼────────────────────────────────────────────────────
US02_GAHVM/120-237       │   M    L    E    S    E  …    F    C    C    -    -
Q782M7_9ALPH/120-237     │   M    L    E    S    D       F    C    C    W    -
A0A1R3T8S2_9ALPH/119-225 │   -    -    -    -    -       -    -    -    -    -
B1A4T1_9ALPH/119-238     │   H    L    S    S    G       A    C    C    I    -
A0A286MM82_9ALPH/107-180 │   -    L    H    T    D       -    -    -    -    -
Q8V727_CHV1/110-256      │   -    L    C    E    P       P    C    V    A    C
E2IUH4_SHV1/110-233      │   -    -    -    -    -       -    -    -    -    -
A0A060Q503_9ALPH/110-250 │   -    L    H    G    P       S    C    P    A    -
⋮                            ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
J9R0A8_9ALPH/178-313     │   -    -    -    -    -       -    -    -    -    -
A0A1V0M8M6_9ALPH/120-239 │   Y    L    E    S    G       L    C    C    -    -
Q67639_ILTV/100-201      │   H    L    S    S    G       -    -    -    -    -
Q5PP72_9ALPH/135-256     │   Y    L    N    S    G       R    C    T    I    -
Q6R5Q3_9ALPH/120-237     │   M    L    E    S    E       F    C    C    -    -
H9E969_HHV1/110-247      │   -    L    H    R    D       P    C    C    A    C
US02_EHV1B/111-262       │   H    L    N    S    S       -    -    -    -    -
A0A455JKG4_9ALPH/102-211 │   L    L    N    R    G  …    -    -    -    -    -

julia> msa_coverage = coverage(msa)
25×1 Named Matrix{Float64}
          Seq ╲ Function │ coverage
─────────────────────────┼─────────
US02_GAHVM/120-237       │ 0.904762
Q782M7_9ALPH/120-237     │ 0.928571
A0A1R3T8S2_9ALPH/119-225 │  0.65873
B1A4T1_9ALPH/119-238     │ 0.912698
A0A286MM82_9ALPH/107-180 │ 0.515873
Q8V727_CHV1/110-256      │ 0.992063
E2IUH4_SHV1/110-233      │ 0.801587
A0A060Q503_9ALPH/110-250 │ 0.984127
⋮                                 ⋮
J9R0A8_9ALPH/178-313     │ 0.761905
A0A1V0M8M6_9ALPH/120-239 │ 0.928571
Q67639_ILTV/100-201      │ 0.325397
Q5PP72_9ALPH/135-256     │ 0.880952
Q6R5Q3_9ALPH/120-237     │ 0.904762
H9E969_HHV1/110-247      │  0.97619
US02_EHV1B/111-262       │ 0.873016
A0A455JKG4_9ALPH/102-211 │ 0.738095

julia> maxcoverage, maxindex = findmax(msa_coverage) # chooses the sequence with more coverage of the MSA
(0.9920634920634921, CartesianIndex(6, 1))

julia> setreference!(msa, maxindex[1])
AnnotatedMultipleSequenceAlignment with 47 annotations : 25×126 Named Matrix{MIToS.MSA.Residue}
               Seq ╲ Col │   9   10   11   12   13  …  195  196  197  198  199
─────────────────────────┼────────────────────────────────────────────────────
Q8V727_CHV1/110-256      │   -    L    C    E    P  …    P    C    V    A    C
Q782M7_9ALPH/120-237     │   M    L    E    S    D       F    C    C    W    -
A0A1R3T8S2_9ALPH/119-225 │   -    -    -    -    -       -    -    -    -    -
B1A4T1_9ALPH/119-238     │   H    L    S    S    G       A    C    C    I    -
A0A286MM82_9ALPH/107-180 │   -    L    H    T    D       -    -    -    -    -
US02_GAHVM/120-237       │   M    L    E    S    E       F    C    C    -    -
E2IUH4_SHV1/110-233      │   -    -    -    -    -       -    -    -    -    -
A0A060Q503_9ALPH/110-250 │   -    L    H    G    P       S    C    P    A    -
⋮                            ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
J9R0A8_9ALPH/178-313     │   -    -    -    -    -       -    -    -    -    -
A0A1V0M8M6_9ALPH/120-239 │   Y    L    E    S    G       L    C    C    -    -
Q67639_ILTV/100-201      │   H    L    S    S    G       -    -    -    -    -
Q5PP72_9ALPH/135-256     │   Y    L    N    S    G       R    C    T    I    -
Q6R5Q3_9ALPH/120-237     │   M    L    E    S    E       F    C    C    -    -
H9E969_HHV1/110-247      │   -    L    H    R    D       P    C    C    A    C
US02_EHV1B/111-262       │   H    L    N    S    S       -    -    -    -    -
A0A455JKG4_9ALPH/102-211 │   L    L    N    R    G  …    -    -    -    -    -

julia> adjustreference!(msa)
AnnotatedMultipleSequenceAlignment with 48 annotations : 25×125 Named Matrix{MIToS.MSA.Residue}
               Seq ╲ Col │  10   11   12   13   14  …  195  196  197  198  199
─────────────────────────┼────────────────────────────────────────────────────
Q8V727_CHV1/110-256      │   L    C    E    P    R  …    P    C    V    A    C
Q782M7_9ALPH/120-237     │   L    E    S    D    V       F    C    C    W    -
A0A1R3T8S2_9ALPH/119-225 │   -    -    -    -    -       -    -    -    -    -
B1A4T1_9ALPH/119-238     │   L    S    S    G    I       A    C    C    I    -
A0A286MM82_9ALPH/107-180 │   L    H    T    D    D       -    -    -    -    -
US02_GAHVM/120-237       │   L    E    S    E    V       F    C    C    -    -
E2IUH4_SHV1/110-233      │   -    -    -    -    -       -    -    -    -    -
A0A060Q503_9ALPH/110-250 │   L    H    G    P    R       S    C    P    A    -
⋮                            ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
J9R0A8_9ALPH/178-313     │   -    -    -    -    -       -    -    -    -    -
A0A1V0M8M6_9ALPH/120-239 │   L    E    S    G    I       L    C    C    -    -
Q67639_ILTV/100-201      │   L    S    S    G    A       -    -    -    -    -
Q5PP72_9ALPH/135-256     │   L    N    S    G    A       R    C    T    I    -
Q6R5Q3_9ALPH/120-237     │   L    E    S    E    V       F    C    C    -    -
H9E969_HHV1/110-247      │   L    H    R    D    Q       P    C    C    A    C
US02_EHV1B/111-262       │   L    N    S    S    L       -    -    -    -    -
A0A455JKG4_9ALPH/102-211 │   L    N    R    G    G  …    -    -    -    -    -

julia> write("tofreecontact.msa", msa, Raw)

julia> print(read("tofreecontact.msa", String)) # It displays the contents of the output file
LCEPRPRPRLYHLWVVGAADLCVPFLEHLRRARRLVTIRVTDAWAGGSWPLPDGLAVGETVPWTPFPTAHNHPLAALFGGYEYRYGVVRPGWLRETVPRLWPGSESAAAEAAKTPHPARRPCVAC
LESDVSENTSYSLWIVGAADLCRAALEYIPLPKRLLAVKVAGTWSGMPWALPDTIPTLLTSTWEPTFETAEDKEHFRDNGMTCVYKIIGS-------PPDPPKPPRTEPSRASSR-SDKVFCCW-
------QTDRFRLWIIGAADICQQALSSFPKNMRRITVKVNGEWPGNPCFLDTNLEPVLISSWKPVSWPEK-ENNIDTSKLLCRYELLIP-----------------------------------
LSSGILGNHTFDMWIIGAADICKPAIEQLPNSKRFITIKVPGTWSGLTWEKPDGLSPLTVTEWDPCDDETMSKIEKKLVGIKCCYDLIGQ----------PAAAKHNSELDDSKDCCNGPACCI-
LHTDDPEGGPYHLWLFGAADLCAPAFTSIPAARRLVYARLNSFVGGSPWRPPVCGQARILVPWNP------------------------------------------------------------
LESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMTPGRLFCC--
------DQRLFHVWIVGAADLCEPLLACLSTGARCVVIEIGGLWGGRSWLPPAYARSGASTSWTPLPPPTGSAAESALEGCEYRYAIIPG----VEARRRPASRDENDERS--------------
LHGPRDRPRLYHMWVVGAADLCAPFLESLWRMRRLITIKIPDGWVGASWHLPEPFLPATSVAWTPFPAPPNHPLESLLQNYEYRYGILSPRWLRNLVNKWKNMGGRPTLPPATSEHITQNSCPA-
------------MWVFGAADLYAPIFAHIAATTRLVYAQLDCTFAGAAWRLP-RRGPAIASPWPPYDTPTLPELVAGGVLLRLVYEVVDR-----SAAPRPAKREPPCPGG--------------
LESEASDNVSYSLWILGAADICRTAIESIPLPKRLFAIKVPGTWAGMPWAIPCEIQTLLTSTWEPKFENIEDKAYFNDSNMACVYQIIGS----------PPDVPQLQGLGIESTPPKRNLCCC-
LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATPGPLTTSHP--VRRPCCAC
LCGPRPRPRLYHLWVVGAADLCAPFLEHLRDARRLVAVRVPDAWAGGSWPLPDGLALGETVPWTPFPTAHNHPLAALFGAYEYRYGVLRPGRLREAASRLWAGPPPRPPWAAETEHPARRPCAAC
LNSGIFGNYPLNLWVFGAADLCEPVISNIPGPKRLIYAYVSCEWPEPSW-KPENVKHIDDSGWVPVLDTFLSSFKVPPMLSDIFYGTTFNTPFNFESSPRCPSISSSSSSSSSSS----SSC---
--------KLYHMWVIGAADICDPFLSCLQQKARFITIKMDFIWEGAAWLPPPRMCPKKTVPWVPCPISQDPALEQLLSNCSYEYGVVGPR----------------------------------
LNSSVMGNRPYHLWVFGAADICRPVFDLLPGPKRLVYAELSEEWPGPSW-QPPP-----AVPWTAPERGTPADLEVPPRVARMVYAVVNRSWLRSRPLRHVPGRATPATPSVSTP-SGRGRC---
LHQERPGPRLYHLWVVGAADLCVPFLEYAQKTRRFIAMKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHP--TQRPCFTC
LHQERPGPRLYHLWVVGAADLCVPFFEYAQKTRRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHP--TQRPCFTC
--------ELFAVWVVGGADICAPAMEAMMALGRVVAIAGAHSLTGSSWPISARLLPAVWHSWEPYPAAPTNPLKNTFAACTFVAGTVNARWLGALTSHTRPQV---------------------
LESGIMSGGPFSLWIIGAADLCKEAIEHIPTPKRMFALQVKGTWSGMPWAIPEAIPVLLESSWSPQFTHPLDQRGFLESGMRGVYKVIGR-------ASDPPRNNSEPETRKPRGRLLKYLCC--
LSSGAYAAKEFHLWVLGTADICMAALN-LPAPKTFLITETG------------------------------------------------------------------------------------
LNSGARGTAPIHLWILGAADLCDQVLLAAS---RSTAAGAPGAPTGARLT---RRRPGLTDA------DALDVIVAGIPATRAMFARVHNEALHAQIVTRGDVRRRRGGRGNGRE--RAPRCTI-
LESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMTPGRLFCC--
LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATSHPLTTSHS--VRRPCCAC
LNSSLIINQPYHLWVLGAADLCKPVFDLIPGPKRMVYAEIADEF-HKSW-QPPETIPWTTVEHNGFSKHSSNSLVRPPTVKRVIYAVVDPARLREIPAPGRPLPRRRPSEG--------------
LNRGGAGARPFHLWVLGAADLFAPVLAHVAAKTRLVYAQLDCAFAGAAWPLP-RRGPAVAGAWPPYETPALAELRAAGAFVRMVYEVVEP-RGE-------------------------------

Column and sequence mappings

Inserts in a Stockholm MSA allow to access the full fragment of the aligned sequences. Using this, combined with the sequence names that contain coordinates used in Pfam, you can know what is the UniProt residue number of each residue in the MSA.

"PROT_SPECI/3-15 .....insertALIGNED"
#                     3456789111111
#                            012345

MIToS read and parse functions delete the insert columns, but they do the mapping between each residue and its residue number before deleting insert columns when generatemapping is true. If you don't set useidcoordinates to true, the residue first i residue will be 1 instead of 3 in the previous example.

using MIToS.MSA

msa = parse("PROT_SPECI/3-15 .....insertALIGNED", Stockholm, generatemapping=true, useidcoordinates=true)
AnnotatedMultipleSequenceAlignment with 4 annotations : 1×7 Named Matrix{MIToS.MSA.Residue}
      Seq ╲ Col │ 12  13  14  15  16  17  18
────────────────┼───────────────────────────
PROT_SPECI/3-15 │  A   L   I   G   N   E   D

MIToS also keeps the column number of the input MSA and its total number of columns. All this data is stored in the MSA annotations using the SeqMap, ColMap and NCol feature names.

annotations(msa)
#=GF NCol	18
#=GF ColMap	12,13,14,15,16,17,18
#=GF MIToS_2021-05-26T22:58:49.715	deletefullgaps!  :  Deletes 11 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2021-05-26T22:58:49.715	filtercolumns! : 11 s have been deleted.
#=GS PROT_SPECI/3-15	SeqMap	9,10,11,12,13,14,15

To have an easy access to mapping data, MIToS provides the getsequencemapping and getcolumnmapping functions.

getsequencemapping(msa, "PROT_SPECI/3-15")
7-element Vector{Int64}:
  9
 10
 11
 12
 13
 14
 15
getcolumnmapping(msa)
7-element Vector{Int64}:
 12
 13
 14
 15
 16
 17
 18

Example: Exporting a MSA for freecontact (part II)

If we want to use the --mincontsep argument of freecontact to calculate scores between distant residues, we will need to add a header to the MSA. This header should contains the residue number of the first residue of the sequence and the full fragment of that sequence (with the inserts). This data is used by FreeContact to calculate the residue number of each residue in the reference sequence. We are going to use MIToS mapping data to create this header, so we read the MSA with generatemapping and useidcoordinates set to true.

using MIToS.MSA

msa = read( "http://pfam.xfam.org/family/PF02476/alignment/full", Stockholm,
            generatemapping=true, useidcoordinates=true)
AnnotatedMultipleSequenceAlignment with 74 annotations : 25×126 Named Matrix{MIToS.MSA.Residue}
               Seq ╲ Col │   9   10   11   12   13  …  195  196  197  198  199
─────────────────────────┼────────────────────────────────────────────────────
US02_GAHVM/120-237       │   M    L    E    S    E  …    F    C    C    -    -
Q782M7_9ALPH/120-237     │   M    L    E    S    D       F    C    C    W    -
A0A1R3T8S2_9ALPH/119-225 │   -    -    -    -    -       -    -    -    -    -
B1A4T1_9ALPH/119-238     │   H    L    S    S    G       A    C    C    I    -
A0A286MM82_9ALPH/107-180 │   -    L    H    T    D       -    -    -    -    -
Q8V727_CHV1/110-256      │   -    L    C    E    P       P    C    V    A    C
E2IUH4_SHV1/110-233      │   -    -    -    -    -       -    -    -    -    -
A0A060Q503_9ALPH/110-250 │   -    L    H    G    P       S    C    P    A    -
⋮                            ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
J9R0A8_9ALPH/178-313     │   -    -    -    -    -       -    -    -    -    -
A0A1V0M8M6_9ALPH/120-239 │   Y    L    E    S    G       L    C    C    -    -
Q67639_ILTV/100-201      │   H    L    S    S    G       -    -    -    -    -
Q5PP72_9ALPH/135-256     │   Y    L    N    S    G       R    C    T    I    -
Q6R5Q3_9ALPH/120-237     │   M    L    E    S    E       F    C    C    -    -
H9E969_HHV1/110-247      │   -    L    H    R    D       P    C    C    A    C
US02_EHV1B/111-262       │   H    L    N    S    S       -    -    -    -    -
A0A455JKG4_9ALPH/102-211 │   L    L    N    R    G  …    -    -    -    -    -

Here, we are going to choose the sequence with more coverage of the MSA as our reference sequence.

msa_coverage = coverage(msa)
maxcoverage, maxindex = findmax(msa_coverage)
setreference!(msa, maxindex[1])
adjustreference!(msa)
AnnotatedMultipleSequenceAlignment with 76 annotations : 25×125 Named Matrix{MIToS.MSA.Residue}
               Seq ╲ Col │  10   11   12   13   14  …  195  196  197  198  199
─────────────────────────┼────────────────────────────────────────────────────
Q8V727_CHV1/110-256      │   L    C    E    P    R  …    P    C    V    A    C
Q782M7_9ALPH/120-237     │   L    E    S    D    V       F    C    C    W    -
A0A1R3T8S2_9ALPH/119-225 │   -    -    -    -    -       -    -    -    -    -
B1A4T1_9ALPH/119-238     │   L    S    S    G    I       A    C    C    I    -
A0A286MM82_9ALPH/107-180 │   L    H    T    D    D       -    -    -    -    -
US02_GAHVM/120-237       │   L    E    S    E    V       F    C    C    -    -
E2IUH4_SHV1/110-233      │   -    -    -    -    -       -    -    -    -    -
A0A060Q503_9ALPH/110-250 │   L    H    G    P    R       S    C    P    A    -
⋮                            ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
J9R0A8_9ALPH/178-313     │   -    -    -    -    -       -    -    -    -    -
A0A1V0M8M6_9ALPH/120-239 │   L    E    S    G    I       L    C    C    -    -
Q67639_ILTV/100-201      │   L    S    S    G    A       -    -    -    -    -
Q5PP72_9ALPH/135-256     │   L    N    S    G    A       R    C    T    I    -
Q6R5Q3_9ALPH/120-237     │   L    E    S    E    V       F    C    C    -    -
H9E969_HHV1/110-247      │   L    H    R    D    Q       P    C    C    A    C
US02_EHV1B/111-262       │   L    N    S    S    L       -    -    -    -    -
A0A455JKG4_9ALPH/102-211 │   L    N    R    G    G  …    -    -    -    -    -

MIToS deletes the residues in insert columns, so we are going to use the sequence mapping to generate the whole fragment of the reference sequence (filling the missing regions with 'x').

seqmap = getsequencemapping(msa, 1) # seqmap will be a vector with the residue numbers of the first sequence (reference)

seq = collect( stringsequence(msa, 1) ) # seq will be a Vector of Chars with the reference sequence

sequence = map(seqmap[1]:seqmap[end]) do seqpos # for each position in the whole fragment
    if seqpos in seqmap                         # if that position is in the MSA
        popfirst!(seq)                          # the residue is taken from seq
    else                                        # otherwise
        'x'                                     # 'x' is included
    end
end

sequence = join(sequence) # join the Chars on the Vector to create a string
"LCEPRPRPRLYHLWVVGAADLCVPFLEHLRRARxxxRLVTIRVTDAWAxGGSWPLPDGLAVGETVPWTPFPTAHNHPLAALFGGYEYRYGVVRPxxxxxxxxxxxxxxGWLRETVPRLWPGSESAAAEAAKTPxxxHPARRPCVAC"

Once we have the whole fragment of the sequence, we create the file and write the header in the required format (as in the man page of freecontact).

open("tofreecontact.msa", "w") do fh

    println(fh, "# querystart=", seqmap[1])

    println(fh, "# query=", sequence )

end

As last (optional) argument, write takes the mode in which is opened the file. We use "a" here to append the MSA to the header.

write("tofreecontact.msa", msa, Raw, "a")
print(read("tofreecontact.msa", String)) # It displays the contents of the output file
# querystart=111
# query=LCEPRPRPRLYHLWVVGAADLCVPFLEHLRRARxxxRLVTIRVTDAWAxGGSWPLPDGLAVGETVPWTPFPTAHNHPLAALFGGYEYRYGVVRPxxxxxxxxxxxxxxGWLRETVPRLWPGSESAAAEAAKTPxxxHPARRPCVAC
LCEPRPRPRLYHLWVVGAADLCVPFLEHLRRARRLVTIRVTDAWAGGSWPLPDGLAVGETVPWTPFPTAHNHPLAALFGGYEYRYGVVRPGWLRETVPRLWPGSESAAAEAAKTPHPARRPCVAC
LESDVSENTSYSLWIVGAADLCRAALEYIPLPKRLLAVKVAGTWSGMPWALPDTIPTLLTSTWEPTFETAEDKEHFRDNGMTCVYKIIGS-------PPDPPKPPRTEPSRASSR-SDKVFCCW-
------QTDRFRLWIIGAADICQQALSSFPKNMRRITVKVNGEWPGNPCFLDTNLEPVLISSWKPVSWPEK-ENNIDTSKLLCRYELLIP-----------------------------------
LSSGILGNHTFDMWIIGAADICKPAIEQLPNSKRFITIKVPGTWSGLTWEKPDGLSPLTVTEWDPCDDETMSKIEKKLVGIKCCYDLIGQ----------PAAAKHNSELDDSKDCCNGPACCI-
LHTDDPEGGPYHLWLFGAADLCAPAFTSIPAARRLVYARLNSFVGGSPWRPPVCGQARILVPWNP------------------------------------------------------------
LESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMTPGRLFCC--
------DQRLFHVWIVGAADLCEPLLACLSTGARCVVIEIGGLWGGRSWLPPAYARSGASTSWTPLPPPTGSAAESALEGCEYRYAIIPG----VEARRRPASRDENDERS--------------
LHGPRDRPRLYHMWVVGAADLCAPFLESLWRMRRLITIKIPDGWVGASWHLPEPFLPATSVAWTPFPAPPNHPLESLLQNYEYRYGILSPRWLRNLVNKWKNMGGRPTLPPATSEHITQNSCPA-
------------MWVFGAADLYAPIFAHIAATTRLVYAQLDCTFAGAAWRLP-RRGPAIASPWPPYDTPTLPELVAGGVLLRLVYEVVDR-----SAAPRPAKREPPCPGG--------------
LESEASDNVSYSLWILGAADICRTAIESIPLPKRLFAIKVPGTWAGMPWAIPCEIQTLLTSTWEPKFENIEDKAYFNDSNMACVYQIIGS----------PPDVPQLQGLGIESTPPKRNLCCC-
LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATPGPLTTSHP--VRRPCCAC
LCGPRPRPRLYHLWVVGAADLCAPFLEHLRDARRLVAVRVPDAWAGGSWPLPDGLALGETVPWTPFPTAHNHPLAALFGAYEYRYGVLRPGRLREAASRLWAGPPPRPPWAAETEHPARRPCAAC
LNSGIFGNYPLNLWVFGAADLCEPVISNIPGPKRLIYAYVSCEWPEPSW-KPENVKHIDDSGWVPVLDTFLSSFKVPPMLSDIFYGTTFNTPFNFESSPRCPSISSSSSSSSSSS----SSC---
--------KLYHMWVIGAADICDPFLSCLQQKARFITIKMDFIWEGAAWLPPPRMCPKKTVPWVPCPISQDPALEQLLSNCSYEYGVVGPR----------------------------------
LNSSVMGNRPYHLWVFGAADICRPVFDLLPGPKRLVYAELSEEWPGPSW-QPPP-----AVPWTAPERGTPADLEVPPRVARMVYAVVNRSWLRSRPLRHVPGRATPATPSVSTP-SGRGRC---
LHQERPGPRLYHLWVVGAADLCVPFLEYAQKTRRFIAMKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHP--TQRPCFTC
LHQERPGPRLYHLWVVGAADLCVPFFEYAQKTRRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHP--TQRPCFTC
--------ELFAVWVVGGADICAPAMEAMMALGRVVAIAGAHSLTGSSWPISARLLPAVWHSWEPYPAAPTNPLKNTFAACTFVAGTVNARWLGALTSHTRPQV---------------------
LESGIMSGGPFSLWIIGAADLCKEAIEHIPTPKRMFALQVKGTWSGMPWAIPEAIPVLLESSWSPQFTHPLDQRGFLESGMRGVYKVIGR-------ASDPPRNNSEPETRKPRGRLLKYLCC--
LSSGAYAAKEFHLWVLGTADICMAALN-LPAPKTFLITETG------------------------------------------------------------------------------------
LNSGARGTAPIHLWILGAADLCDQVLLAAS---RSTAAGAPGAPTGARLT---RRRPGLTDA------DALDVIVAGIPATRAMFARVHNEALHAQIVTRGDVRRRRGGRGNGRE--RAPRCTI-
LESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMTPGRLFCC--
LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATSHPLTTSHS--VRRPCCAC
LNSSLIINQPYHLWVLGAADLCKPVFDLIPGPKRMVYAEIADEF-HKSW-QPPETIPWTTVEHNGFSKHSSNSLVRPPTVKRVIYAVVDPARLREIPAPGRPLPRRRPSEG--------------
LNRGGAGARPFHLWVLGAADLFAPVLAHVAAKTRLVYAQLDCAFAGAAWPLP-RRGPAVAGAWPPYETPALAELRAAGAFVRMVYEVVEP-RGE-------------------------------

Get sequences from a MSA

It's possible to index the MSA as any other matrix to get an aligned sequence. This will be return a Array of Residues without annotations but keeping names/identifiers.

using MIToS.MSA

msa = read( "http://pfam.xfam.org/family/PF16996/alignment/full", Stockholm,
            generatemapping=true, useidcoordinates=true)
AnnotatedMultipleSequenceAlignment with 39 annotations : 8×55 Named Matrix{MIToS.MSA.Residue}
            Seq ╲ Col │  1   2   3   4   5   6  …  52  53  54  55  56  57
──────────────────────┼──────────────────────────────────────────────────
A0A139NMD7_9STRE/5-59 │  K   D   D   I   F   Y  …   F   T   L   F   R   I
A0A139NPI6_9STRE/5-59 │  N   E   D   L   F   Y      F   T   L   L   R   M
A0A0F3HAA3_STRPA/8-62 │  K   K   D   L   F   Y      F   T   L   F   R   V
A0A4Q0VKA2_9LACO/6-62 │  K   K   D   M   L   T      Y   P   L   V   -   -
A0A139NTT2_9STRE/3-57 │  K   K   D   L   F   Y      F   T   L   I   G   -
A8AWV6_STRGC/3-57     │  K   K   D   L   F   Y      F   T   L   I   G   V
F9Q2V2_STROR/1-43     │  -   -   -   -   -   -      F   T   L   L   G   I
A3CM62_STRSV/3-57     │  K   K   D   L   F   Y  …   F   T   L   I   G   -
msa[2,:] # second sequence of the MSA, it keeps column names
55-element Named Vector{MIToS.MSA.Residue}
Col  │ 
─────┼──
1    │ N
2    │ E
3    │ D
4    │ L
5    │ F
6    │ Y
7    │ K
8    │ E
⋮      ⋮
50   │ L
51   │ L
52   │ F
53   │ T
54   │ L
55   │ L
56   │ R
57   │ M
msa[2:2,:] # Using the range 2:2 to select the second sequence, keeping also the sequence name
AnnotatedMultipleSequenceAlignment with 26 annotations : 1×55 Named Matrix{MIToS.MSA.Residue}
            Seq ╲ Col │  1   2   3   4   5   6  …  52  53  54  55  56  57
──────────────────────┼──────────────────────────────────────────────────
A0A139NPI6_9STRE/5-59 │  N   E   D   L   F   Y  …   F   T   L   L   R   M

If you want to obtain the aligned sequence with its name and annotations (and therefore sequence and column mappings), you should use the function getsequence. This function returns an AlignedSequence with the sequence name from a MultipleSequenceAlignment or an AnnotatedAlignedSequence, that also contains annotations, from an AnnotatedMultipleSequenceAlignment.

secondsequence = getsequence(msa, 2)
AnnotatedAlignedSequence with 25 annotations : 1×55 Named Matrix{MIToS.MSA.Residue}
            Seq ╲ Col │  1   2   3   4   5   6  …  52  53  54  55  56  57
──────────────────────┼──────────────────────────────────────────────────
A0A139NPI6_9STRE/5-59 │  N   E   D   L   F   Y  …   F   T   L   L   R   M
annotations(secondsequence)
#=GF ID	Asp4
#=GF AC	PF16996.7
#=GF DE	Accessory secretory protein Sec Asp4
#=GF AU	Coggill P;0000-0001-5731-1588
#=GF SE	Pfam-B_7603 (release 27.0)
#=GF GA	27.70 27.70;
#=GF TC	29.00 28.80;
#=GF NC	25.50 25.40;
#=GF BM	hmmbuild HMM.ann SEED.ann
#=GF SM	hmmsearch -Z 57096847 -E 1000 --cpu 4 HMM pfamseq
#=GF TP	Family
#=GF RN	[1]
#=GF RM	23000954
#=GF RT	Emerging themes in SecA2-mediated protein export.
#=GF RA	Feltcher ME, Braunstein M;
#=GF RL	Nat Rev Microbiol. 2012;10:779-789.
#=GF DR	INTERPRO; IPR031551;
#=GF DR	SO; 0100021; polypeptide_conserved_region;
#=GF CC	Asp4 and Asp5 are putative accessory components of the SecY2
#=GF CC	channel of the SecA2-SecY2 mediated export system, but they are
#=GF CC	not present in all SecA2-SecY2 systems. This family of Asp4 is
#=GF CC	found in Firmicutes [1].
#=GF SQ	8
#=GF NCol	59
#=GF ColMap	1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57
#=GF MIToS_2021-05-26T22:58:50.104	deletefullgaps!  :  Deletes 4 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2021-05-26T22:58:50.104	filtercolumns! : 4 s have been deleted.
#=GS A0A139NPI6_9STRE/5-59	SeqMap	5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59
#=GS A0A139NPI6_9STRE/5-59	AC	A0A139NPI6.1
#=GC seq_cons			KKDLFYKDlEGRM--LK+tsPKKEKsTtGE+lNpsFsluLGLlILlGLIFTLlth

Use stringsequence if you want to get the sequence as a string.

stringsequence(msa, 2)
"NEDLFYKEVEGRMADLQQKAPEKEKKTGAERLNTLFSLALGLVILLGLLFTLLRM"

Because matrices are stored columnwise in Julia, you will find useful the getresiduesequences function when you need to heavily operate over sequences.

getresiduesequences(msa)
8-element Vector{Vector{MIToS.MSA.Residue}}:
 [K, D, D, I, F, Y, K, D, I, E  …  I, G, L, L, F, T, L, F, R, I]
 [N, E, D, L, F, Y, K, E, V, E  …  L, G, L, L, F, T, L, L, R, M]
 [K, K, D, L, F, Y, K, E, V, E  …  L, G, V, I, F, T, L, F, R, V]
 [K, K, D, M, L, T, H, D, I, S  …  A, G, I, L, Y, P, L, V, -, -]
 [K, K, D, L, F, Y, K, D, V, E  …  I, G, L, I, F, T, L, I, G, -]
 [K, K, D, L, F, Y, K, D, I, E  …  I, G, L, I, F, T, L, I, G, V]
 [-, -, -, -, -, -, -, -, -, -  …  L, T, L, I, F, T, L, L, G, I]
 [K, K, D, L, F, Y, K, D, I, E  …  I, G, L, I, F, T, L, I, G, -]

Describing your MSA

The MSA module has a number of functions to gain insight about your MSA. Using MIToS.MSA, one can easily ask for...

  • The number of columns and sequences with the ncolumns and nsequences functions.
  • The fraction of columns with residues (coverage) for each sequence making use of the

coverage method.

  • The fraction or percentage of gaps/residues using with the functions gapfraction,

residuefraction and columngapfraction.

  • The percentage of identity (PID) between each sequence of the MSA or its mean value

with percentidentity and meanpercentidentity.

The percentage identity between two aligned sequences is a common measure of sequence similarity and is used by the hobohmI method to estimate and reduce MSA redundancy. MIToS functions to calculate percent identity don't align the sequences, they need already aligned sequences. Full gaps columns don't count to the alignment length.

using MIToS.MSA

msa = permutedims(
        hcat(   res"--GGG-",      # res"..." uses the @res_str macro to create a (column) Vector{Residue}
                res"---GGG" ), (2,1))
#        identities 000110 sum 2
#  aligned residues 001111 sum 4
percentidentity(msa[1,:], msa[2,:]) # 2 / 4
50.0

To quickly calculate if the percentage of identity is greater than a determined value, use that threshold as third argument. percentidentity(seqa, seqb, pid) is a lot more faster than percentidentity(seqa, seqb) >= pid.

percentidentity(msa[1,:], msa[2,:], 62) # 50% >= 62%
false

Example: Plotting gap percentage per column and coverage per sequence

The gapfraction and coverage functions return a vector of numbers between 0.0 and 1.0 (fraction of...). Sometime it's useful to plot this data to quickly understand the MSA structure. In this example, we are going to use the Plots package for plotting, with the GR backend, but you are free to use any of the Julia plotting libraries.

using MIToS.MSA

msa = read("http://pfam.xfam.org/family/PF09776/alignment/full", Stockholm)

using Plots

gr(size=(600,300))

plot(   1:ncolumns(msa), # x is a range from 1 to the number of columns
        vec(columngapfraction(msa)) .* 100.0, # y is a Vector{Float64} with the percentage of gaps of each column
        linetype = :line,
        ylabel = "gaps [%]",
        xlabel = "columns",
        legend=false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

plot(   1:nsequences(msa), # x is a range from 1 to the number of sequences
        vec(coverage(msa)) .* 100, # y is a Vector{Float64} with the coverage of each sequence
        linetype = :line,
        ylabel = "coverage [%]",
        xlabel = "sequences",
        legend=false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

plot(msa)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

Example: Filter sequences per coverage and columns per gap fraction

Taking advantage of the filter...! functions and the coverage and columngapfraction functions, it's possible to delete short sequences or columns with a lot of gaps.

println("\tsequences\tcolumns")
println( "Before:\t", nsequences(msa), "\t\t", ncolumns(msa)  )
# delete sequences with less than 90% coverage of the MSA length:
filtersequences!(msa, coverage(msa) .>= 0.9)
# delete columns with more than 10% of gaps:
filtercolumns!(msa, columngapfraction(msa) .<= 0.1)
println( "After:\t", nsequences(msa), "\t\t",  ncolumns(msa)  )
	sequences	columns
Before:	386		116
After:	167		107
histogram(  vec(columngapfraction(msa)),
            # Using vec() to get a Vector{Float64} with the fraction of gaps of each column
            xlabel = "gap fraction in [0,1]", bins = 20, legend = false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'

histogram(  vec(coverage(msa) .* 100.0), #  Column with the coverage of each sequence
            xlabel = "coverage [%]", legend=false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'

Example: Plotting the percentage of identity between sequences

The distribution of the percentage of identity between every pair of sequences in an MSA, gives an idea of the MSA diversity. In this example, we are using percentidentity over an MSA to get those identity values.

using MIToS.MSA
msa = read("http://pfam.xfam.org/family/PF09776/alignment/full", Stockholm)
pid = percentidentity(msa)

MIToS stores the matrix of percentage of identity between the aligned sequences as a PairwiseListMatrix from the PairwiseListMatrices package. This matrix type saves RAM, allowing the storage of big matrices. In this example, we use the to_table function of PairwiseListMatrices to convert the matrix into a table with indices.

using PairwiseListMatrices

pidtable = to_table(pid, diagonal=false)
74305×3 Matrix{Any}:
 "A0A553R1G6_9TELE/549-644"  "A0A2K6AF64_MANLE/10-125"   36.5217
 "A0A553R1G6_9TELE/549-644"  "G1RVK4_NOMLE/46-161"       34.7826
 "A0A553R1G6_9TELE/549-644"  "A0A6A4ILB2_APOLU/2-111"    33.6634
 "A0A553R1G6_9TELE/549-644"  "A0A672YV19_9TELE/15-130"   47.1154
 "A0A553R1G6_9TELE/549-644"  "A0A444U283_ACIRT/1-75"     37.5
 "A0A553R1G6_9TELE/549-644"  "A0A0V0S2G9_9BILA/731-840"  30.7692
 "A0A553R1G6_9TELE/549-644"  "A0A6A5D6Z0_SCHHA/3-104"    30.3922
 "A0A553R1G6_9TELE/549-644"  "A0A194PY65_PAPXU/4-116"    32.6923
 "A0A553R1G6_9TELE/549-644"  "A0A1V4KDS6_PATFA/159-270"  36.8932
 "A0A553R1G6_9TELE/549-644"  "M4A0G1_XIPMA/29-139"       42.7184
 ⋮                                                       
 "A0A3P6PBE0_ANISI/14-103"   "M3XPJ7_MUSPF/10-125"       24.3478
 "A0A3P6PBE0_ANISI/14-103"   "A0A2K6LYH7_RHIBE/10-125"   24.3478
 "A0A3P6PBE0_ANISI/14-103"   "F4WNV6_ACREC/302-415"      32.6316
 "G3WPK1_SARHA/11-126"       "M3XPJ7_MUSPF/10-125"       62.6087
 "G3WPK1_SARHA/11-126"       "A0A2K6LYH7_RHIBE/10-125"   61.2069
 "G3WPK1_SARHA/11-126"       "F4WNV6_ACREC/302-415"      29.5652
 "M3XPJ7_MUSPF/10-125"       "A0A2K6LYH7_RHIBE/10-125"   71.5517
 "M3XPJ7_MUSPF/10-125"       "F4WNV6_ACREC/302-415"      28.6957
 "A0A2K6LYH7_RHIBE/10-125"   "F4WNV6_ACREC/302-415"      26.9565

The function quantile gives a quick idea of the percentage identity distribution of the MSA.

using Statistics

quantile(convert(Vector{Float64}, pidtable[:,3]), [0.00, 0.25, 0.50, 0.75, 1.00])
5-element Vector{Float64}:
   0.0
  27.82608695652174
  33.333333333333336
  41.904761904761905
 100.0

The function meanpercentidentity gives the mean value of the percent identity distribution for MSA with less than 300 sequences, or a quick estimate (mean PID in a random sample of sequence pairs) otherwise unless you set exact to true.

meanpercentidentity(msa)
36.405906989830925

One can easily plot that matrix and its distribution using the heatmap and histogram functions of the Plots package.

using Plots
gr()
heatmap(convert(Matrix, pid), yflip=true, ratio=:equal)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

histogram(pidtable[:,3], xlabel ="Percentage of identity", legend=false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

Sequence clustering

The MSA module allows to clusterize sequences in an MSA. The hobohmI function takes as input an MSA followed by an identity threshold value, and returns a Clusters type with the result of a Hobohm I sequence clustering. The Hobohm I algorithm will add a sequence to an existing cluster, if the percentage of identity is equal or greater than the threshold. The Clusters is sub-type of ClusteringResult from the Clustering.jl package. One advantage of use a sub-type of ClusteringResultis that you are able to use any method defined on Clustering.jl like varinfo (Variation of Information) for example. Also, you can use any clustering algorithm included in Clustering.jl, and convert its result to an Clusters object to use it with MIToS. MSA defines the functions nclusters to get the resulting number of clusters, counts to get the number of sequences on each cluster and assignments to get the cluster number of each sequence. The most important method is getweight, which returns the weight of each sequence. This method is used in the Information module of MIToS to reduce redundancy.

Example: Reducing redundancy of a MSA

MSAs can suffer from an unnatural sequence redundancy and a high number of protein fragments. In this example, we are using a sequence clustering to make a non-redundant set of representative sequences. We are going to use the function hobohmI to perform the clustering with the Hobohm I algorithm at 62% identity.

using MIToS.MSA

msa = read("http://pfam.xfam.org/family/PF09776/alignment/full", Stockholm)

println("This MSA has ", nsequences(msa), " sequences...")
This MSA has 386 sequences...
clusters = hobohmI(msa, 62)
MIToS.MSA.Clusters([1, 102, 1, 32, 2, 2, 5, 26, 10, 1  …  1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 2, 3, 4, 5, 6, 7, 8, 9  …  2, 107, 108, 33, 12, 80, 21, 2, 2, 15], [1.0, 0.00980392156862745, 0.00980392156862745, 1.0, 0.03125, 0.5, 0.5, 0.2, 0.038461538461538464, 0.1  …  0.00980392156862745, 1.0, 1.0, 0.3333333333333333, 0.05555555555555555, 0.5, 0.16666666666666666, 0.00980392156862745, 0.00980392156862745, 0.09090909090909091])
println("...but has only ", nclusters(clusters), " sequence clusters after a clustering at 62% identity.")
...but has only 108 sequence clusters after a clustering at 62% identity.
using Plots
gr()

plot(msa)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

We are going to use the DataFrames package to easily select the sequence with the highest coverage of each cluster.

using DataFrames

df = DataFrame( seqnum = 1:nsequences(msa),
                seqname = sequencenames(msa),
                cluster = assignments(clusters), # the cluster number/index of each sequence
                coverage = vec(coverage(msa)))

first(df, 5)

5 rows × 4 columns

seqnumseqnameclustercoverage
Int64StringInt64Float64
11A0A553R1G6_9TELE/549-64410.689655
22A0A2K6AF64_MANLE/10-12520.991379
33G1RVK4_NOMLE/46-16120.991379
44A0A6A4ILB2_APOLU/2-11130.775862
55A0A672YV19_9TELE/15-13040.896552

It is possible to use this DataFrame and Plots to plot the sequence coverage of the MSA and also an histogram of the number of sequences in each cluster:

using StatsPlots # Plotting DataFrames
h = @df df histogram(:cluster, ylabel="nseq")
p = @df df plot(:cluster, :coverage, linetype=:scatter)
plot(p, h, nc=1, xlim=(0, nclusters(clusters)+1 ), legend=false)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

We use the Split-Apply-Combine strategy, though the by function of the DataFrames package, to select the sequence of highest coverage for each cluster.

maxcoverage = by(df, :cluster, cl -> cl[ findmax(cl[:coverage])[2] ,
                 [:seqnum, :seqname, :coverage]])

first(maxcoverage, 5)
p = @df maxcoverage plot(:cluster, :coverage, linetype=:scatter)
h = @df maxcoverage histogram(:cluster, ylabel="nseq")
plot(p, h, nc=1, xlim=(0, nclusters(clusters)+1 ), legend=false)
png("msa_clusters_iii.png") # hide
nothing # hide

We can easily generate a mask using list comprehension, to select only the representative sequences of the MSA (deleting the rest of the sequences with filtersequences!).

cluster_references = Bool[ seqnum in maxcoverage[:seqnum] for seqnum in 1:nsequences(msa) ]
filtersequences!(msa, cluster_references)
plot(msa)
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-juliateam'
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setCompositionMode: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1