1cf21fd9f385ef5b03cf325a34ad424f0dced6bc
[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 symm;
49
50   private MatrixI eigenvector;
51
52   private String details;
53
54   /**
55    * Constructor given the sequences to compute for, the similarity model to
56    * use, and a set of parameters for sequence comparison
57    * 
58    * @param sequences
59    * @param sm
60    * @param options
61    */
62   public PCA(AlignmentView sequences, ScoreModelI sm, SimilarityParamsI options)
63   {
64     this.seqs = sequences;
65     this.scoreModel = sm;
66     this.similarityParams = options;
67   }
68
69   /**
70    * Returns Eigenvalue
71    * 
72    * @param i
73    *          Index of diagonal within matrix
74    * 
75    * @return Returns value of diagonal from matrix
76    */
77   public double getEigenvalue(int i)
78   {
79     return eigenvector.getD()[i];
80   }
81
82   /**
83    * DOCUMENT ME!
84    * 
85    * @param l
86    *          DOCUMENT ME!
87    * @param n
88    *          DOCUMENT ME!
89    * @param mm
90    *          DOCUMENT ME!
91    * @param factor
92    *          DOCUMENT ME!
93    * 
94    * @return DOCUMENT ME!
95    */
96   public Point[] getComponents(int l, int n, int mm, float factor)
97   {
98     Point[] out = new Point[getHeight()];
99
100     for (int i = 0; i < getHeight(); i++)
101     {
102       float x = (float) component(i, l) * factor;
103       float y = (float) component(i, n) * factor;
104       float z = (float) component(i, mm) * factor;
105       out[i] = new Point(x, y, z);
106     }
107
108     return out;
109   }
110
111   /**
112    * DOCUMENT ME!
113    * 
114    * @param n
115    *          DOCUMENT ME!
116    * 
117    * @return DOCUMENT ME!
118    */
119   public double[] component(int n)
120   {
121     // n = index of eigenvector
122     double[] out = new double[getHeight()];
123
124     for (int i = 0; i < out.length; i++)
125     {
126       out[i] = component(i, n);
127     }
128
129     return out;
130   }
131
132   /**
133    * DOCUMENT ME!
134    * 
135    * @param row
136    *          DOCUMENT ME!
137    * @param n
138    *          DOCUMENT ME!
139    * 
140    * @return DOCUMENT ME!
141    */
142   double component(int row, int n)
143   {
144     double out = 0.0;
145
146     for (int i = 0; i < symm.width(); i++)
147     {
148       out += (symm.getValue(row, i) * eigenvector.getValue(i, n));
149     }
150
151     return out / eigenvector.getD()[n];
152   }
153
154   /**
155    * Answers a formatted text report of the PCA calculation results (matrices
156    * and eigenvalues) suitable for display
157    * 
158    * @return
159    */
160   public String getDetails()
161   {
162     return details;
163   }
164
165   /**
166    * Performs the PCA calculation
167    */
168   @Override
169   public void run()
170   {
171     /*
172      * print details to a string buffer as they are computed
173      */
174     StringBuilder sb = new StringBuilder(1024);
175     sb.append("PCA calculation using ").append(scoreModel.getName())
176             .append(" sequence similarity matrix\n========\n\n");
177     PrintStream ps = wrapOutputBuffer(sb);
178
179     try
180     {
181       eigenvector = scoreModel.findSimilarities(seqs, similarityParams);
182
183       sb.append(" --- OrigT * Orig ---- \n");
184       eigenvector.print(ps, "%8.2f");
185
186       symm = eigenvector.copy();
187
188       eigenvector.tred();
189
190       sb.append(" ---Tridiag transform matrix ---\n");
191       sb.append(" --- D vector ---\n");
192       eigenvector.printD(ps, "%15.4e");
193       ps.println();
194       sb.append("--- E vector ---\n");
195       eigenvector.printE(ps, "%15.4e");
196       ps.println();
197
198       // Now produce the diagonalization matrix
199       eigenvector.tqli();
200     } catch (Exception q)
201     {
202       q.printStackTrace();
203       sb.append("\n*** Unexpected exception when performing PCA ***\n"
204               + q.getLocalizedMessage());
205       sb.append(
206               "*** Matrices below may not be fully diagonalised. ***\n");
207     }
208
209     sb.append(" --- New diagonalization matrix ---\n");
210     eigenvector.print(ps, "%8.2f");
211     sb.append(" --- Eigenvalues ---\n");
212     eigenvector.printD(ps, "%15.4e");
213     ps.println();
214
215     details = sb.toString();
216   }
217
218   /**
219    * Returns a PrintStream that wraps (appends its output to) the given
220    * StringBuilder
221    * 
222    * @param sb
223    * @return
224    */
225   protected PrintStream wrapOutputBuffer(StringBuilder sb)
226   {
227     PrintStream ps = new PrintStream(System.out)
228     {
229       @Override
230       public void print(String x)
231       {
232         sb.append(x);
233       }
234
235       @Override
236       public void println()
237       {
238         sb.append("\n");
239       }
240     };
241     return ps;
242   }
243
244   /**
245    * Answers the N dimensions of the NxN PCA matrix. This is the number of
246    * sequences involved in the pairwise score calculation.
247    * 
248    * @return
249    */
250   public int getHeight()
251   {
252     // TODO can any of seqs[] be null?
253     return seqs.getSequences().length;
254   }
255 }