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