JAL-3468 Adapted methods to report how many features have been dropped from the toolt...
[jalview.git] / src / jalview / io / SequenceAnnotationReport.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.io;
22
23 import jalview.api.FeatureColourI;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.GeneLociI;
27 import jalview.datamodel.MappedFeatures;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.util.MessageManager;
31 import jalview.util.StringUtils;
32 import jalview.util.UrlLink;
33 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
34
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Comparator;
38 import java.util.LinkedHashMap;
39 import java.util.List;
40 import java.util.Map;
41
42 /**
43  * generate HTML reports for a sequence
44  * 
45  * @author jimp
46  */
47 public class SequenceAnnotationReport
48 {
49   private static final int MAX_DESCRIPTION_LENGTH = 40;
50
51   private static final String COMMA = ",";
52
53   private static final String ELLIPSIS = "...";
54
55   private static final int MAX_REFS_PER_SOURCE = 4;
56
57   private static final int MAX_SOURCES = 40;
58
59   private static final String[][] PRIMARY_SOURCES = new String[][] {
60       DBRefSource.CODINGDBS, DBRefSource.DNACODINGDBS,
61       DBRefSource.PROTEINDBS };
62
63   final String linkImageURL;
64
65   /*
66    * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
67    * with 'Primary' sources placed before others, and 'chromosome' first of all
68    */
69   private static Comparator<DBRefEntry> comparator = new Comparator<>()
70   {
71
72     @Override
73     public int compare(DBRefEntry ref1, DBRefEntry ref2)
74     {
75       if (ref1 instanceof GeneLociI)
76       {
77         return -1;
78       }
79       if (ref2 instanceof GeneLociI)
80       {
81         return 1;
82       }
83       String s1 = ref1.getSource();
84       String s2 = ref2.getSource();
85       boolean s1Primary = isPrimarySource(s1);
86       boolean s2Primary = isPrimarySource(s2);
87       if (s1Primary && !s2Primary)
88       {
89         return -1;
90       }
91       if (!s1Primary && s2Primary)
92       {
93         return 1;
94       }
95       int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
96               .compareToIgnoreCase(s2));
97       if (comp == 0)
98       {
99         String a1 = ref1.getAccessionId();
100         String a2 = ref2.getAccessionId();
101         comp = a1 == null ? -1 : (a2 == null ? 1 : a1
102                 .compareToIgnoreCase(a2));
103       }
104       return comp;
105     }
106
107     private boolean isPrimarySource(String source)
108     {
109       for (String[] primary : PRIMARY_SOURCES)
110       {
111         for (String s : primary)
112         {
113           if (source.equals(s))
114           {
115             return true;
116           }
117         }
118       }
119       return false;
120     }
121   };
122
123   public SequenceAnnotationReport(String linkURL)
124   {
125     this.linkImageURL = linkURL;
126   }
127
128   /**
129    * Append text for the list of features to the tooltip Returns number of
130    * features left if maxlength limit is (or would have been) reached
131    * 
132    * @param sb
133    * @param residuePos
134    * @param features
135    * @param minmax
136    * @param maxlength
137    */
138   public int appendFeaturesLengthLimit(final StringBuilder sb,
139           int residuePos, List<SequenceFeature> features,
140           FeatureRendererModel fr, int maxlength)
141   {
142     for (int i = 0; i < features.size(); i++)
143     {
144       SequenceFeature feature = features.get(i);
145       if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
146       {
147         return features.size() - i;
148       }
149     }
150     return 0;
151   }
152
153   public void appendFeatures(final StringBuilder sb, int residuePos,
154           List<SequenceFeature> features, FeatureRendererModel fr)
155   {
156     appendFeaturesLengthLimit(sb, residuePos, features, fr, 0);
157   }
158
159   /**
160    * Appends text for mapped features (e.g. CDS feature for peptide or vice versa)
161    * Returns number of features left if maxlength limit is (or would have been)
162    * reached
163    * 
164    * @param sb
165    * @param residuePos
166    * @param mf
167    * @param fr
168    * @param maxlength
169    */
170   public int appendFeaturesLengthLimit(StringBuilder sb, int residuePos,
171           MappedFeatures mf, FeatureRendererModel fr, int maxlength)
172   {
173     for (int i = 0; i < mf.features.size(); i++)
174     {
175       SequenceFeature feature = mf.features.get(i);
176       if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
177       {
178         return mf.features.size() - i;
179       }
180     }
181     return 0;
182   }
183
184   public void appendFeatures(StringBuilder sb, int residuePos,
185           MappedFeatures mf, FeatureRendererModel fr)
186   {
187     appendFeaturesLengthLimit(sb, residuePos, mf, fr, 0);
188   }
189
190   /**
191    * Appends the feature at rpos to the given buffer
192    * 
193    * @param sb
194    * @param rpos
195    * @param minmax
196    * @param feature
197    */
198   boolean appendFeature(final StringBuilder sb0, int rpos,
199           FeatureRendererModel fr, SequenceFeature feature,
200           MappedFeatures mf, int maxlength)
201   {
202     StringBuilder sb = new StringBuilder();
203     if (feature.isContactFeature())
204     {
205       if (feature.getBegin() == rpos || feature.getEnd() == rpos)
206       {
207         if (sb.length() > 6)
208         {
209           sb.append("<br/>");
210         }
211         sb.append(feature.getType()).append(" ").append(feature.getBegin())
212                 .append(":").append(feature.getEnd());
213       }
214       return appendTextMaxLengthReached(sb0, sb, maxlength);
215     }
216
217     if (sb0.length() > 6)
218     {
219       sb.append("<br/>");
220     }
221     // TODO: remove this hack to display link only features
222     boolean linkOnly = feature.getValue("linkonly") != null;
223     if (!linkOnly)
224     {
225       sb.append(feature.getType()).append(" ");
226       if (rpos != 0)
227       {
228         // we are marking a positional feature
229         sb.append(feature.begin);
230       }
231       if (feature.begin != feature.end)
232       {
233         sb.append(" ").append(feature.end);
234       }
235
236       String description = feature.getDescription();
237       if (description != null && !description.equals(feature.getType()))
238       {
239         description = StringUtils.stripHtmlTags(description);
240
241         /*
242          * truncate overlong descriptions unless they contain an href
243          * (as truncation could leave corrupted html)
244          */
245         boolean hasLink = description.indexOf("a href") > -1;
246         if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
247         {
248           description = description.substring(0, MAX_DESCRIPTION_LENGTH)
249                   + ELLIPSIS;
250         }
251
252         sb.append("; ").append(description);
253       }
254
255       if (showScore(feature, fr))
256       {
257         sb.append(" Score=").append(String.valueOf(feature.getScore()));
258       }
259       String status = (String) feature.getValue("status");
260       if (status != null && status.length() > 0)
261       {
262         sb.append("; (").append(status).append(")");
263       }
264
265       /*
266        * add attribute value if coloured by attribute
267        */
268       if (fr != null)
269       {
270         FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
271         if (fc != null && fc.isColourByAttribute())
272         {
273           String[] attName = fc.getAttributeName();
274           String attVal = feature.getValueAsString(attName);
275           if (attVal != null)
276           {
277             sb.append("; ").append(String.join(":", attName)).append("=")
278                     .append(attVal);
279           }
280         }
281       }
282
283       if (mf != null)
284       {
285         String variants = mf.findProteinVariants(feature);
286         if (!variants.isEmpty())
287         {
288           sb.append(" ").append(variants);
289         }
290       }
291     }
292     return appendTextMaxLengthReached(sb0, sb, maxlength);
293   }
294
295   void appendFeature(final StringBuilder sb, int rpos,
296           FeatureRendererModel fr, SequenceFeature feature,
297           MappedFeatures mf)
298   {
299     appendFeature(sb, rpos, fr, feature, mf, 0);
300   }
301
302   private static boolean appendTextMaxLengthReached(StringBuilder sb0,
303           StringBuilder sb, int maxlength)
304   {
305     boolean ret = false;
306     if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
307     {
308       sb0.append(sb);
309       return false;
310     } else {
311       return true;
312     }
313   }
314
315   /**
316    * Answers true if score should be shown, else false. Score is shown if it is
317    * not NaN, and the feature type has a non-trivial min-max score range
318    */
319   boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
320   {
321     if (Float.isNaN(feature.getScore()))
322     {
323       return false;
324     }
325     if (fr == null)
326     {
327       return true;
328     }
329     float[][] minMax = fr.getMinMax().get(feature.getType());
330
331     /*
332      * minMax[0] is the [min, max] score range for positional features
333      */
334     if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
335     {
336       return false;
337     }
338     return true;
339   }
340
341   /**
342    * Format and appends any hyperlinks for the sequence feature to the string
343    * buffer
344    * 
345    * @param sb
346    * @param feature
347    */
348   void appendLinks(final StringBuffer sb, SequenceFeature feature)
349   {
350     if (feature.links != null)
351     {
352       if (linkImageURL != null)
353       {
354         sb.append(" <img src=\"" + linkImageURL + "\">");
355       }
356       else
357       {
358         for (String urlstring : feature.links)
359         {
360           try
361           {
362             for (List<String> urllink : createLinksFrom(null, urlstring))
363             {
364               sb.append("<br/> <a href=\""
365                       + urllink.get(3)
366                       + "\" target=\""
367                       + urllink.get(0)
368                       + "\">"
369                       + (urllink.get(0).toLowerCase()
370                               .equals(urllink.get(1).toLowerCase()) ? urllink
371                               .get(0) : (urllink.get(0) + ":" + urllink
372                               .get(1))) + "</a></br>");
373             }
374           } catch (Exception x)
375           {
376             System.err.println("problem when creating links from "
377                     + urlstring);
378             x.printStackTrace();
379           }
380         }
381       }
382
383     }
384   }
385
386   /**
387    * 
388    * @param seq
389    * @param link
390    * @return Collection< List<String> > { List<String> { link target, link
391    *         label, dynamic component inserted (if any), url }}
392    */
393   Collection<List<String>> createLinksFrom(SequenceI seq, String link)
394   {
395     Map<String, List<String>> urlSets = new LinkedHashMap<>();
396     UrlLink urlLink = new UrlLink(link);
397     if (!urlLink.isValid())
398     {
399       System.err.println(urlLink.getInvalidMessage());
400       return null;
401     }
402
403     urlLink.createLinksFromSeq(seq, urlSets);
404
405     return urlSets.values();
406   }
407
408   public void createSequenceAnnotationReport(final StringBuilder tip,
409           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
410           FeatureRendererModel fr)
411   {
412     createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
413             fr, false);
414   }
415
416   /**
417    * Builds an html formatted report of sequence details and appends it to the
418    * provided buffer.
419    * 
420    * @param sb
421    *          buffer to append report to
422    * @param sequence
423    *          the sequence the report is for
424    * @param showDbRefs
425    *          whether to include database references for the sequence
426    * @param showNpFeats
427    *          whether to include non-positional sequence features
428    * @param fr
429    * @param summary
430    * @return
431    */
432   int createSequenceAnnotationReport(final StringBuilder sb,
433           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
434           FeatureRendererModel fr, boolean summary)
435   {
436     String tmp;
437     sb.append("<i>");
438
439     int maxWidth = 0;
440     if (sequence.getDescription() != null)
441     {
442       tmp = sequence.getDescription();
443       sb.append(tmp);
444       maxWidth = Math.max(maxWidth, tmp.length());
445     }
446     SequenceI ds = sequence;
447     while (ds.getDatasetSequence() != null)
448     {
449       ds = ds.getDatasetSequence();
450     }
451
452     if (showDbRefs)
453     {
454       maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
455     }
456
457     /*
458      * add non-positional features if wanted
459      */
460     if (showNpFeats)
461     {
462       for (SequenceFeature sf : sequence.getFeatures()
463               .getNonPositionalFeatures())
464       {
465         int sz = -sb.length();
466         appendFeature(sb, 0, fr, sf, null);
467         sz += sb.length();
468         maxWidth = Math.max(maxWidth, sz);
469       }
470     }
471     sb.append("</i>");
472     return maxWidth;
473   }
474
475   /**
476    * A helper method that appends any DBRefs, returning the maximum line length
477    * added
478    * 
479    * @param sb
480    * @param ds
481    * @param summary
482    * @return
483    */
484   protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
485           boolean summary)
486   {
487     DBRefEntry[] dbrefs = ds.getDBRefs();
488     if (dbrefs == null)
489     {
490       return 0;
491     }
492
493     // note this sorts the refs held on the sequence!
494     Arrays.sort(dbrefs, comparator);
495     boolean ellipsis = false;
496     String source = null;
497     String lastSource = null;
498     int countForSource = 0;
499     int sourceCount = 0;
500     boolean moreSources = false;
501     int maxLineLength = 0;
502     int lineLength = 0;
503
504     for (DBRefEntry ref : dbrefs)
505     {
506       source = ref.getSource();
507       if (source == null)
508       {
509         // shouldn't happen
510         continue;
511       }
512       boolean sourceChanged = !source.equals(lastSource);
513       if (sourceChanged)
514       {
515         lineLength = 0;
516         countForSource = 0;
517         sourceCount++;
518       }
519       if (sourceCount > MAX_SOURCES && summary)
520       {
521         ellipsis = true;
522         moreSources = true;
523         break;
524       }
525       lastSource = source;
526       countForSource++;
527       if (countForSource == 1 || !summary)
528       {
529         sb.append("<br/>");
530       }
531       if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
532       {
533         String accessionId = ref.getAccessionId();
534         lineLength += accessionId.length() + 1;
535         if (countForSource > 1 && summary)
536         {
537           sb.append(", ").append(accessionId);
538           lineLength++;
539         }
540         else
541         {
542           sb.append(source).append(" ").append(accessionId);
543           lineLength += source.length();
544         }
545         maxLineLength = Math.max(maxLineLength, lineLength);
546       }
547       if (countForSource == MAX_REFS_PER_SOURCE && summary)
548       {
549         sb.append(COMMA).append(ELLIPSIS);
550         ellipsis = true;
551       }
552     }
553     if (moreSources)
554     {
555       sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
556     }
557     if (ellipsis)
558     {
559       sb.append("<br/>(");
560       sb.append(MessageManager.getString("label.output_seq_details"));
561       sb.append(")");
562     }
563
564     return maxLineLength;
565   }
566
567   public void createTooltipAnnotationReport(final StringBuilder tip,
568           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
569           FeatureRendererModel fr)
570   {
571     int maxWidth = createSequenceAnnotationReport(tip, sequence,
572             showDbRefs, showNpFeats, fr, true);
573
574     if (maxWidth > 60)
575     {
576       // ? not sure this serves any useful purpose
577       // tip.insert(0, "<table width=350 border=0><tr><td>");
578       // tip.append("</td></tr></table>");
579     }
580   }
581 }