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