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