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