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