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