Difference between revisions of "My codes"

From Biolecture.org
imported>SeoGaLam
(Created page with "<p><span style="font-size:20px"><strong>Needleman-Wunsch algorithm</strong></span></p> <hr /> <p>The <strong>Needleman–Wunsch algorithm</strong> is an <a hr...")
 
imported>SeoGaLam
Line 46: Line 46:
 
<p>&nbsp;</p>
 
<p>&nbsp;</p>
  
<p>{{Technical|date=September 2013}}<br />
 
{{Infobox algorithm<br />
 
|name= &lt;!-- Defaults to article name --&gt;<br />
 
|class= [[Sequence alignment]]<br />
 
|image=<br />
 
|caption=<br />
 
|data=<br />
 
|time= &lt;math&gt;O(mn)&lt;/math&gt;<br />
 
|best-time=<br />
 
|average-time=<br />
 
|space= &lt;math&gt;O(mn)&lt;/math&gt;<br />
 
}}</p>
 
  
<p>The &#39;&#39;&#39;Needleman&ndash;Wunsch algorithm&#39;&#39;&#39; is an [[algorithm]] used in &nbsp;[[bioinformatics]] to [[sequence alignment|align]] [[protein]] or [[nucleotide]] sequences. It was one of the first applications of [[dynamic programming]] to compare biological sequences. The algorithm was developed by Saul B. Needleman and Christian D. Wunsch and published in 1970.&lt;ref name=Needleman&gt;{{cite journal | journal=Journal of Molecular Biology | volume=48 | issue=3 | pages=443&ndash;53 | year=1970 &nbsp;|author1=Needleman, Saul B. |author2=Wunsch, Christian D. |last-author-amp=yes | title=A general method applicable to the search for similarities in the amino acid sequence of two proteins | url=http://linkinghub.elsevier.com/retrieve/pii/0022-2836(70)90057-4 | pmid=5420325 | doi = 10.1016/0022-2836(70)90057-4 }}&lt;/ref&gt; The algorithm essentially divides a large problem (e.g. the full sequence) into a series of smaller problems and uses the solutions to the smaller problems to reconstruct a solution to the larger problem.&lt;ref&gt;{{cite web|title=bioinformatics |url=http://www.britannica.com/EBchecked/topic/1334661/bioinformatics/285871/Goals-of-bioinformatics#ref1115380|accessdate=10 September 2014}}&lt;/ref&gt; It is also sometimes referred to as the [[optimal matching]] algorithm and the [[Sequence alignment#Global and local alignments|global alignment]] technique. The Needleman&ndash;Wunsch algorithm is still widely used for optimal global alignment, particularly when the quality of the global alignment is of the utmost importance.</p>
 
  
<p>[[File:Needleman-Wunsch pairwise sequence alignment.png|framed|right|Figure 1: Needleman-Wunsch pairwise sequence alignment</p>
+
{{Technical|date=September 2013}}
 +
{{Infobox algorithm
 +
|name= <!-- Defaults to article name -->
 +
|class= [[Sequence alignment]]
 +
|image=
 +
|caption=
 +
|data=
 +
|time= <math>O(mn)</math>
 +
|best-time=
 +
|average-time=
 +
|space= <math>O(mn)</math>
 +
}}
  
<p>&lt;pre&gt;<br />
+
The '''Needleman–Wunsch algorithm''' is an [[algorithm]] used in  [[bioinformatics]] to [[sequence alignment|align]] [[protein]] or [[nucleotide]] sequences. It was one of the first applications of [[dynamic programming]] to compare biological sequences. The algorithm was developed by Saul B. Needleman and Christian D. Wunsch and published in 1970.<ref name=Needleman>{{cite journal | journal=Journal of Molecular Biology | volume=48 | issue=3 | pages=443–53 | year=1970  |author1=Needleman, Saul B. |author2=Wunsch, Christian D. |last-author-amp=yes | title=A general method applicable to the search for similarities in the amino acid sequence of two proteins | url=http://linkinghub.elsevier.com/retrieve/pii/0022-2836(70)90057-4 | pmid=5420325 | doi = 10.1016/0022-2836(70)90057-4 }}</ref> The algorithm essentially divides a large problem (e.g. the full sequence) into a series of smaller problems and uses the solutions to the smaller problems to reconstruct a solution to the larger problem.<ref>{{cite web|title=bioinformatics |url=http://www.britannica.com/EBchecked/topic/1334661/bioinformatics/285871/Goals-of-bioinformatics#ref1115380|accessdate=10 September 2014}}</ref> It is also sometimes referred to as the [[optimal matching]] algorithm and the [[Sequence alignment#Global and local alignments|global alignment]] technique. The Needleman–Wunsch algorithm is still widely used for optimal global alignment, particularly when the quality of the global alignment is of the utmost importance.
Results:</p>
 
  
<p>Sequences &nbsp; &nbsp;Best alignments<br />
+
[[File:Needleman-Wunsch pairwise sequence alignment.png|framed|right|Figure 1: Needleman-Wunsch pairwise sequence alignment
--------- &nbsp; &nbsp;----------------------<br />
 
GCATGCU &nbsp; &nbsp; &nbsp;GCATG-CU &nbsp; &nbsp; &nbsp;GCA-TGCU &nbsp; &nbsp; &nbsp;GCAT-GCU<br />
 
GATTACA &nbsp; &nbsp; &nbsp;G-ATTACA &nbsp; &nbsp; &nbsp;G-ATTACA &nbsp; &nbsp; &nbsp;G-ATTACA</p>
 
  
<p>Interpretation of the initialization step:</p>
+
<pre>
 +
Results:
  
<p>One can interpret the leftmost column in the above figure like this (putting a &quot;handle&quot; before each sequence, annotated as + here):</p>
+
Sequences    Best alignments
 +
---------    ----------------------
 +
GCATGCU      GCATG-CU      GCA-TGCU      GCAT-GCU
 +
GATTACA      G-ATTACA      G-ATTACA      G-ATTACA
  
<p>Alignment: &nbsp;+GCATGCU<br />
+
Interpretation of the initialization step:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; +GATTACA<br />
 
Score: &nbsp; &nbsp; &nbsp;0 &nbsp;// Handle matches handle, doesn&#39;t win any score</p>
 
  
<p>Alignment: &nbsp;+GCATGCU<br />
+
One can interpret the leftmost column in the above figure like this (putting a "handle" before each sequence, annotated as + here):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+GATTACA<br />
 
Score: &nbsp; &nbsp; &nbsp;0 &nbsp;// 1 gap, &nbsp;score -1</p>
 
  
<p>Alignment: &nbsp;+GCATGCU<br />
+
Alignment: +GCATGCU
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; +GATTACA<br />
+
            +GATTACA
Score: &nbsp; &nbsp; &nbsp;0 &nbsp;// 2 gaps, score -2</p>
+
Score:     0 // Handle matches handle, doesn't win any score
  
<p>Alignment: &nbsp;+GCATGCU<br />
+
Alignment: +GCATGCU
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+GATTACA<br />
+
          +GATTACA
Score: &nbsp; &nbsp; &nbsp;0 &nbsp;// 3 gaps, score -3</p>
+
Score:     0 // 1 gap, score -1
  
<p>Alignment: &nbsp;+GCATGCU<br />
+
Alignment: +GCATGCU
&nbsp; &nbsp; &nbsp; &nbsp; +GATTACA<br />
+
          +GATTACA
Score: &nbsp; &nbsp; &nbsp;0 &nbsp;// 4 gaps, score -4</p>
+
Score:     0 // 2 gaps, score -2
  
<p>...</p>
+
Alignment:  +GCATGCU
 +
        +GATTACA
 +
Score:      0  // 3 gaps, score -3
  
<p>The same thing can be done for the uppermost row.<br />
+
Alignment:  +GCATGCU
&lt;/pre&gt;]]<br />
+
        +GATTACA
__TOC__<br />
+
Score:      0  // 4 gaps, score -4
{{-}}</p>
 
  
<p>==Introduction==<br />
+
...
This algorithm can be used for any two [[String (computer science)|strings]]. This guide will use two small [[DNA sequences]] as examples as shown in the diagram:<br />
 
&nbsp;GCATGCU<br />
 
&nbsp;GATTACA</p>
 
  
<p>===Constructing the grid===<br />
+
The same thing can be done for the uppermost row.
First construct a grid such as one shown in Figure 1 above. Start the first string in the top of the third column and start the other string at the start of the third row. Fill out the rest of the column and row headers as in Figure 1. There should be no numbers in the grid yet.</p>
+
</pre>]]
 +
__TOC__
 +
{{-}}
  
<p>{| class=&quot;wikitable&quot;<br />
+
==Introduction==
|-<br />
+
This algorithm can be used for any two [[String (computer science)|strings]]. This guide will use two small [[DNA sequences]] as examples as shown in the diagram:
!| &nbsp;|| &nbsp; || G || C || A || T || G || C || U<br />
+
GCATGCU
|-<br />
+
GATTACA
! scope=&quot;row&quot; |<br />
 
| &amp;nbsp; || &nbsp;|| &nbsp;|| &nbsp;|| &nbsp;|| &nbsp;|| &nbsp;||<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | T<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | T<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | C<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| &nbsp;|| &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|}</p>
 
  
<p>===Choosing a scoring system===<br />
+
===Constructing the grid===
Next, decide how to score each individual pair of letters. Using the example above, one possible alignment candidate might be:<br />
+
First construct a grid such as one shown in Figure 1 above. Start the first string in the top of the third column and start the other string at the start of the third row. Fill out the rest of the column and row headers as in Figure 1. There should be no numbers in the grid yet.
{{DNA sequence|<br />
 
&nbsp;12345678<br />
 
&nbsp;GCATG-CU<br />
 
&nbsp;G-ATTACA<br />
 
}}<br />
 
The letters may match, mismatch, or be matched to a gap (a deletion or insertion ([[indel]]):<br />
 
* Match: The two letters at the current index are the same.<br />
 
* Mismatch: The two letters at the current index are different. &nbsp;<br />
 
* Indel (INsertion or DELetion): The best alignment involves one letter aligning to a gap in the other string.</p>
 
  
<p>Each of these scenarios is assigned a score and the sum of the score of each pairing is the score of the whole alignment candidate. Different systems exist for assigning scores; some have been outlined in the [[#Scoring systems|Scoring systems]] section below. For now, the system used by Needleman and Wunsch&lt;ref name=&quot;Needleman&quot;/&gt; will be used:</p>
+
{| class="wikitable"
 +
|-
 +
!|  ||  || G || C || A || T || G || C || U
 +
|-
 +
! scope="row" |
 +
| &nbsp; ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | G
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | T
 +
|  ||  ||  ||  ||  ||  ||  || 
 +
|-
 +
! scope="row" | T
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | C
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
|  ||  ||  ||  ||  ||  ||  ||
 +
|}
  
<p>* Match: +1<br />
+
===Choosing a scoring system===
* Mismatch or Indel: &minus;1</p>
+
Next, decide how to score each individual pair of letters. Using the example above, one possible alignment candidate might be:
 +
{{DNA sequence|
 +
12345678
 +
GCATG-CU
 +
G-ATTACA
 +
}}
 +
The letters may match, mismatch, or be matched to a gap (a deletion or insertion ([[indel]]):
 +
* Match: The two letters at the current index are the same.
 +
* Mismatch: The two letters at the current index are different. 
 +
* Indel (INsertion or DELetion): The best alignment involves one letter aligning to a gap in the other string.
  
<p>For the Example above, the score of the alignment would be 0:<br />
+
Each of these scenarios is assigned a score and the sum of the score of each pairing is the score of the whole alignment candidate. Different systems exist for assigning scores; some have been outlined in the [[#Scoring systems|Scoring systems]] section below. For now, the system used by Needleman and Wunsch<ref name="Needleman"/> will be used:
{{DNA sequence|<br />
 
&nbsp;GCATG-CU<br />
 
&nbsp;G-ATTACA}}<br />
 
&nbsp;+-++--+- -&gt; -1*4 + 1*4 = 0</p>
 
  
<p>===Filling in the table===<br />
+
* Match: +1
Start with a zero in the second row, second column. Move through the cells row by row, calculating the score for each cell. The score is calculated by comparing the scores of the cells neighboring to the left, top or top-left (diagonal) of the cell and adding the appropriate score for match, mismatch or indel. Calculate the candidate scores for each of the three possibilities:<br />
+
* Mismatch or Indel: −1
* The path from the top or left cell represents an indel pairing, so take the score of the left and the top cell, and add the score for indel to each of them.<br />
 
* The diagonal path represents a match/mismatch, so take the score of the top-left diagonal cell and add the score for match if the corresponding bases in the row and column are matching or the score for mismatch if they do not.<br />
 
The resulting score for the cell is the highest of the three candidate scores.</p>
 
  
<p>Given there is no &#39;top&#39; or &#39;top-left&#39; cells for the second row only the existing cell to the left can be used to calculate the score of each cell. Hence -1 is added for each shift to the right as this represents an indelible from the previous score. This results in the first row being 0, -1, -2, -3, -4, -5, -6, -7. The same applies to the second column as only the existing score above each cell can be used. Thus the resulting table is:</p>
+
For the Example above, the score of the alignment would be 0:
 +
{{DNA sequence|
 +
GCATG-CU
 +
G-ATTACA}}
 +
+-++--+- -> -1*4 + 1*4 = 0
  
<p>{| class=&quot;wikitable&quot;<br />
+
===Filling in the table===
|-<br />
+
Start with a zero in the second row, second column. Move through the cells row by row, calculating the score for each cell. The score is calculated by comparing the scores of the cells neighboring to the left, top or top-left (diagonal) of the cell and adding the appropriate score for match, mismatch or indel. Calculate the candidate scores for each of the three possibilities:
!| &nbsp;|| &nbsp; || G || C || A || T || G || C || U<br />
+
* The path from the top or left cell represents an indel pairing, so take the score of the left and the top cell, and add the score for indel to each of them.
|-<br />
+
* The diagonal path represents a match/mismatch, so take the score of the top-left diagonal cell and add the score for match if the corresponding bases in the row and column are matching or the score for mismatch if they do not.
! scope=&quot;row&quot; |<br />
+
The resulting score for the cell is the highest of the three candidate scores.
| 0 || -1 || -2 || -3 || -4 || -5 || -6 || -7<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| -2 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | T<br />
 
| -3 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | T<br />
 
| -4 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| -5 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | C<br />
 
| -6 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| -7 || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; || &nbsp; ||&nbsp;<br />
 
|}</p>
 
  
<p>The first case with existing scores in all 3 directions is the intersection of our first letters (in this case G and G). The surrounding cells are below:<br />
+
Given there is no 'top' or 'top-left' cells for the second row only the existing cell to the left can be used to calculate the score of each cell. Hence -1 is added for each shift to the right as this represents an indelible from the previous score. This results in the first row being 0, -1, -2, -3, -4, -5, -6, -7. The same applies to the second column as only the existing score above each cell can be used. Thus the resulting table is:
{| class=&quot;wikitable&quot;<br />
 
|-<br />
 
!| &nbsp;|| &nbsp; || G<br />
 
|-<br />
 
! scope=&quot;row&quot; |<br />
 
| 0 || -1<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || &#39;&#39;&#39;X&#39;&#39;&#39;<br />
 
|}</p>
 
  
<p>This cell has three possible candidate sums:</p>
+
{| class="wikitable"
 +
|-
 +
!|  ||  || G || C || A || T || G || C || U
 +
|-
 +
! scope="row" |
 +
| 0 || -1 || -2 || -3 || -4 || -5 || -6 || -7
 +
|-
 +
! scope="row" | G
 +
| -1 ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
| -2 ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | T
 +
| -3 ||  ||  ||  ||  ||  ||  || 
 +
|-
 +
! scope="row" | T
 +
| -4 ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
| -5 ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | C
 +
| -6 ||  ||  ||  ||  ||  ||  ||
 +
|-
 +
! scope="row" | A
 +
| -7 ||  ||  ||  ||  ||  ||  ||
 +
|}
  
<p>* The diagonal top-left neighbor has score 0. The pairing of G and G is a match, so add the score for match: 0+1 = 1<br />
+
The first case with existing scores in all 3 directions is the intersection of our first letters (in this case G and G). The surrounding cells are below:
* The top neighbor has score -1 and moving from there represents an indel, so add the score for indel: (-1) + (-1) = (-2)<br />
+
{| class="wikitable"
* The left neighbor also has score -1, represents an indel and also produces (-2).</p>
+
|-
 +
!|  ||  || G
 +
|-
 +
! scope="row" |
 +
| 0 || -1
 +
|-
 +
! scope="row" | G
 +
| -1 || '''X'''
 +
|}
  
<p>The highest candidate is 1 and is entered into the cell:</p>
+
This cell has three possible candidate sums:
  
<p>{| class=&quot;wikitable&quot;<br />
+
* The diagonal top-left neighbor has score 0. The pairing of G and G is a match, so add the score for match: 0+1 = 1
|-<br />
+
* The top neighbor has score -1 and moving from there represents an indel, so add the score for indel: (-1) + (-1) = (-2)
!| &nbsp;|| &nbsp; || G<br />
+
* The left neighbor also has score -1, represents an indel and also produces (-2).
|-<br />
 
! scope=&quot;row&quot; |<br />
 
| 0 || -1<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || &#39;&#39;&#39;1&#39;&#39;&#39;<br />
 
|}</p>
 
  
<p>The cell which gave the highest candidate score must also be recorded. In the completed diagram in figure 1 above, this is represented as an arrow from the cell in row and column 3 to the cell in row and column 2.</p>
+
The highest candidate is 1 and is entered into the cell:
  
<p>In the next example, the diagonal step for both X and Y represents a mismatch:</p>
+
{| class="wikitable"
 +
|-
 +
!|  ||  || G
 +
|-
 +
! scope="row" |
 +
| 0 || -1
 +
|-
 +
! scope="row" | G
 +
| -1 || '''1'''
 +
|}
  
<p>{| class=&quot;wikitable&quot;<br />
+
The cell which gave the highest candidate score must also be recorded. In the completed diagram in figure 1 above, this is represented as an arrow from the cell in row and column 3 to the cell in row and column 2.
|-<br />
 
!| &nbsp;|| || G || C<br />
 
|-<br />
 
! scope=&quot;row&quot; |<br />
 
| 0 || -1 || -2<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || 1 || &#39;&#39;&#39;X&#39;&#39;&#39;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| -2 || &#39;&#39;&#39;Y&#39;&#39;&#39; ||&nbsp;<br />
 
|}</p>
 
  
<p>X:<br />
+
In the next example, the diagonal step for both X and Y represents a mismatch:
* Top: (-2)+(-1) = (-3)<br />
 
* Left: (+1)+(-1) = (0)<br />
 
* Top-Left: (-1)+(-1) = (-2)</p>
 
  
<p>Y:<br />
+
{| class="wikitable"
* Top: (1)+(-1) = (0)<br />
+
|-
* Left: (-2)+(-1) = (-3)<br />
+
!|  || || G || C
* Top-Left: (-1)+(-1) = (-2)</p>
+
|-
 +
! scope="row" |
 +
| 0 || -1 || -2
 +
|-
 +
! scope="row" | G
 +
| -1 || 1 || '''X'''
 +
|-
 +
! scope="row" | A
 +
| -2 || '''Y''' ||
 +
|}
  
<p>For both X and Y, the highest score is zero:</p>
+
X:
 +
* Top: (-2)+(-1) = (-3)
 +
* Left: (+1)+(-1) = (0)
 +
* Top-Left: (-1)+(-1) = (-2)
  
<p>{| class=&quot;wikitable&quot;<br />
+
Y:
|-<br />
+
* Top: (1)+(-1) = (0)
!| &nbsp;|| || G || C<br />
+
* Left: (-2)+(-1) = (-3)
|-<br />
+
* Top-Left: (-1)+(-1) = (-2)
! scope=&quot;row&quot; |<br />
 
| 0 || -1 || -2<br />
 
|-<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || 1 || &#39;&#39;&#39;0&#39;&#39;&#39;<br />
 
|-<br />
 
! scope=&quot;row&quot; | A<br />
 
| -2 || &#39;&#39;&#39;0&#39;&#39;&#39; ||&nbsp;<br />
 
|}</p>
 
  
<p>The highest candidate score may be reached by two or all neighboring cells:</p>
+
For both X and Y, the highest score is zero:
  
<p>{| class=&quot;wikitable&quot;<br />
+
{| class="wikitable"
|-<br />
+
|-
!| &nbsp;|| T || G<br />
+
!| || || G || C
|-<br />
+
|-
! scope=&quot;row&quot; | T<br />
+
! scope="row" |
| 1 || 1<br />
+
| 0 || -1 || -2
|-<br />
+
|-
! scope=&quot;row&quot; | A<br />
+
! scope="row" | G
| 0 || &#39;&#39;&#39;X&#39;&#39;&#39;<br />
+
| -1 || 1 || '''0'''
|}</p>
+
|-
 +
! scope="row" | A
 +
| -2 || '''0''' ||  
 +
|}
  
<p>* Top: (1)+(-1) = (0)<br />
+
The highest candidate score may be reached by two or all neighboring cells:
* Top-Left: (1)+(-1) = (0)<br />
 
* Left: (0)+(-1) = (-1)</p>
 
  
<p>In this case, all directions reaching the highest candidate score must be noted as possible origin cells in the finished diagram in figure 1, e.g. in the cell in row and column 7.</p>
+
{| class="wikitable"
 +
|-
 +
!|  || T || G
 +
|-
 +
! scope="row" | T
 +
| 1 || 1
 +
|-
 +
! scope="row" | A
 +
| 0 || '''X'''
 +
|}
  
<p>Filling in the table in this manner gives the scores or all possible alignment candidates, the score in the cell on the bottom right represents the alignment score for the best alignment.</p>
+
* Top: (1)+(-1) = (0)
 +
* Top-Left: (1)+(-1) = (0)
 +
* Left: (0)+(-1) = (-1)
  
<p>===Tracing arrows back to origin===<br />
+
In this case, all directions reaching the highest candidate score must be noted as possible origin cells in the finished diagram in figure 1, e.g. in the cell in row and column 7.
Mark a path from the cell on the bottom right back to the cell on the top left by following the direction of the arrows. From this path, the sequence is constructed by these rules:<br />
 
* A diagonal arrow represents a match or mismatch, so the letters of the column and the letter of the row of the origin cell will align.<br />
 
* A horizontal or vertical arrow represents an indel. Horizontal arrows will align a gap (&quot;-&quot;) to the letter of the row (the &quot;side&quot; sequence), vertical arrows will align a gap to the letter of the column (the &quot;top&quot; sequence).<br />
 
* If there are multiple arrows to choose from, they represent a branching of the alignments. If two or more branches all belong to paths from the bottom left to the top right cell, they are equally viable alignments. In this case, note the paths as separate alignment candidates.</p>
 
  
<p>Following these rules, the steps for one possible alignment candidate in figure 1 are:</p>
+
Filling in the table in this manner gives the scores or all possible alignment candidates, the score in the cell on the bottom right represents the alignment score for the best alignment.
  
<p>&nbsp;U &rarr; CU &rarr; GCU &rarr; -GCU &rarr; T-GCU &rarr; AT-GCU &rarr; CAT-GCU &rarr; &#39;&#39;&#39;GCAT-GCU&#39;&#39;&#39;<br />
+
===Tracing arrows back to origin===
&nbsp;A &rarr; CA &rarr; ACA &rarr; TACA &rarr; TTACA &rarr; ATTACA &rarr; -ATTACA &rarr; &#39;&#39;&#39;G-ATTACA&#39;&#39;&#39;<br />
+
Mark a path from the cell on the bottom right back to the cell on the top left by following the direction of the arrows. From this path, the sequence is constructed by these rules:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &darr;<br />
+
* A diagonal arrow represents a match or mismatch, so the letters of the column and the letter of the row of the origin cell will align.
&nbsp; &nbsp; &nbsp;(branch) &rarr; TGCU &rarr; ...<br />
+
* A horizontal or vertical arrow represents an indel. Horizontal arrows will align a gap ("-") to the letter of the row (the "side" sequence), vertical arrows will align a gap to the letter of the column (the "top" sequence).
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &rarr; TACA &rarr; ...</p>
+
* If there are multiple arrows to choose from, they represent a branching of the alignments. If two or more branches all belong to paths from the bottom left to the top right cell, they are equally viable alignments. In this case, note the paths as separate alignment candidates.
  
<p>==Scoring systems==</p>
+
Following these rules, the steps for one possible alignment candidate in figure 1 are:
  
<p>===Basic scoring schemes===<br />
+
U → CU → GCU → -GCU → T-GCU → AT-GCU → CAT-GCU → '''GCAT-GCU'''
The simplest scoring schemes simply give a value for each match, mismatch and indel. The step-by-step guide above uses match = 1, mismatch &nbsp;= &minus;1, indel = &minus;1. Thus the lower the alignment score the larger the [[Levenshtein distance|edit distance]], for this scoring system one wants a high score. Another scoring system might be:<br />
+
A → CA → ACA → TACA → TTACA → ATTACA → -ATTACA → '''G-ATTACA'''
* Match = 0<br />
+
              ↓
* Indel = 1<br />
+
    (branch) → TGCU → ...
* Mismatch = 1<br />
+
              → TACA → ...
For this system the alignment score will represent the edit distance between the two strings.<br />
 
Different scoring systems can be devised for different situations, for example if gaps are considered very bad for your alignment you may use a scoring system that penalises gaps heavily, such as:<br />
 
* Match = 0<br />
 
* Mismatch = 1<br />
 
* Indel = 10<br />
 
[https://blievrouw.github.io/needleman-wunsch/ Try it out].</p>
 
  
<p>===Similarity matrix===<br />
+
==Scoring systems==
More complicated scoring systems attribute values not only for the type of alteration, but also for the letters that are involved. For example, a match between A and A may be given 1, but a match between T and T may be given 4. Here (assuming the first scoring system) more importance is given to the Ts matching than the As, i.e. the Ts matching is &nbsp;assumed to be more significant to the alignment. This weighting based on letters also applies to mismatches.</p>
 
  
<p>In order to represent all the possible combinations of letters and their resulting scores &nbsp;a similarity matrix is used. The similarity matrix for the most basic system is represented as:</p>
+
===Basic scoring schemes===
 +
The simplest scoring schemes simply give a value for each match, mismatch and indel. The step-by-step guide above uses match = 1, mismatch  = −1, indel = −1. Thus the lower the alignment score the larger the [[Levenshtein distance|edit distance]], for this scoring system one wants a high score. Another scoring system might be:
 +
* Match = 0
 +
* Indel = 1
 +
* Mismatch = 1
 +
For this system the alignment score will represent the edit distance between the two strings.
 +
Different scoring systems can be devised for different situations, for example if gaps are considered very bad for your alignment you may use a scoring system that penalises gaps heavily, such as:
 +
* Match = 0
 +
* Mismatch = 1
 +
* Indel = 10
 +
[https://blievrouw.github.io/needleman-wunsch/ Try it out].
  
<p>{| style=&quot;font-family: monospace; font-size: 150%;&quot; cellpadding=&quot;2&quot; class=&quot;wikitable&quot;<br />
+
===Similarity matrix===
! scope=&quot;col&quot; |<br />
+
More complicated scoring systems attribute values not only for the type of alteration, but also for the letters that are involved. For example, a match between A and A may be given 1, but a match between T and T may be given 4. Here (assuming the first scoring system) more importance is given to the Ts matching than the As, i.e. the Ts matching is  assumed to be more significant to the alignment. This weighting based on letters also applies to mismatches.
! scope=&quot;col&quot; | A<br />
 
! scope=&quot;col&quot; | G<br />
 
! scope=&quot;col&quot; | C<br />
 
! scope=&quot;col&quot; | T<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | A<br />
 
| 1 || &nbsp;-1|| -1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || 1 || -1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | C<br />
 
| -1 || -1 || 1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | T<br />
 
| -1 || -1 || -1 || &nbsp;1<br />
 
|}<br />
 
Each score represents a switch from one of the letters the cell matches to the other. Hence this represents all possible matches and deletions (for an alphabet of ACGT). Note all the matches go along the diagonal, also not all the table needs to be filled, only this triangle because the scores are reciprocal.= (Score for A &rarr; C = Score for C &rarr; A). If implementing the T-T = 4 rule from above the following similarity matrix is produced:</p>
 
  
<p>{| style=&quot;font-family: monospace; font-size: 150%;&quot; cellpadding=&quot;2&quot; class=&quot;wikitable&quot;<br />
+
In order to represent all the possible combinations of letters and their resulting scores  a similarity matrix is used. The similarity matrix for the most basic system is represented as:
! scope=&quot;col&quot; |<br />
 
! scope=&quot;col&quot; | A<br />
 
! scope=&quot;col&quot; | G<br />
 
! scope=&quot;col&quot; | C<br />
 
! scope=&quot;col&quot; | T<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | A<br />
 
| 1 || -1 || -1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || 1 || -1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | C<br />
 
| -1 || -1 || 1 || -1<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | T<br />
 
| -1 || -1 || -1 || &nbsp;4<br />
 
|}</p>
 
  
<p>Different scoring matrices have been statistically constructed which give weight to different actions appropriate to a particular scenario. Having weighted scoring matrices is particularly important in protein sequence alignment due to the varying frequency of the different amino acids. There are two broad families of scoring matrices, each with further alterations for specific scenarios:<br />
+
{| style="font-family: monospace; font-size: 150%;" cellpadding="2" class="wikitable"
* [[Point accepted mutation|PAM]]<br />
+
! scope="col" |
* [[BLOSUM]]</p>
+
! scope="col" | A
 +
! scope="col" | G
 +
! scope="col" | C
 +
! scope="col" | T
 +
|- style="text-align: right;"
 +
! scope="row" | A
 +
| 1 ||  -1|| -1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | G
 +
| -1 || 1 || -1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | C
 +
| -1 || -1 || 1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | T
 +
| -1 || -1 || -1 ||  1
 +
|}
 +
Each score represents a switch from one of the letters the cell matches to the other. Hence this represents all possible matches and deletions (for an alphabet of ACGT). Note all the matches go along the diagonal, also not all the table needs to be filled, only this triangle because the scores are reciprocal.= (Score for A → C = Score for C → A). If implementing the T-T = 4 rule from above the following similarity matrix is produced:
  
<p>===Gap penalty===<br />
+
{| style="font-family: monospace; font-size: 150%;" cellpadding="2" class="wikitable"
When aligning sequences there are often gaps (i.e. indels), sometimes large ones. Biologically, a large gap is more likely to occur as one large deletion as opposed to multiple single deletions. Hence two small indels should have a worse score than one large one. The simple and common way to do this is via a large gap-start score for a new indel and a smaller gap-extension score for every letter which extends the indel. For example, new-indel may cost -5 and extend-indel may cost -1. In this way an alignment such as:<br />
+
! scope="col" |
&nbsp;GAAAAAAT<br />
+
! scope="col" | A
&nbsp;G--A-A-T<br />
+
! scope="col" | G
which has multiple equal alignments, some with multiple small alignments will now align as:<br />
+
! scope="col" | C
&nbsp;GAAAAAAT<br />
+
! scope="col" | T
&nbsp;GAA----T<br />
+
|- style="text-align: right;"
or any alignment with a 4 long gap in preference over multiple small gaps.</p>
+
! scope="row" | A
 +
| 1 || -1 || -1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | G
 +
| -1 || 1 || -1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | C
 +
| -1 || -1 || 1 || -1
 +
|- style="text-align: right;"
 +
! scope="row" | T
 +
| -1 || -1 || -1 ||  4
 +
|}
  
<p>==Advanced presentation of algorithm==<br />
+
Different scoring matrices have been statistically constructed which give weight to different actions appropriate to a particular scenario. Having weighted scoring matrices is particularly important in protein sequence alignment due to the varying frequency of the different amino acids. There are two broad families of scoring matrices, each with further alterations for specific scenarios:
Scores for aligned characters are specified by a [[similarity matrix]]. Here, {{math|&#39;&#39;S&#39;&#39;(&#39;&#39;a&#39;&#39;, &#39;&#39;b&#39;&#39;)}} is the similarity of characters &#39;&#39;a&#39;&#39; and &#39;&#39;b&#39;&#39;. It uses a linear [[gap penalty]], here called {{mvar|d}}.</p>
+
* [[Point accepted mutation|PAM]]
 +
* [[BLOSUM]]
  
<p>For example, if the similarity matrix was<br />
+
===Gap penalty===
{| style=&quot;font-family: monospace; font-size: 150%;&quot; cellpadding=&quot;2&quot; class=&quot;wikitable&quot;<br />
+
When aligning sequences there are often gaps (i.e. indels), sometimes large ones. Biologically, a large gap is more likely to occur as one large deletion as opposed to multiple single deletions. Hence two small indels should have a worse score than one large one. The simple and common way to do this is via a large gap-start score for a new indel and a smaller gap-extension score for every letter which extends the indel. For example, new-indel may cost -5 and extend-indel may cost -1. In this way an alignment such as:
! scope=&quot;col&quot; |<br />
+
GAAAAAAT
! scope=&quot;col&quot; | A<br />
+
G--A-A-T
! scope=&quot;col&quot; | G<br />
+
which has multiple equal alignments, some with multiple small alignments will now align as:
! scope=&quot;col&quot; | C<br />
+
GAAAAAAT
! scope=&quot;col&quot; | T<br />
+
GAA----T
|- style=&quot;text-align: right;&quot;<br />
+
or any alignment with a 4 long gap in preference over multiple small gaps.
! scope=&quot;row&quot; | A<br />
 
| 10 || -1 || -3 || -4<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | G<br />
 
| -1 || 7 || -5 || -3<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | C<br />
 
| -3 || -5 || 9 || 0<br />
 
|- style=&quot;text-align: right;&quot;<br />
 
! scope=&quot;row&quot; | T<br />
 
| -4 || -3 || 0 || 8<br />
 
|}</p>
 
  
<p>then the alignment:<br />
+
==Advanced presentation of algorithm==
&nbsp;AGACTAGTTAC<br />
+
Scores for aligned characters are specified by a [[similarity matrix]]. Here, {{math|''S''(''a'', ''b'')}} is the similarity of characters ''a'' and ''b''. It uses a linear [[gap penalty]], here called {{mvar|d}}.
&nbsp;CGA---GACGT<br />
 
with a gap penalty of -5, would have the following score:<br />
 
:{{math|&#39;&#39;S&#39;&#39;(A,C) + &#39;&#39;S&#39;&#39;(G,G) + &#39;&#39;S&#39;&#39;(A,A) + (3 &times; &#39;&#39;d&#39;&#39;) + &#39;&#39;S&#39;&#39;(G,G) + &#39;&#39;S&#39;&#39;(T,A) + &#39;&#39;S&#39;&#39;(T,C) + &#39;&#39;S&#39;&#39;(A,G) + &#39;&#39;S&#39;&#39;(C,T)}}<br />
 
:= -3 + 7 + 10 - (3 &times; 5) + 7 + (-4) + 0 + (-1) + 0 = 1</p>
 
  
<p>To find the alignment with the highest score, a two-dimensional [[Array data structure|array]] (or [[Matrix (mathematics)|matrix]]) &#39;&#39;F&#39;&#39; is allocated. The entry in row &#39;&#39;i&#39;&#39; and column &#39;&#39;j&#39;&#39; is denoted here by<br />
+
For example, if the similarity matrix was
&lt;math&gt;F_{ij}&lt;/math&gt;. There is one row for each character in sequence &#39;&#39;A&#39;&#39;, and one column for each character in sequence &#39;&#39;B&#39;&#39;. Thus, if aligning sequences of sizes &#39;&#39;n&#39;&#39; and &#39;&#39;m&#39;&#39;, the amount of memory used is in &lt;math&gt;O(nm)&lt;/math&gt;. [[Hirschberg&#39;s algorithm]] only holds a subset of the array in memory and uses &lt;math&gt;\Theta(\min \{n,m\})&lt;/math&gt; space, but is otherwise similar to Needleman-Wunsch (and still requires &lt;math&gt;O(nm)&lt;/math&gt; time).</p>
+
{| style="font-family: monospace; font-size: 150%;" cellpadding="2" class="wikitable"
 +
! scope="col" |
 +
! scope="col" | A
 +
! scope="col" | G
 +
! scope="col" | C
 +
! scope="col" | T
 +
|- style="text-align: right;"
 +
! scope="row" | A
 +
| 10 || -1 || -3 || -4
 +
|- style="text-align: right;"
 +
! scope="row" | G
 +
| -1 || 7 || -5 || -3
 +
|- style="text-align: right;"
 +
! scope="row" | C
 +
| -3 || -5 || 9 || 0
 +
|- style="text-align: right;"
 +
! scope="row" | T
 +
| -4 || -3 || 0 || 8
 +
|}
  
<p>As the algorithm progresses, the &lt;math&gt;F_{ij}&lt;/math&gt; will be assigned to be the optimal score for the alignment of the first &lt;math&gt;i=0,\dotsc,n&lt;/math&gt; characters in &#39;&#39;A&#39;&#39; and the first &lt;math&gt;j=0,\dotsc,m&lt;/math&gt; characters in &#39;&#39;B&#39;&#39;. The [[Bellman equation#Bellman&#39;s Principle of Optimality|principle of optimality]] is then applied as follows:<br />
+
then the alignment:
* Basis:<br />
+
AGACTAGTTAC
:&lt;math&gt;F_{0j} = d*j&lt;/math&gt;<br />
+
CGA---GACGT
:&lt;math&gt;F_{i0} = d*i&lt;/math&gt;<br />
+
with a gap penalty of -5, would have the following score:
* Recursion, based on the principle of optimality:<br />
+
:{{math|''S''(A,C) + ''S''(G,G) + ''S''(A,A) + (3 × ''d'') + ''S''(G,G) + ''S''(T,A) + ''S''(T,C) + ''S''(A,G) + ''S''(C,T)}}
:&lt;math&gt;F_{ij} = \max(F_{i-1,j-1} + S(A_{i}, B_{j}), \; F_{i,j-1} + d, \; F_{i-1,j} + d)&lt;/math&gt;</p>
+
:= -3 + 7 + 10 - (3 × 5) + 7 + (-4) + 0 + (-1) + 0 = 1
  
<p>The pseudo-code for the algorithm to compute the F matrix therefore looks like this:<br />
+
To find the alignment with the highest score, a two-dimensional [[Array data structure|array]] (or [[Matrix (mathematics)|matrix]]) ''F'' is allocated. The entry in row ''i'' and column ''j'' is denoted here by
&nbsp;d &larr; MismatchScore<br />
+
<math>F_{ij}</math>. There is one row for each character in sequence ''A'', and one column for each character in sequence ''B''. Thus, if aligning sequences of sizes ''n'' and ''m'', the amount of memory used is in <math>O(nm)</math>. [[Hirschberg's algorithm]] only holds a subset of the array in memory and uses <math>\Theta(\min \{n,m\})</math> space, but is otherwise similar to Needleman-Wunsch (and still requires <math>O(nm)</math> time).
&nbsp;&#39;&#39;&#39;for&#39;&#39;&#39; i=0 &#39;&#39;&#39;to&#39;&#39;&#39; &#39;&#39;&#39;length&#39;&#39;&#39;(A)<br />
 
&nbsp; &nbsp;F(i,0) &larr; d*i<br />
 
&nbsp;&#39;&#39;&#39;for&#39;&#39;&#39; j=0 &#39;&#39;&#39;to&#39;&#39;&#39; &#39;&#39;&#39;length&#39;&#39;&#39;(B)<br />
 
&nbsp; &nbsp;F(0,j) &larr; d*j<br />
 
&nbsp;&#39;&#39;&#39;for&#39;&#39;&#39; i=1 &#39;&#39;&#39;to&#39;&#39;&#39; &#39;&#39;&#39;length&#39;&#39;&#39;(A)<br />
 
&nbsp; &nbsp;&#39;&#39;&#39;for&#39;&#39;&#39; j=1 &#39;&#39;&#39;to&#39;&#39;&#39; &#39;&#39;&#39;length&#39;&#39;&#39;(B)<br />
 
&nbsp; &nbsp;{<br />
 
&nbsp; &nbsp; &nbsp;Match &larr; F(i-1,j-1) + S(A&lt;sub&gt;i&lt;/sub&gt;, B&lt;sub&gt;j&lt;/sub&gt;)<br />
 
&nbsp; &nbsp; &nbsp;Delete &larr; F(i-1, j) + d<br />
 
&nbsp; &nbsp; &nbsp;Insert &larr; F(i, j-1) + d<br />
 
&nbsp; &nbsp; &nbsp;F(i,j) &larr; &#39;&#39;&#39;max&#39;&#39;&#39;(Match, Insert, Delete)<br />
 
&nbsp; &nbsp;}<br />
 
Once the &#39;&#39;F&#39;&#39; matrix is computed, the entry &lt;math&gt;F_{nm}&lt;/math&gt; gives the maximum score among all possible alignments. To compute an alignment that actually gives this score, you start from the bottom right cell, and compare the value with the three possible sources (Match, Insert, and Delete above) to see which it came from. If Match, then &lt;math&gt;A_i&lt;/math&gt; and &lt;math&gt;B_j&lt;/math&gt; are aligned, if Delete, then &lt;math&gt;A_i&lt;/math&gt; is aligned with a gap, and if Insert, then &lt;math&gt;B_j&lt;/math&gt; is aligned with a gap. (In general, more than one choice may have the same value, leading to alternative optimal alignments.)<br />
 
&nbsp;AlignmentA &larr; &quot;&quot;<br />
 
&nbsp;AlignmentB &larr; &quot;&quot;<br />
 
&nbsp;i &larr; &#39;&#39;&#39;length&#39;&#39;&#39;(A)<br />
 
&nbsp;j &larr; &#39;&#39;&#39;length&#39;&#39;&#39;(B)<br />
 
&nbsp;&#39;&#39;&#39;while&#39;&#39;&#39; (i &gt; 0 &#39;&#39;&#39;or&#39;&#39;&#39; j &gt; 0)<br />
 
&nbsp;{<br />
 
&nbsp; &nbsp;&#39;&#39;&#39;if&#39;&#39;&#39; (i &gt; 0 &#39;&#39;&#39;and&#39;&#39;&#39; j &gt; 0 &#39;&#39;&#39;and&#39;&#39;&#39; F(i,j) == F(i-1,j-1) + S(A&lt;sub&gt;i&lt;/sub&gt;, B&lt;sub&gt;j&lt;/sub&gt;))<br />
 
&nbsp; &nbsp;{<br />
 
&nbsp; &nbsp; &nbsp;AlignmentA &larr; A&lt;sub&gt;i&lt;/sub&gt; + AlignmentA<br />
 
&nbsp; &nbsp; &nbsp;AlignmentB &larr; B&lt;sub&gt;j&lt;/sub&gt; + AlignmentB<br />
 
&nbsp; &nbsp; &nbsp;i &larr; i - 1<br />
 
&nbsp; &nbsp; &nbsp;j &larr; j - 1<br />
 
&nbsp; &nbsp;}<br />
 
&nbsp; &nbsp;&#39;&#39;&#39;else&#39;&#39;&#39; &#39;&#39;&#39;if&#39;&#39;&#39; (i &gt; 0 &#39;&#39;&#39;and&#39;&#39;&#39; F(i,j) == F(i-1,j) + d)<br />
 
&nbsp; &nbsp;{<br />
 
&nbsp; &nbsp; &nbsp;AlignmentA &larr; A&lt;sub&gt;i&lt;/sub&gt; + AlignmentA<br />
 
&nbsp; &nbsp; &nbsp;AlignmentB &larr; &quot;-&quot; + AlignmentB<br />
 
&nbsp; &nbsp; &nbsp;i &larr; i - 1<br />
 
&nbsp; &nbsp;}<br />
 
&nbsp; &nbsp;&#39;&#39;&#39;else&#39;&#39;&#39;<br />
 
&nbsp; &nbsp;{<br />
 
&nbsp; &nbsp; &nbsp;AlignmentA &larr; &quot;-&quot; + AlignmentA<br />
 
&nbsp; &nbsp; &nbsp;AlignmentB &larr; B&lt;sub&gt;j&lt;/sub&gt; + AlignmentB<br />
 
&nbsp; &nbsp; &nbsp;j &larr; j - 1<br />
 
&nbsp; &nbsp;}<br />
 
&nbsp;}</p>
 
  
<p>== Complexity ==<br />
+
As the algorithm progresses, the <math>F_{ij}</math> will be assigned to be the optimal score for the alignment of the first <math>i=0,\dotsc,n</math> characters in ''A'' and the first <math>j=0,\dotsc,m</math> characters in ''B''. The [[Bellman equation#Bellman's Principle of Optimality|principle of optimality]] is then applied as follows:
Computing the score &lt;math&gt;F_{ij}&lt;/math&gt; for each cell in the table is an &lt;math&gt;O(1)&lt;/math&gt; operation. Thus the time complexity of the algorithm for two sequences of length &lt;math&gt;n&lt;/math&gt; and &lt;math&gt;m&lt;/math&gt; is &lt;math&gt;O(mn)&lt;/math&gt;.&lt;ref name=&quot;:0&quot;&gt;{{Cite book|url=https://www.worldcat.org/oclc/429634761|title=Algorithms in bioinformatics : a practical introduction|last=Wing-Kin.|first=Sung,|date=2010|publisher=Chapman &amp; Hall/CRC Press|year=|isbn=9781420070330|location=Boca Raton|pages=34&ndash;35|oclc=429634761}}&lt;/ref&gt; It has been shown that it is possible to improve the running time to &lt;math&gt;O(mn/ \log n)&lt;/math&gt; using the [[Method of Four Russians]].&lt;ref name=&quot;:0&quot; /&gt;&lt;ref&gt;{{Cite journal|last=Masek|first=William|last2=Paterson|first2=Michael|date=February 1980|title=A faster algorithm computing string edit distances|url=https://www.sciencedirect.com/science/article/pii/0022000080900021|journal=Journal of Computer and System Sciences|volume=20|pages=18&ndash;31|doi=10.1016/0022-0000(80)90002-1|via=Elsevier Science Direct}}&lt;/ref&gt; Since the algorithm fill an &lt;math&gt;n \times m&lt;/math&gt; table the space complexity is &lt;math&gt;O(mn)&lt;/math&gt;.&lt;ref name=&quot;:0&quot; /&gt;</p>
+
* Basis:
 +
:<math>F_{0j} = d*j</math>
 +
:<math>F_{i0} = d*i</math>
 +
* Recursion, based on the principle of optimality:
 +
:<math>F_{ij} = \max(F_{i-1,j-1} + S(A_{i}, B_{j}), \; F_{i,j-1} + d, \; F_{i-1,j} + d)</math>
  
<p>==Historical notes and algorithm development==<br />
+
The pseudo-code for the algorithm to compute the F matrix therefore looks like this:
The original purpose of the algorithm described by Needleman and Wunsch was to find similarities in the amino acid sequences of two proteins.&lt;ref name=Needleman /&gt;</p>
+
d ← MismatchScore
 +
'''for''' i=0 '''to''' '''length'''(A)
 +
  F(i,0) ← d*i
 +
'''for''' j=0 '''to''' '''length'''(B)
 +
  F(0,j) ← d*j
 +
'''for''' i=1 '''to''' '''length'''(A)
 +
  '''for''' j=1 '''to''' '''length'''(B)
 +
  {
 +
    Match ← F(i-1,j-1) + S(A<sub>i</sub>, B<sub>j</sub>)
 +
    Delete ← F(i-1, j) + d
 +
    Insert ← F(i, j-1) + d
 +
    F(i,j) ← '''max'''(Match, Insert, Delete)
 +
  }
 +
Once the ''F'' matrix is computed, the entry <math>F_{nm}</math> gives the maximum score among all possible alignments. To compute an alignment that actually gives this score, you start from the bottom right cell, and compare the value with the three possible sources (Match, Insert, and Delete above) to see which it came from. If Match, then <math>A_i</math> and <math>B_j</math> are aligned, if Delete, then <math>A_i</math> is aligned with a gap, and if Insert, then <math>B_j</math> is aligned with a gap. (In general, more than one choice may have the same value, leading to alternative optimal alignments.)
 +
AlignmentA ← ""
 +
AlignmentB ← ""
 +
i ← '''length'''(A)
 +
j ← '''length'''(B)
 +
'''while''' (i > 0 '''or''' j > 0)
 +
{
 +
  '''if''' (i > 0 '''and''' j > 0 '''and''' F(i,j) == F(i-1,j-1) + S(A<sub>i</sub>, B<sub>j</sub>))
 +
  {
 +
    AlignmentA ← A<sub>i</sub> + AlignmentA
 +
    AlignmentB ← B<sub>j</sub> + AlignmentB
 +
    i ← i - 1
 +
    j ← j - 1
 +
  }
 +
  '''else''' '''if''' (i > 0 '''and''' F(i,j) == F(i-1,j) + d)
 +
  {
 +
    AlignmentA ← A<sub>i</sub> + AlignmentA
 +
    AlignmentB ← "-" + AlignmentB
 +
    i ← i - 1
 +
  }
 +
  '''else'''
 +
  {
 +
    AlignmentA ← "-" + AlignmentA
 +
    AlignmentB ← B<sub>j</sub> + AlignmentB
 +
    j ← j - 1
 +
  }
 +
}
  
<p>Needleman and Wunsch describe their algorithm explicitly for the case when the alignment is penalized solely by the matches and mismatches, and gaps have no penalty (&#39;&#39;d&#39;&#39;=0). The original publication from 1970 suggests the [[recursion]]<br />
+
== Complexity ==
&lt;math&gt;F_{ij} = \max_{h&lt;i,k&lt;j} \{ F_{h,j-1}+S(A_{i},B_{j}), F_{i-1,k}+S(A_i,B_j) \}&lt;/math&gt;.</p>
+
Computing the score <math>F_{ij}</math> for each cell in the table is an <math>O(1)</math> operation. Thus the time complexity of the algorithm for two sequences of length <math>n</math> and <math>m</math> is <math>O(mn)</math>.<ref name=":0">{{Cite book|url=https://www.worldcat.org/oclc/429634761|title=Algorithms in bioinformatics : a practical introduction|last=Wing-Kin.|first=Sung,|date=2010|publisher=Chapman & Hall/CRC Press|year=|isbn=9781420070330|location=Boca Raton|pages=34–35|oclc=429634761}}</ref> It has been shown that it is possible to improve the running time to <math>O(mn/ \log n)</math> using the [[Method of Four Russians]].<ref name=":0" /><ref>{{Cite journal|last=Masek|first=William|last2=Paterson|first2=Michael|date=February 1980|title=A faster algorithm computing string edit distances|url=https://www.sciencedirect.com/science/article/pii/0022000080900021|journal=Journal of Computer and System Sciences|volume=20|pages=18–31|doi=10.1016/0022-0000(80)90002-1|via=Elsevier Science Direct}}</ref> Since the algorithm fill an <math>n \times m</math> table the space complexity is <math>O(mn)</math>.<ref name=":0" />
  
<p>The corresponding dynamic programming algorithm takes cubic time. The paper also points out that the recursion can accommodate arbitrary gap penalization formulas:</p>
+
==Historical notes and algorithm development==
 +
The original purpose of the algorithm described by Needleman and Wunsch was to find similarities in the amino acid sequences of two proteins.<ref name=Needleman />
  
<p>&lt;blockquote&gt;<br />
+
Needleman and Wunsch describe their algorithm explicitly for the case when the alignment is penalized solely by the matches and mismatches, and gaps have no penalty (''d''=0). The original publication from 1970 suggests the [[recursion]]
A penalty factor, a number subtracted for every gap made, may be assessed as a barrier to allowing the gap. The penalty factor could be a function of the size and/or direction of the gap. [page 444]<br />
+
<math>F_{ij} = \max_{h<i,k<j} \{ F_{h,j-1}+S(A_{i},B_{j}), F_{i-1,k}+S(A_i,B_j) \}</math>.
&lt;/blockquote&gt;</p>
 
  
<p>A better dynamic programming algorithm with quadratic running time for the same problem (no gap penalty) was first introduced&lt;ref name=Sankoff&gt;{{cite journal | doi=10.1073/pnas.69.1.4 | journal=Proceedings of the National Academy of Sciences of the USA | volume=69 | issue=1 | pages=4&ndash;6 | year=1972 &nbsp;| author=Sankoff D | title=Matching sequences under deletion/insertion constraints | url=http://www.pnas.org/content/69/1/4.abstract | pmid=4500555 | pmc=427531}}&lt;/ref&gt; by David Sankoff in 1972.<br />
+
The corresponding dynamic programming algorithm takes cubic time. The paper also points out that the recursion can accommodate arbitrary gap penalization formulas:
Similar quadratic-time algorithms were discovered independently<br />
 
by T. K. Vintsyuk&lt;ref name=Vintsyuk&gt;{{cite journal | journal=Kibernetika | volume=4 | pages=81&ndash;88 | year=1968 &nbsp;| author=Vintsyuk TK | title=Speech discrimination by dynamic programming|url=https://link.springer.com/content/pdf/10.1007/BF01074755.pdf}}&lt;/ref&gt; in 1968 for speech processing<br />
 
([[Dynamic time warping|&quot;time warping&quot;]]), and by Robert A. Wagner and [[Michael J. Fischer]]&lt;ref name=WagnerFischer&gt;{{cite journal |vauthors=Wagner RA, Fischer MJ | journal = [[Journal of the ACM]] | title=The string-to-string correction problem | volume=21 | issue=1 | year=1974 | pages=168&ndash;173 | doi=10.1145/321796.321811}}&lt;/ref&gt; in 1974 for string matching.</p>
 
  
<p>Needleman and Wunsch formulated their problem in terms of maximizing similarity. Another possibility is to minimize the [[Levenshtein distance|edit distance]] between sequences, introduced by [[Vladimir Levenshtein]]. Peter H. Sellers showed&lt;ref name=Sellers&gt;{{cite journal | doi=10.1137/0126070 | title=On the theory and computation of evolutionary distances | author=Sellers PH | journal = SIAM Journal on Applied Mathematics | volume = 26 | issue = 4 | pages = 787&ndash;793 | year = 1974}}&lt;/ref&gt; in 1974 that the two problems are equivalent.</p>
+
<blockquote>
 +
A penalty factor, a number subtracted for every gap made, may be assessed as a barrier to allowing the gap. The penalty factor could be a function of the size and/or direction of the gap. [page 444]
 +
</blockquote>
  
<p>The Needleman&ndash;Wunsch algorithm is still widely used for optimal [[Sequence alignment#Global and local alignments|global alignment]], particularly when the quality of the global alignment is of the utmost importance. However, the algorithm is expensive with respect to time and space, proportional to the product of the length of two sequences and hence is not suitable for long sequences.</p>
+
A better dynamic programming algorithm with quadratic running time for the same problem (no gap penalty) was first introduced<ref name=Sankoff>{{cite journal | doi=10.1073/pnas.69.1.4 | journal=Proceedings of the National Academy of Sciences of the USA | volume=69 | issue=1 | pages=4–6 | year=1972  | author=Sankoff D | title=Matching sequences under deletion/insertion constraints | url=http://www.pnas.org/content/69/1/4.abstract | pmid=4500555 | pmc=427531}}</ref> by David Sankoff in 1972.
 +
Similar quadratic-time algorithms were discovered independently
 +
by T. K. Vintsyuk<ref name=Vintsyuk>{{cite journal | journal=Kibernetika | volume=4 | pages=81–88 | year=1968  | author=Vintsyuk TK | title=Speech discrimination by dynamic programming|url=https://link.springer.com/content/pdf/10.1007/BF01074755.pdf}}</ref> in 1968 for speech processing
 +
([[Dynamic time warping|"time warping"]]), and by Robert A. Wagner and [[Michael J. Fischer]]<ref name=WagnerFischer>{{cite journal |vauthors=Wagner RA, Fischer MJ | journal = [[Journal of the ACM]] | title=The string-to-string correction problem | volume=21 | issue=1 | year=1974 | pages=168–173 | doi=10.1145/321796.321811}}</ref> in 1974 for string matching.
  
<p>Recent development has focused on improving the time and space cost of the algorithm while maintaining quality. For example, in 2013, a Fast Optimal Global Sequence Alignment Algorithm (FOGSAA),&lt;ref&gt;{{cite journal|last1=Chakraborty|first1=Angana|last2=Bandyopadhyay|first2=Sanghamitra|title=FOGSAA: Fast Optimal Global Sequence Alignment Algorithm|journal=Scientific Reports|date=29 April 2013|volume=3|doi=10.1038/srep01746|url=http://www.nature.com/srep/2013/130429/srep01746/full/srep01746.html|accessdate=11 September 2014|pmid=23624407|pmc=3638164}}&lt;/ref&gt; suggested alignment of nucleotide/protein sequences faster than other optimal global alignment methods, including the Needleman&ndash;Wunsch algorithm. The paper claims that when compared to the Needleman&ndash;Wunsch algorithm, FOGSAA achieves a time gain of 70&ndash;90% for highly similar nucleotide sequences (with &gt; 80% similarity), and 54&ndash;70% for sequences having 30&ndash;80% similarity.</p>
+
Needleman and Wunsch formulated their problem in terms of maximizing similarity. Another possibility is to minimize the [[Levenshtein distance|edit distance]] between sequences, introduced by [[Vladimir Levenshtein]]. Peter H. Sellers showed<ref name=Sellers>{{cite journal | doi=10.1137/0126070 | title=On the theory and computation of evolutionary distances | author=Sellers PH | journal = SIAM Journal on Applied Mathematics | volume = 26 | issue = 4 | pages = 787–793 | year = 1974}}</ref> in 1974 that the two problems are equivalent.
  
<p>==Global alignment tools using the Needleman&ndash;Wunsch algorithm==<br />
+
The Needleman–Wunsch algorithm is still widely used for optimal [[Sequence alignment#Global and local alignments|global alignment]], particularly when the quality of the global alignment is of the utmost importance. However, the algorithm is expensive with respect to time and space, proportional to the product of the length of two sequences and hence is not suitable for long sequences.
* [http://www.ebi.ac.uk/Tools/psa EMBOSS Needle and EMBOSS Stretcher Global Alignment Tools]<br />
 
* [https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&amp;PROG_DEF=blastn&amp;BLAST_PROG_DEF=blastn&amp;BLAST_SPEC=GlobalAln&amp;LINK_LOC=BlastHomeLink Needleman-Wunsch alignment for two nucleotide sequences]<br />
 
* [http://www.mathworks.com.au/help/bioinfo/ref/nwalign.html MathWorks - Globally align two sequences using Needleman-Wunsch algorithm]<br />
 
* [https://github.com/bitkeeper-scm/bitkeeper/blob/master/src/libdiff.c#L948 BitKeeper &ndash; Source Control Management Software]</p>
 
  
<p>==Applications outside bioinformatics==</p>
+
Recent development has focused on improving the time and space cost of the algorithm while maintaining quality. For example, in 2013, a Fast Optimal Global Sequence Alignment Algorithm (FOGSAA),<ref>{{cite journal|last1=Chakraborty|first1=Angana|last2=Bandyopadhyay|first2=Sanghamitra|title=FOGSAA: Fast Optimal Global Sequence Alignment Algorithm|journal=Scientific Reports|date=29 April 2013|volume=3|doi=10.1038/srep01746|url=http://www.nature.com/srep/2013/130429/srep01746/full/srep01746.html|accessdate=11 September 2014|pmid=23624407|pmc=3638164}}</ref> suggested alignment of nucleotide/protein sequences faster than other optimal global alignment methods, including the Needleman–Wunsch algorithm. The paper claims that when compared to the Needleman–Wunsch algorithm, FOGSAA achieves a time gain of 70–90% for highly similar nucleotide sequences (with > 80% similarity), and 54–70% for sequences having 30–80% similarity.
  
<p>===[[Computer stereo vision]]===<br />
+
==Global alignment tools using the Needleman–Wunsch algorithm==
Stereo matching is an essential step in the process of 3D reconstruction from a pair of stereo images. When images have been rectified, an analogy can be drawn between aligning nucleotide and protein sequences and matching [[pixels]] belonging to [[scan lines]], since both tasks aim at establishing optimal correspondence between two strings of characters. The &lsquo;right&rsquo; image of a stereo pair can be seen as a mutated version of the &lsquo;left&rsquo; image: noise and individual camera sensitivity alter pixel values (i.e. character substitutions); and different view angle reveals previously occluded data and introduces new occlusions (i.e. insertion and deletion of characters). As consequence, minor modifications of the Needleman&ndash;Wunsch algorithm make it suitable for stereo matching.&lt;ref&gt;Dieny R., Thevenon J., Martinez-del-Rincon J., Nebel J.-C. (2011) &quot;[http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.220.9699 Bioinformatics inspired algorithm for stereo correspondence]&quot;. International Conference on Computer Vision Theory and Applications, March 5&ndash;7, Vilamoura - Algarve, Portugal.&lt;/ref&gt; Although performances in terms of accuracy are not state-of-the-art, the relative simplicity of the algorithm allows its implementation on [[embedded systems]].&lt;ref&gt;Madeo S., Pelliccia R., Salvadori C., Martinez-del-Rincon J., Nebel J.-C. (2014) &quot;[https://pure.qub.ac.uk/portal/files/12586298/stereovision_end.pdf An optimized stereo vision implementation for embedded systems: application to RGB and Infra-Red images]&quot;. Journal of Real-Time Image Processing.&lt;/ref&gt;</p>
+
* [http://www.ebi.ac.uk/Tools/psa EMBOSS Needle and EMBOSS Stretcher Global Alignment Tools]
 +
* [https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&PROG_DEF=blastn&BLAST_PROG_DEF=blastn&BLAST_SPEC=GlobalAln&LINK_LOC=BlastHomeLink Needleman-Wunsch alignment for two nucleotide sequences]
 +
* [http://www.mathworks.com.au/help/bioinfo/ref/nwalign.html MathWorks - Globally align two sequences using Needleman-Wunsch algorithm]
 +
* [https://github.com/bitkeeper-scm/bitkeeper/blob/master/src/libdiff.c#L948 BitKeeper – Source Control Management Software]
  
<p>Although in many applications image rectification can be performed, e.g. by [[camera resectioning]] or calibration, it is sometimes impossible or impractical since the computational cost of accurate rectification models prohibit their usage in [[Real-time computing|real-time]] applications. Moreover, none of these models is suitable when a camera lens displays unexpected [[distortions]], such as those generated by raindrops, weatherproof covers or dust. By extending the Needleman&ndash;Wunsch algorithm, a line in the &lsquo;left&rsquo; image can be associated to a curve in the &lsquo;right&rsquo; image by finding the alignment with the highest score in a three-dimensional array (or matrix). Experiments demonstrated that such extension allows dense pixel matching between unrectified or distorted images.&lt;ref&gt;Martinez-del-Rincon J., Thevenon J., Dieny R., Nebel J.-C. (2012) &quot;[https://www.researchgate.net/profile/Jean-Christophe_Nebel/publication/257928290_Dense_pixel_matching_between_unrectified_and_distorted_images_using_dynamic_programming/links/0c9605266f2d98c719000000.pdf Dense Pixel Matching Between Unrectified and Distorted Images Using Dynamic Programming]&quot;. International Conference on Computer Vision Theory and Applications, 24&ndash;26 February, Rome, Italy.&lt;/ref&gt;</p>
+
==Applications outside bioinformatics==
  
<p>==See also==<br />
+
===[[Computer stereo vision]]===
* [[Smith&ndash;Waterman algorithm]]<br />
+
Stereo matching is an essential step in the process of 3D reconstruction from a pair of stereo images. When images have been rectified, an analogy can be drawn between aligning nucleotide and protein sequences and matching [[pixels]] belonging to [[scan lines]], since both tasks aim at establishing optimal correspondence between two strings of characters. The ‘right’ image of a stereo pair can be seen as a mutated version of the ‘left’ image: noise and individual camera sensitivity alter pixel values (i.e. character substitutions); and different view angle reveals previously occluded data and introduces new occlusions (i.e. insertion and deletion of characters). As consequence, minor modifications of the Needleman–Wunsch algorithm make it suitable for stereo matching.<ref>Dieny R., Thevenon J., Martinez-del-Rincon J., Nebel J.-C. (2011) "[http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.220.9699 Bioinformatics inspired algorithm for stereo correspondence]". International Conference on Computer Vision Theory and Applications, March 5–7, Vilamoura - Algarve, Portugal.</ref> Although performances in terms of accuracy are not state-of-the-art, the relative simplicity of the algorithm allows its implementation on [[embedded systems]].<ref>Madeo S., Pelliccia R., Salvadori C., Martinez-del-Rincon J., Nebel J.-C. (2014) "[https://pure.qub.ac.uk/portal/files/12586298/stereovision_end.pdf An optimized stereo vision implementation for embedded systems: application to RGB and Infra-Red images]". Journal of Real-Time Image Processing.</ref>
* [[Sequence mining]]<br />
 
* [[Levenshtein distance]]<br />
 
* [[Dynamic time warping]]<br />
 
* [[Sequence alignment]]</p>
 
  
<p>==References==<br />
+
Although in many applications image rectification can be performed, e.g. by [[camera resectioning]] or calibration, it is sometimes impossible or impractical since the computational cost of accurate rectification models prohibit their usage in [[Real-time computing|real-time]] applications. Moreover, none of these models is suitable when a camera lens displays unexpected [[distortions]], such as those generated by raindrops, weatherproof covers or dust. By extending the Needleman–Wunsch algorithm, a line in the ‘left’ image can be associated to a curve in the ‘right’ image by finding the alignment with the highest score in a three-dimensional array (or matrix). Experiments demonstrated that such extension allows dense pixel matching between unrectified or distorted images.<ref>Martinez-del-Rincon J., Thevenon J., Dieny R., Nebel J.-C. (2012) "[https://www.researchgate.net/profile/Jean-Christophe_Nebel/publication/257928290_Dense_pixel_matching_between_unrectified_and_distorted_images_using_dynamic_programming/links/0c9605266f2d98c719000000.pdf Dense Pixel Matching Between Unrectified and Distorted Images Using Dynamic Programming]". International Conference on Computer Vision Theory and Applications, 24–26 February, Rome, Italy.</ref>
{{Reflist}}</p>
 
  
<p>==External links==<br />
+
==See also==
{{External links|date=May 2017}}<br />
+
* [[Smith–Waterman algorithm]]
* [http://zhanglab.ccmb.med.umich.edu/NW-align NW-align: A protein sequence-to-sequence alignment program by Needleman-Wunsch algorithm (online server and source code)]<br />
+
* [[Sequence mining]]
* [[:File:ParallelNeedlemanAlgorithm.pdf | Parallel Needleman-Wunsch Algorithm for Grid]] - Implementation by Tahir Naveed, Imitaz Saeed Siddiqui and Shaftab Ahmed - Bahria University<br />
+
* [[Levenshtein distance]]
* [http://chneukirchen.org/blog/archive/2006/03/dynamic-programming-in-haskell.html Needleman-Wunsch Algorithm as Haskell Code]<br />
+
* [[Dynamic time warping]]
* [http://ds9a.nl/nwunsch A live Javascript-based demo of Needleman&ndash;Wunsch]<br />
+
* [[Sequence alignment]]
* [http://alfehrest.org/sub/nwa/index.html An interactive Javascript-based visual explanation of Needleman-Wunsch Algorithm]<br />
 
* [http://baba.sourceforge.net/ B.A.B.A.] &mdash; an applet (with source) which visually explains the algorithm.<br />
 
* [https://web.archive.org/web/20140729133238/http://www.science.marshall.edu/murraye/Clearer%20Matrix%20slide%20show.pdf A clear explanation of NW and its applications to sequence alignment]<br />
 
* [http://technology66.blogspot.com/2008/08/sequence-alignment-techniques.html Sequence Alignment Techniques at Technology Blog]<br />
 
* [https://web.archive.org/web/20091106224548/http://svitsrv25.epfl.ch/R-doc/library/Biostrings/html/00Index.html Biostrings] R package implementing Needleman&ndash;Wunsch algorithm among others<br />
 
* [https://gist.github.com/jonasmalacofilho/5226596 Needleman-Wunsch Algorithm as Haxe Code]</p>
 
  
<p>{{Strings}}</p>
+
==References==
 +
{{Reflist}}
  
<p>{{DEFAULTSORT:Needleman-Wunsch Algorithm}}<br />
+
==External links==
[[Category:Bioinformatics algorithms]]<br />
+
{{External links|date=May 2017}}
[[Category:Sequence alignment algorithms]]<br />
+
* [http://zhanglab.ccmb.med.umich.edu/NW-align NW-align: A protein sequence-to-sequence alignment program by Needleman-Wunsch algorithm (online server and source code)]
[[Category:Computational phylogenetics]]<br />
+
* [[:File:ParallelNeedlemanAlgorithm.pdf | Parallel Needleman-Wunsch Algorithm for Grid]] - Implementation by Tahir Naveed, Imitaz Saeed Siddiqui and Shaftab Ahmed - Bahria University
[[Category:Dynamic programming]]<br />
+
* [http://chneukirchen.org/blog/archive/2006/03/dynamic-programming-in-haskell.html Needleman-Wunsch Algorithm as Haskell Code]
[[Category:Articles with example pseudocode]]</p>
+
* [http://ds9a.nl/nwunsch A live Javascript-based demo of Needleman–Wunsch]
 +
* [http://alfehrest.org/sub/nwa/index.html An interactive Javascript-based visual explanation of Needleman-Wunsch Algorithm]
 +
* [http://baba.sourceforge.net/ B.A.B.A.] — an applet (with source) which visually explains the algorithm.
 +
* [https://web.archive.org/web/20140729133238/http://www.science.marshall.edu/murraye/Clearer%20Matrix%20slide%20show.pdf A clear explanation of NW and its applications to sequence alignment]
 +
* [http://technology66.blogspot.com/2008/08/sequence-alignment-techniques.html Sequence Alignment Techniques at Technology Blog]
 +
* [https://web.archive.org/web/20091106224548/http://svitsrv25.epfl.ch/R-doc/library/Biostrings/html/00Index.html Biostrings] R package implementing Needleman–Wunsch algorithm among others
 +
* [https://gist.github.com/jonasmalacofilho/5226596 Needleman-Wunsch Algorithm as Haxe Code]
 +
 
 +
{{Strings}}
 +
 
 +
{{DEFAULTSORT:Needleman-Wunsch Algorithm}}
 +
[[Category:Bioinformatics algorithms]]
 +
[[Category:Sequence alignment algorithms]]
 +
[[Category:Computational phylogenetics]]
 +
[[Category:Dynamic programming]]
 +
[[Category:Articles with example pseudocode]]

Revision as of 02:53, 7 December 2018

Needleman-Wunsch algorithm


The Needleman–Wunsch algorithm is an algorithm used in bioinformatics to align protein or nucleotide sequences. It was one of the first applications of dynamic programming to compare biological sequences. The algorithm was developed by Saul B. Needleman and Christian D. Wunsch and published in 1970. The algorithm essentially divides a large problem (e.g. the full sequence) into a series of smaller problems and uses the solutions to the smaller problems to reconstruct a solution to the larger problem. It is also sometimes referred to as the optimal matching algorithm and the global alignment technique. The Needleman–Wunsch algorithm is still widely used for optimal global alignment, particularly when the quality of the global alignment is of the utmost importance.

Figure 1: Needleman-Wunsch pairwise sequence alignment

Results:

Sequences    Best alignments
---------    ----------------------
GCATGCU      GCATG-CU      GCA-TGCU      GCAT-GCU
GATTACA      G-ATTACA      G-ATTACA      G-ATTACA

Interpretation of the initialization step:

One can interpret the leftmost column in the above figure like this (putting a "handle" before each sequence, annotated as + here):

Alignment:  +GCATGCU
            +GATTACA
Score:      0  // Handle matches handle, doesn't win any score

Alignment:  +GCATGCU
           +GATTACA
Score:      0  // 1 gap,  score -1

Alignment:  +GCATGCU
          +GATTACA
Score:      0  // 2 gaps, score -2

Alignment:  +GCATGCU
         +GATTACA
Score:      0  // 3 gaps, score -3

Alignment:  +GCATGCU
        +GATTACA
Score:      0  // 4 gaps, score -4

...

The same thing can be done for the uppermost row.

 


Template:Technical Template:Infobox algorithm

The Needleman–Wunsch algorithm is an algorithm used in bioinformatics to align protein or nucleotide sequences. It was one of the first applications of dynamic programming to compare biological sequences. The algorithm was developed by Saul B. Needleman and Christian D. Wunsch and published in 1970.[1] The algorithm essentially divides a large problem (e.g. the full sequence) into a series of smaller problems and uses the solutions to the smaller problems to reconstruct a solution to the larger problem.[2] It is also sometimes referred to as the optimal matching algorithm and the global alignment technique. The Needleman–Wunsch algorithm is still widely used for optimal global alignment, particularly when the quality of the global alignment is of the utmost importance.

Figure 1: Needleman-Wunsch pairwise sequence alignment
Results:

Sequences    Best alignments
---------    ----------------------
GCATGCU      GCATG-CU      GCA-TGCU      GCAT-GCU
GATTACA      G-ATTACA      G-ATTACA      G-ATTACA

Interpretation of the initialization step:

One can interpret the leftmost column in the above figure like this (putting a "handle" before each sequence, annotated as + here):

Alignment:  +GCATGCU
            +GATTACA
Score:      0  // Handle matches handle, doesn't win any score

Alignment:  +GCATGCU
           +GATTACA
Score:      0  // 1 gap,  score -1

Alignment:  +GCATGCU
          +GATTACA
Score:      0  // 2 gaps, score -2

Alignment:  +GCATGCU
         +GATTACA
Score:      0  // 3 gaps, score -3

Alignment:  +GCATGCU
        +GATTACA
Score:      0  // 4 gaps, score -4

...

The same thing can be done for the uppermost row.

Template:-

Introduction

This algorithm can be used for any two strings. This guide will use two small DNA sequences as examples as shown in the diagram:

GCATGCU
GATTACA

Constructing the grid

First construct a grid such as one shown in Figure 1 above. Start the first string in the top of the third column and start the other string at the start of the third row. Fill out the rest of the column and row headers as in Figure 1. There should be no numbers in the grid yet.

G C A T G C U
 
G
A
T
T
A
C
A

Choosing a scoring system

Next, decide how to score each individual pair of letters. Using the example above, one possible alignment candidate might be: Template:DNA sequence The letters may match, mismatch, or be matched to a gap (a deletion or insertion (indel):

  • Match: The two letters at the current index are the same.
  • Mismatch: The two letters at the current index are different.
  • Indel (INsertion or DELetion): The best alignment involves one letter aligning to a gap in the other string.

Each of these scenarios is assigned a score and the sum of the score of each pairing is the score of the whole alignment candidate. Different systems exist for assigning scores; some have been outlined in the Scoring systems section below. For now, the system used by Needleman and Wunsch[1] will be used:

  • Match: +1
  • Mismatch or Indel: −1

For the Example above, the score of the alignment would be 0: Template:DNA sequence

+-++--+- -> -1*4 + 1*4 = 0

Filling in the table

Start with a zero in the second row, second column. Move through the cells row by row, calculating the score for each cell. The score is calculated by comparing the scores of the cells neighboring to the left, top or top-left (diagonal) of the cell and adding the appropriate score for match, mismatch or indel. Calculate the candidate scores for each of the three possibilities:

  • The path from the top or left cell represents an indel pairing, so take the score of the left and the top cell, and add the score for indel to each of them.
  • The diagonal path represents a match/mismatch, so take the score of the top-left diagonal cell and add the score for match if the corresponding bases in the row and column are matching or the score for mismatch if they do not.

The resulting score for the cell is the highest of the three candidate scores.

Given there is no 'top' or 'top-left' cells for the second row only the existing cell to the left can be used to calculate the score of each cell. Hence -1 is added for each shift to the right as this represents an indelible from the previous score. This results in the first row being 0, -1, -2, -3, -4, -5, -6, -7. The same applies to the second column as only the existing score above each cell can be used. Thus the resulting table is:

G C A T G C U
0 -1 -2 -3 -4 -5 -6 -7
G -1
A -2
T -3
T -4
A -5
C -6
A -7

The first case with existing scores in all 3 directions is the intersection of our first letters (in this case G and G). The surrounding cells are below:

G
0 -1
G -1 X

This cell has three possible candidate sums:

  • The diagonal top-left neighbor has score 0. The pairing of G and G is a match, so add the score for match: 0+1 = 1
  • The top neighbor has score -1 and moving from there represents an indel, so add the score for indel: (-1) + (-1) = (-2)
  • The left neighbor also has score -1, represents an indel and also produces (-2).

The highest candidate is 1 and is entered into the cell:

G
0 -1
G -1 1

The cell which gave the highest candidate score must also be recorded. In the completed diagram in figure 1 above, this is represented as an arrow from the cell in row and column 3 to the cell in row and column 2.

In the next example, the diagonal step for both X and Y represents a mismatch:

G C
0 -1 -2
G -1 1 X
A -2 Y

X:

  • Top: (-2)+(-1) = (-3)
  • Left: (+1)+(-1) = (0)
  • Top-Left: (-1)+(-1) = (-2)

Y:

  • Top: (1)+(-1) = (0)
  • Left: (-2)+(-1) = (-3)
  • Top-Left: (-1)+(-1) = (-2)

For both X and Y, the highest score is zero:

G C
0 -1 -2
G -1 1 0
A -2 0

The highest candidate score may be reached by two or all neighboring cells:

T G
T 1 1
A 0 X
  • Top: (1)+(-1) = (0)
  • Top-Left: (1)+(-1) = (0)
  • Left: (0)+(-1) = (-1)

In this case, all directions reaching the highest candidate score must be noted as possible origin cells in the finished diagram in figure 1, e.g. in the cell in row and column 7.

Filling in the table in this manner gives the scores or all possible alignment candidates, the score in the cell on the bottom right represents the alignment score for the best alignment.

Tracing arrows back to origin

Mark a path from the cell on the bottom right back to the cell on the top left by following the direction of the arrows. From this path, the sequence is constructed by these rules:

  • A diagonal arrow represents a match or mismatch, so the letters of the column and the letter of the row of the origin cell will align.
  • A horizontal or vertical arrow represents an indel. Horizontal arrows will align a gap ("-") to the letter of the row (the "side" sequence), vertical arrows will align a gap to the letter of the column (the "top" sequence).
  • If there are multiple arrows to choose from, they represent a branching of the alignments. If two or more branches all belong to paths from the bottom left to the top right cell, they are equally viable alignments. In this case, note the paths as separate alignment candidates.

Following these rules, the steps for one possible alignment candidate in figure 1 are:

U → CU → GCU → -GCU → T-GCU → AT-GCU → CAT-GCU → GCAT-GCU
A → CA → ACA → TACA → TTACA → ATTACA → -ATTACA → G-ATTACA
             ↓
    (branch) → TGCU → ...
             → TACA → ...

Scoring systems

Basic scoring schemes

The simplest scoring schemes simply give a value for each match, mismatch and indel. The step-by-step guide above uses match = 1, mismatch = −1, indel = −1. Thus the lower the alignment score the larger the edit distance, for this scoring system one wants a high score. Another scoring system might be:

  • Match = 0
  • Indel = 1
  • Mismatch = 1

For this system the alignment score will represent the edit distance between the two strings. Different scoring systems can be devised for different situations, for example if gaps are considered very bad for your alignment you may use a scoring system that penalises gaps heavily, such as:

  • Match = 0
  • Mismatch = 1
  • Indel = 10

Try it out.

Similarity matrix

More complicated scoring systems attribute values not only for the type of alteration, but also for the letters that are involved. For example, a match between A and A may be given 1, but a match between T and T may be given 4. Here (assuming the first scoring system) more importance is given to the Ts matching than the As, i.e. the Ts matching is assumed to be more significant to the alignment. This weighting based on letters also applies to mismatches.

In order to represent all the possible combinations of letters and their resulting scores a similarity matrix is used. The similarity matrix for the most basic system is represented as:

A G C T
A 1 -1 -1 -1
G -1 1 -1 -1
C -1 -1 1 -1
T -1 -1 -1 1

Each score represents a switch from one of the letters the cell matches to the other. Hence this represents all possible matches and deletions (for an alphabet of ACGT). Note all the matches go along the diagonal, also not all the table needs to be filled, only this triangle because the scores are reciprocal.= (Score for A → C = Score for C → A). If implementing the T-T = 4 rule from above the following similarity matrix is produced:

A G C T
A 1 -1 -1 -1
G -1 1 -1 -1
C -1 -1 1 -1
T -1 -1 -1 4

Different scoring matrices have been statistically constructed which give weight to different actions appropriate to a particular scenario. Having weighted scoring matrices is particularly important in protein sequence alignment due to the varying frequency of the different amino acids. There are two broad families of scoring matrices, each with further alterations for specific scenarios:

Gap penalty

When aligning sequences there are often gaps (i.e. indels), sometimes large ones. Biologically, a large gap is more likely to occur as one large deletion as opposed to multiple single deletions. Hence two small indels should have a worse score than one large one. The simple and common way to do this is via a large gap-start score for a new indel and a smaller gap-extension score for every letter which extends the indel. For example, new-indel may cost -5 and extend-indel may cost -1. In this way an alignment such as:

GAAAAAAT
G--A-A-T

which has multiple equal alignments, some with multiple small alignments will now align as:

GAAAAAAT
GAA----T

or any alignment with a 4 long gap in preference over multiple small gaps.

Advanced presentation of algorithm

Scores for aligned characters are specified by a similarity matrix. Here, Template:Math is the similarity of characters a and b. It uses a linear gap penalty, here called Template:Mvar.

For example, if the similarity matrix was

A G C T
A 10 -1 -3 -4
G -1 7 -5 -3
C -3 -5 9 0
T -4 -3 0 8

then the alignment:

AGACTAGTTAC
CGA---GACGT

with a gap penalty of -5, would have the following score:

Template:Math
= -3 + 7 + 10 - (3 × 5) + 7 + (-4) + 0 + (-1) + 0 = 1

To find the alignment with the highest score, a two-dimensional array (or matrix) F is allocated. The entry in row i and column j is denoted here by <math>F_{ij}</math>. There is one row for each character in sequence A, and one column for each character in sequence B. Thus, if aligning sequences of sizes n and m, the amount of memory used is in <math>O(nm)</math>. Hirschberg's algorithm only holds a subset of the array in memory and uses <math>\Theta(\min \{n,m\})</math> space, but is otherwise similar to Needleman-Wunsch (and still requires <math>O(nm)</math> time).

As the algorithm progresses, the <math>F_{ij}</math> will be assigned to be the optimal score for the alignment of the first <math>i=0,\dotsc,n</math> characters in A and the first <math>j=0,\dotsc,m</math> characters in B. The principle of optimality is then applied as follows:

  • Basis:
<math>F_{0j} = d*j</math>
<math>F_{i0} = d*i</math>
  • Recursion, based on the principle of optimality:
<math>F_{ij} = \max(F_{i-1,j-1} + S(A_{i}, B_{j}), \; F_{i,j-1} + d, \; F_{i-1,j} + d)</math>

The pseudo-code for the algorithm to compute the F matrix therefore looks like this:

d ← MismatchScore
for i=0 to length(A)
  F(i,0) ← d*i
for j=0 to length(B)
  F(0,j) ← d*j
for i=1 to length(A)
  for j=1 to length(B)
  {
    Match ← F(i-1,j-1) + S(Ai, Bj)
    Delete ← F(i-1, j) + d
    Insert ← F(i, j-1) + d
    F(i,j) ← max(Match, Insert, Delete)
  }

Once the F matrix is computed, the entry <math>F_{nm}</math> gives the maximum score among all possible alignments. To compute an alignment that actually gives this score, you start from the bottom right cell, and compare the value with the three possible sources (Match, Insert, and Delete above) to see which it came from. If Match, then <math>A_i</math> and <math>B_j</math> are aligned, if Delete, then <math>A_i</math> is aligned with a gap, and if Insert, then <math>B_j</math> is aligned with a gap. (In general, more than one choice may have the same value, leading to alternative optimal alignments.)

AlignmentA ← ""
AlignmentB ← ""
i ← length(A)
j ← length(B)
while (i > 0 or j > 0)
{
  if (i > 0 and j > 0 and F(i,j) == F(i-1,j-1) + S(Ai, Bj))
  {
    AlignmentA ← Ai + AlignmentA
    AlignmentB ← Bj + AlignmentB
    i ← i - 1
    j ← j - 1
  }
  else if (i > 0 and F(i,j) == F(i-1,j) + d)
  {
    AlignmentA ← Ai + AlignmentA
    AlignmentB ← "-" + AlignmentB
    i ← i - 1
  }
  else
  {
    AlignmentA ← "-" + AlignmentA
    AlignmentB ← Bj + AlignmentB
    j ← j - 1
  }
}

Complexity

Computing the score <math>F_{ij}</math> for each cell in the table is an <math>O(1)</math> operation. Thus the time complexity of the algorithm for two sequences of length <math>n</math> and <math>m</math> is <math>O(mn)</math>.[3] It has been shown that it is possible to improve the running time to <math>O(mn/ \log n)</math> using the Method of Four Russians.[3][4] Since the algorithm fill an <math>n \times m</math> table the space complexity is <math>O(mn)</math>.[3]

Historical notes and algorithm development

The original purpose of the algorithm described by Needleman and Wunsch was to find similarities in the amino acid sequences of two proteins.[1]

Needleman and Wunsch describe their algorithm explicitly for the case when the alignment is penalized solely by the matches and mismatches, and gaps have no penalty (d=0). The original publication from 1970 suggests the recursion <math>F_{ij} = \max_{h<i,k<j} \{ F_{h,j-1}+S(A_{i},B_{j}), F_{i-1,k}+S(A_i,B_j) \}</math>.

The corresponding dynamic programming algorithm takes cubic time. The paper also points out that the recursion can accommodate arbitrary gap penalization formulas:

A penalty factor, a number subtracted for every gap made, may be assessed as a barrier to allowing the gap. The penalty factor could be a function of the size and/or direction of the gap. [page 444]

A better dynamic programming algorithm with quadratic running time for the same problem (no gap penalty) was first introduced[5] by David Sankoff in 1972. Similar quadratic-time algorithms were discovered independently by T. K. Vintsyuk[6] in 1968 for speech processing ("time warping"), and by Robert A. Wagner and Michael J. Fischer[7] in 1974 for string matching.

Needleman and Wunsch formulated their problem in terms of maximizing similarity. Another possibility is to minimize the edit distance between sequences, introduced by Vladimir Levenshtein. Peter H. Sellers showed[8] in 1974 that the two problems are equivalent.

The Needleman–Wunsch algorithm is still widely used for optimal global alignment, particularly when the quality of the global alignment is of the utmost importance. However, the algorithm is expensive with respect to time and space, proportional to the product of the length of two sequences and hence is not suitable for long sequences.

Recent development has focused on improving the time and space cost of the algorithm while maintaining quality. For example, in 2013, a Fast Optimal Global Sequence Alignment Algorithm (FOGSAA),[9] suggested alignment of nucleotide/protein sequences faster than other optimal global alignment methods, including the Needleman–Wunsch algorithm. The paper claims that when compared to the Needleman–Wunsch algorithm, FOGSAA achieves a time gain of 70–90% for highly similar nucleotide sequences (with > 80% similarity), and 54–70% for sequences having 30–80% similarity.

Global alignment tools using the Needleman–Wunsch algorithm

Applications outside bioinformatics

Computer stereo vision

Stereo matching is an essential step in the process of 3D reconstruction from a pair of stereo images. When images have been rectified, an analogy can be drawn between aligning nucleotide and protein sequences and matching pixels belonging to scan lines, since both tasks aim at establishing optimal correspondence between two strings of characters. The ‘right’ image of a stereo pair can be seen as a mutated version of the ‘left’ image: noise and individual camera sensitivity alter pixel values (i.e. character substitutions); and different view angle reveals previously occluded data and introduces new occlusions (i.e. insertion and deletion of characters). As consequence, minor modifications of the Needleman–Wunsch algorithm make it suitable for stereo matching.[10] Although performances in terms of accuracy are not state-of-the-art, the relative simplicity of the algorithm allows its implementation on embedded systems.[11]

Although in many applications image rectification can be performed, e.g. by camera resectioning or calibration, it is sometimes impossible or impractical since the computational cost of accurate rectification models prohibit their usage in real-time applications. Moreover, none of these models is suitable when a camera lens displays unexpected distortions, such as those generated by raindrops, weatherproof covers or dust. By extending the Needleman–Wunsch algorithm, a line in the ‘left’ image can be associated to a curve in the ‘right’ image by finding the alignment with the highest score in a three-dimensional array (or matrix). Experiments demonstrated that such extension allows dense pixel matching between unrectified or distorted images.[12]

See also

References

Template:Reflist

External links

Template:External links

Template:Strings

  1. 1.0 1.1 1.2 Template:Cite journal
  2. Template:Cite web
  3. 3.0 3.1 3.2 Template:Cite book
  4. Template:Cite journal
  5. Template:Cite journal
  6. Template:Cite journal
  7. Template:Cite journal
  8. Template:Cite journal
  9. Template:Cite journal
  10. Dieny R., Thevenon J., Martinez-del-Rincon J., Nebel J.-C. (2011) "Bioinformatics inspired algorithm for stereo correspondence". International Conference on Computer Vision Theory and Applications, March 5–7, Vilamoura - Algarve, Portugal.
  11. Madeo S., Pelliccia R., Salvadori C., Martinez-del-Rincon J., Nebel J.-C. (2014) "An optimized stereo vision implementation for embedded systems: application to RGB and Infra-Red images". Journal of Real-Time Image Processing.
  12. Martinez-del-Rincon J., Thevenon J., Dieny R., Nebel J.-C. (2012) "Dense Pixel Matching Between Unrectified and Distorted Images Using Dynamic Programming". International Conference on Computer Vision Theory and Applications, 24–26 February, Rome, Italy.