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