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