Jalview 2.8 Source Header
[jalview.git] / src / jalview / ws / rest / params / SeqGroupIndexVector.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.ws.rest.params;
19
20 import jalview.datamodel.AlignmentI;
21 import jalview.datamodel.SequenceGroup;
22 import jalview.datamodel.SequenceI;
23 import jalview.ws.params.OptionI;
24 import jalview.ws.params.simple.IntegerParameter;
25 import jalview.ws.params.simple.Option;
26 import jalview.ws.rest.AlignmentProcessor;
27 import jalview.ws.rest.InputType;
28 import jalview.ws.rest.NoValidInputDataException;
29 import jalview.ws.rest.RestJob;
30 import jalview.ws.rest.RestServiceDescription;
31 import jalview.ws.rest.InputType.molType;
32
33 import java.io.UnsupportedEncodingException;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.List;
37 import java.util.Vector;
38
39 import org.apache.http.entity.mime.content.ContentBody;
40 import org.apache.http.entity.mime.content.StringBody;
41
42 /**
43  * Represents the partitions defined on the alignment as indices e.g. for a
44  * partition (A,B,C),(D,E),(F) The indices would be 3,2,1. Note, the alignment
45  * must be ordered so groups are contiguous before this input type can be used.
46  * 
47  * @author JimP
48  * 
49  */
50 public class SeqGroupIndexVector extends InputType implements
51         AlignmentProcessor
52 {
53   public SeqGroupIndexVector()
54   {
55     super(new Class[]
56     { AlignmentI.class });
57   }
58
59   /**
60    * separator for list of sequence Indices - default is ','
61    */
62   public String sep = ",";
63
64   /**
65    * min size of each partition
66    */
67   public int minsize = 1;
68
69   molType type;
70
71   /**
72    * prepare the context alignment for this input
73    * 
74    * @param al
75    *          - alignment to be processed
76    * @return al or a new alignment with appropriate attributes/order for input
77    */
78   public AlignmentI prepareAlignment(AlignmentI al)
79   {
80     jalview.analysis.AlignmentSorter.sortByGroup(al);
81     return al;
82   }
83
84   @Override
85   public ContentBody formatForInput(RestJob rj)
86           throws UnsupportedEncodingException, NoValidInputDataException
87   {
88     StringBuffer idvector = new StringBuffer();
89     boolean list = false;
90     AlignmentI al = rj.getAlignmentForInput(token, type);
91     // assume that alignment is properly ordered so groups form consecutive
92     // blocks
93     ArrayList<int[]> gl = new ArrayList<int[]>();
94     int p = 0;
95     List<SequenceGroup> sgs;
96     synchronized (sgs = al.getGroups())
97     {
98       for (SequenceGroup sg : sgs)
99       {
100         if (sg.getSize() < minsize)
101         {
102           throw new NoValidInputDataException("Group contains less than "
103                   + minsize + " sequences.");
104         }
105         // TODO: refactor to sequenceGroup for efficiency -
106         // getAlignmentRowInterval(AlignmentI al)
107         int[] se = null;
108         for (SequenceI sq : sg.getSequencesInOrder(al))
109         {
110           p = al.findIndex(sq);
111           if (se == null)
112           {
113             se = new int[]
114             { p, p };
115           }
116           else
117           {
118             if (p < se[0])
119               se[0] = p;
120             if (p > se[1])
121               se[1] = p;
122           }
123         }
124         if (se != null)
125         {
126           gl.add(se);
127         }
128       }
129     }
130     // are there any more sequences ungrouped that should be added as a single
131     // remaining group ? - these might be at the start or the end
132     if (gl.size() > 0)
133     {
134       int[] tail = gl.get(0);
135       if (tail[0] > 0)
136       {
137         if (1 + tail[0] > minsize)
138         {
139           gl.add(0, new int[]
140           { 0, tail[0] - 1 });
141         }
142         else
143         {
144           // lets be intelligent here - if the remaining sequences aren't enough
145           // to make a final group, then don't make one.
146           // throw new
147           // NoValidInputDataException("Group from remaining ungrouped sequences in input contains less than "+minsize+" sequences.");
148         }
149       }
150       else
151       {
152         tail = gl.get(gl.size() - 1);
153         if (1 + tail[1] < al.getHeight())
154         {
155           if (al.getHeight() - (1 + tail[1]) > minsize)
156           {
157             gl.add(new int[]
158             { tail[1] + 1, al.getHeight() - 1 });
159           }
160           else
161           {
162             // lets be intelligent here - if the remaining sequences aren't
163             // enough to make a final group, then don't make one.
164             // throw new
165             // NoValidInputDataException("Group from remaining ungrouped sequences in input contains less than "+minsize+" sequences.");
166           }
167         }
168       }
169     }
170     else
171     {
172       gl.add(new int[]
173       { 0, al.getHeight() - 1 });
174     }
175     if (min >= 0 && gl.size() < min)
176     {
177       throw new NoValidInputDataException(
178               "Not enough sequence groups for input. Need at least " + min
179                       + " groups (including ungrouped regions).");
180     }
181     if (max > 0 && gl.size() > max)
182     {
183       throw new NoValidInputDataException(
184               "Too many sequence groups for input. Need at most " + max
185                       + " groups (including ungrouped regions).");
186     }
187     int[][] vals = gl.toArray(new int[gl.size()][]);
188     int[] srt = new int[gl.size()];
189     for (int i = 0; i < vals.length; i++)
190       srt[i] = vals[i][0];
191     jalview.util.QuickSort.sort(srt, vals);
192     list = false;
193     int last = vals[0][0] - 1;
194     for (int[] range : vals)
195     {
196       if (range[1] > last)
197       {
198         if (list)
199         {
200           idvector.append(sep);
201         }
202         idvector.append(range[1] - last);
203         last = range[1];
204         list = true;
205       }
206     }
207     return new StringBody(idvector.toString());
208   }
209
210   /**
211    * set minimum number of sequences allowed in a partition. Default is 1
212    * sequence.
213    * 
214    * @param i
215    *          (number greater than 1)
216    */
217   public void setMinsize(int i)
218   {
219     if (minsize >= 1)
220     {
221       minsize = i;
222     }
223     else
224     {
225       minsize = 1;
226     }
227   }
228
229   @Override
230   public List<String> getURLEncodedParameter()
231   {
232     ArrayList<String> prms = new ArrayList<String>();
233     super.addBaseParams(prms);
234     prms.add("minsize='" + minsize + "'");
235     prms.add("sep='" + sep + "'");
236     if (type != null)
237     {
238       prms.add("type='" + type + "'");
239     }
240     return prms;
241   }
242
243   @Override
244   public String getURLtokenPrefix()
245   {
246     return "PARTITION";
247   }
248
249   @Override
250   public boolean configureProperty(String tok, String val,
251           StringBuffer warnings)
252   {
253
254     if (tok.startsWith("sep"))
255     {
256       sep = val;
257       return true;
258     }
259     if (tok.startsWith("minsize"))
260     {
261       try
262       {
263         minsize = Integer.valueOf(val);
264         if (minsize >= 0)
265           return true;
266       } catch (Exception x)
267       {
268
269       }
270       warnings.append("Invalid minsize value '" + val
271               + "'. Must be a positive integer.\n");
272     }
273     if (tok.startsWith("type"))
274     {
275       try
276       {
277         type = molType.valueOf(val);
278         return true;
279       } catch (Exception x)
280       {
281         warnings.append("Invalid molecule type '" + val
282                 + "'. Must be one of (");
283         for (molType v : molType.values())
284         {
285           warnings.append(" " + v);
286         }
287         warnings.append(")\n");
288       }
289     }
290     return false;
291   }
292
293   @Override
294   public List<OptionI> getOptions()
295   {
296     List<OptionI> lst = getBaseOptions();
297     lst.add(new Option("sep",
298             "Separator character between elements of vector", true, ",",
299             sep, Arrays.asList(new String[]
300             { " ", ",", ";", "\t", "|" }), null));
301     lst.add(new IntegerParameter("minsize",
302             "Minimum size of partition allowed by service", true, 1,
303             minsize, 1, 0));
304     lst.add(createMolTypeOption("type", "Sequence type", false, type,
305             molType.MIX));
306     return lst;
307   }
308
309 }