51a818f340c81eb9a1c8bfcdc3f4d6b0fa575d9e
[jalview.git] / src / jalview / analysis / Grouping.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.datamodel.ColumnSelection;
24 import jalview.datamodel.SequenceGroup;
25 import jalview.datamodel.SequenceI;
26
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Vector;
32
33 /**
34  * various methods for defining groups on an alignment based on some other
35  * properties
36  * 
37  * @author JimP
38  * 
39  */
40 public class Grouping
41 {
42   /**
43    * Divide the given sequences based on the equivalence of their corresponding
44    * selectedChars string. If exgroups is provided, existing groups will be
45    * subdivided.
46    * 
47    * @param sequences
48    * @param selectedChars
49    * @param list
50    * @return
51    */
52   public static SequenceGroup[] makeGroupsFrom(SequenceI[] sequences,
53           String[] selectedChars, List<SequenceGroup> list)
54   {
55     // TODO: determine how to get/recover input data for group generation
56     Map<String, List<SequenceI>> gps = new HashMap<String, List<SequenceI>>();
57     int width = 0, i;
58     Map<String, SequenceGroup> pgroup = new HashMap<String, SequenceGroup>();
59     if (list != null)
60     {
61       for (SequenceGroup sg : list)
62       {
63         for (SequenceI sq : sg.getSequences(null))
64         {
65           pgroup.put(sq.toString(), sg);
66         }
67       }
68     }
69     for (i = 0; i < sequences.length; i++)
70     {
71       String schar = selectedChars[i];
72       SequenceGroup pgp = pgroup.get(((Object) sequences[i]).toString());
73       if (pgp != null)
74       {
75         schar = pgp.getName() + ":" + schar;
76       }
77       List<SequenceI> svec = gps.get(schar);
78       if (svec == null)
79       {
80         svec = new ArrayList<SequenceI>();
81         gps.put(schar, svec);
82       }
83       if (width < sequences[i].getLength())
84       {
85         width = sequences[i].getLength();
86       }
87       svec.add(sequences[i]);
88     }
89     // make some groups
90     SequenceGroup[] groups = new SequenceGroup[gps.size()];
91     i = 0;
92     for (String key : gps.keySet())
93     {
94       SequenceGroup group = new SequenceGroup(gps.get(key), "Subseq: "
95               + key, null, true, true, false, 0, width - 1);
96
97       groups[i++] = group;
98     }
99     gps.clear();
100     pgroup.clear();
101     return groups;
102   }
103
104   /**
105    * Divide the given sequences based on the equivalence of characters at
106    * selected columns If exgroups is provided, existing groups will be
107    * subdivided.
108    * 
109    * @param sequences
110    * @param columnSelection
111    * @param list
112    * @return
113    */
114   public static SequenceGroup[] makeGroupsFromCols(SequenceI[] sequences,
115           ColumnSelection cs, List<SequenceGroup> list)
116   {
117     // TODO: determine how to get/recover input data for group generation
118     Map<String, List<SequenceI>> gps = new HashMap<String, List<SequenceI>>();
119     Map<String, SequenceGroup> pgroup = new HashMap<String, SequenceGroup>();
120     if (list != null)
121     {
122       for (SequenceGroup sg : list)
123       {
124         for (SequenceI sq : sg.getSequences(null))
125         {
126           pgroup.put(sq.toString(), sg);
127         }
128       }
129     }
130     int[] spos = new int[cs.getSelected().size()];
131     int width = -1;
132     int i = 0;
133     for (Integer pos : cs.getSelected())
134     {
135       spos[i++] = pos.intValue();
136     }
137     ;
138     for (i = 0; i < sequences.length; i++)
139     {
140       int slen = sequences[i].getLength();
141       if (width < slen)
142       {
143         width = slen;
144       }
145
146       SequenceGroup pgp = pgroup.get(((Object) sequences[i]).toString());
147       StringBuilder schar = new StringBuilder();
148       if (pgp != null)
149       {
150         schar.append(pgp.getName() + ":");
151       }
152       for (int p : spos)
153       {
154         if (p >= slen)
155         {
156           schar.append("~");
157         }
158         else
159         {
160           schar.append(sequences[i].getCharAt(p));
161         }
162       }
163       List<SequenceI> svec = gps.get(schar.toString());
164       if (svec == null)
165       {
166         svec = new ArrayList<SequenceI>();
167         gps.put(schar.toString(), svec);
168       }
169       svec.add(sequences[i]);
170     }
171     // make some groups
172     SequenceGroup[] groups = new SequenceGroup[gps.size()];
173     i = 0;
174     for (String key : gps.keySet())
175     {
176       SequenceGroup group = new SequenceGroup(gps.get(key), "Subseq: "
177               + key, null, true, true, false, 0, width - 1);
178
179       groups[i++] = group;
180     }
181     gps.clear();
182     pgroup.clear();
183     return groups;
184   }
185
186   /**
187    * subdivide the given sequences based on the distribution of features
188    * 
189    * @param featureLabels
190    *          - null or one or more feature types to filter on.
191    * @param groupLabels
192    *          - null or set of groups to filter features on
193    * @param start
194    *          - range for feature filter
195    * @param stop
196    *          - range for feature filter
197    * @param sequences
198    *          - sequences to be divided
199    * @param exgroups
200    *          - existing groups to be subdivided
201    * @param method
202    *          - density, description, score
203    */
204   public static void divideByFeature(String[] featureLabels,
205           String[] groupLabels, int start, int stop, SequenceI[] sequences,
206           Vector exgroups, String method)
207   {
208     // TODO implement divideByFeature
209     /*
210      * if (method!=AlignmentSorter.FEATURE_SCORE &&
211      * method!=AlignmentSorter.FEATURE_LABEL &&
212      * method!=AlignmentSorter.FEATURE_DENSITY) { throw newError(
213      * "Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY."
214      * ); } boolean ignoreScore=method!=AlignmentSorter.FEATURE_SCORE;
215      * StringBuffer scoreLabel = new StringBuffer();
216      * scoreLabel.append(start+stop+method); // This doesn't work yet - we'd
217      * like to have a canonical ordering that can be preserved from call to call
218      * for (int i=0;featureLabels!=null && i<featureLabels.length; i++) {
219      * scoreLabel.append(featureLabels[i]==null ? "null" : featureLabels[i]); }
220      * for (int i=0;groupLabels!=null && i<groupLabels.length; i++) {
221      * scoreLabel.append(groupLabels[i]==null ? "null" : groupLabels[i]); }
222      * SequenceI[] seqs = alignment.getSequencesArray();
223      * 
224      * boolean[] hasScore = new boolean[seqs.length]; // per sequence score //
225      * presence int hasScores = 0; // number of scores present on set double[]
226      * scores = new double[seqs.length]; int[] seqScores = new int[seqs.length];
227      * Object[] feats = new Object[seqs.length]; double min = 0, max = 0; for
228      * (int i = 0; i < seqs.length; i++) { SequenceFeature[] sf =
229      * seqs[i].getSequenceFeatures(); if (sf==null &&
230      * seqs[i].getDatasetSequence()!=null) { sf =
231      * seqs[i].getDatasetSequence().getSequenceFeatures(); } if (sf==null) { sf
232      * = new SequenceFeature[0]; } else { SequenceFeature[] tmp = new
233      * SequenceFeature[sf.length]; for (int s=0; s<tmp.length;s++) { tmp[s] =
234      * sf[s]; } sf = tmp; } int sstart = (start==-1) ? start :
235      * seqs[i].findPosition(start); int sstop = (stop==-1) ? stop :
236      * seqs[i].findPosition(stop); seqScores[i]=0; scores[i]=0.0; int
237      * n=sf.length; for (int f=0;f<sf.length;f++) { // filter for selection
238      * criteria if ( // ignore features outwith alignment start-stop positions.
239      * (sf[f].end < sstart || sf[f].begin > sstop) || // or ignore based on
240      * selection criteria (featureLabels != null &&
241      * !AlignmentSorter.containsIgnoreCase(sf[f].type, featureLabels)) ||
242      * (groupLabels != null // problem here: we cannot eliminate null feature
243      * group features && (sf[f].getFeatureGroup() != null &&
244      * !AlignmentSorter.containsIgnoreCase(sf[f].getFeatureGroup(),
245      * groupLabels)))) { // forget about this feature sf[f] = null; n--; } else
246      * { // or, also take a look at the scores if necessary. if (!ignoreScore &&
247      * sf[f].getScore()!=Float.NaN) { if (seqScores[i]==0) { hasScores++; }
248      * seqScores[i]++; hasScore[i] = true; scores[i] += sf[f].getScore(); //
249      * take the first instance of this // score. } } } SequenceFeature[] fs;
250      * feats[i] = fs = new SequenceFeature[n]; if (n>0) { n=0; for (int
251      * f=0;f<sf.length;f++) { if (sf[f]!=null) { ((SequenceFeature[])
252      * feats[i])[n++] = sf[f]; } } if (method==FEATURE_LABEL) { // order the
253      * labels by alphabet String[] labs = new String[fs.length]; for (int
254      * l=0;l<labs.length; l++) { labs[l] = (fs[l].getDescription()!=null ?
255      * fs[l].getDescription() : fs[l].getType()); }
256      * jalview.util.QuickSort.sort(labs, ((Object[]) feats[i])); } } if
257      * (hasScore[i]) { // compute average score scores[i]/=seqScores[i]; //
258      * update the score bounds. if (hasScores == 1) { max = min = scores[i]; }
259      * else { if (max < scores[i]) { max = scores[i]; } if (min > scores[i]) {
260      * min = scores[i]; } } } }
261      * 
262      * if (method==FEATURE_SCORE) { if (hasScores == 0) { return; // do nothing
263      * - no scores present to sort by. } // pad score matrix if (hasScores <
264      * seqs.length) { for (int i = 0; i < seqs.length; i++) { if (!hasScore[i])
265      * { scores[i] = (max + i); } else { int nf=(feats[i]==null) ? 0
266      * :((SequenceFeature[]) feats[i]).length;
267      * System.err.println("Sorting on Score: seq "+seqs[i].getName()+
268      * " Feats: "+nf+" Score : "+scores[i]); } } }
269      * 
270      * jalview.util.QuickSort.sort(scores, seqs); } else if
271      * (method==FEATURE_DENSITY) {
272      * 
273      * // break ties between equivalent numbers for adjacent sequences by adding
274      * 1/Nseq*i on the original order double fr = 0.9/(1.0*seqs.length); for
275      * (int i=0;i<seqs.length; i++) { double nf; scores[i] =
276      * (0.05+fr*i)+(nf=((feats[i]==null) ? 0.0 :1.0*((SequenceFeature[])
277      * feats[i]).length));
278      * System.err.println("Sorting on Density: seq "+seqs[i].getName()+
279      * " Feats: "+nf+" Score : "+scores[i]); }
280      * jalview.util.QuickSort.sort(scores, seqs); } else { if
281      * (method==FEATURE_LABEL) { throw new Error("Not yet implemented."); } } if
282      * (lastSortByFeatureScore ==null ||
283      * scoreLabel.equals(lastSortByFeatureScore)) { setOrder(alignment, seqs); }
284      * else { setReverseOrder(alignment, seqs); } lastSortByFeatureScore =
285      * scoreLabel.toString();
286      */
287   }
288
289 }