JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / ws / jws2 / AADisorderClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
3  * Copyright (C) 2015 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[] { "Globular Domain",
108         "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[] { "REM465", "Missing density" });
114     fmap.put("HOTLOOPS", new String[] { "HOTLOOPS", "Flexible loops" });
115     fmap.put("COILS", new String[] { "COILS", "Random coil" });
116     featureMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
117             fmap = new HashMap<String, String[]>());
118     fmap.put("GlobDoms", new String[] { "Globular Domain",
119         "Predicted globular domain" });
120     fmap.put("Disorder", new String[] { "Protein Disorder",
121         "Probable unstructured peptide region" });
122     Map<String, Map<String, Object>> amap;
123     annotMap = new HashMap<String, Map<String, Map<String, Object>>>();
124     annotMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
125             amap = new HashMap<String, Map<String, Object>>());
126     amap.put("Dydx", new HashMap<String, Object>());
127     amap.get("Dydx").put(DONTCOMBINE, DONTCOMBINE);
128     amap.get("Dydx").put(THRESHOLD, new double[] { 1, 0 });
129     amap.get("Dydx").put(RANGE, new float[] { -1, +1 });
130
131     amap.put("SmoothedScore", new HashMap<String, Object>());
132     amap.get("SmoothedScore").put(INVISIBLE, INVISIBLE);
133     amap.put("RawScore", new HashMap<String, Object>());
134     amap.get("RawScore").put(INVISIBLE, INVISIBLE);
135     annotMap.put(compbio.ws.client.Services.DisemblWS.toString(),
136             amap = new HashMap<String, Map<String, Object>>());
137     amap.put("COILS", new HashMap<String, Object>());
138     amap.put("HOTLOOPS", new HashMap<String, Object>());
139     amap.put("REM465", new HashMap<String, Object>());
140     amap.get("COILS").put(THRESHOLD, new double[] { 1, 0.516 });
141     amap.get("COILS").put(RANGE, new float[] { 0, 1 });
142
143     amap.get("HOTLOOPS").put(THRESHOLD, new double[] { 1, 0.6 });
144     amap.get("HOTLOOPS").put(RANGE, new float[] { 0, 1 });
145     amap.get("REM465").put(THRESHOLD, new double[] { 1, 0.1204 });
146     amap.get("REM465").put(RANGE, new float[] { 0, 1 });
147
148     annotMap.put(compbio.ws.client.Services.IUPredWS.toString(),
149             amap = new HashMap<String, Map<String, Object>>());
150     amap.put("Long", new HashMap<String, Object>());
151     amap.put("Short", new HashMap<String, Object>());
152     amap.get("Long").put(THRESHOLD, new double[] { 1, 0.5 });
153     amap.get("Long").put(RANGE, new float[] { 0, 1 });
154     amap.get("Short").put(THRESHOLD, new double[] { 1, 0.5 });
155     amap.get("Short").put(RANGE, new float[] { 0, 1 });
156     annotMap.put(compbio.ws.client.Services.JronnWS.toString(),
157             amap = new HashMap<String, Map<String, Object>>());
158     amap.put("JRonn", new HashMap<String, Object>());
159     amap.get("JRonn").put(THRESHOLD, new double[] { 1, 0.5 });
160     amap.get("JRonn").put(RANGE, new float[] { 0, 1 });
161   }
162
163   @Override
164   public void updateResultAnnotation(boolean immediate)
165   {
166
167     if (immediate || !calcMan.isWorking(this) && scoremanager != null)
168     {
169       Map<String, String[]> featureTypeMap = featureMap
170               .get(service.serviceType);
171       Map<String, Map<String, Object>> annotTypeMap = annotMap
172               .get(service.serviceType);
173       boolean dispFeatures = false;
174       Map<String, Object> fc = new Hashtable<String, Object>();
175       List<AlignmentAnnotation> ourAnnot = new ArrayList<AlignmentAnnotation>();
176       /**
177        * grouping for any annotation rows created
178        */
179       int graphGroup = 1;
180       if (alignViewport.getAlignment().getAlignmentAnnotation() != null)
181       {
182         for (AlignmentAnnotation ala : alignViewport.getAlignment()
183                 .getAlignmentAnnotation())
184         {
185           if (ala.graphGroup > graphGroup)
186           {
187             graphGroup = ala.graphGroup;
188           }
189         }
190       }
191
192       for (String seqId : seqNames.keySet())
193       {
194         boolean sameGroup = false;
195         SequenceI dseq, aseq, seq = seqNames.get(seqId);
196         int base = seq.findPosition(start) - 1;
197         aseq = seq;
198         while ((dseq = seq).getDatasetSequence() != null)
199         {
200           seq = seq.getDatasetSequence();
201         }
202         ScoreHolder scores = null;
203         try
204         {
205           scores = scoremanager.getAnnotationForSequence(seqId);
206         } catch (Exception q)
207         {
208           Cache.log
209                   .info("Couldn't recover disorder prediction for sequence "
210                           + seq.getName()
211                           + "(Prediction name was "
212                           + seqId
213                           + ")"
214                           + "\nSee http://issues.jalview.org/browse/JAL-1319 for one possible reason why disorder predictions might fail.");
215         }
216         float last = Float.NaN, val = Float.NaN;
217         int lastAnnot = ourAnnot.size();
218         if (scores != null && scores.scores != null)
219         {
220           for (Score scr : scores.scores)
221           {
222
223             if (scr.getRanges() != null && scr.getRanges().size() > 0)
224             {
225               Iterator<Float> vals = scr.getScores().iterator();
226               // make features on sequence
227               for (Range rn : scr.getRanges())
228               {
229
230                 SequenceFeature sf;
231                 String[] type = featureTypeMap.get(scr.getMethod());
232                 if (type == null)
233                 {
234                   // create a default type for this feature
235                   type = new String[] {
236                       typeName + " (" + scr.getMethod() + ")",
237                       service.getActionText() };
238                 }
239                 if (vals.hasNext())
240                 {
241                   sf = new SequenceFeature(type[0], type[1],
242                           base + rn.from, base + rn.to, val = vals.next()
243                                   .floatValue(), methodName);
244                 }
245                 else
246                 {
247                   sf = new SequenceFeature(type[0], type[1], null, base
248                           + rn.from, base + rn.to, methodName);
249                 }
250                 dseq.addSequenceFeature(sf);
251                 if (last != val && !Float.isNaN(last))
252                 {
253                   fc.put(sf.getType(), sf);
254                 }
255                 last = val;
256                 dispFeatures = true;
257               }
258             }
259             else
260             {
261               if (scr.getScores().size() == 0)
262               {
263                 continue;
264               }
265               String typename, calcName;
266               AlignmentAnnotation annot = createAnnotationRowsForScores(
267                       ourAnnot,
268                       typename = service.serviceType + " ("
269                               + scr.getMethod() + ")",
270                       calcName = service.getServiceTypeURI() + "/"
271                               + scr.getMethod(), aseq, base + 1, scr);
272               annot.graph = AlignmentAnnotation.LINE_GRAPH;
273
274               Map<String, Object> styleMap = (annotTypeMap == null) ? null
275                       : annotTypeMap.get(scr.getMethod());
276
277               annot.visible = (styleMap == null || styleMap.get(INVISIBLE) == null);
278               double[] thrsh = (styleMap == null) ? null
279                       : (double[]) styleMap.get(THRESHOLD);
280               float[] range = (styleMap == null) ? null
281                       : (float[]) styleMap.get(RANGE);
282               if (range != null)
283               {
284                 annot.graphMin = range[0];
285                 annot.graphMax = range[1];
286               }
287               if (styleMap == null || styleMap.get(DONTCOMBINE) == null)
288               {
289                 {
290                   if (!sameGroup)
291                   {
292                     graphGroup++;
293                     sameGroup = true;
294                   }
295
296                   annot.graphGroup = graphGroup;
297                 }
298               }
299
300               annot.description = "<html>" + service.getActionText()
301                       + " - raw scores";
302               if (thrsh != null)
303               {
304                 String threshNote = (thrsh[0] > 0 ? "Above " : "Below ")
305                         + thrsh[1] + " indicates disorder";
306                 annot.threshold = new GraphLine((float) thrsh[1],
307                         threshNote, Color.red);
308                 annot.description += "<br/>" + threshNote;
309               }
310               annot.description += "</html>";
311               Color col = new UserColourScheme(typeName)
312                       .createColourFromName(typeName + scr.getMethod());
313               for (int p = 0, ps = annot.annotations.length; p < ps; p++)
314               {
315                 if (annot.annotations[p] != null)
316                 {
317                   annot.annotations[p].colour = col;
318                 }
319               }
320               annot._linecolour = col;
321               // finally, update any dataset annotation
322               replaceAnnotationOnAlignmentWith(annot, typename, calcName,
323                       aseq);
324             }
325           }
326         }
327         if (lastAnnot + 1 == ourAnnot.size())
328         {
329           // remove singleton alignment annotation row
330           ourAnnot.get(lastAnnot).graphGroup = -1;
331         }
332       }
333       {
334         if (dispFeatures)
335         {
336           jalview.api.FeatureRenderer fr = ((jalview.gui.AlignmentPanel) ap)
337                   .cloneFeatureRenderer();
338           for (String ft : fc.keySet())
339           {
340             Object gc = fr.getFeatureStyle(ft);
341             if (gc instanceof Color)
342             {
343               // set graduated color as fading to white for minimum, and
344               // autoscaling to values on alignment
345               GraduatedColor ggc = new GraduatedColor(Color.white,
346                       (Color) gc, Float.MIN_VALUE, Float.MAX_VALUE);
347               ggc.setAutoScaled(true);
348               fr.setColour(ft, ggc);
349             }
350           }
351           // TODO: JAL-1150 - create sequence feature settings API for defining
352           // styles and enabling/disabling feature overlay on alignment panel
353           ((jalview.gui.AlignmentPanel) ap).updateFeatureRendererFrom(fr);
354           if (af.alignPanel == ap)
355           {
356             // only do this if the alignFrame is currently showing this view.
357             af.setShowSeqFeatures(true);
358           }
359           ap.paintAlignment(true);
360         }
361         if (ourAnnot.size() > 0)
362         {
363           // Modify the visible annotation on the alignment viewport with the
364           // new alignment annotation rows created.
365           updateOurAnnots(ourAnnot);
366           ap.adjustAnnotationHeight();
367         }
368       }
369     }
370   }
371
372   @Override
373   public String getCalcId()
374   {
375     // Disorder predictions are not dynamically updated so we return null
376     return null;
377   }
378
379 }