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