JAL-1503 update version in GPL header
[jalview.git] / src / jalview / ws / jws2 / AADisorderClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package jalview.ws.jws2;
20
21 import jalview.api.AlignCalcWorkerI;
22 import jalview.bin.Cache;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.GraphLine;
25 import jalview.datamodel.SequenceFeature;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.AlignFrame;
28 import jalview.schemes.GraduatedColor;
29 import jalview.schemes.UserColourScheme;
30 import jalview.ws.jws2.jabaws2.Jws2Instance;
31 import jalview.ws.params.WsParamSetI;
32
33 import java.awt.Color;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.Hashtable;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40
41 import compbio.data.sequence.Range;
42 import compbio.data.sequence.Score;
43 import compbio.data.sequence.ScoreManager.ScoreHolder;
44 import compbio.metadata.Argument;
45
46 public class AADisorderClient extends JabawsCalcWorker implements
47         AlignCalcWorkerI
48 {
49
50   private static final String THRESHOLD = "THRESHOLD";
51   private static final String RANGE = "RANGE";
52
53   String typeName;
54
55   String methodName;
56
57   String groupName;
58
59   AlignFrame af;
60
61   public AADisorderClient(Jws2Instance sh, AlignFrame alignFrame,
62           WsParamSetI preset, List<Argument> paramset)
63   {
64     super(sh, alignFrame, preset, paramset);
65     af = alignFrame;
66     typeName = sh.action;
67     methodName = sh.serviceType;
68
69     submitGaps = false;
70     alignedSeqs = false;
71     nucleotidesAllowed = false;
72     proteinAllowed = true;
73     bySequence = true;
74   }
75
76   @Override
77   public String getServiceActionText()
78   {
79     return "Submitting amino acid sequences for disorder prediction.";
80   }
81
82   private static Map<String, Map<String, String[]>> featureMap;
83
84   private static Map<String, Map<String, Map<String, Object>>> annotMap;
85
86   private static String DONTCOMBINE = "DONTCOMBINE";
87
88   private static String INVISIBLE = "INVISIBLE";
89   static
90   {
91     // TODO: turn this into some kind of configuration file that's a bit easier
92     // to edit
93     featureMap = new HashMap<String, Map<String, String[]>>();
94     Map<String, String[]> fmap;
95     featureMap.put(compbio.ws.client.Services.IUPredWS.toString(),
96             fmap = new HashMap<String, String[]>());
97     fmap.put("Glob", new String[]
98     { "Globular Domain", "Predicted globular domain" });
99     featureMap.put(compbio.ws.client.Services.JronnWS.toString(),
100             fmap = new HashMap<String, String[]>());
101     featureMap.put(compbio.ws.client.Services.DisemblWS.toString(),
102             fmap = new HashMap<String, String[]>());
103     fmap.put("REM465", new String[]
104     { "REM465", "Missing density" });
105     fmap.put("HOTLOOPS", new String[]
106     { "HOTLOOPS", "Flexible loops" });
107     fmap.put("COILS", new String[]
108     { "COILS", "Random coil" });
109     featureMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
110             fmap = new HashMap<String, String[]>());
111     fmap.put("GlobDoms", new String[]
112     { "Globular Domain", "Predicted globular domain" });
113     fmap.put("Disorder", new String[]
114     { "Protein Disorder", "Probable unstructured peptide region" });
115     Map<String, Map<String, Object>> amap;
116     annotMap = new HashMap<String, Map<String, Map<String, Object>>>();
117     annotMap.put(compbio.ws.client.Services.GlobPlotWS.toString(),
118             amap = new HashMap<String, Map<String, Object>>());
119     amap.put("Dydx", new HashMap<String, Object>());
120     amap.get("Dydx").put(DONTCOMBINE, DONTCOMBINE);
121     amap.get("Dydx").put(THRESHOLD, new double[]
122     { 1, 0 });
123     amap.get("Dydx").put(RANGE, new float[]
124             { -1, +1 });
125
126     amap.put("SmoothedScore", new HashMap<String, Object>());
127     amap.get("SmoothedScore").put(INVISIBLE, INVISIBLE);
128     amap.put("RawScore", new HashMap<String, Object>());
129     amap.get("RawScore").put(INVISIBLE, INVISIBLE);
130     annotMap.put(compbio.ws.client.Services.DisemblWS.toString(),
131             amap = new HashMap<String, Map<String, Object>>());
132     amap.put("COILS", new HashMap<String, Object>());
133     amap.put("HOTLOOPS", new HashMap<String, Object>());
134     amap.put("REM465", new HashMap<String, Object>());
135     amap.get("COILS").put(THRESHOLD, new double[]
136     { 1, 0.516 });
137     amap.get("COILS").put(RANGE, new float[]
138             { 0, 1 });
139
140     amap.get("HOTLOOPS").put(THRESHOLD, new double[]
141     { 1, 0.6 });
142     amap.get("HOTLOOPS").put(RANGE, new float[]
143             { 0, 1 });
144     amap.get("REM465").put(THRESHOLD, new double[]
145     { 1, 0.1204 });
146     amap.get("REM465").put(RANGE, new float[]
147             { 0, 1 });
148
149
150     annotMap.put(compbio.ws.client.Services.IUPredWS.toString(),
151             amap = new HashMap<String, Map<String, Object>>());
152     amap.put("Long", new HashMap<String, Object>());
153     amap.put("Short", new HashMap<String, Object>());
154     amap.get("Long").put(THRESHOLD, new double[]
155     { 1, 0.5 });
156     amap.get("Long").put(RANGE, new float[]
157             { 0, 1 });
158     amap.get("Short").put(THRESHOLD, new double[]
159     { 1, 0.5 });
160     amap.get("Short").put(RANGE, new float[]
161             { 0, 1 });
162     annotMap.put(compbio.ws.client.Services.JronnWS.toString(),
163             amap = new HashMap<String, Map<String, Object>>());
164     amap.put("JRonn", new HashMap<String, Object>());
165     amap.get("JRonn").put(THRESHOLD, new double[]
166     { 1, 0.5 });
167     amap.get("JRonn").put(RANGE, new float[]
168             { 0, 1 });
169   }
170
171   @Override
172   public void updateResultAnnotation(boolean immediate)
173   {
174
175     if (immediate || !calcMan.isWorking(this) && scoremanager != null)
176     {
177       Map<String, String[]> featureTypeMap = featureMap
178               .get(service.serviceType);
179       Map<String, Map<String, Object>> annotTypeMap = annotMap
180               .get(service.serviceType);
181       boolean dispFeatures = false;
182       Map<String, Object> fc = new Hashtable<String, Object>();
183       List<AlignmentAnnotation> ourAnnot = new ArrayList<AlignmentAnnotation>();
184       /**
185        * grouping for any annotation rows created
186        */
187       int graphGroup = 1;
188       if (alignViewport.getAlignment().getAlignmentAnnotation() != null)
189       {
190         for (AlignmentAnnotation ala : alignViewport.getAlignment()
191                 .getAlignmentAnnotation())
192         {
193           if (ala.graphGroup > graphGroup)
194           {
195             graphGroup = ala.graphGroup;
196           }
197         }
198       }
199
200       for (String seqId : seqNames.keySet())
201       {
202         boolean sameGroup = false;
203         SequenceI dseq, aseq, seq = seqNames.get(seqId);
204         int base = seq.findPosition(start)-1;
205         aseq = seq;
206         while ((dseq = seq).getDatasetSequence() != null)
207         {
208           seq = seq.getDatasetSequence();
209         }
210         ScoreHolder scores = null;
211         try {
212           scores = scoremanager.getAnnotationForSequence(seqId);
213         } catch (Exception q)
214         {
215           Cache.log
216                   .info("Couldn't recover disorder prediction for sequence "
217                           + seq.getName()
218                           + "(Prediction name was "
219                           + seqId+")"
220                           + "\nSee http://issues.jalview.org/browse/JAL-1319 for one possible reason why disorder predictions might fail.");
221         }
222         float last = Float.NaN, val = Float.NaN;
223         int lastAnnot = ourAnnot.size();
224         if (scores!=null && scores.scores!=null) {
225           for (Score scr : scores.scores)
226           {
227
228             if (scr.getRanges() != null && scr.getRanges().size() > 0)
229             {
230               Iterator<Float> vals = scr.getScores().iterator();
231               // make features on sequence
232               for (Range rn : scr.getRanges())
233               {
234
235                 SequenceFeature sf;
236                 String[] type = featureTypeMap.get(scr.getMethod());
237                 if (type == null)
238                 {
239                   // create a default type for this feature
240                   type = new String[]
241                   { typeName + " (" + scr.getMethod() + ")",
242                       service.getActionText() };
243                 }
244                 if (vals.hasNext())
245                 {
246                   sf = new SequenceFeature(type[0], type[1],
247                           base + rn.from, base + rn.to, val = vals.next()
248                                   .floatValue(), methodName);
249                 }
250                 else
251                 {
252                   sf = new SequenceFeature(type[0], type[1], null, base
253                           + rn.from, base + rn.to, methodName);
254                 }
255                 dseq.addSequenceFeature(sf);
256                 if (last != val && last != Float.NaN)
257                 {
258                   fc.put(sf.getType(), sf);
259                 }
260                 last = val;
261                 dispFeatures = true;
262               }
263             }
264             else
265             {
266               if (scr.getScores().size() == 0)
267               {
268                 continue;
269               }
270               AlignmentAnnotation annot = createAnnotationRowsForScores(
271                       ourAnnot,
272                       service.serviceType + " (" + scr.getMethod() + ")",
273                       service.getServiceTypeURI() + "/" + scr.getMethod(),
274                       aseq, base + 1, scr);
275               annot.graph = AlignmentAnnotation.LINE_GRAPH;
276               
277               Map<String,Object> styleMap = (annotTypeMap == null) ? null : annotTypeMap.get(scr.getMethod());
278               
279               annot.visible = (styleMap == null || styleMap.get(INVISIBLE) == null);
280               double[] thrsh = (styleMap==null) ? null
281                       : (double[]) styleMap.get(
282                               THRESHOLD);
283               float[] range = (styleMap==null) ? null : (float[]) styleMap.get(
284                       RANGE);
285               if (range!=null)
286               {
287                 annot.graphMin = range[0];
288                 annot.graphMax = range[1];
289               }
290               if (styleMap==null || styleMap.get(DONTCOMBINE) == null)
291               {
292                 {
293                   if (!sameGroup)
294                   {
295                     graphGroup++;
296                     sameGroup = true;
297                   }
298
299                   annot.graphGroup = graphGroup;
300                 }
301               }
302
303               annot.description = "<html>" + service.getActionText()
304                       + " - raw scores";
305               if (thrsh != null)
306               {
307                 String threshNote = (thrsh[0] > 0 ? "Above " : "Below ")
308                         + thrsh[1] + " indicates disorder";
309                 annot.threshold = new GraphLine((float) thrsh[1],
310                         threshNote, Color.red);
311                 annot.description += "<br/>" + threshNote;
312               }
313               annot.description += "</html>";
314               Color col = new UserColourScheme(typeName)
315                       .createColourFromName(typeName + scr.getMethod());
316               for (int p = 0, ps = annot.annotations.length; p < ps; p++)
317               {
318                 if (annot.annotations[p] != null)
319                 {
320                   annot.annotations[p].colour = col;
321                 }
322               }
323               annot._linecolour = col;
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.gui.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 }