JAL-1767 refactorings to enable faithful restore of PCA from project
[jalview.git] / src / jalview / analysis / PCA.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.datamodel.AlignmentView;
26 import jalview.datamodel.Point;
27 import jalview.math.MatrixI;
28
29 import java.io.PrintStream;
30
31 /**
32  * Performs Principal Component Analysis on given sequences
33  */
34 public class PCA implements Runnable
35 {
36   /*
37    * inputs
38    */
39   final private AlignmentView seqs;
40
41   final private ScoreModelI scoreModel;
42
43   final private SimilarityParamsI similarityParams;
44
45   /*
46    * outputs
47    */
48   private MatrixI pairwiseScores;
49
50   private MatrixI afterTred;
51
52   private MatrixI eigenvector;
53
54   private String details;
55
56   /**
57    * Constructor given the sequences to compute for, the similarity model to
58    * use, and a set of parameters for sequence comparison
59    * 
60    * @param sequences
61    * @param sm
62    * @param options
63    */
64   public PCA(AlignmentView sequences, ScoreModelI sm, SimilarityParamsI options)
65   {
66     this.seqs = sequences;
67     this.scoreModel = sm;
68     this.similarityParams = options;
69   }
70
71   /**
72    * Returns Eigenvalue
73    * 
74    * @param i
75    *          Index of diagonal within matrix
76    * 
77    * @return Returns value of diagonal from matrix
78    */
79   public double getEigenvalue(int i)
80   {
81     return eigenvector.getD()[i];
82   }
83
84   /**
85    * DOCUMENT ME!
86    * 
87    * @param l
88    *          DOCUMENT ME!
89    * @param n
90    *          DOCUMENT ME!
91    * @param mm
92    *          DOCUMENT ME!
93    * @param factor
94    *          DOCUMENT ME!
95    * 
96    * @return DOCUMENT ME!
97    */
98   public Point[] getComponents(int l, int n, int mm, float factor)
99   {
100     Point[] out = new Point[getHeight()];
101
102     for (int i = 0; i < getHeight(); i++)
103     {
104       float x = (float) component(i, l) * factor;
105       float y = (float) component(i, n) * factor;
106       float z = (float) component(i, mm) * factor;
107       out[i] = new Point(x, y, z);
108     }
109
110     return out;
111   }
112
113   /**
114    * DOCUMENT ME!
115    * 
116    * @param n
117    *          DOCUMENT ME!
118    * 
119    * @return DOCUMENT ME!
120    */
121   public double[] component(int n)
122   {
123     // n = index of eigenvector
124     double[] out = new double[getHeight()];
125
126     for (int i = 0; i < out.length; i++)
127     {
128       out[i] = component(i, n);
129     }
130
131     return out;
132   }
133
134   /**
135    * DOCUMENT ME!
136    * 
137    * @param row
138    *          DOCUMENT ME!
139    * @param n
140    *          DOCUMENT ME!
141    * 
142    * @return DOCUMENT ME!
143    */
144   double component(int row, int n)
145   {
146     double out = 0.0;
147
148     for (int i = 0; i < pairwiseScores.width(); i++)
149     {
150       out += (pairwiseScores.getValue(row, i) * eigenvector.getValue(i, n));
151     }
152
153     return out / eigenvector.getD()[n];
154   }
155
156   /**
157    * Answers a formatted text report of the PCA calculation results (matrices
158    * and eigenvalues) suitable for display
159    * 
160    * @return
161    */
162   public String getDetails()
163   {
164     return details;
165     /*
166     StringBuilder sb = new StringBuilder(1024);
167     sb.append("PCA calculation using ").append(scoreModel.getName())
168             .append(" sequence similarity matrix\n========\n\n");
169     PrintStream ps = wrapOutputBuffer(sb);
170     
171     sb.append(" --- OrigT * Orig ---- \n");
172     pairwiseScores.print(ps, "%8.2f");
173     
174     sb.append(" ---Tridiag transform matrix ---\n");
175     sb.append(" --- D vector ---\n");
176     afterTred.printD(ps, "%15.4e");
177     ps.println();
178     sb.append("--- E vector ---\n");
179     afterTred.printE(ps, "%15.4e");
180     ps.println();
181     
182     sb.append(" --- New diagonalization matrix ---\n");
183     eigenvector.print(ps, "%8.2f");
184     sb.append(" --- Eigenvalues ---\n");
185     eigenvector.printD(ps, "%15.4e");
186     ps.println();
187     
188     return sb.toString();
189     */
190   }
191
192   /**
193    * Performs the PCA calculation
194    */
195   @Override
196   public void run()
197   {
198     /*
199      * print details to a string buffer as they are computed
200      */
201     StringBuilder sb = new StringBuilder(1024);
202     sb.append("PCA calculation using ").append(scoreModel.getName())
203             .append(" sequence similarity matrix\n========\n\n");
204     PrintStream ps = wrapOutputBuffer(sb);
205
206     try
207     {
208       eigenvector = scoreModel.findSimilarities(seqs, similarityParams);
209
210       sb.append(" --- OrigT * Orig ---- \n");
211       eigenvector.print(ps, "%8.2f");
212
213       pairwiseScores = eigenvector.copy();
214
215       eigenvector.tred();
216
217       afterTred = eigenvector.copy();
218
219       sb.append(" ---Tridiag transform matrix ---\n");
220       sb.append(" --- D vector ---\n");
221       afterTred.printD(ps, "%15.4e");
222       ps.println();
223       sb.append("--- E vector ---\n");
224       afterTred.printE(ps, "%15.4e");
225       ps.println();
226
227       // Now produce the diagonalization matrix
228       eigenvector.tqli();
229     } catch (Exception q)
230     {
231       q.printStackTrace();
232       sb.append("\n*** Unexpected exception when performing PCA ***\n"
233               + q.getLocalizedMessage());
234       sb.append(
235               "*** Matrices below may not be fully diagonalised. ***\n");
236     }
237
238     sb.append(" --- New diagonalization matrix ---\n");
239     eigenvector.print(ps, "%8.2f");
240     sb.append(" --- Eigenvalues ---\n");
241     eigenvector.printD(ps, "%15.4e");
242     ps.println();
243
244     details = sb.toString();
245   }
246
247   /**
248    * Returns a PrintStream that wraps (appends its output to) the given
249    * StringBuilder
250    * 
251    * @param sb
252    * @return
253    */
254   protected PrintStream wrapOutputBuffer(StringBuilder sb)
255   {
256     PrintStream ps = new PrintStream(System.out)
257     {
258       @Override
259       public void print(String x)
260       {
261         sb.append(x);
262       }
263
264       @Override
265       public void println()
266       {
267         sb.append("\n");
268       }
269     };
270     return ps;
271   }
272
273   /**
274    * Answers the N dimensions of the NxN PCA matrix. This is the number of
275    * sequences involved in the pairwise score calculation.
276    * 
277    * @return
278    */
279   public int getHeight()
280   {
281     // TODO can any of seqs[] be null?
282     return pairwiseScores.height();// seqs.getSequences().length;
283   }
284
285   /**
286    * Answers the sequence pairwise similarity scores which were the first step
287    * of the PCA 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 eigenvector;
304   }
305
306   public void setEigenmatrix(MatrixI m)
307   {
308     eigenvector = m;
309   }
310
311   public void setDetails(String d)
312   {
313     details = d;
314   }
315 }