Merge branch 'Jalview-JS/develop' into develop
[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;
211     int[] endRange = null;
212     if (mf != null)
213     {
214       beginRange = mf.getMappedPositions(begin, begin);
215       endRange = mf.getMappedPositions(end, end);
216       if (beginRange == null || endRange == null)
217       {
218         // something went wrong
219         return false;
220       }
221       begin = beginRange[0];
222       end = endRange[endRange.length - 1];
223     }
224
225     StringBuilder sb = new StringBuilder();
226     if (feature.isContactFeature())
227     {
228       /*
229        * include if rpos is at start or end position of [mapped] feature
230        */
231       boolean showContact = (mf == null) && (rpos == begin || rpos == end);
232       boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
233               && rpos <= beginRange[beginRange.length - 1])
234               || (rpos >= endRange[0]
235                       && rpos <= endRange[endRange.length - 1]));
236       if (showContact || showMappedContact)
237       {
238         if (sb0.length() > 6)
239         {
240           sb.append("<br/>");
241         }
242         sb.append(feature.getType()).append(" ").append(begin).append(":")
243                 .append(end);
244       }
245       return appendText(sb0, sb, maxlength);
246     }
247
248     if (sb0.length() > 6)
249     {
250       sb.append("<br/>");
251     }
252     // TODO: remove this hack to display link only features
253     boolean linkOnly = feature.getValue("linkonly") != null;
254     if (!linkOnly)
255     {
256       sb.append(feature.getType()).append(" ");
257       if (rpos != 0)
258       {
259         // we are marking a positional feature
260         sb.append(begin);
261         if (begin != end)
262         {
263           sb.append(" ").append(end);
264         }
265       }
266
267       String description = feature.getDescription();
268       if (description != null && !description.equals(feature.getType()))
269       {
270         description = StringUtils.stripHtmlTags(description);
271
272         /*
273          * truncate overlong descriptions unless they contain an href
274          * before the truncation point (as truncation could leave corrupted html)
275          */
276         int linkindex = description.toLowerCase().indexOf("<a ");
277         boolean hasLink = linkindex > -1
278                 && linkindex < MAX_DESCRIPTION_LENGTH;
279         if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
280         {
281           description = description.substring(0, MAX_DESCRIPTION_LENGTH)
282                   + ELLIPSIS;
283         }
284
285         sb.append("; ").append(description);
286       }
287
288       if (showScore(feature, fr))
289       {
290         sb.append(" Score=").append(String.valueOf(feature.getScore()));
291       }
292       String status = (String) feature.getValue("status");
293       if (status != null && status.length() > 0)
294       {
295         sb.append("; (").append(status).append(")");
296       }
297
298       /*
299        * add attribute value if coloured by attribute
300        */
301       if (fr != null)
302       {
303         FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
304         if (fc != null && fc.isColourByAttribute())
305         {
306           String[] attName = fc.getAttributeName();
307           String attVal = feature.getValueAsString(attName);
308           if (attVal != null)
309           {
310             sb.append("; ").append(String.join(":", attName)).append("=")
311                     .append(attVal);
312           }
313         }
314       }
315
316       if (mf != null)
317       {
318         String variants = mf.findProteinVariants(feature);
319         if (!variants.isEmpty())
320         {
321           sb.append(" ").append(variants);
322         }
323       }
324     }
325     return appendText(sb0, sb, maxlength);
326   }
327
328   /**
329    * Appends sb to sb0, and returns false, unless maxlength is not zero and
330    * appending would make the result longer than or equal to maxlength, in which
331    * case the append is not done and returns true
332    * 
333    * @param sb0
334    * @param sb
335    * @param maxlength
336    * @return
337    */
338   private static boolean appendText(StringBuilder sb0, StringBuilder sb,
339           int maxlength)
340   {
341     if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
342     {
343       sb0.append(sb);
344       return false;
345     }
346     return true;
347   }
348
349   /**
350    * Answers true if score should be shown, else false. Score is shown if it is
351    * not NaN, and the feature type has a non-trivial min-max score range
352    */
353   boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
354   {
355     if (Float.isNaN(feature.getScore()))
356     {
357       return false;
358     }
359     if (fr == null)
360     {
361       return true;
362     }
363     float[][] minMax = fr.getMinMax().get(feature.getType());
364
365     /*
366      * minMax[0] is the [min, max] score range for positional features
367      */
368     if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
369     {
370       return false;
371     }
372     return true;
373   }
374
375   /**
376    * Format and appends any hyperlinks for the sequence feature to the string
377    * buffer
378    * 
379    * @param sb
380    * @param feature
381    */
382   void appendLinks(final StringBuffer sb, SequenceFeature feature)
383   {
384     if (feature.links != null)
385     {
386       if (linkImageURL != null)
387       {
388         sb.append(" <img src=\"" + linkImageURL + "\">");
389       }
390       else
391       {
392         for (String urlstring : feature.links)
393         {
394           try
395           {
396             for (List<String> urllink : createLinksFrom(null, urlstring))
397             {
398               sb.append("<br/> <a href=\""
399                       + urllink.get(3)
400                       + "\" target=\""
401                       + urllink.get(0)
402                       + "\">"
403                       + (urllink.get(0).toLowerCase()
404                               .equals(urllink.get(1).toLowerCase()) ? urllink
405                               .get(0) : (urllink.get(0) + ":" + urllink
406                                               .get(1)))
407                       + "</a><br/>");
408             }
409           } catch (Exception x)
410           {
411             System.err.println("problem when creating links from "
412                     + urlstring);
413             x.printStackTrace();
414           }
415         }
416       }
417
418     }
419   }
420
421   /**
422    * 
423    * @param seq
424    * @param link
425    * @return Collection< List<String> > { List<String> { link target, link
426    *         label, dynamic component inserted (if any), url }}
427    */
428   Collection<List<String>> createLinksFrom(SequenceI seq, String link)
429   {
430     Map<String, List<String>> urlSets = new LinkedHashMap<>();
431     UrlLink urlLink = new UrlLink(link);
432     if (!urlLink.isValid())
433     {
434       System.err.println(urlLink.getInvalidMessage());
435       return null;
436     }
437
438     urlLink.createLinksFromSeq(seq, urlSets);
439
440     return urlSets.values();
441   }
442
443   public void createSequenceAnnotationReport(final StringBuilder tip,
444           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
445           FeatureRendererModel fr)
446   {
447     createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
448             fr, false);
449   }
450
451   /**
452    * Builds an html formatted report of sequence details and appends it to the
453    * provided buffer.
454    * 
455    * @param sb
456    *          buffer to append report to
457    * @param sequence
458    *          the sequence the report is for
459    * @param showDbRefs
460    *          whether to include database references for the sequence
461    * @param showNpFeats
462    *          whether to include non-positional sequence features
463    * @param fr
464    * @param summary
465    * @return
466    */
467   int createSequenceAnnotationReport(final StringBuilder sb,
468           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
469           FeatureRendererModel fr, boolean summary)
470   {
471     String tmp;
472     sb.append("<i>");
473
474     int maxWidth = 0;
475     if (sequence.getDescription() != null)
476     {
477       tmp = sequence.getDescription();
478       sb.append(tmp);
479       maxWidth = Math.max(maxWidth, tmp.length());
480     }
481     SequenceI ds = sequence;
482     while (ds.getDatasetSequence() != null)
483     {
484       ds = ds.getDatasetSequence();
485     }
486
487     if (showDbRefs)
488     {
489       maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
490     }
491
492     /*
493      * add non-positional features if wanted
494      */
495     if (showNpFeats)
496     {
497       for (SequenceFeature sf : sequence.getFeatures()
498               .getNonPositionalFeatures())
499       {
500         int sz = -sb.length();
501         appendFeature(sb, 0, fr, sf, null, 0);
502         sz += sb.length();
503         maxWidth = Math.max(maxWidth, sz);
504       }
505     }
506     sb.append("</i>");
507     return maxWidth;
508   }
509
510   /**
511    * A helper method that appends any DBRefs, returning the maximum line length
512    * added
513    * 
514    * @param sb
515    * @param ds
516    * @param summary
517    * @return
518    */
519   protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
520           boolean summary)
521   {
522     List<DBRefEntry> dbrefs = ds.getDBRefs();
523     if (dbrefs == null)
524     {
525       return 0;
526     }
527
528     // note this sorts the refs held on the sequence!
529     dbrefs.sort(comparator);
530     boolean ellipsis = false;
531     String source = null;
532     String lastSource = null;
533     int countForSource = 0;
534     int sourceCount = 0;
535     boolean moreSources = false;
536     int maxLineLength = 0;
537     int lineLength = 0;
538
539     for (DBRefEntry ref : dbrefs)
540     {
541       source = ref.getSource();
542       if (source == null)
543       {
544         // shouldn't happen
545         continue;
546       }
547       boolean sourceChanged = !source.equals(lastSource);
548       if (sourceChanged)
549       {
550         lineLength = 0;
551         countForSource = 0;
552         sourceCount++;
553       }
554       if (sourceCount > MAX_SOURCES && summary)
555       {
556         ellipsis = true;
557         moreSources = true;
558         break;
559       }
560       lastSource = source;
561       countForSource++;
562       if (countForSource == 1 || !summary)
563       {
564         sb.append("<br/>");
565       }
566       if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
567       {
568         String accessionId = ref.getAccessionId();
569         lineLength += accessionId.length() + 1;
570         if (countForSource > 1 && summary)
571         {
572           sb.append(", ").append(accessionId);
573           lineLength++;
574         }
575         else
576         {
577           sb.append(source).append(" ").append(accessionId);
578           lineLength += source.length();
579         }
580         maxLineLength = Math.max(maxLineLength, lineLength);
581       }
582       if (countForSource == MAX_REFS_PER_SOURCE && summary)
583       {
584         sb.append(COMMA).append(ELLIPSIS);
585         ellipsis = true;
586       }
587     }
588     if (moreSources)
589     {
590       sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
591     }
592     if (ellipsis)
593     {
594       sb.append("<br/>(");
595       sb.append(MessageManager.getString("label.output_seq_details"));
596       sb.append(")");
597     }
598
599     return maxLineLength;
600   }
601
602   public void createTooltipAnnotationReport(final StringBuilder tip,
603           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
604           FeatureRendererModel fr)
605   {
606     int maxWidth = createSequenceAnnotationReport(tip, sequence,
607             showDbRefs, showNpFeats, fr, true);
608
609     if (maxWidth > 60)
610     {
611       // ? not sure this serves any useful purpose
612       // tip.insert(0, "<table width=350 border=0><tr><td>");
613       // tip.append("</td></tr></table>");
614     }
615   }
616 }