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