source: branches/ralph/src/main/java/de/ugoe/cs/autoquest/tasktrees/alignment/algorithms/SmithWatermanRepeated.java @ 1574

Last change on this file since 1574 was 1574, checked in by rkrimmel, 10 years ago

Improvements to smith waterman

File size: 8.0 KB
Line 
1package de.ugoe.cs.autoquest.tasktrees.alignment.algorithms;
2
3import java.util.ArrayList;
4import java.util.Iterator;
5import java.util.LinkedList;
6import java.util.List;
7
8import de.ugoe.cs.autoquest.tasktrees.alignment.matrix.SubstitutionMatrix;
9
10public class SmithWatermanRepeated {
11
12        /**
13         * The first input
14         */
15        private int[] input1;
16
17        /**
18         * The second input String
19         */
20        private int[] input2;
21
22        /**
23         * The lengths of the input
24         */
25        private int length1, length2;
26
27        /**
28         * The score matrix. The true scores should be divided by the normalization
29         * factor.
30         */
31        private MatrixEntry[][] matrix;
32
33
34        private List<NumberSequence> alignment;
35       
36        private float scoreThreshold;
37
38        /**
39         * Substitution matrix to calculate scores
40         */
41        private SubstitutionMatrix submat;
42
43        public SmithWatermanRepeated(int[] input1, int[] input2, SubstitutionMatrix submat,float threshold) {
44                this.input1 = input1;
45                this.input2 = input2;
46                length1 = input1.length;
47                length2 = input2.length;
48                this.submat = submat;
49
50                //System.out.println("Starting SmithWaterman algorithm with a "
51                //              + submat.getClass() + " Substitution Matrix: " + submat.getClass().getCanonicalName());
52                this.scoreThreshold = threshold;
53               
54                matrix = new MatrixEntry[length1+2][length2+1];
55                alignment = new ArrayList<NumberSequence>();
56               
57                for (int i = 0; i <= length1+1; i++) {
58                        for(int j = 0; j< length2; j++) {
59                                matrix[i][j] = new MatrixEntry();
60                        }
61                }
62       
63
64                buildMatrix();
65                traceback();
66        }
67
68        /**
69         * Compute the similarity score of substitution The position of the first
70         * character is 1. A position of 0 represents a gap.
71         *
72         * @param i
73         *            Position of the character in str1
74         * @param j
75         *            Position of the character in str2
76         * @return Cost of substitution of the character in str1 by the one in str2
77         */
78        private double similarity(int i, int j) {
79                return submat.getDistance(input1[i - 1], input2[j - 1]);
80        }
81
82        /**
83         * Build the score matrix using dynamic programming.
84         */
85        private void buildMatrix() {
86                if (submat.getGapPenalty() >= 0) {
87                        throw new Error("Indel score must be negative");
88                }
89               
90                // it's a gap
91                matrix[0][0].setScore(0);
92                matrix[0][0].setPrevious(null); // starting point
93
94                // the first column
95                for (int j = 1; j < length2; j++) {
96                        matrix[0][j].setScore(0);
97                        matrix[0][j].setPrevious(matrix[0][j-1]);
98                       
99                }
100               
101               
102               
103                for (int i = 1; i <= length1 + 1; i++) {
104               
105                        // Formula for first row:
106                        // F(i,0) = max { F(i-1,0), F(i-1,j)-T  j=1,...,m
107                       
108                        double firstRowLeftScore = matrix[i-1][0].getScore();
109                        //for sequences of length 1
110                        double tempMax;
111                        int maxRowIndex;
112                        if(length2 == 1) {
113                                tempMax = matrix[i-1][0].getScore();
114                                maxRowIndex = 0;
115                        } else {
116                                tempMax = matrix[i-1][1].getScore();
117                                maxRowIndex = 1;
118                                //position of the maximal score of the previous row
119                               
120                                for(int j = 2; j < length2;j++) {
121                                        if(matrix[i-1][j].getScore() > tempMax) {
122                                                tempMax = matrix[i-1][j].getScore();
123                                                maxRowIndex = j;
124                                        }
125                                }
126
127                        }
128                       
129                                       
130                        tempMax -= scoreThreshold;
131                        matrix[i][0].setScore(Math.max(firstRowLeftScore, tempMax));
132                        if(tempMax ==matrix[i][0].getScore()){
133                                matrix[i][0].setPrevious(matrix[i-1][maxRowIndex]);
134                        }
135                       
136                        if(firstRowLeftScore == matrix[i][0].getScore()) {
137                                matrix[i][0].setPrevious(matrix[i-1][0]);
138                        }
139                       
140                        //The last additional score is not related to a character in the input sequence, it's the total score. Therefore we don't need to save something for it
141                        if(i<length1+1)
142                        {
143                                matrix[i][0].setXvalue(input1[i-1]);
144                                matrix[i][0].setYvalue(-2);
145                        }
146                        else {
147                        //End after we calculated final score
148                                return;
149                        }
150                       
151                       
152                        for (int j = 1; j < length2; j++) {
153                                double diagScore = matrix[i - 1][j - 1].getScore() + similarity(i, j);
154                                double upScore = matrix[i][j - 1].getScore() + submat.getGapPenalty();
155                                double leftScore = matrix[i - 1][j].getScore() + submat.getGapPenalty();
156
157                                matrix[i][j].setScore(Math.max(diagScore,Math.max(upScore, Math.max(leftScore,matrix[i][0].getScore()))));
158
159                                // find the directions that give the maximum scores.
160                                // Multiple directions are ignored TODO
161                                //True if we had a match
162                                if (diagScore == matrix[i][j].getScore()) {
163                                        matrix[i][j].setPrevious(matrix[i-1][j-1]);
164                                        matrix[i][j].setXvalue(input1[i-1]);
165                                        matrix[i][j].setYvalue(input2[j-1]);
166                                }
167                                //true if we took an event from sequence x and not from y
168                                if (leftScore == matrix[i][j].getScore()) {
169                                        matrix[i][j].setXvalue(input1[i-1]);
170                                        matrix[i][j].setYvalue(-1);
171                                        matrix[i][j].setPrevious(matrix[i-1][j]);
172                                }
173                                //true if we took an event from sequence y and not from x
174                                if (upScore == matrix[i][j].getScore()) {
175                                        matrix[i][j].setXvalue(-1);
176                                        matrix[i][j].setYvalue(input2[j-1]);
177                                        matrix[i][j].setPrevious(matrix[i][j-1]);
178                                }
179                                //true if we ended a matching region
180                                if (matrix[i][0].getScore() == matrix[i][j].getScore()) {
181                                        matrix[i][j].setPrevious(matrix[i][0]);
182                                        matrix[i][j].setXvalue(input1[i-1]);
183                                        matrix[i][j].setYvalue(-2);
184                                }
185                        }
186                       
187                        //Set the complete score cell
188                       
189                }
190        }
191
192        /**
193         * Get the maximum value in the score matrix.
194         */
195        public double getMaxScore() {
196                double maxScore = 0;
197
198                // skip the first row and column
199                for (int i = 1; i <= length1; i++) {
200                        for (int j = 1; j < length2; j++) {
201                                if (matrix[i][j].getScore() > maxScore) {
202                                        maxScore = matrix[i][j].getScore();
203                                }
204                        }
205                }
206
207                return maxScore;
208        }
209
210        /**
211         * Get the alignment score between the two input strings.
212         */
213        public double getAlignmentScore() {
214                return matrix[length1+1][0].getScore();
215        }
216
217       
218       
219        public void traceback() {
220                MatrixEntry tmp = matrix[length1+1][0];
221                //TODO: Why do we need such long arrays, also, add a check if we reach the limit?
222                int aligned1[] = new int[2*length1+2*length2];
223                int aligned2[] = new int[2*length1+2*length2];
224                System.out.println("Aligned length: " + aligned1.length);
225                int count = 0;
226                do
227                {       
228                        if(count != 0)
229                        {
230                                aligned1[count] = tmp.getXvalue();
231                                aligned2[count] = tmp.getYvalue();
232                        }
233                       
234                        tmp = tmp.getPrevious();
235                        count++;
236                        System.out.println(count);
237                       
238                } while(tmp != null);
239
240                //reverse order
241                int reversed1[] = new int[count];
242                int reversed2[] = new int[count];
243               
244               
245                for(int i = count-1; i > 0; i--) {
246                        reversed1[reversed1.length-i]= aligned1[i];
247                        reversed2[reversed2.length-i]= aligned2[i];
248                }
249               
250                NumberSequence ns1 = new NumberSequence(reversed1.length);
251                NumberSequence ns2 = new NumberSequence(reversed2.length);
252                ns1.setSequence(reversed1);
253                ns2.setSequence(reversed2);
254               
255                alignment.add(ns1);
256                alignment.add(ns2);
257        }
258       
259        public void printAlignment() {
260                MatrixEntry tmp = matrix[length1+1][0];
261                String aligned1 = "";
262                String aligned2 = "";
263                int count = 0;
264                do
265                {
266                        String append1="";
267                        String append2="";
268                                       
269                        if(tmp.getXvalue() == -1) {
270                                append1 = "  ___";
271                        }
272                        else if(tmp.getXvalue() == -2) {
273                                append1 = "  ...";
274                        }
275                        else {
276                                append1 = String.format("%5d", tmp.getXvalue());
277                        }
278
279                        if(tmp.getYvalue() == -1) {
280                                append2 = "  ___";
281                        }
282                        else if(tmp.getYvalue() == -2) {
283                                append2 = "  ...";
284                        }
285                        else {
286                                append2 = String.format("%5d", tmp.getYvalue());
287                        }
288                        if(count != 0)
289                        {
290                                aligned1 = append1 + aligned1;
291                                aligned2 = append2 + aligned2;
292                        }
293                       
294                        tmp = tmp.getPrevious();
295                        count++;
296                       
297                } while(tmp != null);
298                System.out.println(aligned1);
299                System.out.println(aligned2);
300        }
301       
302
303       
304        /**
305         * print the dynmaic programming matrix
306         */
307        public void printDPMatrix() {
308                System.out.print("          ");
309                for (int i = 1; i <= length1; i++)
310                        System.out.format("%5d", input1[i - 1]);
311                System.out.println();
312                for (int j = 0; j < length2; j++) {
313                        if (j > 0)
314                                System.out.format("%5d ",input2[j - 1]);
315                        else{
316                                System.out.print("      ");
317                        }
318                        for (int i = 0; i <= length1 + 1; i++) {
319                                if((i<length1+1) || (i==length1+1 && j==0))     {
320                                        System.out.format("%4.1f ",matrix[i][j].getScore());
321                                }
322                               
323                        }                       
324                        System.out.println();
325                }
326        }
327
328
329        public List<NumberSequence> getAlignment() {
330                return alignment;
331        }
332
333        public void setAlignment(List<NumberSequence> alignment) {
334                this.alignment = alignment;
335        }
336
337}
Note: See TracBrowser for help on using the repository browser.