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.
21 package jalview.viewmodel.seqfeatures;
23 import jalview.api.AlignViewportI;
24 import jalview.api.FeatureColourI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.features.SequenceFeatures;
30 import jalview.renderer.seqfeatures.FeatureRenderer;
31 import jalview.schemes.FeatureColour;
32 import jalview.util.ColorUtils;
34 import java.awt.Color;
35 import java.beans.PropertyChangeListener;
36 import java.beans.PropertyChangeSupport;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Hashtable;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.concurrent.ConcurrentHashMap;
48 public abstract class FeatureRendererModel implements
49 jalview.api.FeatureRenderer
53 * global transparency for feature
55 protected float transparency = 1.0f;
57 protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<String, FeatureColourI>();
59 protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<String, Boolean>();
61 protected String[] renderOrder;
63 Map<String, Float> featureOrder = null;
65 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
68 protected AlignViewportI av;
71 public AlignViewportI getViewport()
76 public FeatureRendererSettings getSettings()
78 return new FeatureRendererSettings(this);
81 public void transferSettings(FeatureRendererSettings fr)
83 this.renderOrder = fr.renderOrder;
84 this.featureGroups = fr.featureGroups;
85 this.featureColours = fr.featureColours;
86 this.transparency = fr.transparency;
87 this.featureOrder = fr.featureOrder;
91 * update from another feature renderer
96 public void transferSettings(jalview.api.FeatureRenderer _fr)
98 FeatureRenderer fr = (FeatureRenderer) _fr;
99 FeatureRendererSettings frs = new FeatureRendererSettings(fr);
100 this.renderOrder = frs.renderOrder;
101 this.featureGroups = frs.featureGroups;
102 this.featureColours = frs.featureColours;
103 this.transparency = frs.transparency;
104 this.featureOrder = frs.featureOrder;
105 if (av != null && av != fr.getViewport())
107 // copy over the displayed feature settings
108 if (_fr.getFeaturesDisplayed() != null)
110 FeaturesDisplayedI fd = getFeaturesDisplayed();
113 setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
120 for (String type : _fr.getFeaturesDisplayed()
121 .getVisibleFeatures())
131 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
133 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
137 public void setVisible(String featureType)
139 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
142 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
144 if (!fdi.isRegistered(featureType))
146 pushFeatureType(Arrays.asList(new String[] { featureType }));
148 fdi.setVisible(featureType);
152 public void setAllVisible(List<String> featureTypes)
154 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
157 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
159 List<String> nft = new ArrayList<String>();
160 for (String featureType : featureTypes)
162 if (!fdi.isRegistered(featureType))
164 nft.add(featureType);
169 pushFeatureType(nft);
171 fdi.setAllVisible(featureTypes);
175 * push a set of new types onto the render order stack. Note - this is a
176 * direct mechanism rather than the one employed in updateRenderOrder
180 private void pushFeatureType(List<String> types)
183 int ts = types.size();
184 String neworder[] = new String[(renderOrder == null ? 0
185 : renderOrder.length) + ts];
186 types.toArray(neworder);
187 if (renderOrder != null)
189 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
190 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
192 renderOrder = neworder;
195 protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
197 public Map<String, float[][]> getMinMax()
203 * normalise a score against the max/min bounds for the feature type.
205 * @param sequenceFeature
206 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
209 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
211 float[] mm = minmax.get(sequenceFeature.type)[0];
212 final byte[] r = new byte[] { 0, (byte) 255 };
215 if (r[0] != 0 || mm[0] < 0.0)
218 r[1] = (byte) ((int) 128.0 + 127.0 * (sequenceFeature.score / mm[1]));
222 r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
228 boolean newFeatureAdded = false;
230 boolean findingFeatures = false;
232 protected boolean updateFeatures()
234 if (av.getFeaturesDisplayed() == null || renderOrder == null
238 if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
243 // TODO: decide if we should check for the visible feature count first
248 * search the alignment for all new features, give them a colour and display
249 * them. Then fires a PropertyChangeEvent on the changeSupport object.
252 protected void findAllFeatures()
254 synchronized (firing)
256 if (firing.equals(Boolean.FALSE))
258 firing = Boolean.TRUE;
259 findAllFeatures(true); // add all new features as visible
260 changeSupport.firePropertyChange("changeSupport", null, null);
261 firing = Boolean.FALSE;
267 public List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
270 * include features at the position provided their feature type is
271 * displayed, and feature group is null or marked for display
273 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
274 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
279 Set<String> visibleFeatures = getFeaturesDisplayed()
280 .getVisibleFeatures();
281 String[] visibleTypes = visibleFeatures
282 .toArray(new String[visibleFeatures.size()]);
283 List<SequenceFeature> features = sequence.findFeatures(column, column,
286 for (SequenceFeature sf : features)
288 if (!featureGroupNotShown(sf))
297 * Searches alignment for all features and updates colours
299 * @param newMadeVisible
300 * if true newly added feature types will be rendered immediately
301 * TODO: check to see if this method should actually be proxied so
302 * repaint events can be propagated by the renderer code
305 public synchronized void findAllFeatures(boolean newMadeVisible)
307 newFeatureAdded = false;
311 newFeatureAdded = true;
315 findingFeatures = true;
316 if (av.getFeaturesDisplayed() == null)
318 av.setFeaturesDisplayed(new FeaturesDisplayed());
320 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
322 Set<String> oldfeatures = new HashSet<String>();
323 if (renderOrder != null)
325 for (int i = 0; i < renderOrder.length; i++)
327 if (renderOrder[i] != null)
329 oldfeatures.add(renderOrder[i]);
334 AlignmentI alignment = av.getAlignment();
335 List<String> allfeatures = new ArrayList<String>();
337 for (int i = 0; i < alignment.getHeight(); i++)
339 SequenceI asq = alignment.getSequenceAt(i);
340 for (String group : asq.getFeatures().getFeatureGroups(true))
342 boolean groupDisplayed = true;
345 if (featureGroups.containsKey(group))
347 groupDisplayed = featureGroups.get(group);
351 groupDisplayed = newMadeVisible;
352 featureGroups.put(group, groupDisplayed);
357 Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
359 for (String type : types)
361 if (!allfeatures.contains(type)) // or use HashSet and no test?
363 allfeatures.add(type);
365 updateMinMax(asq, type, true); // todo: for all features?
371 // uncomment to add new features in alphebetical order (but JAL-2575)
372 // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
375 for (String type : allfeatures)
377 if (!oldfeatures.contains(type))
379 featuresDisplayed.setVisible(type);
385 updateRenderOrder(allfeatures);
386 findingFeatures = false;
390 * Updates the global (alignment) min and max values for a feature type from
391 * the score for a sequence, if the score is not NaN. Values are stored
392 * separately for positional and non-positional features.
398 protected void updateMinMax(SequenceI seq, String featureType,
401 float min = seq.getFeatures().getMinimumScore(featureType, positional);
402 if (Float.isNaN(min))
407 float max = seq.getFeatures().getMaximumScore(featureType, positional);
411 * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
415 minmax = new Hashtable<String, float[][]>();
417 synchronized (minmax)
419 float[][] mm = minmax.get(featureType);
420 int index = positional ? 0 : 1;
423 mm = new float[][] { null, null };
424 minmax.put(featureType, mm);
426 if (mm[index] == null)
428 mm[index] = new float[] { min, max };
432 mm[index][0] = Math.min(mm[index][0], min);
433 mm[index][1] = Math.max(mm[index][1], max);
437 protected Boolean firing = Boolean.FALSE;
440 * replaces the current renderOrder with the unordered features in
441 * allfeatures. The ordering of any types in both renderOrder and allfeatures
442 * is preserved, and all new feature types are rendered on top of the existing
443 * types, in the order given by getOrder or the order given in allFeatures.
444 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
445 * eliminate the float storage for computing/recalling the persistent ordering
446 * New Cability: updates min/max for colourscheme range if its dynamic
450 private void updateRenderOrder(List<String> allFeatures)
452 List<String> allfeatures = new ArrayList<String>(allFeatures);
453 String[] oldRender = renderOrder;
454 renderOrder = new String[allfeatures.size()];
455 boolean initOrders = (featureOrder == null);
457 if (oldRender != null && oldRender.length > 0)
459 for (int j = 0; j < oldRender.length; j++)
461 if (oldRender[j] != null)
465 setOrder(oldRender[j], (1 - (1 + (float) j) / oldRender.length));
467 if (allfeatures.contains(oldRender[j]))
469 renderOrder[opos++] = oldRender[j]; // existing features always
470 // appear below new features
471 allfeatures.remove(oldRender[j]);
474 float[][] mmrange = minmax.get(oldRender[j]);
477 FeatureColourI fc = featureColours.get(oldRender[j]);
478 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
480 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
488 if (allfeatures.size() == 0)
490 // no new features - leave order unchanged.
493 int i = allfeatures.size() - 1;
495 boolean sort = false;
496 String[] newf = new String[allfeatures.size()];
497 float[] sortOrder = new float[allfeatures.size()];
498 for (String newfeat : allfeatures)
503 // update from new features minmax if necessary
504 float[][] mmrange = minmax.get(newf[i]);
507 FeatureColourI fc = featureColours.get(newf[i]);
508 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
510 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
514 if (initOrders || !featureOrder.containsKey(newf[i]))
516 int denom = initOrders ? allfeatures.size() : featureOrder.size();
517 // new unordered feature - compute persistent ordering at head of
518 // existing features.
519 setOrder(newf[i], i / (float) denom);
521 // set order from newly found feature from persisted ordering.
522 sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
525 // only sort if we need to
526 sort = sort || sortOrder[i] > sortOrder[i + 1];
530 if (iSize > 1 && sort)
532 jalview.util.QuickSort.sort(sortOrder, newf);
535 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
539 * get a feature style object for the given type string. Creates a
540 * java.awt.Color for a featureType with no existing colourscheme.
546 public FeatureColourI getFeatureStyle(String featureType)
548 FeatureColourI fc = featureColours.get(featureType);
551 Color col = ColorUtils.createColourFromName(featureType);
552 fc = new FeatureColour(col);
553 featureColours.put(featureType, fc);
559 * Returns the configured colour for a particular feature instance. This
560 * includes calculation of 'colour by label', or of a graduated score colour,
561 * if applicable. It does not take into account feature visibility or colour
567 public Color getColour(SequenceFeature feature)
569 FeatureColourI fc = getFeatureStyle(feature.getType());
570 return fc.getColor(feature);
574 * Answers true unless the feature has a graduated colour scheme and the
575 * feature value lies outside the current threshold for display
577 * @param sequenceFeature
580 protected boolean showFeature(SequenceFeature sequenceFeature)
582 FeatureColourI fc = getFeatureStyle(sequenceFeature.type);
583 return fc.isColored(sequenceFeature);
587 * Answers true if the feature type is currently selected to be displayed,
593 protected boolean showFeatureOfType(String type)
595 return type == null ? false : av.getFeaturesDisplayed().isVisible(type);
599 public void setColour(String featureType, FeatureColourI col)
601 featureColours.put(featureType, col);
605 public void setTransparency(float value)
607 transparency = value;
611 public float getTransparency()
617 * analogous to colour - store a normalized ordering for all feature types in
618 * this rendering context.
621 * Feature type string
623 * normalized priority - 0 means always appears on top, 1 means
626 public float setOrder(String type, float position)
628 if (featureOrder == null)
630 featureOrder = new Hashtable<String, Float>();
632 featureOrder.put(type, new Float(position));
637 * get the global priority (0 (top) to 1 (bottom))
640 * @return [0,1] or -1 for a type without a priority
642 public float getOrder(String type)
644 if (featureOrder != null)
646 if (featureOrder.containsKey(type))
648 return featureOrder.get(type).floatValue();
655 public Map<String, FeatureColourI> getFeatureColours()
657 return featureColours;
661 * Replace current ordering with new ordering
664 * { String(Type), Colour(Type), Boolean(Displayed) }
665 * @return true if any visible features have been reordered, else false
667 public boolean setFeaturePriority(Object[][] data)
669 return setFeaturePriority(data, true);
673 * Sets the priority order for features, with the highest priority (displayed
674 * on top) at the start of the data array
677 * { String(Type), Colour(Type), Boolean(Displayed) }
679 * when true current featureDisplay list will be cleared
680 * @return true if any visible features have been reordered or recoloured,
681 * else false (i.e. no need to repaint)
683 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
686 * note visible feature ordering and colours before update
688 List<String> visibleFeatures = getDisplayedFeatureTypes();
689 Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
690 getFeatureColours());
692 FeaturesDisplayedI av_featuresdisplayed = null;
695 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
697 av.getFeaturesDisplayed().clear();
701 av.setFeaturesDisplayed(av_featuresdisplayed = new FeaturesDisplayed());
706 av_featuresdisplayed = av.getFeaturesDisplayed();
712 // The feature table will display high priority
713 // features at the top, but these are the ones
714 // we need to render last, so invert the data
715 renderOrder = new String[data.length];
719 for (int i = 0; i < data.length; i++)
721 String type = data[i][0].toString();
722 setColour(type, (FeatureColourI) data[i][1]);
723 if (((Boolean) data[i][2]).booleanValue())
725 av_featuresdisplayed.setVisible(type);
728 renderOrder[data.length - i - 1] = type;
733 * get the new visible ordering and return true if it has changed
734 * order or any colour has changed
736 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
737 if (!visibleFeatures.equals(reorderedVisibleFeatures))
740 * the list of ordered visible features has changed
746 * return true if any feature colour has changed
748 for (String feature : visibleFeatures)
750 if (visibleColours.get(feature) != getFeatureStyle(feature))
760 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
762 public void addPropertyChangeListener(PropertyChangeListener listener)
764 changeSupport.addPropertyChangeListener(listener);
769 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
771 public void removePropertyChangeListener(PropertyChangeListener listener)
773 changeSupport.removePropertyChangeListener(listener);
776 public Set<String> getAllFeatureColours()
778 return featureColours.keySet();
781 public void clearRenderOrder()
786 public boolean hasRenderOrder()
788 return renderOrder != null;
792 * Returns feature types in ordering of rendering, where last means on top
794 public List<String> getRenderOrder()
796 if (renderOrder == null)
798 return Arrays.asList(new String[] {});
800 return Arrays.asList(renderOrder);
803 public int getFeatureGroupsSize()
805 return featureGroups != null ? 0 : featureGroups.size();
809 public List<String> getFeatureGroups()
811 // conflict between applet and desktop - featureGroups returns the map in
812 // the desktop featureRenderer
813 return (featureGroups == null) ? Arrays.asList(new String[0]) : Arrays
814 .asList(featureGroups.keySet().toArray(new String[0]));
817 public boolean checkGroupVisibility(String group, boolean newGroupsVisible)
819 if (featureGroups == null)
821 // then an exception happens next..
823 if (featureGroups.containsKey(group))
825 return featureGroups.get(group).booleanValue();
827 if (newGroupsVisible)
829 featureGroups.put(group, new Boolean(true));
836 * get visible or invisible groups
839 * true to return visible groups, false to return hidden ones.
840 * @return list of groups
843 public List<String> getGroups(boolean visible)
845 if (featureGroups != null)
847 List<String> gp = new ArrayList<String>();
849 for (String grp : featureGroups.keySet())
851 Boolean state = featureGroups.get(grp);
852 if (state.booleanValue() == visible)
863 public void setGroupVisibility(String group, boolean visible)
865 featureGroups.put(group, new Boolean(visible));
869 public void setGroupVisibility(List<String> toset, boolean visible)
871 if (toset != null && toset.size() > 0 && featureGroups != null)
873 boolean rdrw = false;
874 for (String gst : toset)
876 Boolean st = featureGroups.get(gst);
877 featureGroups.put(gst, new Boolean(visible));
880 rdrw = rdrw || (visible != st.booleanValue());
885 // set local flag indicating redraw needed ?
891 public Map<String, FeatureColourI> getDisplayedFeatureCols()
893 Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
894 if (getViewport().getFeaturesDisplayed() == null)
898 Set<String> features = getViewport().getFeaturesDisplayed()
899 .getVisibleFeatures();
900 for (String feature : features)
902 fcols.put(feature, getFeatureStyle(feature));
908 public FeaturesDisplayedI getFeaturesDisplayed()
910 return av.getFeaturesDisplayed();
914 * Returns a (possibly empty) list of visible feature types, in render order
918 public List<String> getDisplayedFeatureTypes()
920 List<String> typ = getRenderOrder();
921 List<String> displayed = new ArrayList<String>();
922 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
923 if (feature_disp != null)
925 synchronized (feature_disp)
927 for (String type : typ)
929 if (feature_disp.isVisible(type))
940 public List<String> getDisplayedFeatureGroups()
942 List<String> _gps = new ArrayList<String>();
943 for (String gp : getFeatureGroups())
945 if (checkGroupVisibility(gp, false))
954 * Answers true if the feature belongs to a feature group which is not
955 * currently displayed, else false
957 * @param sequenceFeature
960 protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
962 return featureGroups != null
963 && sequenceFeature.featureGroup != null
964 && sequenceFeature.featureGroup.length() != 0
965 && featureGroups.containsKey(sequenceFeature.featureGroup)
966 && !featureGroups.get(sequenceFeature.featureGroup)
974 public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
977 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
978 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
984 * include features at the position provided their feature type is
985 * displayed, and feature group is null or the empty string
986 * or marked for display
988 Set<String> visibleFeatures = getFeaturesDisplayed()
989 .getVisibleFeatures();
990 String[] visibleTypes = visibleFeatures
991 .toArray(new String[visibleFeatures.size()]);
992 List<SequenceFeature> features = sequence.getFeatures().findFeatures(
993 resNo, resNo, visibleTypes);
995 for (SequenceFeature sf : features)
997 if (!featureGroupNotShown(sf))
1006 * Removes from the list of features any that have a feature group that is not
1007 * displayed, or duplicate the location of a feature of the same type (unless
1008 * a graduated colour scheme is applied)
1013 public void filterFeaturesForDisplay(List<SequenceFeature> features,
1016 if (features.isEmpty())
1020 SequenceFeatures.sortFeatures(features, true);
1021 boolean graduated = fc != null && fc.isGraduatedColour();
1022 SequenceFeature lastFeature = null;
1024 Iterator<SequenceFeature> it = features.iterator();
1025 while (it.hasNext())
1027 SequenceFeature sf = it.next();
1028 if (featureGroupNotShown(sf))
1035 * a feature is redundant for rendering purposes if it has the
1036 * same extent as another (so would just redraw the same colour);
1037 * (checking type and isContactFeature as a fail-safe here, although
1038 * currently they are guaranteed to match in this context)
1042 if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1043 && sf.getEnd() == lastFeature.getEnd()
1044 && sf.isContactFeature() == lastFeature.isContactFeature()
1045 && sf.getType().equals(lastFeature.getType()))