1f568d6b46a4a54db5170b618d757c372367423b
[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.ws.params.OptionI;
27 import jalview.ws.params.simple.IntegerParameter;
28 import jalview.ws.params.simple.Option;
29 import jalview.ws.rest.AlignmentProcessor;
30 import jalview.ws.rest.InputType;
31 import jalview.ws.rest.NoValidInputDataException;
32 import jalview.ws.rest.RestJob;
33
34 import java.io.UnsupportedEncodingException;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.List;
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,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("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 (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[] { highest+1, al.getHeight()-1});
150       }
151     }
152     else
153     {
154       gl.add(new int[]
155       { 0, al.getHeight() - 1 });
156     }
157     if (min >= 0 && gl.size() < min)
158     {
159       throw new NoValidInputDataException(
160               "Not enough sequence groups for input. Need at least " + min
161                       + " groups (including ungrouped regions).");
162     }
163     if (max > 0 && gl.size() > max)
164     {
165       throw new NoValidInputDataException(
166               "Too many sequence groups for input. Need at most " + max
167                       + " groups (including ungrouped regions).");
168     }
169     int[][] vals = gl.toArray(new int[gl.size()][]);
170     int[] srt = new int[gl.size()];
171     for (int i = 0; i < vals.length; i++)
172       srt[i] = vals[i][0];
173     jalview.util.QuickSort.sort(srt, vals);
174     list = false;
175     int last = vals[0][0] - 1;
176     for (int[] range : vals)
177     {
178       if (range[1] > last)
179       {
180         if (list)
181         {
182           idvector.append(sep);
183         }
184         idvector.append(range[1] - last);
185         last = range[1];
186         list = true;
187       }
188     }
189     return new StringBody(idvector.toString());
190   }
191
192   /**
193    * set minimum number of sequences allowed in a partition. Default is 1
194    * sequence.
195    * 
196    * @param i
197    *          (number greater than 1)
198    */
199   public void setMinsize(int i)
200   {
201     if (minsize >= 1)
202     {
203       minsize = i;
204     }
205     else
206     {
207       minsize = 1;
208     }
209   }
210
211   @Override
212   public List<String> getURLEncodedParameter()
213   {
214     ArrayList<String> prms = new ArrayList<String>();
215     super.addBaseParams(prms);
216     prms.add("minsize='" + minsize + "'");
217     prms.add("sep='" + sep + "'");
218     if (type != null)
219     {
220       prms.add("type='" + type + "'");
221     }
222     return prms;
223   }
224
225   @Override
226   public String getURLtokenPrefix()
227   {
228     return "PARTITION";
229   }
230
231   @Override
232   public boolean configureProperty(String tok, String val,
233           StringBuffer warnings)
234   {
235
236     if (tok.startsWith("sep"))
237     {
238       sep = val;
239       return true;
240     }
241     if (tok.startsWith("minsize"))
242     {
243       try
244       {
245         minsize = Integer.valueOf(val);
246         if (minsize >= 0)
247           return true;
248       } catch (Exception x)
249       {
250
251       }
252       warnings.append("Invalid minsize value '" + val
253               + "'. Must be a positive integer.\n");
254     }
255     if (tok.startsWith("type"))
256     {
257       try
258       {
259         type = molType.valueOf(val);
260         return true;
261       } catch (Exception x)
262       {
263         warnings.append("Invalid molecule type '" + val
264                 + "'. Must be one of (");
265         for (molType v : molType.values())
266         {
267           warnings.append(" " + v);
268         }
269         warnings.append(")\n");
270       }
271     }
272     return false;
273   }
274
275   @Override
276   public List<OptionI> getOptions()
277   {
278     List<OptionI> lst = getBaseOptions();
279     lst.add(new Option("sep",
280             "Separator character between elements of vector", true, ",",
281             sep, Arrays.asList(new String[]
282             { " ", ",", ";", "\t", "|" }), null));
283     lst.add(new IntegerParameter("minsize",
284             "Minimum size of partition allowed by service", true, 1,
285             minsize, 1, 0));
286     lst.add(createMolTypeOption("type", "Sequence type", false, type,
287             molType.MIX));
288     return lst;
289   }
290
291 }