Merge branch 'develop' into features/JAL-2393customMatrices
[jalview.git] / src / jalview / viewmodel / PCAModel.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.viewmodel;
22
23 import jalview.analysis.PCA;
24 import jalview.api.RotatableCanvasI;
25 import jalview.datamodel.AlignmentView;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.SequencePoint;
28
29 import java.util.Vector;
30
31 public class PCAModel
32 {
33   /*
34    * Jalview 2.10.1 treated gaps as X (peptide) or N (nucleotide)
35    * for pairwise scoring; 2.10.2 uses gap score (last column) in
36    * score matrix (JAL-2397)
37    * Set this flag to true (via Groovy) for 2.10.1 behaviour
38    */
39   private static boolean scoreGapAsAny = false;
40
41   public PCAModel(AlignmentView seqstrings2, SequenceI[] seqs2,
42           boolean nucleotide2)
43   {
44     seqstrings = seqstrings2;
45     seqs = seqs2;
46     nucleotide = nucleotide2;
47     score_matrix = nucleotide2 ? "DNA" : "BLOSUM62";
48   }
49
50   private volatile PCA pca;
51
52   int top;
53
54   AlignmentView seqstrings;
55
56   SequenceI[] seqs;
57
58   /**
59    * Score matrix used to calculate PC
60    */
61   String score_matrix;
62
63   /**
64    * use the identity matrix for calculating similarity between sequences.
65    */
66   private boolean nucleotide = false;
67
68   private Vector<SequencePoint> points;
69
70   private boolean jvCalcMode = true;
71
72   public boolean isJvCalcMode()
73   {
74     return jvCalcMode;
75   }
76
77   public void run()
78   {
79     char gapChar = scoreGapAsAny ? (nucleotide ? 'N' : 'X') : ' ';
80     String[] sequenceStrings = seqstrings.getSequenceStrings(gapChar);
81     pca = new PCA(sequenceStrings, nucleotide,
82             score_matrix);
83     pca.setJvCalcMode(jvCalcMode);
84     pca.run();
85
86     // Now find the component coordinates
87     int ii = 0;
88
89     while ((ii < seqs.length) && (seqs[ii] != null))
90     {
91       ii++;
92     }
93
94     int height = pca.getHeight();
95     // top = pca.getM().height() - 1;
96     top = height - 1;
97
98     points = new Vector<SequencePoint>();
99     float[][] scores = pca.getComponents(top - 1, top - 2, top - 3, 100);
100
101     for (int i = 0; i < height; i++)
102     {
103       SequencePoint sp = new SequencePoint(seqs[i], scores[i]);
104       points.addElement(sp);
105     }
106   }
107
108   public void updateRc(RotatableCanvasI rc)
109   {
110     rc.setPoints(points, pca.getHeight());
111   }
112
113   public boolean isNucleotide()
114   {
115     return nucleotide;
116   }
117
118   public void setNucleotide(boolean nucleotide)
119   {
120     this.nucleotide = nucleotide;
121   }
122
123   /**
124    * 
125    * 
126    * @return index of principle dimension of PCA
127    */
128   public int getTop()
129   {
130     return top;
131   }
132
133   /**
134    * update the 2d coordinates for the list of points to the given dimensions
135    * Principal dimension is getTop(). Next greatest eigenvector is getTop()-1.
136    * Note - pca.getComponents starts counting the spectrum from rank-2 to zero,
137    * rather than rank-1, so getComponents(dimN ...) == updateRcView(dimN+1 ..)
138    * 
139    * @param dim1
140    * @param dim2
141    * @param dim3
142    */
143   public void updateRcView(int dim1, int dim2, int dim3)
144   {
145     // note: actual indices for components are dim1-1, etc (patch for JAL-1123)
146     float[][] scores = pca.getComponents(dim1 - 1, dim2 - 1, dim3 - 1, 100);
147
148     for (int i = 0; i < pca.getHeight(); i++)
149     {
150       points.elementAt(i).coord = scores[i];
151     }
152   }
153
154   public String getDetails()
155   {
156     return pca.getDetails();
157   }
158
159   public AlignmentView getSeqtrings()
160   {
161     return seqstrings;
162   }
163
164   public String getPointsasCsv(boolean transformed, int xdim, int ydim,
165           int zdim)
166   {
167     StringBuffer csv = new StringBuffer();
168     csv.append("\"Sequence\"");
169     if (transformed)
170     {
171       csv.append(",");
172       csv.append(xdim);
173       csv.append(",");
174       csv.append(ydim);
175       csv.append(",");
176       csv.append(zdim);
177     }
178     else
179     {
180       for (int d = 1, dmax = pca.component(1).length; d <= dmax; d++)
181       {
182         csv.append("," + d);
183       }
184     }
185     csv.append("\n");
186     for (int s = 0; s < seqs.length; s++)
187     {
188       csv.append("\"" + seqs[s].getName() + "\"");
189       double fl[];
190       if (!transformed)
191       {
192         // output pca in correct order
193         fl = pca.component(s);
194         for (int d = fl.length - 1; d >= 0; d--)
195         {
196           csv.append(",");
197           csv.append(fl[d]);
198         }
199       }
200       else
201       {
202         // output current x,y,z coords for points
203         fl = getPointPosition(s);
204         for (int d = 0; d < fl.length; d++)
205         {
206           csv.append(",");
207           csv.append(fl[d]);
208         }
209       }
210       csv.append("\n");
211     }
212     return csv.toString();
213   }
214
215   /**
216    * 
217    * @return x,y,z positions of point s (index into points) under current
218    *         transform.
219    */
220   public double[] getPointPosition(int s)
221   {
222     double pts[] = new double[3];
223     float[] p = points.elementAt(s).coord;
224     pts[0] = p[0];
225     pts[1] = p[1];
226     pts[2] = p[2];
227     return pts;
228   }
229
230   public void setJvCalcMode(boolean state)
231   {
232     jvCalcMode = state;
233   }
234
235   public String getScore_matrix()
236   {
237     return score_matrix;
238   }
239
240   public void setScore_matrix(String score_matrix)
241   {
242     this.score_matrix = score_matrix;
243   }
244
245 }