JAL-2418 source formatting
[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.datamodel.AlignmentI;
24 import jalview.datamodel.SequenceGroup;
25 import jalview.datamodel.SequenceI;
26 import jalview.util.MessageManager;
27 import jalview.ws.params.OptionI;
28 import jalview.ws.params.simple.IntegerParameter;
29 import jalview.ws.params.simple.Option;
30 import jalview.ws.rest.AlignmentProcessor;
31 import jalview.ws.rest.InputType;
32 import jalview.ws.rest.NoValidInputDataException;
33 import jalview.ws.rest.RestJob;
34
35 import java.io.UnsupportedEncodingException;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.List;
39
40 import org.apache.http.entity.mime.content.ContentBody;
41 import org.apache.http.entity.mime.content.StringBody;
42
43 /**
44  * Represents the partitions defined on the alignment as indices e.g. for a
45  * partition (A,B,C),(D,E),(F) The indices would be 3,2,1. Note, the alignment
46  * must be ordered so groups are contiguous before this input type can be used.
47  * 
48  * @author JimP
49  * 
50  */
51 public class SeqGroupIndexVector extends InputType
52         implements AlignmentProcessor
53 {
54   public SeqGroupIndexVector()
55   {
56     super(new Class[] { 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, lowest = al.getHeight(), highest = 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(MessageManager.formatMessage(
103                   "exception.notvaliddata_group_contains_less_than_min_seqs",
104                   new String[]
105                   { 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[] { p, p };
124           }
125           else
126           {
127             if (p < se[0])
128               se[0] = p;
129             if (p > se[1])
130               se[1] = p;
131           }
132         }
133         if (se != null)
134         {
135           gl.add(se);
136         }
137       }
138     }
139     // are there any more sequences ungrouped that should be added as a single
140     // remaining group ? - these might be at the start or the end
141     if (gl.size() > 0)
142     {
143       if (lowest - 1 > minsize)
144       {
145         gl.add(0, new int[] { 0, lowest - 2 });
146       }
147       if ((al.getHeight() - 1 - highest) > minsize)
148       {
149         gl.add(new int[] { highest + 1, al.getHeight() - 1 });
150       }
151     }
152     else
153     {
154       gl.add(new int[] { 0, al.getHeight() - 1 });
155     }
156     if (min >= 0 && gl.size() < min)
157     {
158       throw new NoValidInputDataException(
159               "Not enough sequence groups for input. Need at least " + min
160                       + " groups (including ungrouped regions).");
161     }
162     if (max > 0 && gl.size() > max)
163     {
164       throw new NoValidInputDataException(
165               "Too many sequence groups for input. Need at most " + max
166                       + " groups (including ungrouped regions).");
167     }
168     int[][] vals = gl.toArray(new int[gl.size()][]);
169     int[] srt = new int[gl.size()];
170     for (int i = 0; i < vals.length; i++)
171       srt[i] = vals[i][0];
172     jalview.util.QuickSort.sort(srt, vals);
173     list = false;
174     int last = vals[0][0] - 1;
175     for (int[] range : vals)
176     {
177       if (range[1] > last)
178       {
179         if (list)
180         {
181           idvector.append(sep);
182         }
183         idvector.append(range[1] - last);
184         last = range[1];
185         list = true;
186       }
187     }
188     return new StringBody(idvector.toString());
189   }
190
191   /**
192    * set minimum number of sequences allowed in a partition. Default is 1
193    * sequence.
194    * 
195    * @param i
196    *          (number greater than 1)
197    */
198   public void setMinsize(int i)
199   {
200     if (minsize >= 1)
201     {
202       minsize = i;
203     }
204     else
205     {
206       minsize = 1;
207     }
208   }
209
210   @Override
211   public List<String> getURLEncodedParameter()
212   {
213     ArrayList<String> prms = new ArrayList<String>();
214     super.addBaseParams(prms);
215     prms.add("minsize='" + minsize + "'");
216     prms.add("sep='" + sep + "'");
217     if (type != null)
218     {
219       prms.add("type='" + type + "'");
220     }
221     return prms;
222   }
223
224   @Override
225   public String getURLtokenPrefix()
226   {
227     return "PARTITION";
228   }
229
230   @Override
231   public boolean configureProperty(String tok, String val,
232           StringBuffer warnings)
233   {
234
235     if (tok.startsWith("sep"))
236     {
237       sep = val;
238       return true;
239     }
240     if (tok.startsWith("minsize"))
241     {
242       try
243       {
244         minsize = Integer.valueOf(val);
245         if (minsize >= 0)
246           return true;
247       } catch (Exception x)
248       {
249
250       }
251       warnings.append("Invalid minsize value '" + val
252               + "'. Must be a positive integer.\n");
253     }
254     if (tok.startsWith("type"))
255     {
256       try
257       {
258         type = molType.valueOf(val);
259         return true;
260       } catch (Exception x)
261       {
262         warnings.append(
263                 "Invalid molecule type '" + val + "'. Must be one of (");
264         for (molType v : molType.values())
265         {
266           warnings.append(" " + v);
267         }
268         warnings.append(")\n");
269       }
270     }
271     return false;
272   }
273
274   @Override
275   public List<OptionI> getOptions()
276   {
277     List<OptionI> lst = getBaseOptions();
278     lst.add(new Option("sep",
279             "Separator character between elements of vector", true, ",",
280             sep, Arrays.asList(new String[]
281             { " ", ",", ";", "\t", "|" }), null));
282     lst.add(new IntegerParameter("minsize",
283             "Minimum size of partition allowed by service", true, 1,
284             minsize, 1, 0));
285     lst.add(createMolTypeOption("type", "Sequence type", false, type,
286             molType.MIX));
287     return lst;
288   }
289
290 }