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