update author list in license for (JAL-826)
[jalview.git] / src / jalview / ws / rest / params / SeqGroupIndexVector.java
1 /*******************************************************************************
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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     for (SequenceGroup sg : (Vector<SequenceGroup>) al.getGroups())
96     {
97       if (sg.getSize() < minsize)
98       {
99         throw new NoValidInputDataException("Group contains less than "
100                 + minsize + " sequences.");
101       }
102       // TODO: refactor to sequenceGroup for efficiency -
103       // getAlignmentRowInterval(AlignmentI al)
104       int[] se = null;
105       for (SequenceI sq : sg.getSequencesInOrder(al))
106       {
107         p = al.findIndex(sq);
108         if (se == null)
109         {
110           se = new int[]
111           { p, p };
112         }
113         else
114         {
115           if (p < se[0])
116             se[0] = p;
117           if (p > se[1])
118             se[1] = p;
119         }
120       }
121       if (se != null)
122       {
123         gl.add(se);
124       }
125     }
126     // are there any more sequences ungrouped that should be added as a single
127     // remaining group ? - these might be at the start or the end
128     if (gl.size() > 0)
129     {
130       int[] tail = gl.get(0);
131       if (tail[0] > 0)
132       {
133         if (1 + tail[0] > minsize)
134         {
135           gl.add(0, new int[]
136           { 0, tail[0] - 1 });
137         }
138         else
139         {
140           // lets be intelligent here - if the remaining sequences aren't enough
141           // to make a final group, then don't make one.
142           // throw new
143           // NoValidInputDataException("Group from remaining ungrouped sequences in input contains less than "+minsize+" sequences.");
144         }
145       }
146       else
147       {
148         tail = gl.get(gl.size() - 1);
149         if (1 + tail[1] < al.getHeight())
150         {
151           if (al.getHeight() - (1 + tail[1]) > minsize)
152           {
153             gl.add(new int[]
154             { tail[1] + 1, al.getHeight() - 1 });
155           }
156           else
157           {
158             // lets be intelligent here - if the remaining sequences aren't
159             // enough to make a final group, then don't make one.
160             // throw new
161             // NoValidInputDataException("Group from remaining ungrouped sequences in input contains less than "+minsize+" sequences.");
162           }
163         }
164       }
165     }
166     else
167     {
168       gl.add(new int[]
169       { 0, al.getHeight() - 1 });
170     }
171     if (min >= 0 && gl.size() < min)
172     {
173       throw new NoValidInputDataException(
174               "Not enough sequence groups for input. Need at least " + min
175                       + " groups (including ungrouped regions).");
176     }
177     if (max > 0 && gl.size() > max)
178     {
179       throw new NoValidInputDataException(
180               "Too many sequence groups for input. Need at most " + max
181                       + " groups (including ungrouped regions).");
182     }
183     int[][] vals = gl.toArray(new int[gl.size()][]);
184     int[] srt = new int[gl.size()];
185     for (int i = 0; i < vals.length; i++)
186       srt[i] = vals[i][0];
187     jalview.util.QuickSort.sort(srt, vals);
188     list = false;
189     int last = vals[0][0] - 1;
190     for (int[] range : vals)
191     {
192       if (range[1] > last)
193       {
194         if (list)
195         {
196           idvector.append(sep);
197         }
198         idvector.append(range[1] - last);
199         last = range[1];
200         list = true;
201       }
202     }
203     return new StringBody(idvector.toString());
204   }
205
206   /**
207    * set minimum number of sequences allowed in a partition. Default is 1
208    * sequence.
209    * 
210    * @param i
211    *          (number greater than 1)
212    */
213   public void setMinsize(int i)
214   {
215     if (minsize >= 1)
216     {
217       minsize = i;
218     }
219     else
220     {
221       minsize = 1;
222     }
223   }
224
225   @Override
226   public List<String> getURLEncodedParameter()
227   {
228     ArrayList<String> prms = new ArrayList<String>();
229     super.addBaseParams(prms);
230     prms.add("minsize='" + minsize + "'");
231     prms.add("sep='" + sep + "'");
232     if (type != null)
233     {
234       prms.add("type='" + type + "'");
235     }
236     return prms;
237   }
238
239   @Override
240   public String getURLtokenPrefix()
241   {
242     return "PARTITION";
243   }
244
245   @Override
246   public boolean configureProperty(String tok, String val,
247           StringBuffer warnings)
248   {
249
250     if (tok.startsWith("sep"))
251     {
252       sep = val;
253       return true;
254     }
255     if (tok.startsWith("minsize"))
256     {
257       try
258       {
259         minsize = Integer.valueOf(val);
260         if (minsize >= 0)
261           return true;
262       } catch (Exception x)
263       {
264
265       }
266       warnings.append("Invalid minsize value '" + val
267               + "'. Must be a positive integer.\n");
268     }
269     if (tok.startsWith("type"))
270     {
271       try
272       {
273         type = molType.valueOf(val);
274         return true;
275       } catch (Exception x)
276       {
277         warnings.append("Invalid molecule type '" + val
278                 + "'. Must be one of (");
279         for (molType v : molType.values())
280         {
281           warnings.append(" " + v);
282         }
283         warnings.append(")\n");
284       }
285     }
286     return false;
287   }
288
289   @Override
290   public List<OptionI> getOptions()
291   {
292     List<OptionI> lst = getBaseOptions();
293     lst.add(new Option("sep",
294             "Separator character between elements of vector", true, ",",
295             sep, Arrays.asList(new String[]
296             { " ", ",", ";", "\t", "|" }), null));
297     lst.add(new IntegerParameter("minsize", "Minimum size of partition allowed by service", true, 1, minsize, 1,0));
298     lst.add(createMolTypeOption("type", "Sequence type", false, type, molType.MIX));
299     return lst;
300   }
301
302 }