JAL-1620 version bump and release notes
[jalview.git] / src / jalview / ws / jws2 / AADisorderClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
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.jws2;
22
23 import jalview.api.AlignCalcWorkerI;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.GraphLine;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.schemes.GraduatedColor;
31 import jalview.schemes.UserColourScheme;
32 import jalview.ws.jws2.jabaws2.Jws2Instance;
33 import jalview.ws.params.WsParamSetI;
34
35 import java.awt.Color;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Hashtable;
39 import java.util.Iterator;
40 import java.util.List;
41 import java.util.Map;
42
43 import compbio.data.sequence.FastaSequence;
44 import compbio.data.sequence.Range;
45 import compbio.data.sequence.Score;
46 import compbio.data.sequence.ScoreManager.ScoreHolder;
47 import compbio.metadata.Argument;
48
49 public class AADisorderClient extends JabawsCalcWorker implements
50         AlignCalcWorkerI
51 {
52
53   private static final String THRESHOLD = "THRESHOLD";
54
55   private static final String RANGE = "RANGE";
56
57   String typeName;
58
59   String methodName;
60
61   String groupName;
62
63   AlignFrame af;
64
65   public AADisorderClient(Jws2Instance sh, AlignFrame alignFrame,
66           WsParamSetI preset, List<Argument> paramset)
67   {
68     super(sh, alignFrame, preset, paramset);
69     af = alignFrame;
70     typeName = sh.action;
71     methodName = sh.serviceType;
72
73     submitGaps = false;
74     alignedSeqs = false;
75     nucleotidesAllowed = false;
76     proteinAllowed = true;
77     bySequence = true;
78   }
79
80   @Override
81   public String getServiceActionText()
82   {
83     return "Submitting amino acid sequences for disorder prediction.";
84   }
85
86   @Override
87   boolean checkValidInputSeqs(boolean dynamic, List<FastaSequence> seqs)
88   {
89     return (seqs.size() > 0);
90   }
91
92   private static Map<String, Map<String, String[]>> featureMap;
93
94   private static Map<String, Map<String, Map<String, Object>>> annotMap;
95
96   private static String DONTCOMBINE = "DONTCOMBINE";
97
98   private static String INVISIBLE = "INVISIBLE";
99   static
100   {
101     // TODO: turn this into some kind of configuration file that's a bit easier
102     // to edit
103     featureMap = new HashMap<String, Map<String, String[]>>();
104     Map<String, String[]> fmap;
105     featureMap.put(compbio.ws.client.Services.IUPredWS.toString(),
106             fmap = new HashMap<String, String[]>());
107     fmap.put("Glob", new String[]
108     { "Globular Domain", "Predicted globular domain" });
109     featureMap.put(compbio.ws.client.Services.JronnWS.toString(),
110             fmap = new HashMap<String, String[]>());
111     featureMap.put(compbio.ws.client.Services.DisemblWS.toString(),
112             fmap = new HashMap<String, String[]>());
113     fmap.put("REM465", new String[]
114     { "REM465", "Missing density" });
115     fmap.put("HOTLOOPS", new String[]
116     { "HOTLOOPS", "Flexible loops" });
117     fmap.put("COILS", new String[]
118     { "COILS", "Random coil" });
119     featureMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
120             fmap = new HashMap<String, String[]>());
121     fmap.put("GlobDoms", new String[]
122     { "Globular Domain", "Predicted globular domain" });
123     fmap.put("Disorder", new String[]
124     { "Protein Disorder", "Probable unstructured peptide region" });
125     Map<String, Map<String, Object>> amap;
126     annotMap = new HashMap<String, Map<String, Map<String, Object>>>();
127     annotMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
128             amap = new HashMap<String, Map<String, Object>>());
129     amap.put("Dydx", new HashMap<String, Object>());
130     amap.get("Dydx").put(DONTCOMBINE, DONTCOMBINE);
131     amap.get("Dydx").put(THRESHOLD, new double[]
132     { 1, 0 });
133     amap.get("Dydx").put(RANGE, new float[]
134     { -1, +1 });
135
136     amap.put("SmoothedScore", new HashMap<String, Object>());
137     amap.get("SmoothedScore").put(INVISIBLE, INVISIBLE);
138     amap.put("RawScore", new HashMap<String, Object>());
139     amap.get("RawScore").put(INVISIBLE, INVISIBLE);
140     annotMap.put(compbio.ws.client.Services.DisemblWS.toString(),
141             amap = new HashMap<String, Map<String, Object>>());
142     amap.put("COILS", new HashMap<String, Object>());
143     amap.put("HOTLOOPS", new HashMap<String, Object>());
144     amap.put("REM465", new HashMap<String, Object>());
145     amap.get("COILS").put(THRESHOLD, new double[]
146     { 1, 0.516 });
147     amap.get("COILS").put(RANGE, new float[]
148     { 0, 1 });
149
150     amap.get("HOTLOOPS").put(THRESHOLD, new double[]
151     { 1, 0.6 });
152     amap.get("HOTLOOPS").put(RANGE, new float[]
153     { 0, 1 });
154     amap.get("REM465").put(THRESHOLD, new double[]
155     { 1, 0.1204 });
156     amap.get("REM465").put(RANGE, new float[]
157     { 0, 1 });
158
159     annotMap.put(compbio.ws.client.Services.IUPredWS.toString(),
160             amap = new HashMap<String, Map<String, Object>>());
161     amap.put("Long", new HashMap<String, Object>());
162     amap.put("Short", new HashMap<String, Object>());
163     amap.get("Long").put(THRESHOLD, new double[]
164     { 1, 0.5 });
165     amap.get("Long").put(RANGE, new float[]
166     { 0, 1 });
167     amap.get("Short").put(THRESHOLD, new double[]
168     { 1, 0.5 });
169     amap.get("Short").put(RANGE, new float[]
170     { 0, 1 });
171     annotMap.put(compbio.ws.client.Services.JronnWS.toString(),
172             amap = new HashMap<String, Map<String, Object>>());
173     amap.put("JRonn", new HashMap<String, Object>());
174     amap.get("JRonn").put(THRESHOLD, new double[]
175     { 1, 0.5 });
176     amap.get("JRonn").put(RANGE, new float[]
177     { 0, 1 });
178   }
179
180   @Override
181   public void updateResultAnnotation(boolean immediate)
182   {
183
184     if (immediate || !calcMan.isWorking(this) && scoremanager != null)
185     {
186       Map<String, String[]> featureTypeMap = featureMap
187               .get(service.serviceType);
188       Map<String, Map<String, Object>> annotTypeMap = annotMap
189               .get(service.serviceType);
190       boolean dispFeatures = false;
191       Map<String, Object> fc = new Hashtable<String, Object>();
192       List<AlignmentAnnotation> ourAnnot = new ArrayList<AlignmentAnnotation>();
193       /**
194        * grouping for any annotation rows created
195        */
196       int graphGroup = 1;
197       if (alignViewport.getAlignment().getAlignmentAnnotation() != null)
198       {
199         for (AlignmentAnnotation ala : alignViewport.getAlignment()
200                 .getAlignmentAnnotation())
201         {
202           if (ala.graphGroup > graphGroup)
203           {
204             graphGroup = ala.graphGroup;
205           }
206         }
207       }
208
209       for (String seqId : seqNames.keySet())
210       {
211         boolean sameGroup = false;
212         SequenceI dseq, aseq, seq = seqNames.get(seqId);
213         int base = seq.findPosition(start) - 1;
214         aseq = seq;
215         while ((dseq = seq).getDatasetSequence() != null)
216         {
217           seq = seq.getDatasetSequence();
218         }
219         ScoreHolder scores = null;
220         try
221         {
222           scores = scoremanager.getAnnotationForSequence(seqId);
223         } catch (Exception q)
224         {
225           Cache.log
226                   .info("Couldn't recover disorder prediction for sequence "
227                           + seq.getName()
228                           + "(Prediction name was "
229                           + seqId
230                           + ")"
231                           + "\nSee http://issues.jalview.org/browse/JAL-1319 for one possible reason why disorder predictions might fail.");
232         }
233         float last = Float.NaN, val = Float.NaN;
234         int lastAnnot = ourAnnot.size();
235         if (scores != null && scores.scores != null)
236         {
237           for (Score scr : scores.scores)
238           {
239
240             if (scr.getRanges() != null && scr.getRanges().size() > 0)
241             {
242               Iterator<Float> vals = scr.getScores().iterator();
243               // make features on sequence
244               for (Range rn : scr.getRanges())
245               {
246
247                 SequenceFeature sf;
248                 String[] type = featureTypeMap.get(scr.getMethod());
249                 if (type == null)
250                 {
251                   // create a default type for this feature
252                   type = new String[]
253                   { typeName + " (" + scr.getMethod() + ")",
254                       service.getActionText() };
255                 }
256                 if (vals.hasNext())
257                 {
258                   sf = new SequenceFeature(type[0], type[1],
259                           base + rn.from, base + rn.to, val = vals.next()
260                                   .floatValue(), methodName);
261                 }
262                 else
263                 {
264                   sf = new SequenceFeature(type[0], type[1], null, base
265                           + rn.from, base + rn.to, methodName);
266                 }
267                 dseq.addSequenceFeature(sf);
268                 if (last != val && last != Float.NaN)
269                 {
270                   fc.put(sf.getType(), sf);
271                 }
272                 last = val;
273                 dispFeatures = true;
274               }
275             }
276             else
277             {
278               if (scr.getScores().size() == 0)
279               {
280                 continue;
281               }
282               String typename, calcName;
283               AlignmentAnnotation annot = createAnnotationRowsForScores(
284                       ourAnnot,
285                       typename = service.serviceType + " ("
286                               + scr.getMethod() + ")",
287                       calcName = service.getServiceTypeURI() + "/"
288                               + scr.getMethod(),
289                       aseq, base + 1, scr);
290               annot.graph = AlignmentAnnotation.LINE_GRAPH;
291
292               Map<String, Object> styleMap = (annotTypeMap == null) ? null
293                       : annotTypeMap.get(scr.getMethod());
294
295               annot.visible = (styleMap == null || styleMap.get(INVISIBLE) == null);
296               double[] thrsh = (styleMap == null) ? null
297                       : (double[]) styleMap.get(THRESHOLD);
298               float[] range = (styleMap == null) ? null
299                       : (float[]) styleMap.get(RANGE);
300               if (range != null)
301               {
302                 annot.graphMin = range[0];
303                 annot.graphMax = range[1];
304               }
305               if (styleMap == null || styleMap.get(DONTCOMBINE) == null)
306               {
307                 {
308                   if (!sameGroup)
309                   {
310                     graphGroup++;
311                     sameGroup = true;
312                   }
313
314                   annot.graphGroup = graphGroup;
315                 }
316               }
317
318               annot.description = "<html>" + service.getActionText()
319                       + " - raw scores";
320               if (thrsh != null)
321               {
322                 String threshNote = (thrsh[0] > 0 ? "Above " : "Below ")
323                         + thrsh[1] + " indicates disorder";
324                 annot.threshold = new GraphLine((float) thrsh[1],
325                         threshNote, Color.red);
326                 annot.description += "<br/>" + threshNote;
327               }
328               annot.description += "</html>";
329               Color col = new UserColourScheme(typeName)
330                       .createColourFromName(typeName + scr.getMethod());
331               for (int p = 0, ps = annot.annotations.length; p < ps; p++)
332               {
333                 if (annot.annotations[p] != null)
334                 {
335                   annot.annotations[p].colour = col;
336                 }
337               }
338               annot._linecolour = col;
339               // finally, update any dataset annotation
340               replaceAnnotationOnAlignmentWith(annot, typename, calcName,
341                       aseq);
342             }
343           }
344         }
345         if (lastAnnot + 1 == ourAnnot.size())
346         {
347           // remove singleton alignment annotation row
348           ourAnnot.get(lastAnnot).graphGroup = -1;
349         }
350       }
351       {
352         if (dispFeatures)
353         {
354           jalview.gui.FeatureRenderer fr = ((jalview.gui.AlignmentPanel) ap)
355                   .cloneFeatureRenderer();
356           for (String ft : fc.keySet())
357           {
358             Object gc = fr.getFeatureStyle(ft);
359             if (gc instanceof Color)
360             {
361               // set graduated color as fading to white for minimum, and
362               // autoscaling to values on alignment
363               GraduatedColor ggc = new GraduatedColor(Color.white,
364                       (Color) gc, Float.MIN_VALUE, Float.MAX_VALUE);
365               ggc.setAutoScaled(true);
366               fr.setColour(ft, ggc);
367             }
368           }
369           // TODO: JAL-1150 - create sequence feature settings API for defining
370           // styles and enabling/disabling feature overlay on alignment panel
371           ((jalview.gui.AlignmentPanel) ap).updateFeatureRendererFrom(fr);
372           if (af.alignPanel == ap)
373           {
374             // only do this if the alignFrame is currently showing this view.
375             af.setShowSeqFeatures(true);
376           }
377           ap.paintAlignment(true);
378         }
379         if (ourAnnot.size() > 0)
380         {
381           // Modify the visible annotation on the alignment viewport with the
382           // new alignment annotation rows created.
383           updateOurAnnots(ourAnnot);
384           ap.adjustAnnotationHeight();
385         }
386       }
387     }
388   }
389
390   @Override
391   public String getCalcId()
392   {
393     // Disorder predictions are not dynamically updated so we return null
394     return null;
395   }
396
397 }