2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
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;
43 * generate HTML reports for a sequence
47 public class SequenceAnnotationReport
49 private static final int MAX_DESCRIPTION_LENGTH = 40;
51 private static final String COMMA = ",";
53 private static final String ELLIPSIS = "...";
55 private static final int MAX_REFS_PER_SOURCE = 4;
57 private static final int MAX_SOURCES = 40;
59 private static String linkImageURL;
61 private static final String[][] PRIMARY_SOURCES = new String[][] {
62 DBRefSource.CODINGDBS, DBRefSource.DNACODINGDBS,
63 DBRefSource.PROTEINDBS };
66 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
67 * with 'Primary' sources placed before others, and 'chromosome' first of all
69 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
73 public int compare(DBRefEntry ref1, DBRefEntry ref2)
75 if (ref1 instanceof GeneLociI)
79 if (ref2 instanceof GeneLociI)
83 String s1 = ref1.getSource();
84 String s2 = ref2.getSource();
85 boolean s1Primary = isPrimarySource(s1);
86 boolean s2Primary = isPrimarySource(s2);
87 if (s1Primary && !s2Primary)
91 if (!s1Primary && s2Primary)
95 int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
96 .compareToIgnoreCase(s2));
99 String a1 = ref1.getAccessionId();
100 String a2 = ref2.getAccessionId();
101 comp = a1 == null ? -1 : (a2 == null ? 1 : a1
102 .compareToIgnoreCase(a2));
107 private boolean isPrimarySource(String source)
109 for (String[] primary : PRIMARY_SOURCES)
111 for (String s : primary)
113 if (source.equals(s))
123 private boolean forTooltip;
126 * Constructor given a flag which affects behaviour
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>
133 * @param isForTooltip
135 public SequenceAnnotationReport(boolean isForTooltip)
137 this.forTooltip = isForTooltip;
138 if (linkImageURL == null)
140 linkImageURL = getClass().getResource("/images/link.gif").toString();
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.
154 public int appendFeatures(final StringBuilder sb,
155 int residuePos, List<SequenceFeature> features,
156 FeatureRendererModel fr, int maxlength)
158 for (int i = 0; i < features.size(); i++)
160 SequenceFeature feature = features.get(i);
161 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
163 return features.size() - i;
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
180 public int appendFeatures(StringBuilder sb, int residuePos,
181 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
183 for (int i = 0; i < mf.features.size(); i++)
185 SequenceFeature feature = mf.features.get(i);
186 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
188 return mf.features.size() - i;
195 * Appends the feature at rpos to the given buffer
202 boolean appendFeature(final StringBuilder sb0, int rpos,
203 FeatureRendererModel fr, SequenceFeature feature,
204 MappedFeatures mf, int maxlength)
206 int begin = feature.getBegin();
207 int end = feature.getEnd();
210 * if this is a virtual features, convert begin/end to the
211 * coordinates of the sequence it is mapped to
213 int[] beginRange = null;
214 int[] endRange = null;
217 beginRange = mf.getMappedPositions(begin, begin);
218 endRange = mf.getMappedPositions(end, end);
219 begin = beginRange[0];
220 end = endRange[endRange.length - 1];
223 StringBuilder sb = new StringBuilder();
224 if (feature.isContactFeature())
227 * include if rpos is at start or end position of [mapped] feature
229 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
230 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
231 && rpos <= beginRange[beginRange.length - 1])
232 || (rpos >= endRange[0]
233 && rpos <= endRange[endRange.length - 1]));
234 if (showContact || showMappedContact)
236 if (sb0.length() > 6)
240 sb.append(feature.getType()).append(" ").append(begin).append(":")
243 return appendText(sb0, sb, maxlength);
246 if (sb0.length() > 6)
250 // TODO: remove this hack to display link only features
251 boolean linkOnly = feature.getValue("linkonly") != null;
254 sb.append(feature.getType()).append(" ");
257 // we are marking a positional feature
261 sb.append(" ").append(end);
265 String description = feature.getDescription();
266 if (description != null && !description.equals(feature.getType()))
268 description = StringUtils.stripHtmlTags(description);
271 * truncate overlong descriptions unless they contain an href
272 * before the truncation point (as truncation could leave corrupted html)
274 int linkindex = description.toLowerCase().indexOf("<a ");
275 boolean hasLink = linkindex > -1
276 && linkindex < MAX_DESCRIPTION_LENGTH;
277 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
279 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
283 sb.append("; ").append(description);
286 if (showScore(feature, fr))
288 sb.append(" Score=").append(String.valueOf(feature.getScore()));
290 String status = (String) feature.getValue("status");
291 if (status != null && status.length() > 0)
293 sb.append("; (").append(status).append(")");
297 * add attribute value if coloured by attribute
301 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
302 if (fc != null && fc.isColourByAttribute())
304 String[] attName = fc.getAttributeName();
305 String attVal = feature.getValueAsString(attName);
308 sb.append("; ").append(String.join(":", attName)).append("=")
316 String variants = mf.findProteinVariants(feature);
317 if (!variants.isEmpty())
319 sb.append(" ").append(variants);
323 return appendText(sb0, sb, maxlength);
327 * Appends sb to sb0, and returns false, unless maxlength is not zero and
328 * appending would make the result longer than or equal to maxlength, in which
329 * case the append is not done and returns true
336 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
339 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
348 * Answers true if score should be shown, else false. Score is shown if it is
349 * not NaN, and the feature type has a non-trivial min-max score range
351 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
353 if (Float.isNaN(feature.getScore()))
361 float[][] minMax = fr.getMinMax().get(feature.getType());
364 * minMax[0] is the [min, max] score range for positional features
366 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
374 * Format and appends any hyperlinks for the sequence feature to the string
380 void appendLinks(final StringBuffer sb, SequenceFeature feature)
382 if (feature.links != null)
384 if (linkImageURL != null)
386 sb.append(" <img src=\"" + linkImageURL + "\">");
390 for (String urlstring : feature.links)
394 for (List<String> urllink : createLinksFrom(null, urlstring))
396 sb.append("<br/> <a href=\""
401 + (urllink.get(0).toLowerCase()
402 .equals(urllink.get(1).toLowerCase()) ? urllink
403 .get(0) : (urllink.get(0) + ":" + urllink
407 } catch (Exception x)
409 System.err.println("problem when creating links from "
423 * @return Collection< List<String> > { List<String> { link target, link
424 * label, dynamic component inserted (if any), url }}
426 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
428 Map<String, List<String>> urlSets = new LinkedHashMap<>();
429 UrlLink urlLink = new UrlLink(link);
430 if (!urlLink.isValid())
432 System.err.println(urlLink.getInvalidMessage());
436 urlLink.createLinksFromSeq(seq, urlSets);
438 return urlSets.values();
441 public void createSequenceAnnotationReport(final StringBuilder tip,
442 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
443 FeatureRendererModel fr)
445 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
450 * Builds an html formatted report of sequence details and appends it to the
454 * buffer to append report to
456 * the sequence the report is for
458 * whether to include database references for the sequence
460 * whether to include non-positional sequence features
465 int createSequenceAnnotationReport(final StringBuilder sb,
466 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
467 FeatureRendererModel fr, boolean summary)
473 if (sequence.getDescription() != null)
475 tmp = sequence.getDescription();
477 maxWidth = Math.max(maxWidth, tmp.length());
479 SequenceI ds = sequence;
480 while (ds.getDatasetSequence() != null)
482 ds = ds.getDatasetSequence();
487 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
491 * add non-positional features if wanted
495 for (SequenceFeature sf : sequence.getFeatures()
496 .getNonPositionalFeatures())
498 int sz = -sb.length();
499 appendFeature(sb, 0, fr, sf, null, 0);
501 maxWidth = Math.max(maxWidth, sz);
509 * A helper method that appends any DBRefs, returning the maximum line length
517 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
520 DBRefEntry[] dbrefs = ds.getDBRefs();
526 // note this sorts the refs held on the sequence!
527 Arrays.sort(dbrefs, comparator);
528 boolean ellipsis = false;
529 String source = null;
530 String lastSource = null;
531 int countForSource = 0;
533 boolean moreSources = false;
534 int maxLineLength = 0;
537 for (DBRefEntry ref : dbrefs)
539 source = ref.getSource();
545 boolean sourceChanged = !source.equals(lastSource);
552 if (sourceCount > MAX_SOURCES && summary)
560 if (countForSource == 1 || !summary)
564 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
566 String accessionId = ref.getAccessionId();
567 lineLength += accessionId.length() + 1;
568 if (countForSource > 1 && summary)
570 sb.append(", ").append(accessionId);
575 sb.append(source).append(" ").append(accessionId);
576 lineLength += source.length();
578 maxLineLength = Math.max(maxLineLength, lineLength);
580 if (countForSource == MAX_REFS_PER_SOURCE && summary)
582 sb.append(COMMA).append(ELLIPSIS);
588 sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
593 sb.append(MessageManager.getString("label.output_seq_details"));
597 return maxLineLength;
600 public void createTooltipAnnotationReport(final StringBuilder tip,
601 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
602 FeatureRendererModel fr)
604 int maxWidth = createSequenceAnnotationReport(tip, sequence,
605 showDbRefs, showNpFeats, fr, true);
609 // ? not sure this serves any useful purpose
610 // tip.insert(0, "<table width=350 border=0><tr><td>");
611 // tip.append("</td></tr></table>");