JAL-3981 patch tests and remove errant imports
[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.ArrayList;
24 import java.util.Collection;
25 import java.util.Comparator;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Locale;
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
95               : (s2 == null ? 1 : s1.compareToIgnoreCase(s2));
96       if (comp == 0)
97       {
98         String a1 = ref1.getAccessionId();
99         String a2 = ref2.getAccessionId();
100         comp = a1 == null ? -1
101                 : (a2 == null ? 1 : a1.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, int residuePos,
154           List<SequenceFeature> features, FeatureRendererModel fr,
155           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; // feature start in local coordinates
213     int[] endRange = null; // feature end in local coordinates
214     if (mf != null)
215     {
216       if (feature.isContactFeature())
217       {
218         /*
219          * map start and end points individually
220          */
221         beginRange = mf.getMappedPositions(begin, begin);
222         endRange = begin == end ? beginRange
223                 : mf.getMappedPositions(end, end);
224       }
225       else
226       {
227         /*
228          * map the feature extent
229          */
230         beginRange = mf.getMappedPositions(begin, end);
231         endRange = beginRange;
232       }
233       if (beginRange == null || endRange == null)
234       {
235         // something went wrong
236         return false;
237       }
238       begin = beginRange[0];
239       end = endRange[endRange.length - 1];
240     }
241
242     StringBuilder sb = new StringBuilder();
243     if (feature.isContactFeature())
244     {
245       /*
246        * include if rpos is at start or end position of [mapped] feature
247        */
248       boolean showContact = (mf == null) && (rpos == begin || rpos == end);
249       boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
250               && rpos <= beginRange[beginRange.length - 1])
251               || (rpos >= endRange[0]
252                       && rpos <= endRange[endRange.length - 1]));
253       if (showContact || showMappedContact)
254       {
255         if (sb0.length() > 6)
256         {
257           sb.append("<br/>");
258         }
259         sb.append(feature.getType()).append(" ").append(begin).append(":")
260                 .append(end);
261       }
262       return appendText(sb0, sb, maxlength);
263     }
264
265     if (sb0.length() > 6)
266     {
267       sb.append("<br/>");
268     }
269     // TODO: remove this hack to display link only features
270     boolean linkOnly = feature.getValue("linkonly") != null;
271     if (!linkOnly)
272     {
273       sb.append(feature.getType()).append(" ");
274       if (rpos != 0)
275       {
276         // we are marking a positional feature
277         sb.append(begin);
278         if (begin != end)
279         {
280           sb.append(" ").append(end);
281         }
282       }
283
284       String description = feature.getDescription();
285       if (description != null && !description.equals(feature.getType()))
286       {
287         description = StringUtils.stripHtmlTags(description);
288
289         /*
290          * truncate overlong descriptions unless they contain an href
291          * before the truncation point (as truncation could leave corrupted html)
292          */
293         int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
294         boolean hasLink = linkindex > -1
295                 && linkindex < MAX_DESCRIPTION_LENGTH;
296         if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
297         {
298           description = description.substring(0, MAX_DESCRIPTION_LENGTH)
299                   + ELLIPSIS;
300         }
301
302         sb.append("; ").append(description);
303       }
304
305       if (showScore(feature, fr))
306       {
307         sb.append(" Score=").append(String.valueOf(feature.getScore()));
308       }
309       String status = (String) feature.getValue("status");
310       if (status != null && status.length() > 0)
311       {
312         sb.append("; (").append(status).append(")");
313       }
314
315       /*
316        * add attribute value if coloured by attribute
317        */
318       if (fr != null)
319       {
320         FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
321         if (fc != null && fc.isColourByAttribute())
322         {
323           String[] attName = fc.getAttributeName();
324           String attVal = feature.getValueAsString(attName);
325           if (attVal != null)
326           {
327             sb.append("; ").append(String.join(":", attName)).append("=")
328                     .append(attVal);
329           }
330         }
331       }
332
333       if (mf != null)
334       {
335         String variants = mf.findProteinVariants(feature);
336         if (!variants.isEmpty())
337         {
338           sb.append(" ").append(variants);
339         }
340       }
341     }
342     return appendText(sb0, sb, maxlength);
343   }
344
345   /**
346    * Appends sb to sb0, and returns false, unless maxlength is not zero and
347    * appending would make the result longer than or equal to maxlength, in which
348    * case the append is not done and returns true
349    * 
350    * @param sb0
351    * @param sb
352    * @param maxlength
353    * @return
354    */
355   private static boolean appendText(StringBuilder sb0, StringBuilder sb,
356           int maxlength)
357   {
358     if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
359     {
360       sb0.append(sb);
361       return false;
362     }
363     return true;
364   }
365
366   /**
367    * Answers true if score should be shown, else false. Score is shown if it is
368    * not NaN, and the feature type has a non-trivial min-max score range
369    */
370   boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
371   {
372     if (Float.isNaN(feature.getScore()))
373     {
374       return false;
375     }
376     if (fr == null)
377     {
378       return true;
379     }
380     float[][] minMax = fr.getMinMax().get(feature.getType());
381
382     /*
383      * minMax[0] is the [min, max] score range for positional features
384      */
385     if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
386     {
387       return false;
388     }
389     return true;
390   }
391
392   /**
393    * Format and appends any hyperlinks for the sequence feature to the string
394    * buffer
395    * 
396    * @param sb
397    * @param feature
398    */
399   void appendLinks(final StringBuffer sb, SequenceFeature feature)
400   {
401     if (feature.links != null)
402     {
403       if (linkImageURL != null)
404       {
405         sb.append(" <img src=\"" + linkImageURL + "\">");
406       }
407       else
408       {
409         for (String urlstring : feature.links)
410         {
411           try
412           {
413             for (List<String> urllink : createLinksFrom(null, urlstring))
414             {
415               sb.append("<br/> <a href=\"" + urllink.get(3) + "\" target=\""
416                       + urllink.get(0) + "\">"
417                       + (urllink.get(0).toLowerCase(Locale.ROOT).equals(
418                               urllink.get(1).toLowerCase(Locale.ROOT))
419                                       ? urllink.get(0)
420                                       : (urllink.get(0) + ":"
421                                               + urllink.get(1)))
422                       + "</a><br/>");
423             }
424           } catch (Exception x)
425           {
426             System.err.println(
427                     "problem when creating links from " + 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     sb.append("\n");
497     SequenceI ds = sequence;
498     while (ds.getDatasetSequence() != null)
499     {
500       ds = ds.getDatasetSequence();
501     }
502
503     if (showDbRefs)
504     {
505       maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
506     }
507     sb.append("\n");
508
509     /*
510      * add non-positional features if wanted
511      */
512     if (showNpFeats)
513     {
514       for (SequenceFeature sf : sequence.getFeatures()
515               .getNonPositionalFeatures())
516       {
517         int sz = -sb.length();
518         appendFeature(sb, 0, fr, sf, null, 0);
519         sz += sb.length();
520         maxWidth = Math.max(maxWidth, sz);
521       }
522     }
523     sb.append("</i>");
524     return maxWidth;
525   }
526
527   /**
528    * A helper method that appends any DBRefs, returning the maximum line length
529    * added
530    * 
531    * @param sb
532    * @param ds
533    * @param summary
534    * @return
535    */
536   protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
537           boolean summary)
538   {
539     List<DBRefEntry> dbrefs, dbrefset = ds.getDBRefs();
540
541     if (dbrefset == null)
542     {
543       return 0;
544     }
545
546     // PATCH for JAL-3980 defensive copy
547
548     dbrefs = new ArrayList<DBRefEntry>();
549
550     dbrefs.addAll(dbrefset);
551
552     // note this sorts the refs held on the sequence!
553     dbrefs.sort(comparator);
554     boolean ellipsis = false;
555     String source = null;
556     String lastSource = null;
557     int countForSource = 0;
558     int sourceCount = 0;
559     boolean moreSources = false;
560     int maxLineLength = 0;
561     int lineLength = 0;
562
563     for (DBRefEntry ref : dbrefs)
564     {
565       source = ref.getSource();
566       if (source == null)
567       {
568         // shouldn't happen
569         continue;
570       }
571       boolean sourceChanged = !source.equals(lastSource);
572       if (sourceChanged)
573       {
574         lineLength = 0;
575         countForSource = 0;
576         sourceCount++;
577       }
578       if (sourceCount > MAX_SOURCES && summary)
579       {
580         ellipsis = true;
581         moreSources = true;
582         break;
583       }
584       lastSource = source;
585       countForSource++;
586       if (countForSource == 1 || !summary)
587       {
588         sb.append("<br/>\n");
589       }
590       if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
591       {
592         String accessionId = ref.getAccessionId();
593         lineLength += accessionId.length() + 1;
594         if (countForSource > 1 && summary)
595         {
596           sb.append(",\n ").append(accessionId);
597           lineLength++;
598         }
599         else
600         {
601           sb.append(source).append(" ").append(accessionId);
602           lineLength += source.length();
603         }
604         maxLineLength = Math.max(maxLineLength, lineLength);
605       }
606       if (countForSource == MAX_REFS_PER_SOURCE && summary)
607       {
608         sb.append(COMMA).append(ELLIPSIS);
609         ellipsis = true;
610       }
611     }
612     if (moreSources)
613     {
614       sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
615     }
616     if (ellipsis)
617     {
618       sb.append("<br/>\n(");
619       sb.append(MessageManager.getString("label.output_seq_details"));
620       sb.append(")");
621     }
622
623     return maxLineLength;
624   }
625
626   public void createTooltipAnnotationReport(final StringBuilder tip,
627           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
628           FeatureRendererModel fr)
629   {
630     int maxWidth = createSequenceAnnotationReport(tip, sequence, showDbRefs,
631             showNpFeats, fr, true);
632
633     if (maxWidth > 60)
634     {
635       // ? not sure this serves any useful purpose
636       // tip.insert(0, "<table width=350 border=0><tr><td>");
637       // tip.append("</td></tr></table>");
638     }
639   }
640 }