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))
126 public SequenceAnnotationReport(boolean isForTooltip)
128 if (linkImageURL == null)
130 linkImageURL = getClass().getResource("/images/link.gif").toString();
135 * Append text for the list of features to the tooltip. Returns the number of
136 * features not added if maxlength limit is (or would have been) reached.
144 public int appendFeatures(final StringBuilder sb,
145 int residuePos, List<SequenceFeature> features,
146 FeatureRendererModel fr, int maxlength)
148 for (int i = 0; i < features.size(); i++)
150 SequenceFeature feature = features.get(i);
151 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
153 return features.size() - i;
160 * Appends text for mapped features (e.g. CDS feature for peptide or vice
161 * versa) Returns number of features left if maxlength limit is (or would have
170 public int appendFeatures(StringBuilder sb, int residuePos,
171 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
173 for (int i = 0; i < mf.features.size(); i++)
175 SequenceFeature feature = mf.features.get(i);
176 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
178 return mf.features.size() - i;
185 * Appends the feature at rpos to the given buffer
192 boolean appendFeature(final StringBuilder sb0, int rpos,
193 FeatureRendererModel fr, SequenceFeature feature,
194 MappedFeatures mf, int maxlength)
196 int begin = feature.getBegin();
197 int end = feature.getEnd();
200 * if this is a virtual features, convert begin/end to the
201 * coordinates of the sequence it is mapped to
203 int[] localRange = null;
206 localRange = mf.getMappedPositions(begin, end);
207 if (localRange == null)
209 // something went wrong
212 begin = localRange[0];
213 end = localRange[localRange.length - 1];
216 StringBuilder sb = new StringBuilder();
217 if (feature.isContactFeature())
220 * contact features are rendered slightly differently; note the check for
221 * 'start or end position only' was applied earlier when finding features
223 if (sb0.length() > 6)
227 sb.append(feature.getType()).append(" ").append(begin).append(":")
229 return appendText(sb0, sb, maxlength);
232 if (sb0.length() > 6)
236 // TODO: remove this hack to display link only features
237 boolean linkOnly = feature.getValue("linkonly") != null;
240 sb.append(feature.getType()).append(" ");
243 // we are marking a positional feature
247 sb.append(" ").append(end);
251 String description = feature.getDescription();
252 if (description != null && !description.equals(feature.getType()))
254 description = StringUtils.stripHtmlTags(description);
257 * truncate overlong descriptions unless they contain an href
258 * before the truncation point (as truncation could leave corrupted html)
260 int linkindex = description.toLowerCase().indexOf("<a ");
261 boolean hasLink = linkindex > -1
262 && linkindex < MAX_DESCRIPTION_LENGTH;
263 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
265 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
269 sb.append("; ").append(description);
272 if (showScore(feature, fr))
274 sb.append(" Score=").append(String.valueOf(feature.getScore()));
276 String status = (String) feature.getValue("status");
277 if (status != null && status.length() > 0)
279 sb.append("; (").append(status).append(")");
283 * add attribute value if coloured by attribute
287 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
288 if (fc != null && fc.isColourByAttribute())
290 String[] attName = fc.getAttributeName();
291 String attVal = feature.getValueAsString(attName);
294 sb.append("; ").append(String.join(":", attName)).append("=")
302 String variants = mf.findProteinVariants(feature);
303 if (!variants.isEmpty())
305 sb.append(" ").append(variants);
309 return appendText(sb0, sb, maxlength);
313 * Appends sb to sb0, and returns false, unless maxlength is not zero and
314 * appending would make the result longer than or equal to maxlength, in which
315 * case the append is not done and returns true
322 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
325 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
334 * Answers true if score should be shown, else false. Score is shown if it is
335 * not NaN, and the feature type has a non-trivial min-max score range
337 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
339 if (Float.isNaN(feature.getScore()))
347 float[][] minMax = fr.getMinMax().get(feature.getType());
350 * minMax[0] is the [min, max] score range for positional features
352 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
360 * Format and appends any hyperlinks for the sequence feature to the string
366 void appendLinks(final StringBuffer sb, SequenceFeature feature)
368 if (feature.links != null)
370 if (linkImageURL != null)
372 sb.append(" <img src=\"" + linkImageURL + "\">");
376 for (String urlstring : feature.links)
380 for (List<String> urllink : createLinksFrom(null, urlstring))
382 sb.append("<br/> <a href=\""
387 + (urllink.get(0).toLowerCase()
388 .equals(urllink.get(1).toLowerCase()) ? urllink
389 .get(0) : (urllink.get(0) + ":" + urllink
393 } catch (Exception x)
395 System.err.println("problem when creating links from "
409 * @return Collection< List<String> > { List<String> { link target, link
410 * label, dynamic component inserted (if any), url }}
412 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
414 Map<String, List<String>> urlSets = new LinkedHashMap<>();
415 UrlLink urlLink = new UrlLink(link);
416 if (!urlLink.isValid())
418 System.err.println(urlLink.getInvalidMessage());
422 urlLink.createLinksFromSeq(seq, urlSets);
424 return urlSets.values();
427 public void createSequenceAnnotationReport(final StringBuilder tip,
428 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
429 FeatureRendererModel fr)
431 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
436 * Builds an html formatted report of sequence details and appends it to the
440 * buffer to append report to
442 * the sequence the report is for
444 * whether to include database references for the sequence
446 * whether to include non-positional sequence features
451 int createSequenceAnnotationReport(final StringBuilder sb,
452 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
453 FeatureRendererModel fr, boolean summary)
459 if (sequence.getDescription() != null)
461 tmp = sequence.getDescription();
463 maxWidth = Math.max(maxWidth, tmp.length());
465 SequenceI ds = sequence;
466 while (ds.getDatasetSequence() != null)
468 ds = ds.getDatasetSequence();
473 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
477 * add non-positional features if wanted
481 for (SequenceFeature sf : sequence.getFeatures()
482 .getNonPositionalFeatures())
484 int sz = -sb.length();
485 appendFeature(sb, 0, fr, sf, null, 0);
487 maxWidth = Math.max(maxWidth, sz);
495 * A helper method that appends any DBRefs, returning the maximum line length
503 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
506 DBRefEntry[] dbrefs = ds.getDBRefs();
512 // note this sorts the refs held on the sequence!
513 Arrays.sort(dbrefs, comparator);
514 boolean ellipsis = false;
515 String source = null;
516 String lastSource = null;
517 int countForSource = 0;
519 boolean moreSources = false;
520 int maxLineLength = 0;
523 for (DBRefEntry ref : dbrefs)
525 source = ref.getSource();
531 boolean sourceChanged = !source.equals(lastSource);
538 if (sourceCount > MAX_SOURCES && summary)
546 if (countForSource == 1 || !summary)
550 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
552 String accessionId = ref.getAccessionId();
553 lineLength += accessionId.length() + 1;
554 if (countForSource > 1 && summary)
556 sb.append(", ").append(accessionId);
561 sb.append(source).append(" ").append(accessionId);
562 lineLength += source.length();
564 maxLineLength = Math.max(maxLineLength, lineLength);
566 if (countForSource == MAX_REFS_PER_SOURCE && summary)
568 sb.append(COMMA).append(ELLIPSIS);
574 sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
579 sb.append(MessageManager.getString("label.output_seq_details"));
583 return maxLineLength;
586 public void createTooltipAnnotationReport(final StringBuilder tip,
587 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
588 FeatureRendererModel fr)
590 int maxWidth = createSequenceAnnotationReport(tip, sequence,
591 showDbRefs, showNpFeats, fr, true);
595 // ? not sure this serves any useful purpose
596 // tip.insert(0, "<table width=350 border=0><tr><td>");
597 // tip.append("</td></tr></table>");