MSA

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 and suffixes of the file name, while parse does the actual parsing of the file. You can read gzipped 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 Format. The supported MSA formats at the moment are Stockholm, FASTA 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 28 annotations : 7×459 Named Array{MIToS.MSA.Residue,2}
               Seq ╲ Col │  23   24   25   26   27  …  522  523  524  525  526
─────────────────────────┼────────────────────────────────────────────────────
M5A3D2_9ACTN/208-402     │   -    -    -    -    -  …    -    -    -    -    -
Q4W584_NEIMB/1-222       │   M    L    K    K    I       -    -    -    -    -
C5ZW53_9HELI/1-498       │   -    -    K    K    L       K    Y    L    Q    L
M5A3D2_9ACTN/2-157       │   -    -    -    -    -       -    -    -    -    -
A0A157SWM6_9BORD/1-413   │   -    L    K    K    L       -    -    -    -    -
A0A0B0IGB5_9BACI/201-416 │   -    -    -    -    -       -    -    -    -    -
A0A0B0IGB5_9BACI/1-170   │   -    -    -    -    -  …    -    -    -    -    -

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

names/identifiers.

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})
7×459 Array{MIToS.MSA.Residue,2}:
 -  -  -  -  -  -  -  -  -  -  -  -  -  …  -  -  -  -  -  -  -  -  -  -  -  -
 M  L  K  K  I  K  K  A  L  F  Q  P  K     -  -  -  -  -  -  -  -  -  -  -  -
 -  -  K  K  L  S  G  L  M  Q  D  I  K     D  F  Q  K  Y  R  I  K  Y  L  Q  L
 -  -  -  -  -  -  -  -  -  -  -  -  -     -  -  -  -  -  -  -  -  -  -  -  -
 -  L  K  K  L  R  K  L  I  L  H  P  V     -  -  -  -  -  -  -  -  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -  …  -  -  -  -  -  -  -  -  -  -  -  -
 -  -  -  -  -  -  -  -  -  -  -  -  -     -  -  -  -  -  -  -  -  -  -  -  -

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

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.

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.

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 this notes, use printmodifications:

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

printmodifications(msa)
-------------------
2018-08-08T23:10:34.375

deletefullgaps!  :  Deletes 746 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
-------------------
2018-08-08T23:10:34.689

filtercolumns! : 746 columns 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 Format FASTA, Stockholm 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/4-59
KDDIFYKDIEGRMDELKRKPPKKEKKTRAERISTFFSVSLGLVILIGLLFTLFRI
>A0A139NPI6_9STRE/5-59
-EDLFYKEVEGRMADLQQKAPEKEKKTGAERLNTLFSLALGLVILLGLLFTLLR-
>J0UVX5_STREE/3-39
-EDLFYKDVEGRMEELKQKPIKKEKKP----------------------------
>A0A139NTT2_9STRE/3-57
KKDLFYKDVEQKLDSLKQGQPKKEKASLGEKLNKAFVIALGLVILIGLIFTLI--
>A3CM62_STRSV/3-57
KKDLFYKDIEGRLDELKHGKPKKEKASLGENLNKAFVIVLGLMILIGLIFTLI--
>T0TY77_9STRE/5-59
KKDLFYKEVEGRMESLKRRPAEKEKTTRSEKINVTFNVIIGLVILLGVIFTLFRV

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.

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

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

name. The values are free text (strings). Lines starting with #=GS in Stockholm format.

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.4
#=GF DE	Accessory secretory protein Sec Asp4
#=GF AU	Coggill P
#=GF SE	Pfam-B_7603 (release 27.0)
#=GF GA	25.70 25.70;
#=GF TC	26.50 37.80;
#=GF NC	21.60 20.60;
#=GF BM	hmmbuild HMM.ann SEED.ann
#=GF SM	hmmsearch -Z 26740544 -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 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	6
#=GF MIToS_2018-08-08T23:10:35.219	deletefullgaps!  :  Deletes 11 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2018-08-08T23:10:35.219	filtercolumns! : 11 columns have been deleted.
#=GS A3CM62_STRSV/3-57	AC	A3CM62.1
#=GS A0A139NTT2_9STRE/3-57	AC	A0A139NTT2.1
#=GS A0A139NMD7_9STRE/4-59	AC	A0A139NMD7.1
#=GS J0UVX5_STREE/3-39	AC	J0UVX5.1
#=GS T0TY77_9STRE/5-59	AC	T0TY77.1
#=GS A0A139NPI6_9STRE/5-59	AC	A0A139NPI6.1
#=GC seq_cons			KcDLFYKDVEGRM--LKp+sPKKEKpohuE+lNphFslsLGLVILlGLlFTLh..

Particular annotations can be accessed using the functions getannot.... This 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, "J0UVX5_STREE/3-39", "AC") # ("J0UVX5_STREE/3-39", "AC") is the key in the dictionary
"J0UVX5.1"

If you want to add new annotations, you should use the setannot…! functions. This functions have the same arguments that getannot... functions but with an extra argument to indicate the new annotation.

setannotsequence!(msa, "J0UVX5_STREE/3-39", "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 7 entries:
  ("A3CM62_STRSV/3-57", "AC")               => "A3CM62.1"
  ("A0A139NTT2_9STRE/3-57", "AC")           => "A0A139NTT2.1"
  ("A0A139NMD7_9STRE/4-59", "AC")           => "A0A139NMD7.1"
  ("J0UVX5_STREE/3-39", "New_Feature_Name") => "New_Annotation"
  ("J0UVX5_STREE/3-39", "AC")               => "J0UVX5.1"
  ("T0TY77_9STRE/5-59", "AC")               => "T0TY77.1"
  ("A0A139NPI6_9STRE/5-59", "AC")           => "A0A139NPI6.1"

Editing your MSA

MIToS offers functions to edit your MSA. Given that this 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 is 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!. This 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. This 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:

reference sequence).

(reference).

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
7-element Array{String,1}:
 "M5A3D2_9ACTN/208-402"
 "Q4W584_NEIMB/1-222"
 "C5ZW53_9HELI/1-498"
 "M5A3D2_9ACTN/2-157"
 "A0A157SWM6_9BORD/1-413"
 "A0A0B0IGB5_9BACI/201-416"
 "A0A0B0IGB5_9BACI/1-170"
mask = map(x -> ismatch(r"_9ACTN", x), sequencenames(msa)) # an element of mask is true if "_9ACTN" is in the name
7-element Array{Bool,1}:
  true
 false
 false
  true
 false
 false
 false
filtersequences!(msa, mask) # deletes all the sequences where mask is false

sequencenames(msa)
2-element Array{String,1}:
 "M5A3D2_9ACTN/208-402"
 "M5A3D2_9ACTN/2-157"

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 24 annotations : 3×126 Named Array{MIToS.MSA.Residue,2}
         Seq ╲ Col │   2    3    4    5    6  …  140  141  142  143  144
───────────────────┼────────────────────────────────────────────────────
US02_GAHVM/120-237 │   M    L    E    S    E  …    F    C    C    -    -
US02_HHV2H/110-246 │   L    L    H    Q    E       P    C    F    T    C
US02_HHV11/110-247 │   -    L    H    R    D  …    P    C    C    A    C

julia> maxcoverage, indice = findmax(coverage(msa)) # chooses the sequence with more coverage of the MSA
(0.9841269841269842, 2)

julia> setreference!(msa, indice)
AnnotatedMultipleSequenceAlignment with 25 annotations : 3×126 Named Array{MIToS.MSA.Residue,2}
         Seq ╲ Col │   2    3    4    5    6  …  140  141  142  143  144
───────────────────┼────────────────────────────────────────────────────
US02_HHV2H/110-246 │   L    L    H    Q    E  …    P    C    F    T    C
US02_GAHVM/120-237 │   M    L    E    S    E       F    C    C    -    -
US02_HHV11/110-247 │   -    L    H    R    D  …    P    C    C    A    C

julia> adjustreference!(msa)
AnnotatedMultipleSequenceAlignment with 26 annotations : 3×124 Named Array{MIToS.MSA.Residue,2}
         Seq ╲ Col │   2    3    4    5    6  …  140  141  142  143  144
───────────────────┼────────────────────────────────────────────────────
US02_HHV2H/110-246 │   L    L    H    Q    E  …    P    C    F    T    C
US02_GAHVM/120-237 │   M    L    E    S    E       F    C    C    -    -
US02_HHV11/110-247 │   -    L    H    R    D  …    P    C    C    A    C

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

julia> print(readstring("tofreecontact.msa")) # It displays the contents of the output file
LLHQERPGPRLYHLWVVGAADLCVPFFEYAQKTRRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHPTQRPCFTC
MLESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMGRLFCC--
-LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATPGPLTTSHPVRRPCCAC

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 with 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 deletes the insert columns, but they do the mapping of each residue to its residue number before deleting insert columns if 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 5 annotations : 1×7 Named Array{MIToS.MSA.Residue,2}
      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_2018-08-08T23:10:41.924	deletefullgaps!  :  Deletes 11 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2018-08-08T23:10:41.933	filtercolumns! : 11 columns 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 Array{Int64,1}:
  9
 10
 11
 12
 13
 14
 15
getcolumnmapping(msa)
7-element Array{Int64,1}:
 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 setted to true.

using MIToS.MSA

msa = read( "http://pfam.xfam.org/family/PF02476/alignment/full", Stockholm,
            generatemapping=true, useidcoordinates=true)
AnnotatedMultipleSequenceAlignment with 29 annotations : 3×126 Named Array{MIToS.MSA.Residue,2}
         Seq ╲ Col │   2    3    4    5    6  …  140  141  142  143  144
───────────────────┼────────────────────────────────────────────────────
US02_GAHVM/120-237 │   M    L    E    S    E  …    F    C    C    -    -
US02_HHV2H/110-246 │   L    L    H    Q    E       P    C    F    T    C
US02_HHV11/110-247 │   -    L    H    R    D  …    P    C    C    A    C

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

maxcoverage, indice = findmax(coverage(msa))
setreference!(msa, indice)
adjustreference!(msa)
AnnotatedMultipleSequenceAlignment with 31 annotations : 3×124 Named Array{MIToS.MSA.Residue,2}
         Seq ╲ Col │   2    3    4    5    6  …  140  141  142  143  144
───────────────────┼────────────────────────────────────────────────────
US02_HHV2H/110-246 │   L    L    H    Q    E  …    P    C    F    T    C
US02_GAHVM/120-237 │   M    L    E    S    E       F    C    C    -    -
US02_HHV11/110-247 │   -    L    H    R    D  …    P    C    C    A    C

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
        shift!(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
"LLHQERPGPxRLYHLWVVGAADLCVPFFEYAQKTRxxxRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPxxxxxxxxRWLRSLVAPHxKPRPASSRPHPATHPTQRPCFTC"

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(readstring("tofreecontact.msa")) # It displays the contents of the output file
# querystart=110
# query=LLHQERPGPxRLYHLWVVGAADLCVPFFEYAQKTRxxxRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPxxxxxxxxRWLRSLVAPHxKPRPASSRPHPATHPTQRPCFTC
LLHQERPGPRLYHLWVVGAADLCVPFFEYAQKTRRFIATKTNDAWVGEPWPLPDRFLPERTVSWTPFPAAPNHPLENLLSRYEYQYGVVVPRWLRSLVAPHKPRPASSRPHPATHPTQRPCFTC
MLESEVSGNAPHSLWIVGAADICRIALECIPLPKRLLAIKVSGTWSGMPWAIPDNIQTLLTSTWEPKFDTPEDRAHFCDSDMVCVYKILGS----------PPNPLKPPEIEPPQMGRLFCC--
-LHRDQPSPRLYHLWVVGAADLCVPFLEYAQKIRRFIAIKTPDAWVGEPWAVPTRFLPEWTVAWTPFPAAPNHPLETLLSRYEYQYGVVLPRWLRSLIALHKPHPATPGPLTTSHPVRRPCCAC

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 35 annotations : 6×55 Named Array{MIToS.MSA.Residue,2}
            Seq ╲ Col │  2   3   4   5   6   7  …  51  52  53  54  55  56
──────────────────────┼──────────────────────────────────────────────────
A0A139NMD7_9STRE/4-59 │  K   D   D   I   F   Y  …   F   T   L   F   R   I
A0A139NPI6_9STRE/5-59 │  -   E   D   L   F   Y      F   T   L   L   R   -
J0UVX5_STREE/3-39     │  -   E   D   L   F   Y      -   -   -   -   -   -
A0A139NTT2_9STRE/3-57 │  K   K   D   L   F   Y      F   T   L   I   -   -
A3CM62_STRSV/3-57     │  K   K   D   L   F   Y      F   T   L   I   -   -
T0TY77_9STRE/5-59     │  K   K   D   L   F   Y  …   F   T   L   F   R   V
msa[2,:] # second sequence of the MSA, it keeps column names
55-element Named Array{MIToS.MSA.Residue,1}
Col  │
─────┼──
2    │ -
3    │ E
4    │ D
5    │ L
6    │ F
7    │ Y
8    │ K
9    │ E
10   │ V
⋮      ⋮
48   │ G
49   │ L
50   │ L
51   │ F
52   │ T
53   │ L
54   │ L
55   │ R
56   │ -
msa[2:2,:] # Using the range 2:2 to select the second sequence, keeping the sequence name
1×55 Named Array{MIToS.MSA.Residue,2}
            Seq ╲ Col │  2   3   4   5   6   7  …  51  52  53  54  55  56
──────────────────────┼──────────────────────────────────────────────────
A0A139NPI6_9STRE/5-59 │  -   E   D   L   F   Y  …   F   T   L   L   R   -

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 Array{MIToS.MSA.Residue,2}
            Seq ╲ Col │  2   3   4   5   6   7  …  51  52  53  54  55  56
──────────────────────┼──────────────────────────────────────────────────
A0A139NPI6_9STRE/5-59 │  -   E   D   L   F   Y  …   F   T   L   L   R   -
annotations(secondsequence)
#=GF ID	Asp4
#=GF AC	PF16996.4
#=GF DE	Accessory secretory protein Sec Asp4
#=GF AU	Coggill P
#=GF SE	Pfam-B_7603 (release 27.0)
#=GF GA	25.70 25.70;
#=GF TC	26.50 37.80;
#=GF NC	21.60 20.60;
#=GF BM	hmmbuild HMM.ann SEED.ann
#=GF SM	hmmsearch -Z 26740544 -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 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	6
#=GF NCol	66
#=GF ColMap	2,3,4,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
#=GF MIToS_2018-08-08T23:10:43.805	deletefullgaps!  :  Deletes 11 columns full of gaps (inserts generate full gap columns on MIToS because lowercase and dots are not allowed)
#=GF MIToS_2018-08-08T23:10:43.805	filtercolumns! : 11 columns have been deleted.
#=GS A0A139NPI6_9STRE/5-59	SeqMap	,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,
#=GS A0A139NPI6_9STRE/5-59	AC	A0A139NPI6.1
#=GC seq_cons			KcDLFYKDVEGRM--LKp+sPKKEKpohuE+lNphFslsLGLVILlGLlFTLh..

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

stringsequence(msa, 2)
"-EDLFYKEVEGRMADLQQKAPEKEKKTGAERLNTLFSLALGLVILLGLLFTLLR-"

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

getresiduesequences(msa)
6-element Array{Array{MIToS.MSA.Residue,1},1}:
 MIToS.MSA.Residue[K, D, D, I, F, Y, K, D, I, E  …  I, G, L, L, F, T, L, F, R, I]
 MIToS.MSA.Residue[-, E, D, L, F, Y, K, E, V, E  …  L, G, L, L, F, T, L, L, R, -]
 MIToS.MSA.Residue[-, E, D, L, F, Y, K, D, V, E  …  -, -, -, -, -, -, -, -, -, -]
 MIToS.MSA.Residue[K, K, D, L, F, Y, K, D, V, E  …  I, G, L, I, F, T, L, I, -, -]
 MIToS.MSA.Residue[K, K, D, L, F, Y, K, D, I, E  …  I, G, L, I, F, T, L, I, -, -]
 MIToS.MSA.Residue[K, K, D, L, F, Y, K, E, V, E  …  L, G, V, I, F, T, L, F, R, V]

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...

coverage method.

residuefraction and columngapfraction.

with percentidentity and meanpercentidentity.

The percentage identity between two aligned sequences it's a common measure of sequence similarity and it's used by the hobohmI method to estimate and reduce MSA redundancy. MIToS functions to calculate percent identity don't align the sequences, they need sequences already aligned. Full gaps columns don't count to the align 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 number 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 a PyPlot 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

pyplot(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)

plot(   1:nsequences(msa), # x is a range from 1 to the number of sequences
        coverage(msa) .* 100, # y is a Vector{Float64} with the coverage of each sequence
        linetype = :line,
        ylabel = "coverage [%]",
        xlabel = "sequences",
        legend=false)

plot(msa)

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:	178		116
After:	55		108
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)

histogram(  vec(coverage(msa) .* 100.0), #  Column with the coverage of each sequence
            xlabel = "coverage [%]", legend=false)

Example: Plotting the percentage of identity between sequences

The distribution of the percentage of identity between every pairs of sequences in a MSA, gives an idea of the MSA diversity. In this example, we are going to use percentidentity over a MSA to get that 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)
15753×3 Array{Any,2}:
 "E4XN03_OIKDI/34-146"     "G1RVK4_NOMLE/46-161"       22.6087
 "E4XN03_OIKDI/34-146"     "A0A0V0S2G9_9BILA/731-840"  25.4902
 "E4XN03_OIKDI/34-146"     "B4NHY3_DROWI/2-106"        26.0417
 "E4XN03_OIKDI/34-146"     "G6CRH5_DANPL/1-73"         23.3333
 "E4XN03_OIKDI/34-146"     "A0A194PY65_PAPXU/4-116"    23.9583
 "E4XN03_OIKDI/34-146"     "RM55_DROME/2-106"          24.7312
 "E4XN03_OIKDI/34-146"     "G5C999_HETGA/5-102"        25.5319
 "E4XN03_OIKDI/34-146"     "G7Y6C1_CLOSI/30-139"       20.6522
 "E4XN03_OIKDI/34-146"     "E0VEI6_PEDHC/4-112"        30.0
 "E4XN03_OIKDI/34-146"     "G3SRJ5_LOXAF/9-123"        19.8276
 ⋮
 "T1FXF3_HELRO/1-90"       "G3WPK1_SARHA/11-126"       33.0435
 "T1FXF3_HELRO/1-90"       "RM55_MOUSE/9-124"          31.8966
 "T1FXF3_HELRO/1-90"       "M3XPJ7_MUSPF/10-125"       31.3043
 "A0A090MXF3_STRRB/2-104"  "G3WPK1_SARHA/11-126"       33.913
 "A0A090MXF3_STRRB/2-104"  "RM55_MOUSE/9-124"          30.1724
 "A0A090MXF3_STRRB/2-104"  "M3XPJ7_MUSPF/10-125"       31.3043
 "G3WPK1_SARHA/11-126"     "RM55_MOUSE/9-124"          54.3103
 "G3WPK1_SARHA/11-126"     "M3XPJ7_MUSPF/10-125"       62.6087
 "RM55_MOUSE/9-124"        "M3XPJ7_MUSPF/10-125"       70.6897

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

quantile(convert(Vector{Float64}, pidtable[:,3]), [0.00, 0.25, 0.50, 0.75, 1.00])
5-element Array{Float64,1}:
   0.0
  27.1028
  31.8966
  38.2353
 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)
34.396463641886754

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

using Plots
pyplot()
heatmap(full(pid), yflip=true, ratio=:equal)

histogram(pidtable[:,3], xlabel ="Percentage of identity", legend=false)

Sequence clustering

The MSA module allows to clusterize sequences in a MSA. The hobohmI function takes as input a 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 them 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 will use a sequence clustering to make a non-redundant set of representative sequences using the function hobohmI to perform a 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 178 sequences...
clusters = hobohmI(msa, 62)
MIToS.MSA.Clusters([1, 41, 2, 15, 2, 2, 1, 1, 1, 4  …  2, 3, 1, 1, 1, 2, 1, 1, 1, 1], [1, 2, 3, 4, 5, 4, 4, 2, 6, 7  …  16, 2, 17, 29, 4, 66, 29, 15, 2, 2], [1.0, 0.0243902, 0.5, 0.0666667, 0.5, 0.0666667, 0.0666667, 0.0243902, 0.5, 1.0  …  0.142857, 0.0243902, 0.142857, 0.25, 0.0666667, 1.0, 0.25, 0.333333, 0.0243902, 0.0243902])
println("...but has only ", nclusters(clusters), " sequence clusters after a clustering at 62% identity.")
...but has only 66 sequence clusters after a clustering at 62% identity.
using Plots
pyplot()

plot(msa)

We are going to use the DataFrames package to easily select the sequence with 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)))
178×4 DataFrames.DataFrame
│ Row │ seqnum │ seqname                  │ cluster │ coverage │
├─────┼────────┼──────────────────────────┼─────────┼──────────┤
│ 1   │ 1      │ E4XN03_OIKDI/34-146      │ 1       │ 0.706897 │
│ 2   │ 2      │ G1RVK4_NOMLE/46-161      │ 2       │ 0.991379 │
│ 3   │ 3      │ A0A0V0S2G9_9BILA/731-840 │ 3       │ 0.853448 │
│ 4   │ 4      │ B4NHY3_DROWI/2-106       │ 4       │ 0.810345 │
│ 5   │ 5      │ G6CRH5_DANPL/1-73        │ 5       │ 0.62931  │
│ 6   │ 6      │ A0A194PY65_PAPXU/4-116   │ 4       │ 0.810345 │
│ 7   │ 7      │ RM55_DROME/2-106         │ 4       │ 0.784483 │
│ 8   │ 8      │ G5C999_HETGA/5-102       │ 2       │ 0.801724 │
⋮
│ 170 │ 170    │ M3WM55_FELCA/10-125      │ 2       │ 1.0      │
│ 171 │ 171    │ A0A0C2BEU2_9BILA/5-105   │ 17      │ 0.801724 │
│ 172 │ 172    │ A0A0N5CCD5_STREA/1-104   │ 29      │ 0.836207 │
│ 173 │ 173    │ B4QTH5_DROSI/2-106       │ 4       │ 0.793103 │
│ 174 │ 174    │ T1FXF3_HELRO/1-90        │ 66      │ 0.775862 │
│ 175 │ 175    │ A0A090MXF3_STRRB/2-104   │ 29      │ 0.836207 │
│ 176 │ 176    │ G3WPK1_SARHA/11-126      │ 15      │ 0.991379 │
│ 177 │ 177    │ RM55_MOUSE/9-124         │ 2       │ 1.0      │
│ 178 │ 178    │ M3XPJ7_MUSPF/10-125      │ 2       │ 0.991379 │

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 StatPlots # 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)

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]])
66×4 DataFrames.DataFrame
│ Row │ cluster │ seqnum │ seqname                  │ coverage │
├─────┼─────────┼────────┼──────────────────────────┼──────────┤
│ 1   │ 1       │ 1      │ E4XN03_OIKDI/34-146      │ 0.706897 │
│ 2   │ 2       │ 27     │ F7GI04_MACMU/7-122       │ 1.0      │
│ 3   │ 3       │ 145    │ A0A0V0TDB0_9BILA/725-833 │ 0.862069 │
│ 4   │ 4       │ 72     │ Q177J1_AEDAE/3-112       │ 0.87069  │
│ 5   │ 5       │ 5      │ G6CRH5_DANPL/1-73        │ 0.62931  │
│ 6   │ 6       │ 167    │ A0A094ZMR1_SCHHA/3-104   │ 0.810345 │
│ 7   │ 7       │ 10     │ E0VEI6_PEDHC/4-112       │ 0.844828 │
│ 8   │ 8       │ 12     │ A0A0L8FVE8_OCTBM/8-111   │ 0.818966 │
⋮
│ 58  │ 58      │ 168    │ B0WMT9_CULQU/9-116       │ 0.818966 │
│ 59  │ 59      │ 153    │ A0A0N4ZNS7_PARTI/19-127  │ 0.793103 │
│ 60  │ 60      │ 155    │ H3DW02_PRIPA/2-128       │ 0.887931 │
│ 61  │ 61      │ 156    │ A0A0N4U7G0_DRAME/2-90    │ 0.612069 │
│ 62  │ 62      │ 165    │ Q2KHY3_BOVIN/10-82       │ 0.594828 │
│ 63  │ 63      │ 159    │ A0A0N5CW25_THECL/95-207  │ 0.844828 │
│ 64  │ 64      │ 160    │ X6R631_HUMAN/1-52        │ 0.448276 │
│ 65  │ 65      │ 163    │ A7RNQ0_NEMVE/28-143      │ 0.818966 │
│ 66  │ 66      │ 174    │ T1FXF3_HELRO/1-90        │ 0.775862 │
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)

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) ]
178-element Array{Bool,1}:
  true
 false
 false
 false
  true
 false
 false
 false
 false
  true
     ⋮
 false
 false
 false
 false
  true
 false
 false
 false
 false
filtersequences!(msa, cluster_references)
AnnotatedMultipleSequenceAlignment with 89 annotations : 66×116 Named Array{MIToS.MSA.Residue,2}
                 Seq ╲ Col │  26   27   28   29   30  …  165  166  167  168  169
───────────────────────────┼────────────────────────────────────────────────────
E4XN03_OIKDI/34-146        │   -    -    -    -    -  …    -    -    -    -    -
G6CRH5_DANPL/1-73          │   -    -    -    -    -       K    Y    L    K    K
E0VEI6_PEDHC/4-112         │   -    -    -    -    -       N    L    L    K    K
A0A0L8FVE8_OCTBM/8-111     │   -    -    -    -    -       H    L    W    K    K
W4XCA5_STRPU/9-121         │   -    -    -    -    -       H    L    W    N    K
A0A0D8XRC7_DICVI/3-105     │   -    -    -    -    S       -    -    -    -    -
C4WSU2_ACYPI/2-101         │   -    -    -    -    -       K    Y    F    K    K
A0A0R3QN38_9BILA/5-118     │   -    -    -    -    -       D    L    W    R    K
G1TZ81_RABIT/10-122        │   L    L    W    Q    T       W    V    W    N    R
⋮                              ⋮    ⋮    ⋮    ⋮    ⋮  ⋱    ⋮    ⋮    ⋮    ⋮    ⋮
H3DW02_PRIPA/2-128         │   -    -    -    -    -       S    -    -    -    -
A0A0N4U7G0_DRAME/2-90      │   -    -    -    -    -       -    -    -    -    -
A0A0N5CW25_THECL/95-207    │   -    -    -    -    -       D    L    W    R    K
X6R631_HUMAN/1-52          │   -    -    -    -    -       Q    F    W    T    R
A7RNQ0_NEMVE/28-143        │   -    -    -    -    -       R    L    I    K    K
Q2KHY3_BOVIN/10-82         │   L    L    W    Q    C       -    -    -    -    -
A0A094ZMR1_SCHHA/3-104     │   -    -    -    -    -       F    L    L    K    K
B0WMT9_CULQU/9-116         │   -    -    -    -    -       K    Y    I    K    -
T1FXF3_HELRO/1-90          │   -    -    -    -    -  …    Y    L    W    K    K
plot(msa)