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