4235779b69d48193b3a912f6b950e4edfc9a28f7
[jalview.git] / src / jalview / analysis / PaSiMap.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.analysis;
22
23 import jalview.api.analysis.ScoreModelI;
24 import jalview.api.analysis.SimilarityParamsI;
25 import jalview.bin.Console;
26 import jalview.datamodel.AlignmentView;
27 import jalview.datamodel.Point;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.PairwiseAlignPanel;
30 import jalview.gui.PaSiMapPanel;
31 import jalview.math.Matrix;
32 import jalview.math.MatrixI;
33 import jalview.viewmodel.AlignmentViewport;
34
35
36 import java.io.PrintStream;
37 import java.util.Hashtable;
38 import java.util.Enumeration;
39
40 /**
41  * Performs Principal Component Analysis on given sequences
42  * @AUTHOR MorellThomas 
43  */
44 public class PaSiMap implements Runnable
45 {
46   /*
47    * inputs
48    */
49   final private AlignmentViewport seqs;
50
51   final private ScoreModelI scoreModel;
52
53   final private SimilarityParamsI similarityParams;
54
55   final private byte dim = 3;
56
57   /*
58    * outputs
59    */
60   private MatrixI pairwiseScores;
61
62   private MatrixI eigenMatrix;
63
64   /**
65    * Constructor given the sequences to compute for, the similarity model to
66    * use, and a set of parameters for sequence comparison
67    * 
68    * @param sequences
69    * @param sm
70    * @param options
71    */
72   public PaSiMap(AlignmentViewport sequences, ScoreModelI sm,
73           SimilarityParamsI options)
74   {
75     this.seqs = sequences;
76     this.scoreModel = sm;
77     this.similarityParams = options;
78   }
79
80   /**
81    * Returns Eigenvalue
82    * 
83    * @param i
84    *          Index of diagonal within matrix
85    * 
86    * @return Returns value of diagonal from matrix
87    */
88   public double getEigenvalue(int i)
89   {
90     return eigenMatrix.getD()[i];
91   }
92
93   /**
94    * Returns coordinates for each datapoint
95    * 
96    * @param l
97    *          DOCUMENT ME!
98    * @param n
99    *          DOCUMENT ME!
100    * @param mm
101    *          DOCUMENT ME!
102    * @param factor ~ is 1
103    * 
104    * @return DOCUMENT ME!
105    */
106   public Point[] getComponents(int l, int n, int mm, float factor)
107   {
108     Point[] out = new Point[getHeight()];
109
110     for (int i = 0; i < out.length; i++)
111     {
112       float x = (float) component(i, l) * factor;
113       float y = (float) component(i, n) * factor;
114       float z = (float) component(i, mm) * factor;
115       out[i] = new Point(x, y, z);
116     }
117     //&!
118     System.out.println("Points:");
119     for (Point point : out)
120     {
121       System.out.println(point.toString());
122     }
123
124     return out;
125   }
126
127   /**
128    * DOCUMENT ME!
129    * 
130    * @param n
131    *          DOCUMENT ME!
132    * 
133    * @return DOCUMENT ME!
134    */
135   public double[] component(int n)
136   {
137     // n = index of eigenvector
138     double[] out = new double[getHeight()];
139
140     for (int i = 0; i < out.length; i++)
141     {
142       out[i] = component(i, n);
143     }
144
145     return out;
146   }
147
148   /**
149    * DOCUMENT ME!
150    * 
151    * @param row
152    *          DOCUMENT ME!
153    * @param n
154    *          DOCUMENT ME!
155    * 
156    * @return DOCUMENT ME!
157    */
158   double component(int row, int n)
159   {
160     return eigenMatrix.getValue(row, n);
161   }
162
163   /**
164    * Answers a formatted text report of the PaSiMap calculation results (matrices
165    * and eigenvalues) suitable for display
166    * 
167    * @return
168    */
169   public String getDetails()
170   {
171     StringBuilder sb = new StringBuilder(1024);
172     sb.append("PaSiMap calculation using ").append(scoreModel.getName())
173             .append(" sequence similarity matrix\n========\n\n");
174     PrintStream ps = wrapOutputBuffer(sb);
175
176     /*
177      * pairwise similarity scores
178      */
179     sb.append(" --- OrigT * Orig ---- \n");
180     pairwiseScores.print(ps, "%8.2f");
181
182     /*
183      * eigenvalues matrix, with D vector
184      */
185     sb.append(" --- New diagonalization matrix ---\n");
186     eigenMatrix.print(ps, "%8.2f");
187     sb.append(" --- Eigenvalues ---\n");
188     eigenMatrix.printD(ps, "%15.4e");
189     ps.println();
190
191     return sb.toString();
192   }
193
194   /**
195    * Performs the PaSiMap calculation
196    *
197    * creates a new gui/PairwiseAlignPanel with the input sequences (AlignmentViewport)
198    * uses analysis/AlignSeq to creatue the pairwise alignments and calculate the AlignmentScores (float for each pair)
199    * gets all float[][] scores from the gui/PairwiseAlignPanel
200    * checks the connections for each sequence with AlignmentViewport seqs.calculateConnectivity(float[][] scores, int dim) (from analysis/Connectivity) -- throws an Exception if insufficient
201    * creates a math/MatrixI pairwiseScores of the float[][] scores
202    * copys the scores and fills the diagonal to create a symmetric matrix using math/Matrix.fillDiagonal()
203    * performs the analysis/ccAnalysis with the symmetric matrix
204    * gets the eigenmatrix and the eigenvalues using math/Matrix.tqli()
205    */
206   @Override
207   public void run()
208   {
209     try
210     {
211       PairwiseAlignPanel alignment = new PairwiseAlignPanel(seqs, true);
212       float[][] scores = alignment.getAlignmentScores();        //bigger index first -- eg scores[14][13]
213
214       Hashtable<SequenceI, Integer> connectivity = seqs.calculateConnectivity(scores, dim);
215
216       pairwiseScores = new Matrix(scores);
217       pairwiseScores.fillDiagonal();
218
219       ccAnalysis cc = new ccAnalysis(pairwiseScores, dim);
220       pairwiseScores = cc.run();
221
222       /** perform the eigendecomposition for the plot */
223       eigenMatrix = pairwiseScores.copy();
224       eigenMatrix.setD(pairwiseScores.getD());
225       System.out.println(getDetails());
226       
227
228     } catch (Exception q)
229     {
230       Console.error("Error computing PaSiMap:  " + q.getMessage());
231       q.printStackTrace();
232     }
233   }
234
235   /**
236    * Returns a PrintStream that wraps (appends its output to) the given
237    * StringBuilder
238    * 
239    * @param sb
240    * @return
241    */
242   protected PrintStream wrapOutputBuffer(StringBuilder sb)
243   {
244     PrintStream ps = new PrintStream(System.out)
245     {
246       @Override
247       public void print(String x)
248       {
249         sb.append(x);
250       }
251
252       @Override
253       public void println()
254       {
255         sb.append("\n");
256       }
257     };
258     return ps;
259   }
260
261   /**
262    * Answers the N dimensions of the NxM PaSiMap matrix. This is the number of
263    * sequences involved in the pairwise score calculation.
264    * 
265    * @return
266    */
267   public int getHeight()
268   {
269     // TODO can any of seqs[] be null?
270     return pairwiseScores.height();// seqs.getSequences().length;
271   }
272
273   /**
274    * Answers the M dimensions of the NxM PaSiMap matrix. This is the number of
275    * sequences involved in the pairwise score calculation.
276    * 
277    * @return
278    */
279   public int getWidth()
280   {
281     // TODO can any of seqs[] be null?
282     return pairwiseScores.width();// seqs.getSequences().length;
283   }
284
285   /**
286    * Answers the sequence pairwise similarity scores which were the first step
287    * of the PaSiMap calculation
288    * 
289    * @return
290    */
291   public MatrixI getPairwiseScores()
292   {
293     return pairwiseScores;
294   }
295
296   public void setPairwiseScores(MatrixI m)
297   {
298     pairwiseScores = m;
299   }
300
301   public MatrixI getEigenmatrix()
302   {
303     return eigenMatrix;
304   }
305
306   public void setEigenmatrix(MatrixI m)
307   {
308     eigenMatrix = m;
309   }
310 }