Merge branch 'develop' into Jalview-JS/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 jalview.api.FeatureColourI;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.GeneLociI;
27 import jalview.datamodel.MappedFeatures;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.util.MessageManager;
31 import jalview.util.StringUtils;
32 import jalview.util.UrlLink;
33 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
34
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Comparator;
38 import java.util.LinkedHashMap;
39 import java.util.List;
40 import java.util.Map;
41
42 /**
43  * generate HTML reports for a sequence
44  * 
45  * @author jimp
46  */
47 public class SequenceAnnotationReport
48 {
49   private static final String COMMA = ",";
50
51   private static final String ELLIPSIS = "...";
52
53   private static final int MAX_REFS_PER_SOURCE = 4;
54
55   private static final int MAX_SOURCES = 40;
56
57  // public static final String[][] PRIMARY_SOURCES  moved to DBRefSource.java
58
59   final String linkImageURL;
60
61   /*
62    * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
63    * with 'Primary' sources placed before others, and 'chromosome' first of all
64    */
65   private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
66   {
67
68     @Override
69     public int compare(DBRefEntry ref1, DBRefEntry ref2)
70     {
71       if (ref1 instanceof GeneLociI)
72       {
73         return -1;
74       }
75       if (ref2 instanceof GeneLociI)
76       {
77         return 1;
78       }
79       String s1 = ref1.getSource();
80       String s2 = ref2.getSource();
81       boolean s1Primary = DBRefSource.isPrimarySource(s1);
82       boolean s2Primary = DBRefSource.isPrimarySource(s2);
83       if (s1Primary && !s2Primary)
84       {
85         return -1;
86       }
87       if (!s1Primary && s2Primary)
88       {
89         return 1;
90       }
91       int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
92               .compareToIgnoreCase(s2));
93       if (comp == 0)
94       {
95         String a1 = ref1.getAccessionId();
96         String a2 = ref2.getAccessionId();
97         comp = a1 == null ? -1 : (a2 == null ? 1 : a1
98                 .compareToIgnoreCase(a2));
99       }
100       return comp;
101     }
102
103 //    private boolean isPrimarySource(String source)
104 //    {
105 //      for (String[] primary : DBRefSource.PRIMARY_SOURCES)
106 //      {
107 //        for (String s : primary)
108 //        {
109 //          if (source.equals(s))
110 //          {
111 //            return true;
112 //          }
113 //        }
114 //      }
115 //      return false;
116 //    }
117   };
118
119   public SequenceAnnotationReport(String linkURL)
120   {
121     this.linkImageURL = linkURL;
122   }
123
124   /**
125    * Append text for the list of features to the tooltip
126    * 
127    * @param sb
128    * @param residuePos
129    * @param features
130    * @param minmax
131    */
132   public void appendFeatures(final StringBuilder sb, int residuePos,
133           List<SequenceFeature> features, FeatureRendererModel fr)
134   {
135     for (SequenceFeature feature : features)
136     {
137       appendFeature(sb, residuePos, fr, feature, null);
138     }
139   }
140
141   /**
142    * Appends text for mapped features (e.g. CDS feature for peptide or vice versa)
143    * 
144    * @param sb
145    * @param residuePos
146    * @param mf
147    * @param fr
148    */
149   public void appendFeatures(StringBuilder sb, int residuePos,
150           MappedFeatures mf, FeatureRendererModel fr)
151   {
152     for (SequenceFeature feature : mf.features)
153     {
154       appendFeature(sb, residuePos, fr, feature, mf);
155     }
156   }
157
158   /**
159    * Appends the feature at rpos to the given buffer
160    * 
161    * @param sb
162    * @param rpos
163    * @param minmax
164    * @param feature
165    */
166   void appendFeature(final StringBuilder sb, int rpos,
167           FeatureRendererModel fr, SequenceFeature feature,
168           MappedFeatures mf)
169   {
170     if (feature.isContactFeature())
171     {
172       if (feature.getBegin() == rpos || feature.getEnd() == rpos)
173       {
174         if (sb.length() > 6)
175         {
176           sb.append("<br>");
177         }
178         sb.append(feature.getType()).append(" ").append(feature.getBegin())
179                 .append(":").append(feature.getEnd());
180       }
181       return;
182     }
183
184     if (sb.length() > 6)
185     {
186       sb.append("<br>");
187     }
188     // TODO: remove this hack to display link only features
189     boolean linkOnly = feature.getValue("linkonly") != null;
190     if (!linkOnly)
191     {
192       sb.append(feature.getType()).append(" ");
193       if (rpos != 0)
194       {
195         // we are marking a positional feature
196         sb.append(feature.begin);
197       }
198       if (feature.begin != feature.end)
199       {
200         sb.append(" ").append(feature.end);
201       }
202
203       String description = feature.getDescription();
204       if (description != null && !description.equals(feature.getType()))
205       {
206         description = StringUtils.stripHtmlTags(description);
207         sb.append("; ").append(description);
208       }
209
210       if (showScore(feature, fr))
211       {
212         sb.append(" Score=").append(String.valueOf(feature.getScore()));
213       }
214       String status = (String) feature.getValue("status");
215       if (status != null && status.length() > 0)
216       {
217         sb.append("; (").append(status).append(")");
218       }
219
220       /*
221        * add attribute value if coloured by attribute
222        */
223       if (fr != null)
224       {
225         FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
226         if (fc != null && fc.isColourByAttribute())
227         {
228           String[] attName = fc.getAttributeName();
229           String attVal = feature.getValueAsString(attName);
230           if (attVal != null)
231           {
232             sb.append("; ").append(String.join(":", attName)).append("=")
233                     .append(attVal);
234           }
235         }
236       }
237
238       if (mf != null)
239       {
240         String variants = mf.findProteinVariants(feature);
241         if (!variants.isEmpty())
242         {
243           sb.append(" ").append(variants);
244         }
245       }
246     }
247   }
248
249   /**
250    * Answers true if score should be shown, else false. Score is shown if it is
251    * not NaN, and the feature type has a non-trivial min-max score range
252    */
253   boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
254   {
255     if (Float.isNaN(feature.getScore()))
256     {
257       return false;
258     }
259     if (fr == null)
260     {
261       return true;
262     }
263     float[][] minMax = fr.getMinMax().get(feature.getType());
264
265     /*
266      * minMax[0] is the [min, max] score range for positional features
267      */
268     if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
269     {
270       return false;
271     }
272     return true;
273   }
274
275   /**
276    * Format and appends any hyperlinks for the sequence feature to the string
277    * buffer
278    * 
279    * @param sb
280    * @param feature
281    */
282   void appendLinks(final StringBuffer sb, SequenceFeature feature)
283   {
284     if (feature.links != null)
285     {
286       if (linkImageURL != null)
287       {
288         sb.append(" <img src=\"" + linkImageURL + "\">");
289       }
290       else
291       {
292         for (String urlstring : feature.links)
293         {
294           try
295           {
296             for (List<String> urllink : createLinksFrom(null, urlstring))
297             {
298               sb.append("<br/> <a href=\""
299                       + urllink.get(3)
300                       + "\" target=\""
301                       + urllink.get(0)
302                       + "\">"
303                       + (urllink.get(0).toLowerCase()
304                               .equals(urllink.get(1).toLowerCase()) ? urllink
305                               .get(0) : (urllink.get(0) + ":" + urllink
306                               .get(1))) + "</a></br>");
307             }
308           } catch (Exception x)
309           {
310             System.err.println("problem when creating links from "
311                     + urlstring);
312             x.printStackTrace();
313           }
314         }
315       }
316
317     }
318   }
319
320   /**
321    * 
322    * @param seq
323    * @param link
324    * @return Collection< List<String> > { List<String> { link target, link
325    *         label, dynamic component inserted (if any), url }}
326    */
327   Collection<List<String>> createLinksFrom(SequenceI seq, String link)
328   {
329     Map<String, List<String>> urlSets = new LinkedHashMap<>();
330     UrlLink urlLink = new UrlLink(link);
331     if (!urlLink.isValid())
332     {
333       System.err.println(urlLink.getInvalidMessage());
334       return null;
335     }
336
337     urlLink.createLinksFromSeq(seq, urlSets);
338
339     return urlSets.values();
340   }
341
342   public void createSequenceAnnotationReport(final StringBuilder tip,
343           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
344           FeatureRendererModel fr)
345   {
346     createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
347             fr, false);
348   }
349
350   /**
351    * Builds an html formatted report of sequence details and appends it to the
352    * provided buffer.
353    * 
354    * @param sb
355    *          buffer to append report to
356    * @param sequence
357    *          the sequence the report is for
358    * @param showDbRefs
359    *          whether to include database references for the sequence
360    * @param showNpFeats
361    *          whether to include non-positional sequence features
362    * @param fr
363    * @param summary
364    * @return
365    */
366   int createSequenceAnnotationReport(final StringBuilder sb,
367           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
368           FeatureRendererModel fr, boolean summary)
369   {
370     String tmp;
371     sb.append("<i>");
372
373     int maxWidth = 0;
374     if (sequence.getDescription() != null)
375     {
376       tmp = sequence.getDescription();
377       sb.append("<br>").append(tmp);
378       maxWidth = Math.max(maxWidth, tmp.length());
379     }
380     SequenceI ds = sequence;
381     while (ds.getDatasetSequence() != null)
382     {
383       ds = ds.getDatasetSequence();
384     }
385
386     if (showDbRefs)
387     {
388       maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
389     }
390
391     /*
392      * add non-positional features if wanted
393      */
394     if (showNpFeats)
395     {
396       for (SequenceFeature sf : sequence.getFeatures()
397               .getNonPositionalFeatures())
398       {
399         int sz = -sb.length();
400         appendFeature(sb, 0, fr, sf, null);
401         sz += sb.length();
402         maxWidth = Math.max(maxWidth, sz);
403       }
404     }
405     sb.append("</i>");
406     return maxWidth;
407   }
408
409   /**
410    * A helper method that appends any DBRefs, returning the maximum line length
411    * added
412    * 
413    * @param sb
414    * @param ds
415    * @param summary
416    * @return
417    */
418   protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
419           boolean summary)
420   {
421     List<DBRefEntry> dbrefs = ds.getDBRefs();
422     if (dbrefs == null)
423     {
424       return 0;
425     }
426
427     // note this sorts the refs held on the sequence!
428     dbrefs.sort(comparator);
429     boolean ellipsis = false;
430     String source = null;
431     String lastSource = null;
432     int countForSource = 0;
433     int sourceCount = 0;
434     boolean moreSources = false;
435     int maxLineLength = 0;
436     int lineLength = 0;
437
438     for (DBRefEntry ref : dbrefs)
439     {
440       source = ref.getSource();
441       if (source == null)
442       {
443         // shouldn't happen
444         continue;
445       }
446       boolean sourceChanged = !source.equals(lastSource);
447       if (sourceChanged)
448       {
449         lineLength = 0;
450         countForSource = 0;
451         sourceCount++;
452       }
453       if (sourceCount > MAX_SOURCES && summary)
454       {
455         ellipsis = true;
456         moreSources = true;
457         break;
458       }
459       lastSource = source;
460       countForSource++;
461       if (countForSource == 1 || !summary)
462       {
463         sb.append("<br>");
464       }
465       if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
466       {
467         String accessionId = ref.getAccessionId();
468         lineLength += accessionId.length() + 1;
469         if (countForSource > 1 && summary)
470         {
471           sb.append(", ").append(accessionId);
472           lineLength++;
473         }
474         else
475         {
476           sb.append(source).append(" ").append(accessionId);
477           lineLength += source.length();
478         }
479         maxLineLength = Math.max(maxLineLength, lineLength);
480       }
481       if (countForSource == MAX_REFS_PER_SOURCE && summary)
482       {
483         sb.append(COMMA).append(ELLIPSIS);
484         ellipsis = true;
485       }
486     }
487     if (moreSources)
488     {
489       sb.append("<br>").append(source).append(COMMA).append(ELLIPSIS);
490     }
491     if (ellipsis)
492     {
493       sb.append("<br>(");
494       sb.append(MessageManager.getString("label.output_seq_details"));
495       sb.append(")");
496     }
497
498     return maxLineLength;
499   }
500
501   public void createTooltipAnnotationReport(final StringBuilder tip,
502           SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
503           FeatureRendererModel fr)
504   {
505     int maxWidth = createSequenceAnnotationReport(tip, sequence,
506             showDbRefs, showNpFeats, fr, true);
507
508     if (maxWidth > 60)
509     {
510       // ? not sure this serves any useful purpose
511       // tip.insert(0, "<table width=350 border=0><tr><td>");
512       // tip.append("</td></tr></table>");
513     }
514   }
515 }