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