From e894eb87d40be6e8452d19032ddffe80dad5f804 Mon Sep 17 00:00:00 2001 From: jprocter Date: Sun, 10 Sep 2006 12:48:27 +0000 Subject: [PATCH] updated to jalview 2.1 and begun ArchiveClient/VamsasClient/VamsasStore updates. --- src/MCview/AppletPDBCanvas.java | 2006 +++---- src/MCview/AppletPDBViewer.java | 531 +- src/MCview/Atom.java | 116 +- src/MCview/Bond.java | 156 +- src/MCview/MCMatrix.java | 304 +- src/MCview/PDBCanvas.java | 2011 +++---- src/MCview/PDBChain.java | 538 +- src/MCview/PDBViewer.java | 133 +- src/MCview/PDBfile.java | 357 +- src/MCview/Residue.java | 96 +- src/MCview/Zsort.java | 126 +- src/ext/vamsas/MuscleWS.java | 40 +- src/ext/vamsas/MuscleWSService.java | 30 +- src/ext/vamsas/MuscleWSServiceLocator.java | 270 +- src/ext/vamsas/MuscleWSSoapBindingStub.java | 746 +-- src/jalview/analysis/AAFrequency.java | 278 +- src/jalview/analysis/AlignSeq.java | 1648 +++--- src/jalview/analysis/AlignmentSorter.java | 939 ++-- src/jalview/analysis/Conservation.java | 1139 ++-- src/jalview/analysis/NJTree.java | 2438 ++++----- src/jalview/analysis/PCA.java | 482 +- src/jalview/analysis/SeqsetUtils.java | 444 +- src/jalview/analysis/SequenceIdMatcher.java | 374 +- src/jalview/appletgui/APopupMenu.java | 1104 ++-- src/jalview/appletgui/AlignFrame.java | 4582 ++++++++-------- src/jalview/appletgui/AlignViewport.java | 1773 +++--- src/jalview/appletgui/AlignmentPanel.java | 1152 ++-- src/jalview/appletgui/AnnotationColourChooser.java | 806 +-- src/jalview/appletgui/AnnotationLabels.java | 446 +- src/jalview/appletgui/AnnotationPanel.java | 1464 ++--- src/jalview/appletgui/ColumnSelection.java | 124 - src/jalview/appletgui/CutAndPasteTransfer.java | 368 +- src/jalview/appletgui/FeatureRenderer.java | 844 +-- src/jalview/appletgui/FeatureSettings.java | 888 +-- src/jalview/appletgui/Finder.java | 696 +-- src/jalview/appletgui/FontChooser.java | 516 +- src/jalview/appletgui/IdCanvas.java | 621 ++- src/jalview/appletgui/IdPanel.java | 689 ++- src/jalview/appletgui/IdwidthAdjuster.java | 208 +- src/jalview/appletgui/OverviewPanel.java | 813 +-- src/jalview/appletgui/PCAPanel.java | 551 +- src/jalview/appletgui/PaintRefresher.java | 144 +- src/jalview/appletgui/PairwiseAlignPanel.java | 299 +- src/jalview/appletgui/RedundancyPanel.java | 418 +- src/jalview/appletgui/RotatableCanvas.java | 1238 ++--- src/jalview/appletgui/ScalePanel.java | 642 ++- src/jalview/appletgui/SeqCanvas.java | 1430 ++--- src/jalview/appletgui/SeqPanel.java | 2306 +++++--- src/jalview/appletgui/SequenceRenderer.java | 564 +- src/jalview/appletgui/SliderPanel.java | 685 +-- src/jalview/appletgui/TreeCanvas.java | 1133 ++-- src/jalview/appletgui/TreePanel.java | 569 +- src/jalview/appletgui/UserDefinedColours.java | 950 ++-- src/jalview/bin/Cache.java | 595 +-- src/jalview/bin/Jalview.java | 631 +-- src/jalview/bin/JalviewLite.java | 870 +-- src/jalview/datamodel/Alignment.java | 1684 +++--- src/jalview/datamodel/AlignmentAnnotation.java | 589 +- src/jalview/datamodel/AlignmentI.java | 583 +- src/jalview/datamodel/AlignmentOrder.java | 459 +- src/jalview/datamodel/Annotation.java | 128 +- src/jalview/datamodel/BinaryNode.java | 568 +- src/jalview/datamodel/BinarySequence.java | 338 +- src/jalview/datamodel/DBRefEntry.java | 82 +- src/jalview/datamodel/GraphLine.java | 74 +- src/jalview/datamodel/HiddenSequences.java | 299 +- src/jalview/datamodel/HistoryItem.java | 336 +- src/jalview/datamodel/PDBEntry.java | 115 +- src/jalview/datamodel/Provenance.java | 88 +- src/jalview/datamodel/ProvenanceEntry.java | 82 +- src/jalview/datamodel/SearchResults.java | 260 +- src/jalview/datamodel/Sequence.java | 1419 ++--- src/jalview/datamodel/SequenceFeature.java | 408 +- src/jalview/datamodel/SequenceGroup.java | 1106 ++-- src/jalview/datamodel/SequenceI.java | 543 +- src/jalview/datamodel/SequenceNode.java | 298 +- src/jalview/datamodel/SequencePoint.java | 86 +- src/jalview/datamodel/UniprotEntry.java | 185 +- src/jalview/datamodel/UniprotFile.java | 66 +- src/jalview/datamodel/UniprotSequence.java | 84 +- src/jalview/gui/AlignFrame.java | 5639 ++++++++++---------- src/jalview/gui/AlignViewport.java | 2527 +++++---- src/jalview/gui/AlignmentPanel.java | 2573 ++++----- src/jalview/gui/AnnotationColourChooser.java | 924 ++-- src/jalview/gui/AnnotationLabels.java | 1099 ++-- src/jalview/gui/AnnotationPanel.java | 2239 ++++---- src/jalview/gui/ColumnSelection.java | 362 -- src/jalview/gui/CutAndPasteTransfer.java | 472 +- src/jalview/gui/Desktop.java | 1327 ++--- src/jalview/gui/EPSOptions.java | 276 +- src/jalview/gui/FeatureRenderer.java | 947 ++-- src/jalview/gui/FeatureSettings.java | 1369 ++--- src/jalview/gui/Finder.java | 671 +-- src/jalview/gui/FontChooser.java | 486 +- src/jalview/gui/IdCanvas.java | 743 +-- src/jalview/gui/IdPanel.java | 881 ++- src/jalview/gui/IdwidthAdjuster.java | 324 +- src/jalview/gui/Jalview2XML.java | 2452 +++++---- src/jalview/gui/OverviewPanel.java | 931 ++-- src/jalview/gui/PCAPanel.java | 773 +-- src/jalview/gui/PaintRefresher.java | 197 +- src/jalview/gui/PairwiseAlignPanel.java | 292 +- src/jalview/gui/PopupMenu.java | 2297 ++++---- src/jalview/gui/Preferences.java | 929 ++-- src/jalview/gui/RedundancyPanel.java | 499 +- src/jalview/gui/RotatableCanvas.java | 1515 +++--- src/jalview/gui/ScalePanel.java | 837 +-- src/jalview/gui/SeqCanvas.java | 1696 +++--- src/jalview/gui/SeqPanel.java | 2878 +++++----- src/jalview/gui/SequenceFetcher.java | 967 ++-- src/jalview/gui/SequenceRenderer.java | 758 +-- src/jalview/gui/SliderPanel.java | 697 +-- src/jalview/gui/SplashScreen.java | 338 +- src/jalview/gui/TreeCanvas.java | 1621 +++--- src/jalview/gui/TreePanel.java | 1027 ++-- src/jalview/gui/UserDefinedColours.java | 1514 +++--- src/jalview/gui/WebserviceInfo.java | 807 +-- src/jalview/io/AlignFile.java | 376 +- src/jalview/io/AnnotationReader.java | 275 - src/jalview/io/AppletFormatAdapter.java | 436 +- src/jalview/io/BLCFile.java | 461 +- src/jalview/io/ClustalFile.java | 451 +- src/jalview/io/EBIFetchClient.java | 491 +- src/jalview/io/FastaFile.java | 350 +- src/jalview/io/FileLoader.java | 334 +- src/jalview/io/FileParse.java | 136 +- src/jalview/io/FormatAdapter.java | 233 +- src/jalview/io/HTMLOutput.java | 802 +-- src/jalview/io/IdentifyFile.java | 300 +- src/jalview/io/JPredFile.java | 794 +-- src/jalview/io/JalviewFileChooser.java | 456 +- src/jalview/io/JalviewFileFilter.java | 344 +- src/jalview/io/JalviewFileView.java | 222 +- src/jalview/io/MSFfile.java | 813 ++- src/jalview/io/ModellerDescription.java | 767 +-- src/jalview/io/NewickFile.java | 1584 +++--- src/jalview/io/PIRFile.java | 354 +- src/jalview/io/PfamFile.java | 361 +- src/jalview/io/PileUpfile.java | 376 +- src/jalview/io/SequenceFeatureFetcher.java | 359 -- src/jalview/io/VamsasDatastore.java | 2129 +++++--- src/jalview/io/WSWUBlastClient.java | 611 ++- src/jalview/jbgui/GAlignFrame.java | 3009 ++++++----- src/jalview/jbgui/GAlignmentPanel.java | 216 +- src/jalview/jbgui/GCutAndPasteTransfer.java | 420 +- src/jalview/jbgui/GDesktop.java | 652 +-- src/jalview/jbgui/GFinder.java | 365 +- src/jalview/jbgui/GFontChooser.java | 462 +- src/jalview/jbgui/GPCAPanel.java | 449 +- src/jalview/jbgui/GPairwiseAlignPanel.java | 148 +- src/jalview/jbgui/GPreferences.java | 1053 ++-- src/jalview/jbgui/GSequenceLink.java | 296 +- src/jalview/jbgui/GSliderPanel.java | 339 +- src/jalview/jbgui/GTreePanel.java | 435 +- src/jalview/jbgui/GUserDefinedColours.java | 483 +- src/jalview/jbgui/GWebserviceInfo.java | 204 +- src/jalview/math/Matrix.java | 1704 +++--- src/jalview/math/RotatableMatrix.java | 664 +-- src/jalview/schemes/AnnotationColourGradient.java | 348 +- src/jalview/schemes/Blosum62ColourScheme.java | 176 +- src/jalview/schemes/BuriedColourScheme.java | 104 +- src/jalview/schemes/ClustalxColourScheme.java | 610 +-- src/jalview/schemes/ColourSchemeI.java | 88 +- src/jalview/schemes/ColourSchemeProperty.java | 848 +-- src/jalview/schemes/Consensus.java | 160 +- src/jalview/schemes/HelixColourScheme.java | 72 +- src/jalview/schemes/HydrophobicColourScheme.java | 104 +- src/jalview/schemes/NucleotideColourScheme.java | 168 +- src/jalview/schemes/PIDColourScheme.java | 166 +- src/jalview/schemes/ResidueColourScheme.java | 526 +- src/jalview/schemes/ResidueProperties.java | 2421 ++++----- src/jalview/schemes/ScoreColourScheme.java | 242 +- src/jalview/schemes/StrandColourScheme.java | 104 +- src/jalview/schemes/TaylorColourScheme.java | 56 +- src/jalview/schemes/TurnColourScheme.java | 104 +- src/jalview/schemes/UserColourScheme.java | 293 +- src/jalview/schemes/ZappoColourScheme.java | 74 +- src/jalview/util/BrowserLauncher.java | 1856 +++---- src/jalview/util/Comparison.java | 496 +- src/jalview/util/DBRefUtils.java | 76 +- src/jalview/util/ImageMaker.java | 354 +- src/jalview/util/QuickSort.java | 260 +- src/jalview/ws/Discoverer.java | 53 +- src/jalview/ws/JPredClient.java | 1325 +++-- src/jalview/ws/MsaWSClient.java | 646 +-- src/jalview/ws/WSClient.java | 2 +- src/jalview/ws/WSClientI.java | 14 +- src/vamsas/IMsaWS.java | 2 +- src/vamsas/objects/simple/Alignment.java | 246 +- src/vamsas/objects/simple/Alignment_Helper.java | 112 +- src/vamsas/objects/simple/MsaResult.java | 154 +- src/vamsas/objects/simple/MsaResult_Helper.java | 88 +- src/vamsas/objects/simple/Object.java | 108 +- src/vamsas/objects/simple/Object_Helper.java | 74 +- src/vamsas/objects/simple/SequenceSet.java | 168 +- src/vamsas/objects/simple/SequenceSet_Helper.java | 88 +- src/vamsas/objects/simple/WsJobId.java | 180 +- src/vamsas/objects/simple/WsJobId_Helper.java | 100 +- 198 files changed, 72674 insertions(+), 66191 deletions(-) delete mode 100755 src/jalview/appletgui/ColumnSelection.java delete mode 100755 src/jalview/gui/ColumnSelection.java delete mode 100755 src/jalview/io/AnnotationReader.java delete mode 100755 src/jalview/io/SequenceFeatureFetcher.java diff --git a/src/MCview/AppletPDBCanvas.java b/src/MCview/AppletPDBCanvas.java index 107d98d..9689468 100755 --- a/src/MCview/AppletPDBCanvas.java +++ b/src/MCview/AppletPDBCanvas.java @@ -1,1003 +1,1003 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import jalview.analysis.AlignSeq; - -import jalview.datamodel.*; - -// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug -import java.awt.*; -import java.awt.event.*; - -import java.io.*; - -import java.util.*; - - - -public class AppletPDBCanvas extends Panel implements MouseListener, MouseMotionListener -{ - - MCMatrix idmat = new MCMatrix(3, 3); - MCMatrix objmat = new MCMatrix(3, 3); - boolean redrawneeded = true; - int omx = 0; - int mx = 0; - int omy = 0; - int my = 0; - public PDBfile pdb; - int bsize; - Image img; - Graphics ig; - Dimension prefsize; - float[] centre = new float[3]; - float[] width = new float[3]; - float maxwidth; - float scale; - String inStr; - String inType; - boolean bysequence = true; - boolean depthcue = true; - boolean wire = false; - boolean bymolecule = false; - boolean zbuffer = true; - boolean dragging; - int xstart; - int xend; - int ystart; - int yend; - int xmid; - int ymid; - Font font = new Font("Helvetica", Font.PLAIN, 10); - jalview.appletgui.SeqCanvas seqcanvas; - public Sequence sequence; - final StringBuffer mappingDetails = new StringBuffer(); - String appletToolTip = null; - int toolx, tooly; - PDBChain mainchain; - Vector highlightRes; - boolean pdbAction = false; - Bond highlightBond1, highlightBond2; - boolean errorLoading = false; - boolean seqColoursReady = false; - jalview.appletgui.FeatureRenderer fr; - - public AppletPDBCanvas(jalview.appletgui.SeqCanvas seqcanvas, Sequence seq) - { - this.seqcanvas = seqcanvas; - this.sequence = seq; - - seqcanvas.setPDBCanvas(this); - addKeyListener(new KeyAdapter() - { - - public void keyPressed(KeyEvent evt) - { - doKeyPressed(evt); - } - }); - } - - - public void setPDBFile(PDBfile pdb) - { - int max = -10; - int maxchain = -1; - int pdbstart = 0; - int pdbend = 0; - int seqstart = 0; - int seqend = 0; - AlignSeq maxAlignseq = null;; - - for (int i = 0; i < pdb.chains.size(); i++) - { - - mappingDetails.append("\n\nPDB Sequence is :\nSequence = " + ((PDBChain) pdb.chains.elementAt(i)).sequence.getSequence()); - mappingDetails.append("\nNo of residues = " + ((PDBChain) pdb.chains.elementAt(i)).residues.size()+"\n\n"); - - // Now lets compare the sequences to get - // the start and end points. - // Align the sequence to the pdb - AlignSeq as = new AlignSeq(sequence, - ((PDBChain) pdb.chains.elementAt(i)).sequence, "pep"); - as.calcScoreMatrix(); - as.traceAlignment(); - PrintStream ps = new PrintStream(System.out) - { - public void print(String x) { - mappingDetails.append(x); - } - public void println() - { - mappingDetails.append("\n"); - } - }; - - as.printAlignment(ps); - - if (as.maxscore > max) { - max = as.maxscore; - maxchain = i; - - pdbstart = as.seq2start; - pdbend = as.seq2end; - seqstart = as.seq1start + sequence.getStart()-1; - seqend = as.seq1end + sequence.getEnd()-1; - maxAlignseq = as; - } - - mappingDetails.append("\nPDB start/end " + pdbstart + " " + pdbend); - mappingDetails.append("\nSEQ start/end "+ seqstart + " " + seqend); - } - - mainchain = (PDBChain) pdb.chains.elementAt(maxchain); - - mainchain.pdbstart = pdbstart; - mainchain.pdbend = pdbend; - mainchain.seqstart = seqstart; - mainchain.seqend = seqend; - mainchain.isVisible = true; - mainchain.makeExactMapping(maxAlignseq, sequence); - - this.pdb = pdb; - this.prefsize = new Dimension(getSize().width, getSize().height); - - //Initialize the matrices to identity - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - if (i != j) { - idmat.addElement(i, j, 0); - objmat.addElement(i, j, 0); - } else { - idmat.addElement(i, j, 1); - objmat.addElement(i, j, 1); - } - } - } - - addMouseMotionListener(this); - addMouseListener(this); - - - findCentre(); - findWidth(); - - setupBonds(); - - scale = findScale(); - } - - - Vector visiblebonds; - void setupBonds() - { - seqColoursReady = false; - // Sort the bonds by z coord - visiblebonds = new Vector(); - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - if ( ( (PDBChain) pdb.chains.elementAt(ii)).isVisible) - { - Vector tmp = ( (PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < tmp.size(); i++) - { - visiblebonds.addElement(tmp.elementAt(i)); - } - } - } - updateSeqColours(); - seqColoursReady = true; - redrawneeded = true; - repaint(); - } - - - public void findWidth() { - float[] max = new float[3]; - float[] min = new float[3]; - - max[0] = (float) -1e30; - max[1] = (float) -1e30; - max[2] = (float) -1e30; - - min[0] = (float) 1e30; - min[1] = (float) 1e30; - min[2] = (float) 1e30; - - for (int ii = 0; ii < pdb.chains.size(); ii++) { - if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) { - Bond tmp = (Bond) bonds.elementAt(i); - - if (tmp.start[0] >= max[0]) { - max[0] = tmp.start[0]; - } - - if (tmp.start[1] >= max[1]) { - max[1] = tmp.start[1]; - } - - if (tmp.start[2] >= max[2]) { - max[2] = tmp.start[2]; - } - - if (tmp.start[0] <= min[0]) { - min[0] = tmp.start[0]; - } - - if (tmp.start[1] <= min[1]) { - min[1] = tmp.start[1]; - } - - if (tmp.start[2] <= min[2]) { - min[2] = tmp.start[2]; - } - - if (tmp.end[0] >= max[0]) { - max[0] = tmp.end[0]; - } - - if (tmp.end[1] >= max[1]) { - max[1] = tmp.end[1]; - } - - if (tmp.end[2] >= max[2]) { - max[2] = tmp.end[2]; - } - - if (tmp.end[0] <= min[0]) { - min[0] = tmp.end[0]; - } - - if (tmp.end[1] <= min[1]) { - min[1] = tmp.end[1]; - } - - if (tmp.end[2] <= min[2]) { - min[2] = tmp.end[2]; - } - } - } - } - - width[0] = (float) Math.abs(max[0] - min[0]); - width[1] = (float) Math.abs(max[1] - min[1]); - width[2] = (float) Math.abs(max[2] - min[2]); - - maxwidth = width[0]; - - if (width[1] > width[0]) { - maxwidth = width[1]; - } - - if (width[2] > width[1]) { - maxwidth = width[2]; - } - - // System.out.println("Maxwidth = " + maxwidth); - } - - public float findScale() { - int dim; - int width; - int height; - - if (getSize().width != 0) { - width = getSize().width; - height = getSize().height; - } else { - width = prefsize.width; - height = prefsize.height; - } - - if (width < height) { - dim = width; - } else { - dim = height; - } - - return (float) (dim / (1.5d * maxwidth)); - } - - public void findCentre() { - float xtot = 0; - float ytot = 0; - float ztot = 0; - - int bsize = 0; - - //Find centre coordinate - for (int ii = 0; ii < pdb.chains.size(); ii++) { - if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - bsize += bonds.size(); - - for (int i = 0; i < bonds.size(); i++) { - xtot = xtot + ((Bond) bonds.elementAt(i)).start[0] + - ((Bond) bonds.elementAt(i)).end[0]; - - ytot = ytot + ((Bond) bonds.elementAt(i)).start[1] + - ((Bond) bonds.elementAt(i)).end[1]; - - ztot = ztot + ((Bond) bonds.elementAt(i)).start[2] + - ((Bond) bonds.elementAt(i)).end[2]; - } - } - } - - centre[0] = xtot / (2 * (float) bsize); - centre[1] = ytot / (2 * (float) bsize); - centre[2] = ztot / (2 * (float) bsize); - } - - public void paint(Graphics g) - { - - if(errorLoading) - { - g.setColor(Color.white); - g.fillRect(0,0,getSize().width, getSize().height); - g.setColor(Color.black); - g.setFont(new Font("Verdana", Font.BOLD, 14)); - g.drawString("Error loading PDB data!!", 50, getSize().height/2); - return; - } - - if( !seqColoursReady ) - { - g.setColor(Color.black); - g.setFont(new Font("Verdana", Font.BOLD, 14)); - g.drawString("Fetching PDB data...", 50, getSize().height/2); - return; - } - - - - //Only create the image at the beginning - - //this saves much memory usage - if ((img == null) || (prefsize.width != getSize().width) || - (prefsize.height != getSize().height)) { - - try{ prefsize.width = getSize().width; - prefsize.height = getSize().height; - - scale = findScale(); - img = createImage(prefsize.width, prefsize.height); - ig = img.getGraphics(); - - redrawneeded = true; - }catch(Exception ex) - { - ex.printStackTrace(); - } - } - - - if (redrawneeded) - { - drawAll(ig, prefsize.width, prefsize.height); - redrawneeded = false; - } - if(appletToolTip!=null) - { - ig.setColor(Color.red); - ig.drawString(appletToolTip, toolx, tooly); - } - - g.drawImage(img, 0, 0, this); - - pdbAction = false; - } - - public void drawAll(Graphics g, int width, int height) - { - ig.setColor(Color.black); - ig.fillRect(0, 0, width, height); - drawScene(ig); - drawLabels(ig); - } - - void setColours(jalview.schemes.ColourSchemeI cs) - { - bysequence = false; - pdb.setColours(cs); - redrawneeded = true; - repaint(); - } - public void updateSeqColours() - { - if (pdbAction) - { - return; - } - - if(bysequence && pdb!=null) - { - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - colourBySequence((PDBChain) pdb.chains.elementAt(ii)); - } - } - - redrawneeded=true; - repaint(); - } - - - int findTrueIndex(int pos) - { - // returns the alignment position for a residue - int j = sequence.getStart(); - int i = 0; - - while ( (i < sequence.getLength()) && (j <= sequence.getEnd()) && (j <= pos+1)) - { - if (!jalview.util.Comparison.isGap(sequence.getCharAt(i))) - { - j++; - } - - i++; - } - - if(i>1) - i--; - - if ( (j == sequence.getEnd()) && (j < pos)) - { - return sequence.getEnd() + 1; - } - else - { - return i; - } - } - - - // This method has been taken out of PDBChain to allow - // Applet and Application specific sequence renderers to be used - void colourBySequence(PDBChain chain) - { - boolean showFeatures = false; - - if(seqcanvas.getViewport().getShowSequenceFeatures()) - { - if(fr==null) - { - fr = new jalview.appletgui.FeatureRenderer(seqcanvas.getViewport()); - } - fr.transferSettings( seqcanvas.getFeatureRenderer()); - showFeatures = true; - } - - for (int i = 0; i < chain.bonds.size(); i++) - { - Bond tmp = (Bond) chain.bonds.elementAt(i); - tmp.startCol = Color.lightGray; - tmp.endCol = Color.lightGray; - if(chain!=mainchain) - continue; - - if ( (tmp.at1.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && - (tmp.at1.resNumber <= ( (chain.offset + chain.pdbend) - 1))) - { - - int index = findTrueIndex(tmp.at1.alignmentMapping); - //sequence.findIndex(tmp.at1.alignmentMapping); - if (index != -1) - { - tmp.startCol = seqcanvas.getSequenceRenderer(). - getResidueBoxColour( sequence, index); - - if(showFeatures) - tmp.startCol = fr.findFeatureColour(tmp.startCol, sequence, index); - } - } - - int index = findTrueIndex(tmp.at2.alignmentMapping); - //sequence.findIndex( tmp.at2.alignmentMapping ); - if (index != -1) - { - tmp.endCol = seqcanvas.getSequenceRenderer(). - getResidueBoxColour( sequence, index); - - if(showFeatures) - tmp.endCol = fr.findFeatureColour(tmp.endCol, sequence, index); - } - } - } - - - Zsort zsort; - public void drawScene(Graphics g) - { - if (zbuffer) - { - if(zsort ==null) - zsort = new Zsort(); - - zsort.Zsort(visiblebonds); - } - - - Bond tmpBond=null; - for (int i = 0; i < visiblebonds.size(); i++) - { - tmpBond = (Bond) visiblebonds.elementAt(i); - - - xstart = (int) (((tmpBond.start[0] - centre[0]) * scale) + - (getSize().width / 2)); - ystart = (int) (((tmpBond.start[1] - centre[1]) * scale) + - (getSize().height / 2)); - - xend = (int) (((tmpBond.end[0] - centre[0]) * scale) + - (getSize().width / 2)); - yend = (int) (((tmpBond.end[1] - centre[1]) * scale) + - (getSize().height / 2)); - - xmid = (xend + xstart) / 2; - ymid = (yend + ystart) / 2; - - if (depthcue && !bymolecule) - { - if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) { - g.setColor(tmpBond.startCol.darker().darker()); - drawLine(g, xstart, ystart, xmid, ymid); - - g.setColor(tmpBond.endCol.darker().darker()); - drawLine(g, xmid, ymid, xend, yend); - } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { - g.setColor(tmpBond.startCol.darker()); - drawLine(g, xstart, ystart, xmid, ymid); - - g.setColor(tmpBond.endCol.darker()); - drawLine(g, xmid, ymid, xend, yend); - } else { - g.setColor(tmpBond.startCol); - drawLine(g, xstart, ystart, xmid, ymid); - - g.setColor(tmpBond.endCol); - drawLine(g, xmid, ymid, xend, yend); - } - - } else if (depthcue && bymolecule) { - if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) { - g.setColor(Color.green.darker().darker()); - drawLine(g, xstart, ystart, xend, yend); - } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { - g.setColor(Color.green.darker()); - drawLine(g, xstart, ystart, xend, yend); - } else { - g.setColor(Color.green); - drawLine(g, xstart, ystart, xend, yend); - } - } else if (!depthcue && !bymolecule) { - g.setColor(tmpBond.startCol); - drawLine(g, xstart, ystart, xmid, ymid); - g.setColor(tmpBond.endCol); - drawLine(g, xmid, ymid, xend, yend); - } else { - drawLine(g, xstart, ystart, xend, yend); - } - - if(highlightBond1!=null && highlightBond1==tmpBond) - { - g.setColor(Color.white); - drawLine(g, xmid, ymid, xend, yend); - } - - if(highlightBond2!=null && highlightBond2==tmpBond) - { - g.setColor(Color.white); - drawLine(g, xstart, ystart, xmid, ymid); - } - - } - } - - public void drawLine(Graphics g, int x1, int y1, int x2, int y2) { - if (!wire) { - if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5) { - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1); - g.drawLine(x1, y1 - 1, x2, y2 - 1); - } else { - g.setColor(g.getColor().brighter()); - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1 + 1, y1, x2 + 1, y2); - g.drawLine(x1 - 1, y1, x2 - 1, y2); - } - } else { - g.drawLine(x1, y1, x2, y2); - } - } - - public Dimension minimumsize() { - return prefsize; - } - - public Dimension preferredsize() { - return prefsize; - } - - public void doKeyPressed(KeyEvent evt) - { - if (evt.getKeyCode() == KeyEvent.VK_UP) - { - scale = (float) (scale * 1.1); - redrawneeded = true; - repaint(); - } - else if (evt.getKeyCode() == KeyEvent.VK_DOWN) - { - scale = (float) (scale * 0.9); - redrawneeded = true; - repaint(); - } - } - - public void mousePressed(MouseEvent e) { - pdbAction = true; - Atom fatom = findAtom(e.getX(), e.getY()); - if(fatom!=null) - { - fatom.isSelected = !fatom.isSelected; - - redrawneeded = true; - repaint(); - if (foundchain != -1) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(foundchain); - if (chain == mainchain) - { - if (fatom.alignmentMapping != -1) - { - if (highlightRes == null) - highlightRes = new Vector(); - - if (highlightRes.contains(fatom.alignmentMapping+"" + "")) - highlightRes.removeElement(fatom.alignmentMapping + ""); - else - highlightRes.addElement(fatom.alignmentMapping + ""); - } - } - } - - } - mx = e.getX(); - my = e.getY(); - omx = mx; - omy = my; - dragging = false; - } - - public void mouseMoved(MouseEvent e) { - pdbAction = true; - if(highlightBond1!=null) - { - highlightBond1.at2.isSelected = false; - highlightBond2.at1.isSelected = false; - highlightBond1 = null; - highlightBond2 = null; - } - - Atom fatom = findAtom(e.getX(), e.getY()); - - PDBChain chain = null; - if(foundchain!=-1) - { - chain = (PDBChain) pdb.chains.elementAt(foundchain); - if(chain == mainchain) - { - highlightSeqcanvas( fatom.alignmentMapping ); - } - } - - if (fatom != null) { - toolx = e.getX(); - tooly = e.getY(); - - appletToolTip = chain.id+":"+ fatom.resNumber+" "+ fatom.resName; - redrawneeded = true; - repaint(); - } else { - highlightSeqcanvas( -1); - appletToolTip = null; - redrawneeded = true; - repaint(); - } - } - - - void highlightSeqcanvas(int pos) - { - SearchResults searchResults = new SearchResults(); - if(highlightRes!=null) - { - for (int i = 0; i < highlightRes.size(); i++) - { - int a = Integer.parseInt(highlightRes.elementAt( - i).toString())+1; - - searchResults.addResult(sequence, a, a); - } - } - - if(pos!=-1) - { - searchResults.addResult(sequence, pos+1, pos+1); - } - - seqcanvas.highlightSearchResults(searchResults); - } - - - public void mouseClicked(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseDragged(MouseEvent evt) { - int x = evt.getX(); - int y = evt.getY(); - mx = x; - my = y; - - MCMatrix objmat = new MCMatrix(3, 3); - objmat.setIdentity(); - - if ((evt.getModifiers() & Event.META_MASK) != 0) { - objmat.rotatez((float) ((mx - omx))); - } else { - objmat.rotatex((float) ((my - omy))); - objmat.rotatey((float) ((omx - mx))); - } - - //Alter the bonds - for (int ii = 0; ii < pdb.chains.size(); ii++) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) { - Bond tmpBond = (Bond) bonds.elementAt(i); - - //Translate the bond so the centre is 0,0,0 - tmpBond.translate(-centre[0], -centre[1], -centre[2]); - - //Now apply the rotation matrix - tmpBond.start = objmat.vectorMultiply(tmpBond.start); - tmpBond.end = objmat.vectorMultiply(tmpBond.end); - - //Now translate back again - tmpBond.translate(centre[0], centre[1], centre[2]); - } - } - - objmat = null; - - omx = mx; - omy = my; - - dragging = true; - - redrawneeded = true; - - repaint(); - } - - public void mouseReleased(MouseEvent evt) { - dragging = false; - return; - } - - void drawLabels(Graphics g) { - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - - if (chain.isVisible) - { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) - { - Bond tmpBond = (Bond) bonds.elementAt(i); - - if (tmpBond.at1.isSelected) - { - labelAtom(g, tmpBond, 1); - } - - if (tmpBond.at2.isSelected) - { - - labelAtom(g, tmpBond, 2); - } - } - } - } - } - - public void labelAtom(Graphics g, Bond b, int n) { - g.setFont(font); - - if (n == 1) { - int xstart = (int) (((b.start[0] - centre[0]) * scale) + - (getSize().width / 2)); - int ystart = (int) (((b.start[1] - centre[1]) * scale) + - (getSize().height / 2)); - - g.setColor(Color.red); - g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart); - } - - if (n == 2) { - int xstart = (int) (((b.end[0] - centre[0]) * scale) + - (getSize().width / 2)); - int ystart = (int) (((b.end[1] - centre[1]) * scale) + - (getSize().height / 2)); - - g.setColor(Color.red); - g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart); - } - } - - int foundchain = -1; - public Atom findAtom(int x, int y) { - Atom fatom = null; - - foundchain = -1; - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - int truex; - Bond tmpBond=null; - - if (chain.isVisible) - { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) - { - tmpBond = (Bond) bonds.elementAt(i); - - truex = (int) (((tmpBond.start[0] - centre[0]) * scale) + - (getSize().width / 2)); - - if (Math.abs(truex - x) <= 2) - { - int truey = (int) (((tmpBond.start[1] - centre[1]) * scale) + - (getSize().height / 2)); - - if (Math.abs(truey - y) <= 2) - { - fatom = tmpBond.at1; - foundchain = ii; - break; - } - } - } - - // Still here? Maybe its the last bond - - truex = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) + - (getSize().width / 2)); - - if (Math.abs(truex - x) <= 2) - { - int truey = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) + - (getSize().height / 2)); - - if (Math.abs(truey - y) <= 2) - { - fatom = tmpBond.at2; - foundchain = ii; - break; - } - } - - } - - if (fatom != null) //)&& chain.ds != null) - { - chain = (PDBChain) pdb.chains.elementAt(foundchain); - } - } - - return fatom; - } - - public void update(Graphics g) - { - paint(g); - } - - public void highlightRes(int ii) - { - if(!seqColoursReady) - return; - - if (highlightRes != null - && highlightRes.contains((ii-1) + "")) - { - return; - } - - int index = -1; - Bond tmpBond; - for(index=0; index 0) - { - highlightBond1 = (Bond) mainchain.bonds.elementAt(index - 1); - highlightBond1.at2.isSelected = true; - } - - if (index != mainchain.bonds.size()) - { - highlightBond2 = (Bond) mainchain.bonds.elementAt(index); - highlightBond2.at1.isSelected = true; - } - - break; - } - } - - redrawneeded = true; - repaint(); - } - - - public void setAllchainsVisible(boolean b) - { - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - chain.isVisible = b; - } - mainchain.isVisible = true; - findCentre(); - setupBonds(); - } - -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import jalview.analysis.AlignSeq; + +import jalview.datamodel.*; + +// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug +import java.awt.*; +import java.awt.event.*; + +import java.io.*; + +import java.util.*; + + + +public class AppletPDBCanvas extends Panel implements MouseListener, MouseMotionListener +{ + + MCMatrix idmat = new MCMatrix(3, 3); + MCMatrix objmat = new MCMatrix(3, 3); + boolean redrawneeded = true; + int omx = 0; + int mx = 0; + int omy = 0; + int my = 0; + public PDBfile pdb; + int bsize; + Image img; + Graphics ig; + Dimension prefsize; + float[] centre = new float[3]; + float[] width = new float[3]; + float maxwidth; + float scale; + String inStr; + String inType; + boolean bysequence = true; + boolean depthcue = true; + boolean wire = false; + boolean bymolecule = false; + boolean zbuffer = true; + boolean dragging; + int xstart; + int xend; + int ystart; + int yend; + int xmid; + int ymid; + Font font = new Font("Helvetica", Font.PLAIN, 10); + jalview.appletgui.SeqCanvas seqcanvas; + public Sequence sequence; + final StringBuffer mappingDetails = new StringBuffer(); + String appletToolTip = null; + int toolx, tooly; + PDBChain mainchain; + Vector highlightRes; + boolean pdbAction = false; + Bond highlightBond1, highlightBond2; + boolean errorLoading = false; + boolean seqColoursReady = false; + jalview.appletgui.FeatureRenderer fr; + + public AppletPDBCanvas(jalview.appletgui.SeqCanvas seqcanvas, Sequence seq) + { + this.seqcanvas = seqcanvas; + this.sequence = seq; + + seqcanvas.setPDBCanvas(this); + addKeyListener(new KeyAdapter() + { + + public void keyPressed(KeyEvent evt) + { + doKeyPressed(evt); + } + }); + } + + + public void setPDBFile(PDBfile pdb) + { + int max = -10; + int maxchain = -1; + int pdbstart = 0; + int pdbend = 0; + int seqstart = 0; + int seqend = 0; + AlignSeq maxAlignseq = null;; + + for (int i = 0; i < pdb.chains.size(); i++) + { + + mappingDetails.append("\n\nPDB Sequence is :\nSequence = " + ((PDBChain) pdb.chains.elementAt(i)).sequence.getSequence()); + mappingDetails.append("\nNo of residues = " + ((PDBChain) pdb.chains.elementAt(i)).residues.size()+"\n\n"); + + // Now lets compare the sequences to get + // the start and end points. + // Align the sequence to the pdb + AlignSeq as = new AlignSeq(sequence, + ((PDBChain) pdb.chains.elementAt(i)).sequence, "pep"); + as.calcScoreMatrix(); + as.traceAlignment(); + PrintStream ps = new PrintStream(System.out) + { + public void print(String x) { + mappingDetails.append(x); + } + public void println() + { + mappingDetails.append("\n"); + } + }; + + as.printAlignment(ps); + + if (as.maxscore > max) { + max = as.maxscore; + maxchain = i; + + pdbstart = as.seq2start; + pdbend = as.seq2end; + seqstart = as.seq1start + sequence.getStart()-1; + seqend = as.seq1end + sequence.getEnd()-1; + maxAlignseq = as; + } + + mappingDetails.append("\nPDB start/end " + pdbstart + " " + pdbend); + mappingDetails.append("\nSEQ start/end "+ seqstart + " " + seqend); + } + + mainchain = (PDBChain) pdb.chains.elementAt(maxchain); + + mainchain.pdbstart = pdbstart; + mainchain.pdbend = pdbend; + mainchain.seqstart = seqstart; + mainchain.seqend = seqend; + mainchain.isVisible = true; + mainchain.makeExactMapping(maxAlignseq, sequence); + + this.pdb = pdb; + this.prefsize = new Dimension(getSize().width, getSize().height); + + //Initialize the matrices to identity + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (i != j) { + idmat.addElement(i, j, 0); + objmat.addElement(i, j, 0); + } else { + idmat.addElement(i, j, 1); + objmat.addElement(i, j, 1); + } + } + } + + addMouseMotionListener(this); + addMouseListener(this); + + + findCentre(); + findWidth(); + + setupBonds(); + + scale = findScale(); + } + + + Vector visiblebonds; + void setupBonds() + { + seqColoursReady = false; + // Sort the bonds by z coord + visiblebonds = new Vector(); + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + if ( ( (PDBChain) pdb.chains.elementAt(ii)).isVisible) + { + Vector tmp = ( (PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < tmp.size(); i++) + { + visiblebonds.addElement(tmp.elementAt(i)); + } + } + } + updateSeqColours(); + seqColoursReady = true; + redrawneeded = true; + repaint(); + } + + + public void findWidth() { + float[] max = new float[3]; + float[] min = new float[3]; + + max[0] = (float) -1e30; + max[1] = (float) -1e30; + max[2] = (float) -1e30; + + min[0] = (float) 1e30; + min[1] = (float) 1e30; + min[2] = (float) 1e30; + + for (int ii = 0; ii < pdb.chains.size(); ii++) { + if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) { + Bond tmp = (Bond) bonds.elementAt(i); + + if (tmp.start[0] >= max[0]) { + max[0] = tmp.start[0]; + } + + if (tmp.start[1] >= max[1]) { + max[1] = tmp.start[1]; + } + + if (tmp.start[2] >= max[2]) { + max[2] = tmp.start[2]; + } + + if (tmp.start[0] <= min[0]) { + min[0] = tmp.start[0]; + } + + if (tmp.start[1] <= min[1]) { + min[1] = tmp.start[1]; + } + + if (tmp.start[2] <= min[2]) { + min[2] = tmp.start[2]; + } + + if (tmp.end[0] >= max[0]) { + max[0] = tmp.end[0]; + } + + if (tmp.end[1] >= max[1]) { + max[1] = tmp.end[1]; + } + + if (tmp.end[2] >= max[2]) { + max[2] = tmp.end[2]; + } + + if (tmp.end[0] <= min[0]) { + min[0] = tmp.end[0]; + } + + if (tmp.end[1] <= min[1]) { + min[1] = tmp.end[1]; + } + + if (tmp.end[2] <= min[2]) { + min[2] = tmp.end[2]; + } + } + } + } + + width[0] = (float) Math.abs(max[0] - min[0]); + width[1] = (float) Math.abs(max[1] - min[1]); + width[2] = (float) Math.abs(max[2] - min[2]); + + maxwidth = width[0]; + + if (width[1] > width[0]) { + maxwidth = width[1]; + } + + if (width[2] > width[1]) { + maxwidth = width[2]; + } + + // System.out.println("Maxwidth = " + maxwidth); + } + + public float findScale() { + int dim; + int width; + int height; + + if (getSize().width != 0) { + width = getSize().width; + height = getSize().height; + } else { + width = prefsize.width; + height = prefsize.height; + } + + if (width < height) { + dim = width; + } else { + dim = height; + } + + return (float) (dim / (1.5d * maxwidth)); + } + + public void findCentre() { + float xtot = 0; + float ytot = 0; + float ztot = 0; + + int bsize = 0; + + //Find centre coordinate + for (int ii = 0; ii < pdb.chains.size(); ii++) { + if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + bsize += bonds.size(); + + for (int i = 0; i < bonds.size(); i++) { + xtot = xtot + ((Bond) bonds.elementAt(i)).start[0] + + ((Bond) bonds.elementAt(i)).end[0]; + + ytot = ytot + ((Bond) bonds.elementAt(i)).start[1] + + ((Bond) bonds.elementAt(i)).end[1]; + + ztot = ztot + ((Bond) bonds.elementAt(i)).start[2] + + ((Bond) bonds.elementAt(i)).end[2]; + } + } + } + + centre[0] = xtot / (2 * (float) bsize); + centre[1] = ytot / (2 * (float) bsize); + centre[2] = ztot / (2 * (float) bsize); + } + + public void paint(Graphics g) + { + + if(errorLoading) + { + g.setColor(Color.white); + g.fillRect(0,0,getSize().width, getSize().height); + g.setColor(Color.black); + g.setFont(new Font("Verdana", Font.BOLD, 14)); + g.drawString("Error loading PDB data!!", 50, getSize().height/2); + return; + } + + if( !seqColoursReady ) + { + g.setColor(Color.black); + g.setFont(new Font("Verdana", Font.BOLD, 14)); + g.drawString("Fetching PDB data...", 50, getSize().height/2); + return; + } + + + + //Only create the image at the beginning - + //this saves much memory usage + if ((img == null) || (prefsize.width != getSize().width) || + (prefsize.height != getSize().height)) { + + try{ prefsize.width = getSize().width; + prefsize.height = getSize().height; + + scale = findScale(); + img = createImage(prefsize.width, prefsize.height); + ig = img.getGraphics(); + + redrawneeded = true; + }catch(Exception ex) + { + ex.printStackTrace(); + } + } + + + if (redrawneeded) + { + drawAll(ig, prefsize.width, prefsize.height); + redrawneeded = false; + } + if(appletToolTip!=null) + { + ig.setColor(Color.red); + ig.drawString(appletToolTip, toolx, tooly); + } + + g.drawImage(img, 0, 0, this); + + pdbAction = false; + } + + public void drawAll(Graphics g, int width, int height) + { + ig.setColor(Color.black); + ig.fillRect(0, 0, width, height); + drawScene(ig); + drawLabels(ig); + } + + void setColours(jalview.schemes.ColourSchemeI cs) + { + bysequence = false; + pdb.setColours(cs); + redrawneeded = true; + repaint(); + } + public void updateSeqColours() + { + if (pdbAction) + { + return; + } + + if(bysequence && pdb!=null) + { + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + colourBySequence((PDBChain) pdb.chains.elementAt(ii)); + } + } + + redrawneeded=true; + repaint(); + } + + + int findTrueIndex(int pos) + { + // returns the alignment position for a residue + int j = sequence.getStart(); + int i = 0; + + while ( (i < sequence.getLength()) && (j <= sequence.getEnd()) && (j <= pos+1)) + { + if (!jalview.util.Comparison.isGap(sequence.getCharAt(i))) + { + j++; + } + + i++; + } + + if(i>1) + i--; + + if ( (j == sequence.getEnd()) && (j < pos)) + { + return sequence.getEnd() + 1; + } + else + { + return i; + } + } + + + // This method has been taken out of PDBChain to allow + // Applet and Application specific sequence renderers to be used + void colourBySequence(PDBChain chain) + { + boolean showFeatures = false; + + if(seqcanvas.getViewport().getShowSequenceFeatures()) + { + if(fr==null) + { + fr = new jalview.appletgui.FeatureRenderer(seqcanvas.getViewport()); + } + fr.transferSettings( seqcanvas.getFeatureRenderer()); + showFeatures = true; + } + + for (int i = 0; i < chain.bonds.size(); i++) + { + Bond tmp = (Bond) chain.bonds.elementAt(i); + tmp.startCol = Color.lightGray; + tmp.endCol = Color.lightGray; + if(chain!=mainchain) + continue; + + if ( (tmp.at1.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && + (tmp.at1.resNumber <= ( (chain.offset + chain.pdbend) - 1))) + { + + int index = findTrueIndex(tmp.at1.alignmentMapping); + //sequence.findIndex(tmp.at1.alignmentMapping); + if (index != -1) + { + tmp.startCol = seqcanvas.getSequenceRenderer(). + getResidueBoxColour( sequence, index); + + if(showFeatures) + tmp.startCol = fr.findFeatureColour(tmp.startCol, sequence, index); + } + } + + int index = findTrueIndex(tmp.at2.alignmentMapping); + //sequence.findIndex( tmp.at2.alignmentMapping ); + if (index != -1) + { + tmp.endCol = seqcanvas.getSequenceRenderer(). + getResidueBoxColour( sequence, index); + + if(showFeatures) + tmp.endCol = fr.findFeatureColour(tmp.endCol, sequence, index); + } + } + } + + + Zsort zsort; + public void drawScene(Graphics g) + { + if (zbuffer) + { + if(zsort ==null) + zsort = new Zsort(); + + zsort.Zsort(visiblebonds); + } + + + Bond tmpBond=null; + for (int i = 0; i < visiblebonds.size(); i++) + { + tmpBond = (Bond) visiblebonds.elementAt(i); + + + xstart = (int) (((tmpBond.start[0] - centre[0]) * scale) + + (getSize().width / 2)); + ystart = (int) (((tmpBond.start[1] - centre[1]) * scale) + + (getSize().height / 2)); + + xend = (int) (((tmpBond.end[0] - centre[0]) * scale) + + (getSize().width / 2)); + yend = (int) (((tmpBond.end[1] - centre[1]) * scale) + + (getSize().height / 2)); + + xmid = (xend + xstart) / 2; + ymid = (yend + ystart) / 2; + + if (depthcue && !bymolecule) + { + if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) { + g.setColor(tmpBond.startCol.darker().darker()); + drawLine(g, xstart, ystart, xmid, ymid); + + g.setColor(tmpBond.endCol.darker().darker()); + drawLine(g, xmid, ymid, xend, yend); + } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { + g.setColor(tmpBond.startCol.darker()); + drawLine(g, xstart, ystart, xmid, ymid); + + g.setColor(tmpBond.endCol.darker()); + drawLine(g, xmid, ymid, xend, yend); + } else { + g.setColor(tmpBond.startCol); + drawLine(g, xstart, ystart, xmid, ymid); + + g.setColor(tmpBond.endCol); + drawLine(g, xmid, ymid, xend, yend); + } + + } else if (depthcue && bymolecule) { + if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) { + g.setColor(Color.green.darker().darker()); + drawLine(g, xstart, ystart, xend, yend); + } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { + g.setColor(Color.green.darker()); + drawLine(g, xstart, ystart, xend, yend); + } else { + g.setColor(Color.green); + drawLine(g, xstart, ystart, xend, yend); + } + } else if (!depthcue && !bymolecule) { + g.setColor(tmpBond.startCol); + drawLine(g, xstart, ystart, xmid, ymid); + g.setColor(tmpBond.endCol); + drawLine(g, xmid, ymid, xend, yend); + } else { + drawLine(g, xstart, ystart, xend, yend); + } + + if(highlightBond1!=null && highlightBond1==tmpBond) + { + g.setColor(Color.white); + drawLine(g, xmid, ymid, xend, yend); + } + + if(highlightBond2!=null && highlightBond2==tmpBond) + { + g.setColor(Color.white); + drawLine(g, xstart, ystart, xmid, ymid); + } + + } + } + + public void drawLine(Graphics g, int x1, int y1, int x2, int y2) { + if (!wire) { + if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5) { + g.drawLine(x1, y1, x2, y2); + g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1); + g.drawLine(x1, y1 - 1, x2, y2 - 1); + } else { + g.setColor(g.getColor().brighter()); + g.drawLine(x1, y1, x2, y2); + g.drawLine(x1 + 1, y1, x2 + 1, y2); + g.drawLine(x1 - 1, y1, x2 - 1, y2); + } + } else { + g.drawLine(x1, y1, x2, y2); + } + } + + public Dimension minimumsize() { + return prefsize; + } + + public Dimension preferredsize() { + return prefsize; + } + + public void doKeyPressed(KeyEvent evt) + { + if (evt.getKeyCode() == KeyEvent.VK_UP) + { + scale = (float) (scale * 1.1); + redrawneeded = true; + repaint(); + } + else if (evt.getKeyCode() == KeyEvent.VK_DOWN) + { + scale = (float) (scale * 0.9); + redrawneeded = true; + repaint(); + } + } + + public void mousePressed(MouseEvent e) { + pdbAction = true; + Atom fatom = findAtom(e.getX(), e.getY()); + if(fatom!=null) + { + fatom.isSelected = !fatom.isSelected; + + redrawneeded = true; + repaint(); + if (foundchain != -1) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(foundchain); + if (chain == mainchain) + { + if (fatom.alignmentMapping != -1) + { + if (highlightRes == null) + highlightRes = new Vector(); + + if (highlightRes.contains(fatom.alignmentMapping+"" + "")) + highlightRes.removeElement(fatom.alignmentMapping + ""); + else + highlightRes.addElement(fatom.alignmentMapping + ""); + } + } + } + + } + mx = e.getX(); + my = e.getY(); + omx = mx; + omy = my; + dragging = false; + } + + public void mouseMoved(MouseEvent e) { + pdbAction = true; + if(highlightBond1!=null) + { + highlightBond1.at2.isSelected = false; + highlightBond2.at1.isSelected = false; + highlightBond1 = null; + highlightBond2 = null; + } + + Atom fatom = findAtom(e.getX(), e.getY()); + + PDBChain chain = null; + if(foundchain!=-1) + { + chain = (PDBChain) pdb.chains.elementAt(foundchain); + if(chain == mainchain) + { + highlightSeqcanvas( fatom.alignmentMapping ); + } + } + + if (fatom != null) { + toolx = e.getX(); + tooly = e.getY(); + + appletToolTip = chain.id+":"+ fatom.resNumber+" "+ fatom.resName; + redrawneeded = true; + repaint(); + } else { + highlightSeqcanvas( -1); + appletToolTip = null; + redrawneeded = true; + repaint(); + } + } + + + void highlightSeqcanvas(int pos) + { + SearchResults searchResults = new SearchResults(); + if(highlightRes!=null) + { + for (int i = 0; i < highlightRes.size(); i++) + { + int a = Integer.parseInt(highlightRes.elementAt( + i).toString())+1; + + searchResults.addResult(sequence, a, a); + } + } + + if(pos!=-1) + { + searchResults.addResult(sequence, pos+1, pos+1); + } + + seqcanvas.highlightSearchResults(searchResults); + } + + + public void mouseClicked(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mouseDragged(MouseEvent evt) { + int x = evt.getX(); + int y = evt.getY(); + mx = x; + my = y; + + MCMatrix objmat = new MCMatrix(3, 3); + objmat.setIdentity(); + + if ((evt.getModifiers() & Event.META_MASK) != 0) { + objmat.rotatez((float) ((mx - omx))); + } else { + objmat.rotatex((float) ((my - omy))); + objmat.rotatey((float) ((omx - mx))); + } + + //Alter the bonds + for (int ii = 0; ii < pdb.chains.size(); ii++) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) { + Bond tmpBond = (Bond) bonds.elementAt(i); + + //Translate the bond so the centre is 0,0,0 + tmpBond.translate(-centre[0], -centre[1], -centre[2]); + + //Now apply the rotation matrix + tmpBond.start = objmat.vectorMultiply(tmpBond.start); + tmpBond.end = objmat.vectorMultiply(tmpBond.end); + + //Now translate back again + tmpBond.translate(centre[0], centre[1], centre[2]); + } + } + + objmat = null; + + omx = mx; + omy = my; + + dragging = true; + + redrawneeded = true; + + repaint(); + } + + public void mouseReleased(MouseEvent evt) { + dragging = false; + return; + } + + void drawLabels(Graphics g) { + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + + if (chain.isVisible) + { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) + { + Bond tmpBond = (Bond) bonds.elementAt(i); + + if (tmpBond.at1.isSelected) + { + labelAtom(g, tmpBond, 1); + } + + if (tmpBond.at2.isSelected) + { + + labelAtom(g, tmpBond, 2); + } + } + } + } + } + + public void labelAtom(Graphics g, Bond b, int n) { + g.setFont(font); + + if (n == 1) { + int xstart = (int) (((b.start[0] - centre[0]) * scale) + + (getSize().width / 2)); + int ystart = (int) (((b.start[1] - centre[1]) * scale) + + (getSize().height / 2)); + + g.setColor(Color.red); + g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart); + } + + if (n == 2) { + int xstart = (int) (((b.end[0] - centre[0]) * scale) + + (getSize().width / 2)); + int ystart = (int) (((b.end[1] - centre[1]) * scale) + + (getSize().height / 2)); + + g.setColor(Color.red); + g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart); + } + } + + int foundchain = -1; + public Atom findAtom(int x, int y) { + Atom fatom = null; + + foundchain = -1; + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + int truex; + Bond tmpBond=null; + + if (chain.isVisible) + { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) + { + tmpBond = (Bond) bonds.elementAt(i); + + truex = (int) (((tmpBond.start[0] - centre[0]) * scale) + + (getSize().width / 2)); + + if (Math.abs(truex - x) <= 2) + { + int truey = (int) (((tmpBond.start[1] - centre[1]) * scale) + + (getSize().height / 2)); + + if (Math.abs(truey - y) <= 2) + { + fatom = tmpBond.at1; + foundchain = ii; + break; + } + } + } + + // Still here? Maybe its the last bond + + truex = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) + + (getSize().width / 2)); + + if (Math.abs(truex - x) <= 2) + { + int truey = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) + + (getSize().height / 2)); + + if (Math.abs(truey - y) <= 2) + { + fatom = tmpBond.at2; + foundchain = ii; + break; + } + } + + } + + if (fatom != null) //)&& chain.ds != null) + { + chain = (PDBChain) pdb.chains.elementAt(foundchain); + } + } + + return fatom; + } + + public void update(Graphics g) + { + paint(g); + } + + public void highlightRes(int ii) + { + if(!seqColoursReady) + return; + + if (highlightRes != null + && highlightRes.contains((ii-1) + "")) + { + return; + } + + int index = -1; + Bond tmpBond; + for(index=0; index 0) + { + highlightBond1 = (Bond) mainchain.bonds.elementAt(index - 1); + highlightBond1.at2.isSelected = true; + } + + if (index != mainchain.bonds.size()) + { + highlightBond2 = (Bond) mainchain.bonds.elementAt(index); + highlightBond2.at1.isSelected = true; + } + + break; + } + } + + redrawneeded = true; + repaint(); + } + + + public void setAllchainsVisible(boolean b) + { + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + chain.isVisible = b; + } + mainchain.isVisible = true; + findCentre(); + setupBonds(); + } + +} diff --git a/src/MCview/AppletPDBViewer.java b/src/MCview/AppletPDBViewer.java index e80178a..351de12 100755 --- a/src/MCview/AppletPDBViewer.java +++ b/src/MCview/AppletPDBViewer.java @@ -1,265 +1,266 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer - * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ -package MCview; - -import java.awt.*; - -import java.awt.event.*; -import jalview.datamodel.*; -import jalview.appletgui.*; -import jalview.schemes.*; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; - - -public class AppletPDBViewer extends Frame implements ActionListener, ItemListener -{ - AppletPDBCanvas pdbcanvas; - public AppletPDBViewer(String pdbtext,String type, - Sequence seq, - SeqCanvas seqcanvas) - { - - try - { - jbInit(); - } - catch (Exception ex) - { - ex.printStackTrace(); - } - - pdbcanvas = new AppletPDBCanvas(seqcanvas, seq); - - add(pdbcanvas, BorderLayout.CENTER); - - StringBuffer title = new StringBuffer(seq.getName() + ":"); - - jalview.bin.JalviewLite.addFrame(this,title.toString(),400, 400); - - try{ - PDBfile pdbfile = new PDBfile(pdbtext, type); - pdbcanvas.setPDBFile(pdbfile); - } - catch(Exception ex){ - pdbcanvas.errorLoading = true; - pdbcanvas.repaint(); - } - } - - public void actionPerformed(ActionEvent evt) - { - if(evt.getSource()==mapping) - mapping_actionPerformed(); - else if(evt.getSource()==wire) - wire_actionPerformed(); - else if(evt.getSource()==depth) - depth_actionPerformed(); - else if(evt.getSource()==zbuffer) - zbuffer_actionPerformed(); - else if(evt.getSource()==charge) - charge_actionPerformed(); - - else if(evt.getSource()==chain) - chain_actionPerformed(); - else if(evt.getSource()==seqButton) - seqButton_actionPerformed(); - else if(evt.getSource()==zappo) - pdbcanvas.setColours(new ZappoColourScheme()); - else if(evt.getSource()==taylor) - pdbcanvas.setColours(new TaylorColourScheme()); - else if(evt.getSource()==hydro) - pdbcanvas.setColours(new HydrophobicColourScheme()); - else if(evt.getSource()==helix) - pdbcanvas.setColours(new HelixColourScheme()); - else if(evt.getSource()==strand) - pdbcanvas.setColours(new StrandColourScheme()); - else if(evt.getSource()==turn) - pdbcanvas.setColours(new TurnColourScheme()); - else if(evt.getSource()==buried) - pdbcanvas.setColours(new BuriedColourScheme()); - else if(evt.getSource()==user) - { - pdbcanvas.bysequence = false; - new jalview.appletgui.UserDefinedColours(pdbcanvas); - } - } - - public void itemStateChanged(ItemEvent evt) - { - if (evt.getSource() == allchains) - allchains_itemStateChanged(); - else if (evt.getSource() == wire) - wire_actionPerformed(); - else if (evt.getSource() == depth) - depth_actionPerformed(); - else if (evt.getSource() == zbuffer) - zbuffer_actionPerformed(); - } - - - private void jbInit() - throws Exception - { - setMenuBar(jMenuBar1); - fileMenu.setLabel("File"); - coloursMenu.setLabel("Colours"); - mapping.setLabel("View Mapping"); - mapping.addActionListener(this); - wire.setLabel("Wireframe"); - wire.addItemListener(this); - depth.setState(true); - depth.setLabel("Depthcue"); - depth.addItemListener(this); - zbuffer.setState(true); - zbuffer.setLabel("Z Buffering"); - zbuffer.addItemListener(this); - charge.setLabel("Charge & Cysteine"); - charge.addActionListener(this); - hydro.setLabel("Hydrophobicity"); - hydro.addActionListener(this); - chain.setLabel("By Chain"); - chain.addActionListener(this); - seqButton.setLabel("By Sequence"); - seqButton.addActionListener(this); - allchains.setLabel("All Chains Visible"); - allchains.addItemListener(this); - viewMenu.setLabel("View"); - zappo.setLabel("Zappo"); - zappo.addActionListener(this); - taylor.setLabel("Taylor"); - taylor.addActionListener(this); - helix.setLabel("Helix Propensity"); - helix.addActionListener(this); - strand.setLabel("Strand Propensity"); - strand.addActionListener(this); - turn.setLabel("Turn Propensity"); - turn.addActionListener(this); - buried.setLabel("Buried Index"); - buried.addActionListener(this); - user.setLabel("User Defined..."); - user.addActionListener(this); - jMenuBar1.add(fileMenu); - jMenuBar1.add(coloursMenu); - jMenuBar1.add(viewMenu); - fileMenu.add(mapping);; - - coloursMenu.add(seqButton); - coloursMenu.add(chain); - coloursMenu.add(charge); - coloursMenu.add(zappo); - coloursMenu.add(taylor); - coloursMenu.add(hydro); - coloursMenu.add(helix); - coloursMenu.add(strand); - coloursMenu.add(turn); - coloursMenu.add(buried); - coloursMenu.add(user); - viewMenu.add(wire); - viewMenu.add(depth); - viewMenu.add(zbuffer); - viewMenu.add(allchains); - allchains.setState(true); - } - - MenuBar jMenuBar1 = new MenuBar(); - Menu fileMenu = new Menu(); - Menu coloursMenu = new Menu(); - MenuItem mapping = new MenuItem(); - CheckboxGroup bg = new CheckboxGroup(); - CheckboxMenuItem wire = new CheckboxMenuItem(); - CheckboxMenuItem depth = new CheckboxMenuItem(); - CheckboxMenuItem zbuffer = new CheckboxMenuItem(); - - MenuItem charge = new MenuItem(); - MenuItem hydro = new MenuItem(); - MenuItem chain = new MenuItem(); - MenuItem seqButton = new MenuItem(); - - CheckboxMenuItem allchains = new CheckboxMenuItem(); - Menu viewMenu = new Menu(); - MenuItem turn = new MenuItem(); - MenuItem strand = new MenuItem(); - MenuItem helix = new MenuItem(); - MenuItem taylor = new MenuItem(); - MenuItem zappo = new MenuItem(); - MenuItem buried = new MenuItem(); - MenuItem user = new MenuItem(); - - public void charge_actionPerformed() - { - pdbcanvas.bysequence = false; - pdbcanvas.pdb.setChargeColours(); - pdbcanvas.redrawneeded=true; - pdbcanvas.repaint(); - } - - public void chain_actionPerformed() - { - pdbcanvas.bysequence = false; - pdbcanvas.pdb.setChainColours(); - pdbcanvas.redrawneeded=true; - pdbcanvas.repaint(); - } - - public void zbuffer_actionPerformed() - { - pdbcanvas.zbuffer = ! pdbcanvas.zbuffer; - pdbcanvas.redrawneeded=true; - pdbcanvas.repaint(); - } - - public void depth_actionPerformed() - { - pdbcanvas.depthcue = ! pdbcanvas.depthcue; - pdbcanvas.redrawneeded=true; - pdbcanvas.repaint(); - } - - public void wire_actionPerformed() - { - pdbcanvas.wire = ! pdbcanvas.wire; - pdbcanvas.redrawneeded=true; - pdbcanvas.repaint(); - } - - public void seqButton_actionPerformed() - { - pdbcanvas.bysequence = true; - pdbcanvas.updateSeqColours(); - pdbcanvas.repaint(); - } - - - public void mapping_actionPerformed() - { - jalview.appletgui.CutAndPasteTransfer cap - = new jalview.appletgui.CutAndPasteTransfer(false, null); - Frame frame = new Frame(); - frame.add(cap); - jalview.bin.JalviewLite.addFrame(frame, "PDB - Sequence Mapping", 500, 600); - cap.setText(pdbcanvas.mappingDetails.toString()); - } - - public void allchains_itemStateChanged() - { - pdbcanvas.setAllchainsVisible(allchains.getState()); - } - -} +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ +package MCview; + +import java.awt.*; + +import java.awt.event.*; +import jalview.datamodel.*; +import jalview.appletgui.*; +import jalview.schemes.*; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + + +public class AppletPDBViewer extends Frame implements ActionListener, ItemListener +{ + AppletPDBCanvas pdbcanvas; + public AppletPDBViewer(String pdbtext,String type, + Sequence seq, + SeqCanvas seqcanvas) + { + + try + { + jbInit(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + pdbcanvas = new AppletPDBCanvas(seqcanvas, seq); + + add(pdbcanvas, BorderLayout.CENTER); + + StringBuffer title = new StringBuffer(seq.getName() + ":"); + + jalview.bin.JalviewLite.addFrame(this,title.toString(),400, 400); + + try{ + PDBfile pdbfile = new PDBfile(pdbtext, type); + pdbcanvas.setPDBFile(pdbfile); + } + catch(Exception ex){ + ex.printStackTrace(); + pdbcanvas.errorLoading = true; + pdbcanvas.repaint(); + } + } + + public void actionPerformed(ActionEvent evt) + { + if(evt.getSource()==mapping) + mapping_actionPerformed(); + else if(evt.getSource()==wire) + wire_actionPerformed(); + else if(evt.getSource()==depth) + depth_actionPerformed(); + else if(evt.getSource()==zbuffer) + zbuffer_actionPerformed(); + else if(evt.getSource()==charge) + charge_actionPerformed(); + + else if(evt.getSource()==chain) + chain_actionPerformed(); + else if(evt.getSource()==seqButton) + seqButton_actionPerformed(); + else if(evt.getSource()==zappo) + pdbcanvas.setColours(new ZappoColourScheme()); + else if(evt.getSource()==taylor) + pdbcanvas.setColours(new TaylorColourScheme()); + else if(evt.getSource()==hydro) + pdbcanvas.setColours(new HydrophobicColourScheme()); + else if(evt.getSource()==helix) + pdbcanvas.setColours(new HelixColourScheme()); + else if(evt.getSource()==strand) + pdbcanvas.setColours(new StrandColourScheme()); + else if(evt.getSource()==turn) + pdbcanvas.setColours(new TurnColourScheme()); + else if(evt.getSource()==buried) + pdbcanvas.setColours(new BuriedColourScheme()); + else if(evt.getSource()==user) + { + pdbcanvas.bysequence = false; + new jalview.appletgui.UserDefinedColours(pdbcanvas); + } + } + + public void itemStateChanged(ItemEvent evt) + { + if (evt.getSource() == allchains) + allchains_itemStateChanged(); + else if (evt.getSource() == wire) + wire_actionPerformed(); + else if (evt.getSource() == depth) + depth_actionPerformed(); + else if (evt.getSource() == zbuffer) + zbuffer_actionPerformed(); + } + + + private void jbInit() + throws Exception + { + setMenuBar(jMenuBar1); + fileMenu.setLabel("File"); + coloursMenu.setLabel("Colours"); + mapping.setLabel("View Mapping"); + mapping.addActionListener(this); + wire.setLabel("Wireframe"); + wire.addItemListener(this); + depth.setState(true); + depth.setLabel("Depthcue"); + depth.addItemListener(this); + zbuffer.setState(true); + zbuffer.setLabel("Z Buffering"); + zbuffer.addItemListener(this); + charge.setLabel("Charge & Cysteine"); + charge.addActionListener(this); + hydro.setLabel("Hydrophobicity"); + hydro.addActionListener(this); + chain.setLabel("By Chain"); + chain.addActionListener(this); + seqButton.setLabel("By Sequence"); + seqButton.addActionListener(this); + allchains.setLabel("All Chains Visible"); + allchains.addItemListener(this); + viewMenu.setLabel("View"); + zappo.setLabel("Zappo"); + zappo.addActionListener(this); + taylor.setLabel("Taylor"); + taylor.addActionListener(this); + helix.setLabel("Helix Propensity"); + helix.addActionListener(this); + strand.setLabel("Strand Propensity"); + strand.addActionListener(this); + turn.setLabel("Turn Propensity"); + turn.addActionListener(this); + buried.setLabel("Buried Index"); + buried.addActionListener(this); + user.setLabel("User Defined..."); + user.addActionListener(this); + jMenuBar1.add(fileMenu); + jMenuBar1.add(coloursMenu); + jMenuBar1.add(viewMenu); + fileMenu.add(mapping);; + + coloursMenu.add(seqButton); + coloursMenu.add(chain); + coloursMenu.add(charge); + coloursMenu.add(zappo); + coloursMenu.add(taylor); + coloursMenu.add(hydro); + coloursMenu.add(helix); + coloursMenu.add(strand); + coloursMenu.add(turn); + coloursMenu.add(buried); + coloursMenu.add(user); + viewMenu.add(wire); + viewMenu.add(depth); + viewMenu.add(zbuffer); + viewMenu.add(allchains); + allchains.setState(true); + } + + MenuBar jMenuBar1 = new MenuBar(); + Menu fileMenu = new Menu(); + Menu coloursMenu = new Menu(); + MenuItem mapping = new MenuItem(); + CheckboxGroup bg = new CheckboxGroup(); + CheckboxMenuItem wire = new CheckboxMenuItem(); + CheckboxMenuItem depth = new CheckboxMenuItem(); + CheckboxMenuItem zbuffer = new CheckboxMenuItem(); + + MenuItem charge = new MenuItem(); + MenuItem hydro = new MenuItem(); + MenuItem chain = new MenuItem(); + MenuItem seqButton = new MenuItem(); + + CheckboxMenuItem allchains = new CheckboxMenuItem(); + Menu viewMenu = new Menu(); + MenuItem turn = new MenuItem(); + MenuItem strand = new MenuItem(); + MenuItem helix = new MenuItem(); + MenuItem taylor = new MenuItem(); + MenuItem zappo = new MenuItem(); + MenuItem buried = new MenuItem(); + MenuItem user = new MenuItem(); + + public void charge_actionPerformed() + { + pdbcanvas.bysequence = false; + pdbcanvas.pdb.setChargeColours(); + pdbcanvas.redrawneeded=true; + pdbcanvas.repaint(); + } + + public void chain_actionPerformed() + { + pdbcanvas.bysequence = false; + pdbcanvas.pdb.setChainColours(); + pdbcanvas.redrawneeded=true; + pdbcanvas.repaint(); + } + + public void zbuffer_actionPerformed() + { + pdbcanvas.zbuffer = ! pdbcanvas.zbuffer; + pdbcanvas.redrawneeded=true; + pdbcanvas.repaint(); + } + + public void depth_actionPerformed() + { + pdbcanvas.depthcue = ! pdbcanvas.depthcue; + pdbcanvas.redrawneeded=true; + pdbcanvas.repaint(); + } + + public void wire_actionPerformed() + { + pdbcanvas.wire = ! pdbcanvas.wire; + pdbcanvas.redrawneeded=true; + pdbcanvas.repaint(); + } + + public void seqButton_actionPerformed() + { + pdbcanvas.bysequence = true; + pdbcanvas.updateSeqColours(); + pdbcanvas.repaint(); + } + + + public void mapping_actionPerformed() + { + jalview.appletgui.CutAndPasteTransfer cap + = new jalview.appletgui.CutAndPasteTransfer(false, null); + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, "PDB - Sequence Mapping", 500, 600); + cap.setText(pdbcanvas.mappingDetails.toString()); + } + + public void allchains_itemStateChanged() + { + pdbcanvas.setAllchainsVisible(allchains.getState()); + } + +} diff --git a/src/MCview/Atom.java b/src/MCview/Atom.java index 51c4f01..269fbaa 100755 --- a/src/MCview/Atom.java +++ b/src/MCview/Atom.java @@ -1,58 +1,58 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import java.awt.*; - - -public class Atom { - float x; - float y; - float z; - int number; - String name; - String resName; - int resNumber; - int type; - Color color; - String chain; - int alignmentMapping=-1; - - public boolean isSelected = false; - - public Atom(String str) - { - name = str.substring(12,15).trim(); - - resName = str.substring(17,20); - - chain = str.substring(21,22); - - resNumber = Integer.parseInt(str.substring(22,26).trim()); - - this.x = (float) (new Float(str.substring(30,38).trim()).floatValue()); - this.y = (float) (new Float(str.substring(38,46).trim()).floatValue()); - this.z = (float) (new Float(str.substring(47,55).trim()).floatValue()); - - } - - public void setColor(Color col) { - this.color = col; - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import java.awt.*; + + +public class Atom { + float x; + float y; + float z; + int number; + String name; + String resName; + int resNumber; + int type; + Color color = Color.lightGray; + String chain; + int alignmentMapping=-1; + + public boolean isSelected = false; + + public Atom(String str) + { + name = str.substring(12,15).trim(); + + resName = str.substring(17,20); + + chain = str.substring(21,22); + + resNumber = Integer.parseInt(str.substring(22,26).trim()); + + this.x = (float) (new Float(str.substring(30,38).trim()).floatValue()); + this.y = (float) (new Float(str.substring(38,46).trim()).floatValue()); + this.z = (float) (new Float(str.substring(47,55).trim()).floatValue()); + + } + + // public void setColor(Color col) { + // this.color = col; + // } +} diff --git a/src/MCview/Bond.java b/src/MCview/Bond.java index 5f162b0..98edc45 100755 --- a/src/MCview/Bond.java +++ b/src/MCview/Bond.java @@ -1,78 +1,78 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import java.awt.*; - - -public class Bond { - float[] start; - float[] end; - Color startCol; - Color endCol; - public Atom at1; - public Atom at2; - - public Bond(float[] start, float[] end, Atom at1, Atom at2) { - this.start = start; - this.end = end; - this.startCol = at1.color; - this.endCol = at2.color; - this.at1 = at1; - this.at2 = at2; - } - - public Bond(Bond bond) { - this.start = new float[3]; - - this.start[0] = bond.start[0]; - this.start[1] = bond.start[1]; - this.start[2] = bond.start[2]; - - this.end = new float[3]; - - this.end[0] = bond.end[0]; - this.end[1] = bond.end[1]; - this.end[2] = bond.end[2]; - - this.startCol = bond.startCol; - this.endCol = bond.endCol; - } - - public float length() { - float len = ((end[0] - start[0]) * (end[0] - start[0])) + - ((end[1] - start[1]) * (end[1] - start[1])) + - ((end[2] - start[2]) * (end[2] - start[2])); - - len = (float) (Math.sqrt(len)); - - return len; - } - - public void translate(float x, float y, float z) { - start[0] = (start[0] + x); - end[0] = (end[0] + x); - - start[1] = (start[1] + y); - end[1] = (end[1] + y); - - start[2] = (start[2] + z); - end[2] = (end[2] + z); - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import java.awt.*; + + +public class Bond { + float[] start; + float[] end; + Color startCol = Color.lightGray; + Color endCol= Color.lightGray; + public Atom at1; + public Atom at2; + + public Bond(float[] start, float[] end, Atom at1, Atom at2) { + this.start = start; + this.end = end; + this.startCol = at1.color; + this.endCol = at2.color; + this.at1 = at1; + this.at2 = at2; + } + + /* public Bond(Bond bond) { + this.start = new float[3]; + + this.start[0] = bond.start[0]; + this.start[1] = bond.start[1]; + this.start[2] = bond.start[2]; + + this.end = new float[3]; + + this.end[0] = bond.end[0]; + this.end[1] = bond.end[1]; + this.end[2] = bond.end[2]; + + this.startCol = bond.startCol; + this.endCol = bond.endCol; + } + + public float length() { + float len = ((end[0] - start[0]) * (end[0] - start[0])) + + ((end[1] - start[1]) * (end[1] - start[1])) + + ((end[2] - start[2]) * (end[2] - start[2])); + + len = (float) (Math.sqrt(len)); + + return len; + }*/ + + public void translate(float x, float y, float z) { + start[0] = (start[0] + x); + end[0] = (end[0] + x); + + start[1] = (start[1] + y); + end[1] = (end[1] + y); + + start[2] = (start[2] + z); + end[2] = (end[2] + z); + } +} diff --git a/src/MCview/MCMatrix.java b/src/MCview/MCMatrix.java index 66c3798..36aff78 100755 --- a/src/MCview/MCMatrix.java +++ b/src/MCview/MCMatrix.java @@ -1,152 +1,152 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -public class MCMatrix { - float[][] matrix; - float[][] tmp; - float mycos; - float mysin; - float myconst = (float) (Math.PI / 180); - - public MCMatrix(int rows, int cols) { - matrix = new float[rows][cols]; - tmp = new float[rows][cols]; - } - - public void addElement(int i, int j, float value) { - matrix[i][j] = value; - } - - public void rotatex(float degrees) { - mycos = (float) (Math.cos(degrees * myconst)); - mysin = (float) (Math.sin(degrees * myconst)); - - tmp[0][0] = 1; - tmp[0][1] = 0; - tmp[0][2] = 0; - tmp[1][0] = 0; - tmp[1][1] = mycos; - tmp[1][2] = mysin; - tmp[2][0] = 0; - tmp[2][1] = -mysin; - tmp[2][2] = mycos; - preMultiply(tmp); - } - - public void rotatez(float degrees) { - mycos = (float) (Math.cos(degrees * myconst)); - mysin = (float) (Math.sin(degrees * myconst)); - - tmp[0][0] = mycos; - tmp[0][1] = -mysin; - tmp[0][2] = 0; - tmp[1][0] = mysin; - tmp[1][1] = mycos; - tmp[1][2] = 0; - tmp[2][0] = 0; - tmp[2][1] = 0; - tmp[2][2] = 1; - - preMultiply(tmp); - } - - public void rotatey(float degrees) { - mycos = (float) (Math.cos(degrees * myconst)); - mysin = (float) (Math.sin(degrees * myconst)); - - tmp[0][0] = mycos; - tmp[0][1] = 0; - tmp[0][2] = -mysin; - tmp[1][0] = 0; - tmp[1][1] = 1; - tmp[1][2] = 0; - tmp[2][0] = mysin; - tmp[2][1] = 0; - tmp[2][2] = mycos; - - preMultiply(tmp); - } - - public float[] vectorMultiply(float[] vect) { - float[] temp = new float[3]; - - temp[0] = vect[0]; - temp[1] = vect[1]; - temp[2] = vect[2]; - - for (int i = 0; i < 3; i++) { - temp[i] = ((float) matrix[i][0] * vect[0]) + - ((float) matrix[i][1] * vect[1]) + - ((float) matrix[i][2] * vect[2]); - } - - vect[0] = temp[0]; - vect[1] = temp[1]; - vect[2] = temp[2]; - - return vect; - } - - public void preMultiply(float[][] mat) { - float[][] tmp = new float[3][3]; - - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - tmp[i][j] = (mat[i][0] * matrix[0][j]) + - (mat[i][1] * matrix[1][j]) + (mat[i][2] * matrix[2][j]); - } - } - - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - matrix[i][j] = tmp[i][j]; - } - } - } - - public void postMultiply(float[][] mat) { - float[][] tmp = new float[3][3]; - - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - tmp[i][j] = (matrix[i][0] * mat[0][j]) + - (matrix[i][1] * mat[1][j]) + (matrix[i][2] * mat[2][j]); - } - } - - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - matrix[i][j] = tmp[i][j]; - } - } - } - - public void setIdentity() { - matrix[0][0] = 1; - matrix[1][1] = 1; - matrix[2][2] = 1; - matrix[0][1] = 0; - matrix[0][2] = 0; - matrix[1][0] = 0; - matrix[1][2] = 0; - matrix[2][0] = 0; - matrix[2][1] = 0; - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +public class MCMatrix { + float[][] matrix; + float[][] tmp; + float mycos; + float mysin; + float myconst = (float) (Math.PI / 180); + + public MCMatrix(int rows, int cols) { + matrix = new float[rows][cols]; + tmp = new float[rows][cols]; + } + + public void addElement(int i, int j, float value) { + matrix[i][j] = value; + } + + public void rotatex(float degrees) { + mycos = (float) (Math.cos(degrees * myconst)); + mysin = (float) (Math.sin(degrees * myconst)); + + tmp[0][0] = 1; + tmp[0][1] = 0; + tmp[0][2] = 0; + tmp[1][0] = 0; + tmp[1][1] = mycos; + tmp[1][2] = mysin; + tmp[2][0] = 0; + tmp[2][1] = -mysin; + tmp[2][2] = mycos; + preMultiply(tmp); + } + + public void rotatez(float degrees) { + mycos = (float) (Math.cos(degrees * myconst)); + mysin = (float) (Math.sin(degrees * myconst)); + + tmp[0][0] = mycos; + tmp[0][1] = -mysin; + tmp[0][2] = 0; + tmp[1][0] = mysin; + tmp[1][1] = mycos; + tmp[1][2] = 0; + tmp[2][0] = 0; + tmp[2][1] = 0; + tmp[2][2] = 1; + + preMultiply(tmp); + } + + public void rotatey(float degrees) { + mycos = (float) (Math.cos(degrees * myconst)); + mysin = (float) (Math.sin(degrees * myconst)); + + tmp[0][0] = mycos; + tmp[0][1] = 0; + tmp[0][2] = -mysin; + tmp[1][0] = 0; + tmp[1][1] = 1; + tmp[1][2] = 0; + tmp[2][0] = mysin; + tmp[2][1] = 0; + tmp[2][2] = mycos; + + preMultiply(tmp); + } + + public float[] vectorMultiply(float[] vect) { + float[] temp = new float[3]; + + temp[0] = vect[0]; + temp[1] = vect[1]; + temp[2] = vect[2]; + + for (int i = 0; i < 3; i++) { + temp[i] = ((float) matrix[i][0] * vect[0]) + + ((float) matrix[i][1] * vect[1]) + + ((float) matrix[i][2] * vect[2]); + } + + vect[0] = temp[0]; + vect[1] = temp[1]; + vect[2] = temp[2]; + + return vect; + } + + public void preMultiply(float[][] mat) { + float[][] tmp = new float[3][3]; + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + tmp[i][j] = (mat[i][0] * matrix[0][j]) + + (mat[i][1] * matrix[1][j]) + (mat[i][2] * matrix[2][j]); + } + } + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + matrix[i][j] = tmp[i][j]; + } + } + } + + public void postMultiply(float[][] mat) { + float[][] tmp = new float[3][3]; + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + tmp[i][j] = (matrix[i][0] * mat[0][j]) + + (matrix[i][1] * mat[1][j]) + (matrix[i][2] * mat[2][j]); + } + } + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + matrix[i][j] = tmp[i][j]; + } + } + } + + public void setIdentity() { + matrix[0][0] = 1; + matrix[1][1] = 1; + matrix[2][2] = 1; + matrix[0][1] = 0; + matrix[0][2] = 0; + matrix[1][0] = 0; + matrix[1][2] = 0; + matrix[2][0] = 0; + matrix[2][1] = 0; + } +} diff --git a/src/MCview/PDBCanvas.java b/src/MCview/PDBCanvas.java index d702264..ca4e5be 100755 --- a/src/MCview/PDBCanvas.java +++ b/src/MCview/PDBCanvas.java @@ -1,996 +1,1015 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import jalview.analysis.AlignSeq; - -import jalview.datamodel.*; - -// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug -import java.awt.*; -import java.awt.event.*; - -import java.io.*; - -import java.util.*; - -import javax.swing.*; - - -public class PDBCanvas extends JPanel implements MouseListener, MouseMotionListener -{ - MCMatrix idmat = new MCMatrix(3, 3); - MCMatrix objmat = new MCMatrix(3, 3); - boolean redrawneeded = true; - int omx = 0; - int mx = 0; - int omy = 0; - int my = 0; - public PDBfile pdb; - int bsize; - Image img; - Graphics ig; - Dimension prefsize; - float[] centre = new float[3]; - float[] width = new float[3]; - float maxwidth; - float scale; - String inStr; - String inType; - boolean bysequence = true; - boolean depthcue = true; - boolean wire = false; - boolean bymolecule = false; - boolean zbuffer = true; - boolean dragging; - int xstart; - int xend; - int ystart; - int yend; - int xmid; - int ymid; - Font font = new Font("Helvetica", Font.PLAIN, 10); - jalview.gui.SeqCanvas seqcanvas; - public Sequence sequence; - final StringBuffer mappingDetails = new StringBuffer(); - PDBChain mainchain; - Vector highlightRes; - boolean pdbAction = false; - boolean seqColoursReady = false; - jalview.gui.FeatureRenderer fr; - - public PDBCanvas(jalview.gui.SeqCanvas seqcanvas, Sequence seq) - { - this.seqcanvas = seqcanvas; - this.sequence = seq; - seqcanvas.setPDBCanvas(this); - } - - public void setPDBFile(PDBfile pdb) - { - int max = -10; - int maxchain = -1; - int pdbstart = 0; - int pdbend = 0; - int seqstart = 0; - int seqend = 0; - AlignSeq maxAlignseq = null; - - for (int i = 0; i < pdb.chains.size(); i++) - { - - mappingDetails.append("\n\nPDB Sequence is :\nSequence = " + ((PDBChain) pdb.chains.elementAt(i)).sequence.getSequence()); - mappingDetails.append("\nNo of residues = " + ((PDBChain) pdb.chains.elementAt(i)).residues.size()+"\n\n"); - - // Now lets compare the sequences to get - // the start and end points. - // Align the sequence to the pdb - AlignSeq as = new AlignSeq(sequence, - ((PDBChain) pdb.chains.elementAt(i)).sequence, "pep"); - as.calcScoreMatrix(); - as.traceAlignment(); - PrintStream ps = new PrintStream(System.out) - { - public void print(String x) { - mappingDetails.append(x); - } - public void println() - { - mappingDetails.append("\n"); - } - }; - - as.printAlignment(ps); - - - - if (as.maxscore > max) - { - max = as.maxscore; - maxchain = i; - pdbstart = as.seq2start; - pdbend = as.seq2end; - seqstart = as.seq1start + sequence.getStart()-1; - seqend = as.seq1end + sequence.getEnd()-1; - maxAlignseq = as; - } - - mappingDetails.append("\nPDB start/end " + pdbstart + " " + pdbend); - mappingDetails.append("\nSEQ start/end "+ seqstart + " " + seqend); - } - - mainchain = (PDBChain) pdb.chains.elementAt(maxchain); - - mainchain.pdbstart = pdbstart; - mainchain.pdbend = pdbend; - mainchain.seqstart = seqstart; - mainchain.seqend = seqend; - mainchain.isVisible = true; - mainchain.makeExactMapping(maxAlignseq, sequence); - - this.pdb = pdb; - this.prefsize = new Dimension(getWidth(), getHeight()); - - //Initialize the matrices to identity - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - if (i != j) { - idmat.addElement(i, j, 0); - objmat.addElement(i, j, 0); - } else { - idmat.addElement(i, j, 1); - objmat.addElement(i, j, 1); - } - } - } - - addMouseMotionListener(this); - addMouseListener(this); - - addMouseWheelListener(new MouseWheelListener() - { - public void mouseWheelMoved(MouseWheelEvent e) - { - if (e.getWheelRotation() > 0) - { - scale = (float) (scale * 1.1); - redrawneeded = true; - repaint(); - } - - else - { - scale = (float) (scale * 0.9); - redrawneeded = true; - repaint(); - } - } - }); - - - findCentre(); - findWidth(); - - setupBonds(); - - scale = findScale(); - - ToolTipManager.sharedInstance().registerComponent(this); - ToolTipManager.sharedInstance().setInitialDelay(0); - ToolTipManager.sharedInstance().setDismissDelay(10000); - } - - - Vector visiblebonds; - void setupBonds() - { - seqColoursReady = false; - // Sort the bonds by z coord - visiblebonds = new Vector(); - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - if ( ( (PDBChain) pdb.chains.elementAt(ii)).isVisible) - { - Vector tmp = ( (PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < tmp.size(); i++) - { - visiblebonds.addElement(tmp.elementAt(i)); - } - } - } - - updateSeqColours(); - seqColoursReady = true; - redrawneeded = true; - repaint(); - } - - - public void findWidth() { - float[] max = new float[3]; - float[] min = new float[3]; - - max[0] = (float) -1e30; - max[1] = (float) -1e30; - max[2] = (float) -1e30; - - min[0] = (float) 1e30; - min[1] = (float) 1e30; - min[2] = (float) 1e30; - - for (int ii = 0; ii < pdb.chains.size(); ii++) { - if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) { - Bond tmp = (Bond) bonds.elementAt(i); - - if (tmp.start[0] >= max[0]) { - max[0] = tmp.start[0]; - } - - if (tmp.start[1] >= max[1]) { - max[1] = tmp.start[1]; - } - - if (tmp.start[2] >= max[2]) { - max[2] = tmp.start[2]; - } - - if (tmp.start[0] <= min[0]) { - min[0] = tmp.start[0]; - } - - if (tmp.start[1] <= min[1]) { - min[1] = tmp.start[1]; - } - - if (tmp.start[2] <= min[2]) { - min[2] = tmp.start[2]; - } - - if (tmp.end[0] >= max[0]) { - max[0] = tmp.end[0]; - } - - if (tmp.end[1] >= max[1]) { - max[1] = tmp.end[1]; - } - - if (tmp.end[2] >= max[2]) { - max[2] = tmp.end[2]; - } - - if (tmp.end[0] <= min[0]) { - min[0] = tmp.end[0]; - } - - if (tmp.end[1] <= min[1]) { - min[1] = tmp.end[1]; - } - - if (tmp.end[2] <= min[2]) { - min[2] = tmp.end[2]; - } - } - } - } - /* - System.out.println("xmax " + max[0] + " min " + min[0]); - System.out.println("ymax " + max[1] + " min " + min[1]); - System.out.println("zmax " + max[2] + " min " + min[2]);*/ - - width[0] = (float) Math.abs(max[0] - min[0]); - width[1] = (float) Math.abs(max[1] - min[1]); - width[2] = (float) Math.abs(max[2] - min[2]); - - maxwidth = width[0]; - - if (width[1] > width[0]) { - maxwidth = width[1]; - } - - if (width[2] > width[1]) { - maxwidth = width[2]; - } - - // System.out.println("Maxwidth = " + maxwidth); - } - - public float findScale() { - int dim; - int width; - int height; - - if (getWidth() != 0) { - width = getWidth(); - height = getHeight(); - } else { - width = prefsize.width; - height = prefsize.height; - } - - if (width < height) { - dim = width; - } else { - dim = height; - } - - return (float) (dim / (1.5d * maxwidth)); - } - - public void findCentre() { - float xtot = 0; - float ytot = 0; - float ztot = 0; - - int bsize = 0; - - //Find centre coordinate - for (int ii = 0; ii < pdb.chains.size(); ii++) { - if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - bsize += bonds.size(); - - for (int i = 0; i < bonds.size(); i++) { - xtot = xtot + ((Bond) bonds.elementAt(i)).start[0] + - ((Bond) bonds.elementAt(i)).end[0]; - - ytot = ytot + ((Bond) bonds.elementAt(i)).start[1] + - ((Bond) bonds.elementAt(i)).end[1]; - - ztot = ztot + ((Bond) bonds.elementAt(i)).start[2] + - ((Bond) bonds.elementAt(i)).end[2]; - } - } - } - - centre[0] = xtot / (2 * (float) bsize); - centre[1] = ytot / (2 * (float) bsize); - centre[2] = ztot / (2 * (float) bsize); - } - - public void paintComponent(Graphics g) - { - super.paintComponent(g); - - if(!seqColoursReady) - { - g.setColor(Color.black); - g.setFont(new Font("Verdana", Font.BOLD, 14)); - g.drawString("Retrieving PDB data....", 20, getHeight()/2); - return; - } - - - //Only create the image at the beginning - - //this saves much memory usage - if ((img == null) - || (prefsize.width != getWidth()) - || (prefsize.height != getHeight())) - - { - prefsize.width = getWidth(); - prefsize.height = getHeight(); - - scale = findScale(); - img = createImage(prefsize.width, prefsize.height); - ig = img.getGraphics(); - Graphics2D ig2 = (Graphics2D) ig; - - ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - redrawneeded = true; - } - - - if (redrawneeded) - { - drawAll(ig, prefsize.width, prefsize.height); - redrawneeded = false; - } - - g.drawImage(img, 0, 0, this); - - pdbAction = false; - } - - public void drawAll(Graphics g, int width, int height) - { - g.setColor(Color.black); - g.fillRect(0, 0, width, height); - drawScene(g); - drawLabels(g); - } - - - public void updateSeqColours() - { - if(pdbAction) - { - return; - } - - // System.out.println("update seq colours"); - if(bysequence && pdb!=null) - { - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - colourBySequence( (PDBChain) pdb.chains.elementAt(ii)); - } - } - - redrawneeded=true; - repaint(); - } - - int findTrueIndex(int pos) - { - // returns the alignment position for a residue - int j = sequence.getStart(); - int i = 0; - - while ( (i < sequence.getLength()) && (j <= sequence.getEnd()) && (j <= pos+1)) - { - if (!jalview.util.Comparison.isGap(sequence.getCharAt(i))) - { - j++; - } - - i++; - } - - if(i>1) - i--; - - if ( (j == sequence.getEnd()) && (j < pos)) - { - return sequence.getEnd() + 1; - } - else - { - return i; - } - } - - // This method has been taken out of PDBChain to allow - // Applet and Application specific sequence renderers to be used - void colourBySequence(PDBChain chain) - { - // System.out.println("colour by seq"); - boolean showFeatures = false; - if(seqcanvas.getViewport().getShowSequenceFeatures()) - { - showFeatures = true; - if (fr == null) - fr = new jalview.gui.FeatureRenderer(seqcanvas.getViewport()); - - fr.transferSettings( seqcanvas.getFeatureRenderer() ); - } - - for (int i = 0; i < chain.bonds.size(); i++) - { - Bond tmp = (Bond) chain.bonds.elementAt(i); - tmp.startCol = Color.lightGray; - tmp.endCol = Color.lightGray; - - if(chain!=mainchain) - continue; - - if ( (tmp.at1.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && - (tmp.at1.resNumber <= ( (chain.offset + chain.pdbend) - 1))) - { - int index = findTrueIndex(tmp.at1.alignmentMapping); - //sequence.findIndex(tmp.at1.alignmentMapping); - if (index != -1) - { - tmp.startCol = seqcanvas.getSequenceRenderer(). - getResidueBoxColour( sequence, index); - if(tmp.startCol==null) - tmp.startCol = Color.white; - - if(showFeatures) - tmp.startCol = fr.findFeatureColour(tmp.startCol, sequence, index); - } - } - - if ( (tmp.at2.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && - (tmp.at2.resNumber <= ( (chain.pdbend + chain.offset) - 1))) - { - - int index = findTrueIndex(tmp.at2.alignmentMapping); - //sequence.findIndex( tmp.at2.alignmentMapping ); - if (index != -1) - { - tmp.endCol = seqcanvas.getSequenceRenderer(). - getResidueBoxColour( sequence, index); - if(tmp.endCol==null) - tmp.endCol = Color.white; - if(showFeatures) - tmp.endCol = fr.findFeatureColour(tmp.endCol, sequence, index); - } - } - } - } - - - Zsort zsort; - public void drawScene(Graphics g) - { - if (zbuffer) - { - if(zsort==null) - zsort = new Zsort(); - - zsort.Zsort(visiblebonds); - } - - Bond tmpBond=null; - for (int i = 0; i < visiblebonds.size(); i++) - { - tmpBond = (Bond) visiblebonds.elementAt(i); - - xstart = (int) (((tmpBond.start[0] - centre[0]) * scale) + - (getWidth() / 2)); - ystart = (int) (((tmpBond.start[1] - centre[1]) * scale) + - (getHeight() / 2)); - - xend = (int) (((tmpBond.end[0] - centre[0]) * scale) + - (getWidth() / 2)); - yend = (int) (((tmpBond.end[1] - centre[1]) * scale) + - (getHeight() / 2)); - - xmid = (xend + xstart) / 2; - ymid = (yend + ystart) / 2; - - if (depthcue && !bymolecule) - { - if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) - { - g.setColor(tmpBond.startCol.darker().darker()); - drawLine(g, xstart, ystart, xmid, ymid); - g.setColor(tmpBond.endCol.darker().darker()); - drawLine(g, xmid, ymid, xend, yend); - } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { - g.setColor(tmpBond.startCol.darker()); - drawLine(g, xstart, ystart, xmid, ymid); - - g.setColor(tmpBond.endCol.darker()); - drawLine(g, xmid, ymid, xend, yend); - } else { - g.setColor(tmpBond.startCol); - drawLine(g, xstart, ystart, xmid, ymid); - - g.setColor(tmpBond.endCol); - drawLine(g, xmid, ymid, xend, yend); - } - } else if (depthcue && bymolecule) { - if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) { - g.setColor(Color.green.darker().darker()); - drawLine(g, xstart, ystart, xend, yend); - } else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) { - g.setColor(Color.green.darker()); - drawLine(g, xstart, ystart, xend, yend); - } else { - g.setColor(Color.green); - drawLine(g, xstart, ystart, xend, yend); - } - } else if (!depthcue && !bymolecule) { - g.setColor(tmpBond.startCol); - drawLine(g, xstart, ystart, xmid, ymid); - g.setColor(tmpBond.endCol); - drawLine(g, xmid, ymid, xend, yend); - } else { - drawLine(g, xstart, ystart, xend, yend); - } - - if(highlightBond1!=null && highlightBond1==tmpBond) - { - g.setColor(tmpBond.endCol.brighter().brighter().brighter().brighter()); - drawLine(g, xmid, ymid, xend, yend); - } - - if(highlightBond2!=null && highlightBond2==tmpBond) - { - g.setColor(tmpBond.startCol.brighter().brighter().brighter().brighter()); - drawLine(g, xstart, ystart, xmid, ymid); - } - - } - - - } - - public void drawLine(Graphics g, int x1, int y1, int x2, int y2) { - if (!wire) { - if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5) { - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1); - g.drawLine(x1, y1 - 1, x2, y2 - 1); - } else { - g.setColor(g.getColor().brighter()); - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1 + 1, y1, x2 + 1, y2); - g.drawLine(x1 - 1, y1, x2 - 1, y2); - } - } else { - g.drawLine(x1, y1, x2, y2); - } - } - - public Dimension minimumsize() { - return prefsize; - } - - public Dimension preferredsize() { - return prefsize; - } - - public void keyPressed(KeyEvent evt) - { - if (evt.getKeyCode() == KeyEvent.VK_UP) - { - scale = (float) (scale * 1.1); - redrawneeded = true; - repaint(); - } - else if (evt.getKeyCode() == KeyEvent.VK_DOWN) - { - scale = (float) (scale * 0.9); - redrawneeded = true; - repaint(); - } - } - - public void mousePressed(MouseEvent e) - { - pdbAction = true; - Atom fatom = findAtom(e.getX(), e.getY()); - if(fatom!=null) - { - fatom.isSelected = !fatom.isSelected; - - redrawneeded = true; - repaint(); - if (foundchain != -1) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(foundchain); - if (chain == mainchain) - { - if (fatom.alignmentMapping != -1) - { - if (highlightRes == null) - highlightRes = new Vector(); - - if (highlightRes.contains(fatom.alignmentMapping+"")) - highlightRes.remove(fatom.alignmentMapping + ""); - else - highlightRes.add(fatom.alignmentMapping + ""); - } - } - } - - } - mx = e.getX(); - my = e.getY(); - omx = mx; - omy = my; - dragging = false; - } - - public void mouseMoved(MouseEvent e) - { - pdbAction = true; - if(highlightBond1!=null) - { - highlightBond1.at2.isSelected = false; - highlightBond2.at1.isSelected = false; - highlightBond1 = null; - highlightBond2 = null; - } - - Atom fatom = findAtom(e.getX(), e.getY()); - - PDBChain chain = null; - if(foundchain!=-1) - { - chain = (PDBChain) pdb.chains.elementAt(foundchain); - if(chain == mainchain) - { - highlightSeqcanvas( fatom.alignmentMapping ); - } - } - - if (fatom != null) - { - this.setToolTipText(chain.id+":"+ fatom.resNumber+" "+ fatom.resName); - } else - { - highlightSeqcanvas( -1); - this.setToolTipText(null); - } - } - - - void highlightSeqcanvas(int pos) - { - SearchResults searchResults = new SearchResults(); - if(highlightRes!=null) - { - for (int i = 0; i < highlightRes.size(); i++) - { - int a = Integer.parseInt(highlightRes.elementAt( - i).toString())+1; - - searchResults.addResult(sequence, a, a); - } - } - - if(pos!=-1) - { - searchResults.addResult(sequence, pos+1, pos+1); - } - - seqcanvas.highlightSearchResults(searchResults); - } - - - public void mouseClicked(MouseEvent e) { } - - public void mouseEntered(MouseEvent e) { } - - public void mouseExited(MouseEvent e) { } - - public void mouseDragged(MouseEvent evt) - { - int x = evt.getX(); - int y = evt.getY(); - mx = x; - my = y; - - - MCMatrix objmat = new MCMatrix(3, 3); - objmat.setIdentity(); - - if ((evt.getModifiers() & Event.META_MASK) != 0) { - objmat.rotatez((float) ((mx - omx))); - } else { - objmat.rotatex((float) ((my - omy))); - objmat.rotatey((float) ((omx - mx))); - } - - //Alter the bonds - for (int ii = 0; ii < pdb.chains.size(); ii++) { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) { - Bond tmpBond = (Bond) bonds.elementAt(i); - - //Translate the bond so the centre is 0,0,0 - tmpBond.translate(-centre[0], -centre[1], -centre[2]); - - //Now apply the rotation matrix - tmpBond.start = objmat.vectorMultiply(tmpBond.start); - tmpBond.end = objmat.vectorMultiply(tmpBond.end); - - //Now translate back again - tmpBond.translate(centre[0], centre[1], centre[2]); - } - } - - objmat = null; - - omx = mx; - omy = my; - - dragging = true; - - redrawneeded = true; - - repaint(); - } - - public void mouseReleased(MouseEvent evt) - { - dragging = false; - return; - } - - void drawLabels(Graphics g) { - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - - if (chain.isVisible) - { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) - { - Bond tmpBond = (Bond) bonds.elementAt(i); - - if (tmpBond.at1.isSelected) - { - labelAtom(g, tmpBond, 1); - } - - if (tmpBond.at2.isSelected) - { - - labelAtom(g, tmpBond, 2); - } - } - } - } - } - - public void labelAtom(Graphics g, Bond b, int n) { - g.setFont(font); - g.setColor(Color.red); - if (n == 1) - { - int xstart = (int) (((b.start[0] - centre[0]) * scale) + - (getWidth() / 2)); - int ystart = (int) (((b.start[1] - centre[1]) * scale) + - (getHeight() / 2)); - - g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart); - } - - if (n == 2) { - int xstart = (int) (((b.end[0] - centre[0]) * scale) + - (getWidth() / 2)); - int ystart = (int) (((b.end[1] - centre[1]) * scale) + - (getHeight() / 2)); - - g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart); - } - } - - int foundchain = -1; - public Atom findAtom(int x, int y) { - Atom fatom = null; - - foundchain = -1; - - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - int truex; - Bond tmpBond=null; - - if (chain.isVisible) - { - Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; - - for (int i = 0; i < bonds.size(); i++) - { - tmpBond = (Bond) bonds.elementAt(i); - - truex = (int) (((tmpBond.start[0] - centre[0]) * scale) + - (getWidth() / 2)); - - if (Math.abs(truex - x) <= 2) - { - int truey = (int) (((tmpBond.start[1] - centre[1]) * scale) + - (getHeight() / 2)); - - if (Math.abs(truey - y) <= 2) - { - fatom = tmpBond.at1; - foundchain = ii; - break; - } - } - } - - // Still here? Maybe its the last bond - - truex = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) + - (getWidth() / 2)); - - if (Math.abs(truex - x) <= 2) - { - int truey = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) + - (getHeight() / 2)); - - if (Math.abs(truey - y) <= 2) - { - fatom = tmpBond.at2; - foundchain = ii; - break; - } - } - - } - - if (fatom != null) //)&& chain.ds != null) - { - chain = (PDBChain) pdb.chains.elementAt(foundchain); - } - } - - return fatom; - } - - Bond highlightBond1, highlightBond2; - public void highlightRes(int ii) - { - if( !seqColoursReady ) - return; - - if (highlightRes != null - && highlightRes.contains((ii-1) + "")) - { - return; - } - - int index = -1; - Bond tmpBond; - for(index=0; index 0) - { - highlightBond1 = (Bond) mainchain.bonds.elementAt(index - 1); - highlightBond1.at2.isSelected = true; - } - - if (index != mainchain.bonds.size()) - { - highlightBond2 = (Bond) mainchain.bonds.elementAt(index); - highlightBond2.at1.isSelected = true; - } - - break; - } - } - - redrawneeded = true; - repaint(); - } - - public void setAllchainsVisible(boolean b) - { - for (int ii = 0; ii < pdb.chains.size(); ii++) - { - PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); - chain.isVisible = b; - } - mainchain.isVisible = true; - findCentre(); - setupBonds(); - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import jalview.analysis.AlignSeq; + +import jalview.datamodel.*; + +// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug +import java.awt.*; +import java.awt.event.*; + +import java.io.*; + +import java.util.*; + +import javax.swing.*; + + +public class PDBCanvas extends JPanel implements MouseListener, MouseMotionListener +{ + MCMatrix idmat = new MCMatrix(3, 3); + MCMatrix objmat = new MCMatrix(3, 3); + boolean redrawneeded = true; + int omx = 0; + int mx = 0; + int omy = 0; + int my = 0; + public PDBfile pdb; + int bsize; + Image img; + Graphics ig; + Dimension prefsize; + float[] centre = new float[3]; + float[] width = new float[3]; + float maxwidth; + float scale; + String inStr; + String inType; + boolean bysequence = true; + boolean depthcue = true; + boolean wire = false; + boolean bymolecule = false; + boolean zbuffer = true; + boolean dragging; + int xstart; + int xend; + int ystart; + int yend; + int xmid; + int ymid; + Font font = new Font("Helvetica", Font.PLAIN, 10); + jalview.gui.SeqCanvas seqcanvas; + public Sequence sequence; + final StringBuffer mappingDetails = new StringBuffer(); + PDBChain mainchain; + Vector highlightRes; + boolean pdbAction = false; + boolean seqColoursReady = false; + jalview.gui.FeatureRenderer fr; + Color backgroundColour = Color.black; + + public PDBCanvas(jalview.gui.SeqCanvas seqcanvas, Sequence seq) + { + this.seqcanvas = seqcanvas; + this.sequence = seq; + seqcanvas.setPDBCanvas(this); + } + + public void setPDBFile(PDBfile pdb) + { + int max = -10; + int maxchain = -1; + int pdbstart = 0; + int pdbend = 0; + int seqstart = 0; + int seqend = 0; + AlignSeq maxAlignseq = null; + + for (int i = 0; i < pdb.chains.size(); i++) + { + + mappingDetails.append("\n\nPDB Sequence is :\nSequence = " + ((PDBChain) pdb.chains.elementAt(i)).sequence.getSequence()); + mappingDetails.append("\nNo of residues = " + ((PDBChain) pdb.chains.elementAt(i)).residues.size()+"\n\n"); + + // Now lets compare the sequences to get + // the start and end points. + // Align the sequence to the pdb + AlignSeq as = new AlignSeq(sequence, + ((PDBChain) pdb.chains.elementAt(i)).sequence, "pep"); + as.calcScoreMatrix(); + as.traceAlignment(); + PrintStream ps = new PrintStream(System.out) + { + public void print(String x) { + mappingDetails.append(x); + } + public void println() + { + mappingDetails.append("\n"); + } + }; + + as.printAlignment(ps); + + + + if (as.maxscore > max) + { + max = as.maxscore; + maxchain = i; + pdbstart = as.seq2start; + pdbend = as.seq2end; + seqstart = as.seq1start + sequence.getStart()-1; + seqend = as.seq1end + sequence.getEnd()-1; + maxAlignseq = as; + } + + mappingDetails.append("\nPDB start/end " + pdbstart + " " + pdbend); + mappingDetails.append("\nSEQ start/end "+ seqstart + " " + seqend); + } + + mainchain = (PDBChain) pdb.chains.elementAt(maxchain); + + mainchain.pdbstart = pdbstart; + mainchain.pdbend = pdbend; + mainchain.seqstart = seqstart; + mainchain.seqend = seqend; + mainchain.isVisible = true; + mainchain.makeExactMapping(maxAlignseq, sequence); + + this.pdb = pdb; + this.prefsize = new Dimension(getWidth(), getHeight()); + + //Initialize the matrices to identity + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (i != j) { + idmat.addElement(i, j, 0); + objmat.addElement(i, j, 0); + } else { + idmat.addElement(i, j, 1); + objmat.addElement(i, j, 1); + } + } + } + + addMouseMotionListener(this); + addMouseListener(this); + + addMouseWheelListener(new MouseWheelListener() + { + public void mouseWheelMoved(MouseWheelEvent e) + { + if (e.getWheelRotation() > 0) + { + scale = (float) (scale * 1.1); + redrawneeded = true; + repaint(); + } + + else + { + scale = (float) (scale * 0.9); + redrawneeded = true; + repaint(); + } + } + }); + + + findCentre(); + findWidth(); + + setupBonds(); + + scale = findScale(); + + ToolTipManager.sharedInstance().registerComponent(this); + ToolTipManager.sharedInstance().setInitialDelay(0); + ToolTipManager.sharedInstance().setDismissDelay(10000); + } + + + Vector visiblebonds; + void setupBonds() + { + seqColoursReady = false; + // Sort the bonds by z coord + visiblebonds = new Vector(); + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + if ( ( (PDBChain) pdb.chains.elementAt(ii)).isVisible) + { + Vector tmp = ( (PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < tmp.size(); i++) + { + visiblebonds.addElement(tmp.elementAt(i)); + } + } + } + + updateSeqColours(); + seqColoursReady = true; + redrawneeded = true; + repaint(); + } + + + public void findWidth() { + float[] max = new float[3]; + float[] min = new float[3]; + + max[0] = (float) -1e30; + max[1] = (float) -1e30; + max[2] = (float) -1e30; + + min[0] = (float) 1e30; + min[1] = (float) 1e30; + min[2] = (float) 1e30; + + for (int ii = 0; ii < pdb.chains.size(); ii++) { + if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) { + Bond tmp = (Bond) bonds.elementAt(i); + + if (tmp.start[0] >= max[0]) { + max[0] = tmp.start[0]; + } + + if (tmp.start[1] >= max[1]) { + max[1] = tmp.start[1]; + } + + if (tmp.start[2] >= max[2]) { + max[2] = tmp.start[2]; + } + + if (tmp.start[0] <= min[0]) { + min[0] = tmp.start[0]; + } + + if (tmp.start[1] <= min[1]) { + min[1] = tmp.start[1]; + } + + if (tmp.start[2] <= min[2]) { + min[2] = tmp.start[2]; + } + + if (tmp.end[0] >= max[0]) { + max[0] = tmp.end[0]; + } + + if (tmp.end[1] >= max[1]) { + max[1] = tmp.end[1]; + } + + if (tmp.end[2] >= max[2]) { + max[2] = tmp.end[2]; + } + + if (tmp.end[0] <= min[0]) { + min[0] = tmp.end[0]; + } + + if (tmp.end[1] <= min[1]) { + min[1] = tmp.end[1]; + } + + if (tmp.end[2] <= min[2]) { + min[2] = tmp.end[2]; + } + } + } + } + /* + System.out.println("xmax " + max[0] + " min " + min[0]); + System.out.println("ymax " + max[1] + " min " + min[1]); + System.out.println("zmax " + max[2] + " min " + min[2]);*/ + + width[0] = (float) Math.abs(max[0] - min[0]); + width[1] = (float) Math.abs(max[1] - min[1]); + width[2] = (float) Math.abs(max[2] - min[2]); + + maxwidth = width[0]; + + if (width[1] > width[0]) { + maxwidth = width[1]; + } + + if (width[2] > width[1]) { + maxwidth = width[2]; + } + + // System.out.println("Maxwidth = " + maxwidth); + } + + public float findScale() { + int dim; + int width; + int height; + + if (getWidth() != 0) { + width = getWidth(); + height = getHeight(); + } else { + width = prefsize.width; + height = prefsize.height; + } + + if (width < height) { + dim = width; + } else { + dim = height; + } + + return (float) (dim / (1.5d * maxwidth)); + } + + public void findCentre() { + float xtot = 0; + float ytot = 0; + float ztot = 0; + + int bsize = 0; + + //Find centre coordinate + for (int ii = 0; ii < pdb.chains.size(); ii++) { + if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + bsize += bonds.size(); + + for (int i = 0; i < bonds.size(); i++) { + xtot = xtot + ((Bond) bonds.elementAt(i)).start[0] + + ((Bond) bonds.elementAt(i)).end[0]; + + ytot = ytot + ((Bond) bonds.elementAt(i)).start[1] + + ((Bond) bonds.elementAt(i)).end[1]; + + ztot = ztot + ((Bond) bonds.elementAt(i)).start[2] + + ((Bond) bonds.elementAt(i)).end[2]; + } + } + } + + centre[0] = xtot / (2 * (float) bsize); + centre[1] = ytot / (2 * (float) bsize); + centre[2] = ztot / (2 * (float) bsize); + } + + public void paintComponent(Graphics g) + { + super.paintComponent(g); + + if(!seqColoursReady) + { + g.setColor(Color.black); + g.setFont(new Font("Verdana", Font.BOLD, 14)); + g.drawString("Retrieving PDB data....", 20, getHeight()/2); + return; + } + + + //Only create the image at the beginning - + //this saves much memory usage + if ((img == null) + || (prefsize.width != getWidth()) + || (prefsize.height != getHeight())) + + { + prefsize.width = getWidth(); + prefsize.height = getHeight(); + + scale = findScale(); + img = createImage(prefsize.width, prefsize.height); + ig = img.getGraphics(); + Graphics2D ig2 = (Graphics2D) ig; + + ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + redrawneeded = true; + } + + + if (redrawneeded) + { + drawAll(ig, prefsize.width, prefsize.height); + redrawneeded = false; + } + + g.drawImage(img, 0, 0, this); + + pdbAction = false; + } + + public void drawAll(Graphics g, int width, int height) + { + g.setColor(backgroundColour); + g.fillRect(0, 0, width, height); + drawScene(g); + drawLabels(g); + } + + + public void updateSeqColours() + { + if(pdbAction) + { + return; + } + + // System.out.println("update seq colours"); + if(bysequence && pdb!=null) + { + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + colourBySequence( (PDBChain) pdb.chains.elementAt(ii)); + } + } + + redrawneeded=true; + repaint(); + } + + int findTrueIndex(int pos) + { + // returns the alignment position for a residue + int j = sequence.getStart(); + int i = 0; + + while ( (i < sequence.getLength()) && (j <= sequence.getEnd()) && (j <= pos+1)) + { + if (!jalview.util.Comparison.isGap(sequence.getCharAt(i))) + { + j++; + } + + i++; + } + + if(i>1) + i--; + + if ( (j == sequence.getEnd()) && (j < pos)) + { + return sequence.getEnd() + 1; + } + else + { + return i; + } + } + + // This method has been taken out of PDBChain to allow + // Applet and Application specific sequence renderers to be used + void colourBySequence(PDBChain chain) + { + // System.out.println("colour by seq"); + boolean showFeatures = false; + if(seqcanvas.getViewport().getShowSequenceFeatures()) + { + showFeatures = true; + if (fr == null) + fr = new jalview.gui.FeatureRenderer(seqcanvas.getViewport()); + + fr.transferSettings( seqcanvas.getFeatureRenderer() ); + } + + Bond tmp; + for (int i = 0; i < chain.bonds.size(); i++) + { + tmp = (Bond) chain.bonds.elementAt(i); + + if(chain!=mainchain) + continue; + + if ( (tmp.at1.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && + (tmp.at1.resNumber <= ( (chain.offset + chain.pdbend) - 1))) + { + int index = findTrueIndex(tmp.at1.alignmentMapping); + //sequence.findIndex(tmp.at1.alignmentMapping); + if (index != -1) + { + tmp.startCol = seqcanvas.getSequenceRenderer(). + getResidueBoxColour( sequence, index); + + if(showFeatures) + tmp.startCol = fr.findFeatureColour(tmp.startCol, sequence, index); + + if(tmp.startCol==null) + tmp.startCol = Color.white; + } + } + + if ( (tmp.at2.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) && + (tmp.at2.resNumber <= ( (chain.pdbend + chain.offset) - 1))) + { + + int index = findTrueIndex(tmp.at2.alignmentMapping); + //sequence.findIndex( tmp.at2.alignmentMapping ); + if (index != -1) + { + tmp.endCol = seqcanvas.getSequenceRenderer(). + getResidueBoxColour( sequence, index); + + if(showFeatures) + tmp.endCol = fr.findFeatureColour(tmp.endCol, sequence, index); + + if(tmp.endCol==null) + tmp.endCol = Color.white; + } + } + } + } + + + Zsort zsort; + public void drawScene(Graphics g) + { + if (zbuffer) + { + if (zsort == null) + zsort = new Zsort(); + + zsort.Zsort(visiblebonds); + } + + Bond tmpBond = null; + for (int i = 0; i < visiblebonds.size(); i++) + { + tmpBond = (Bond) visiblebonds.elementAt(i); + + xstart = (int) ( ( (tmpBond.start[0] - centre[0]) * scale) + + (getWidth() / 2)); + ystart = (int) ( ( (tmpBond.start[1] - centre[1]) * scale) + + (getHeight() / 2)); + + xend = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) + + (getWidth() / 2)); + yend = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) + + (getHeight() / 2)); + + xmid = (xend + xstart) / 2; + ymid = (yend + ystart) / 2; + if (depthcue && !bymolecule) + { + if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) + { + + g.setColor(tmpBond.startCol.darker().darker()); + drawLine(g, xstart, ystart, xmid, ymid); + g.setColor(tmpBond.endCol.darker().darker()); + drawLine(g, xmid, ymid, xend, yend); + + } + else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) + { + g.setColor(tmpBond.startCol.darker()); + drawLine(g, xstart, ystart, xmid, ymid); + + g.setColor(tmpBond.endCol.darker()); + drawLine(g, xmid, ymid, xend, yend); + } + else + { + g.setColor(tmpBond.startCol); + drawLine(g, xstart, ystart, xmid, ymid); + + g.setColor(tmpBond.endCol); + drawLine(g, xmid, ymid, xend, yend); + } + } + else if (depthcue && bymolecule) + { + if (tmpBond.start[2] < (centre[2] - (maxwidth / 6))) + { + g.setColor(Color.green.darker().darker()); + drawLine(g, xstart, ystart, xend, yend); + } + else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6))) + { + g.setColor(Color.green.darker()); + drawLine(g, xstart, ystart, xend, yend); + } + else + { + g.setColor(Color.green); + drawLine(g, xstart, ystart, xend, yend); + } + } + else if (!depthcue && !bymolecule) + { + g.setColor(tmpBond.startCol); + drawLine(g, xstart, ystart, xmid, ymid); + g.setColor(tmpBond.endCol); + drawLine(g, xmid, ymid, xend, yend); + } + else + { + drawLine(g, xstart, ystart, xend, yend); + } + + if (highlightBond1 != null && highlightBond1 == tmpBond) + { + g.setColor(tmpBond.endCol.brighter().brighter().brighter().brighter()); + drawLine(g, xmid, ymid, xend, yend); + } + + if (highlightBond2 != null && highlightBond2 == tmpBond) + { + g.setColor(tmpBond.startCol.brighter().brighter().brighter().brighter()); + drawLine(g, xstart, ystart, xmid, ymid); + } + + } + + + } + + public void drawLine(Graphics g, int x1, int y1, int x2, int y2) { + if (!wire) { + if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5) { + g.drawLine(x1, y1, x2, y2); + g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1); + g.drawLine(x1, y1 - 1, x2, y2 - 1); + } else { + g.setColor(g.getColor().brighter()); + g.drawLine(x1, y1, x2, y2); + g.drawLine(x1 + 1, y1, x2 + 1, y2); + g.drawLine(x1 - 1, y1, x2 - 1, y2); + } + } else { + g.drawLine(x1, y1, x2, y2); + } + } + + public Dimension minimumsize() { + return prefsize; + } + + public Dimension preferredsize() { + return prefsize; + } + + public void keyPressed(KeyEvent evt) + { + if (evt.getKeyCode() == KeyEvent.VK_UP) + { + scale = (float) (scale * 1.1); + redrawneeded = true; + repaint(); + } + else if (evt.getKeyCode() == KeyEvent.VK_DOWN) + { + scale = (float) (scale * 0.9); + redrawneeded = true; + repaint(); + } + } + + public void mousePressed(MouseEvent e) + { + pdbAction = true; + Atom fatom = findAtom(e.getX(), e.getY()); + if(fatom!=null) + { + fatom.isSelected = !fatom.isSelected; + + redrawneeded = true; + repaint(); + if (foundchain != -1) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(foundchain); + if (chain == mainchain) + { + if (fatom.alignmentMapping != -1) + { + if (highlightRes == null) + highlightRes = new Vector(); + + if (highlightRes.contains(fatom.alignmentMapping+"")) + highlightRes.remove(fatom.alignmentMapping + ""); + else + highlightRes.add(fatom.alignmentMapping + ""); + } + } + } + + } + mx = e.getX(); + my = e.getY(); + omx = mx; + omy = my; + dragging = false; + } + + public void mouseMoved(MouseEvent e) + { + pdbAction = true; + if(highlightBond1!=null) + { + highlightBond1.at2.isSelected = false; + highlightBond2.at1.isSelected = false; + highlightBond1 = null; + highlightBond2 = null; + } + + Atom fatom = findAtom(e.getX(), e.getY()); + + PDBChain chain = null; + if(foundchain!=-1) + { + chain = (PDBChain) pdb.chains.elementAt(foundchain); + if(chain == mainchain) + { + highlightSeqcanvas( fatom.alignmentMapping ); + } + } + + if (fatom != null) + { + this.setToolTipText(chain.id+":"+ fatom.resNumber+" "+ fatom.resName); + } else + { + highlightSeqcanvas( -1); + this.setToolTipText(null); + } + } + + + void highlightSeqcanvas(int pos) + { + SearchResults searchResults = new SearchResults(); + if(highlightRes!=null) + { + for (int i = 0; i < highlightRes.size(); i++) + { + int a = Integer.parseInt(highlightRes.elementAt( + i).toString())+1; + + searchResults.addResult(sequence, a, a); + } + } + + if(pos!=-1) + { + searchResults.addResult(sequence, pos+1, pos+1); + } + + seqcanvas.highlightSearchResults(searchResults); + } + + + public void mouseClicked(MouseEvent e) { } + + public void mouseEntered(MouseEvent e) { } + + public void mouseExited(MouseEvent e) { } + + public void mouseDragged(MouseEvent evt) + { + int x = evt.getX(); + int y = evt.getY(); + mx = x; + my = y; + + + MCMatrix objmat = new MCMatrix(3, 3); + objmat.setIdentity(); + + if ((evt.getModifiers() & Event.META_MASK) != 0) { + objmat.rotatez((float) ((mx - omx))); + } else { + objmat.rotatex((float) ((my - omy))); + objmat.rotatey((float) ((omx - mx))); + } + + //Alter the bonds + for (int ii = 0; ii < pdb.chains.size(); ii++) { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) { + Bond tmpBond = (Bond) bonds.elementAt(i); + + //Translate the bond so the centre is 0,0,0 + tmpBond.translate(-centre[0], -centre[1], -centre[2]); + + //Now apply the rotation matrix + tmpBond.start = objmat.vectorMultiply(tmpBond.start); + tmpBond.end = objmat.vectorMultiply(tmpBond.end); + + //Now translate back again + tmpBond.translate(centre[0], centre[1], centre[2]); + } + } + + objmat = null; + + omx = mx; + omy = my; + + dragging = true; + + redrawneeded = true; + + repaint(); + } + + public void mouseReleased(MouseEvent evt) + { + dragging = false; + return; + } + + void drawLabels(Graphics g) { + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + + if (chain.isVisible) + { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) + { + Bond tmpBond = (Bond) bonds.elementAt(i); + + if (tmpBond.at1.isSelected) + { + labelAtom(g, tmpBond, 1); + } + + if (tmpBond.at2.isSelected) + { + + labelAtom(g, tmpBond, 2); + } + } + } + } + } + + public void labelAtom(Graphics g, Bond b, int n) { + g.setFont(font); + g.setColor(Color.red); + if (n == 1) + { + int xstart = (int) (((b.start[0] - centre[0]) * scale) + + (getWidth() / 2)); + int ystart = (int) (((b.start[1] - centre[1]) * scale) + + (getHeight() / 2)); + + g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart); + } + + if (n == 2) { + int xstart = (int) (((b.end[0] - centre[0]) * scale) + + (getWidth() / 2)); + int ystart = (int) (((b.end[1] - centre[1]) * scale) + + (getHeight() / 2)); + + g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart); + } + } + + int foundchain = -1; + public Atom findAtom(int x, int y) { + Atom fatom = null; + + foundchain = -1; + + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + int truex; + Bond tmpBond=null; + + if (chain.isVisible) + { + Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds; + + for (int i = 0; i < bonds.size(); i++) + { + tmpBond = (Bond) bonds.elementAt(i); + + truex = (int) (((tmpBond.start[0] - centre[0]) * scale) + + (getWidth() / 2)); + + if (Math.abs(truex - x) <= 2) + { + int truey = (int) (((tmpBond.start[1] - centre[1]) * scale) + + (getHeight() / 2)); + + if (Math.abs(truey - y) <= 2) + { + fatom = tmpBond.at1; + foundchain = ii; + break; + } + } + } + + // Still here? Maybe its the last bond + + truex = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) + + (getWidth() / 2)); + + if (Math.abs(truex - x) <= 2) + { + int truey = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) + + (getHeight() / 2)); + + if (Math.abs(truey - y) <= 2) + { + fatom = tmpBond.at2; + foundchain = ii; + break; + } + } + + } + + if (fatom != null) //)&& chain.ds != null) + { + chain = (PDBChain) pdb.chains.elementAt(foundchain); + } + } + + return fatom; + } + + Bond highlightBond1, highlightBond2; + public void highlightRes(int ii) + { + if( !seqColoursReady ) + return; + + if (highlightRes != null + && highlightRes.contains((ii-1) + "")) + { + return; + } + + int index = -1; + Bond tmpBond; + for(index=0; index 0) + { + highlightBond1 = (Bond) mainchain.bonds.elementAt(index - 1); + highlightBond1.at2.isSelected = true; + } + + if (index != mainchain.bonds.size()) + { + highlightBond2 = (Bond) mainchain.bonds.elementAt(index); + highlightBond2.at1.isSelected = true; + } + + break; + } + } + + redrawneeded = true; + repaint(); + } + + public void setAllchainsVisible(boolean b) + { + for (int ii = 0; ii < pdb.chains.size(); ii++) + { + PDBChain chain = (PDBChain) pdb.chains.elementAt(ii); + chain.isVisible = b; + } + mainchain.isVisible = true; + findCentre(); + setupBonds(); + } +} diff --git a/src/MCview/PDBChain.java b/src/MCview/PDBChain.java index fa4bbf9..36681a1 100755 --- a/src/MCview/PDBChain.java +++ b/src/MCview/PDBChain.java @@ -1,269 +1,269 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import jalview.datamodel.*; - -import jalview.schemes.ResidueProperties; - -import java.awt.*; - -import java.util.*; -import jalview.analysis.AlignSeq; - - -public class PDBChain { - public String id; - public Vector bonds = new Vector(); - public Vector atoms = new Vector(); - public Vector residues = new Vector(); - public int offset; - public Sequence sequence; - public boolean isVisible = true; - public int pdbstart = 0; - public int pdbend = 0; - public int seqstart = 0; - public int seqend = 0; - - public PDBChain(String id) { - this.id = id; - } - - public String print() { - String tmp = ""; - - for (int i = 0; i < bonds.size(); i++) { - tmp = tmp + ((Bond) bonds.elementAt(i)).at1.resName + " " + - ((Bond) bonds.elementAt(i)).at1.resNumber + " " + offset + - "\n"; - } - - return tmp; - } - - void makeExactMapping(AlignSeq as, Sequence s1) - { - int pdbpos = as.getSeq2Start()-2; - int alignpos = s1.getStart() + as.getSeq1Start()-3; - - for(int i=0; i") > -1 || data.indexOf("") > -1) + ) + out.println(data); + } + out.close(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + } } diff --git a/src/MCview/PDBfile.java b/src/MCview/PDBfile.java index 63728ae..5824575 100755 --- a/src/MCview/PDBfile.java +++ b/src/MCview/PDBfile.java @@ -1,186 +1,171 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import java.io.*; - -import java.net.*; - -import java.util.*; -import java.awt.Color; -import jalview.io.AppletFormatAdapter; - - -public class PDBfile extends jalview.io.FileParse { - public Vector chains = new Vector(); - Vector lineArray = new Vector(); - public String id; - - public PDBfile(String[] lines) { - for (int i = 0; i < lines.length; i++) - lineArray.addElement(lines[i]); - - parse(); - } - - public PDBfile(String inFile, String inType) throws IOException { - super(inFile, inType); - - String line; - this.lineArray = new Vector(); - - BufferedReader dataIn; - - - if (inType.equals(AppletFormatAdapter.FILE)) { - dataIn = new BufferedReader(new FileReader(inFile)); - } - else if(inType.equals(AppletFormatAdapter.PASTE)) - { - dataIn = new BufferedReader(new StringReader(inFile)); - } - else if (inType.equalsIgnoreCase(AppletFormatAdapter.CLASSLOADER)) - { - java.io.InputStream is = getClass().getResourceAsStream("/" + - inFile); - - dataIn = new BufferedReader(new java.io.InputStreamReader(is)); - } - else - { - URL url = new URL(inFile); - dataIn = new BufferedReader(new InputStreamReader(url.openStream())); - } - - while ((line = dataIn.readLine()) != null) { - lineArray.addElement(line); - } - - - parse(); - lineArray = null; - } - - public void parse() - { - PDBChain tmpchain; - String line; - boolean modelFlag = false; - boolean terFlag = false; - - - for (int i = 0; i < lineArray.size(); i++) - { - - line = lineArray.elementAt(i).toString(); - - - if (line.indexOf("HEADER") == 0) - { - id = line.substring(62, 67).trim(); - continue; - } - - if(line.indexOf("MODEL")==0) - modelFlag = true; - - if(line.indexOf("TER")==0) - terFlag = true; - - if(modelFlag && line.indexOf("ENDMDL")==0) - break; - - if ( line.indexOf("ATOM")==0 - || (line.indexOf("HETATM")==0 && !terFlag) - ) - { - terFlag = false; - - - //Jalview is only interested in CA bonds???? - if (!line.substring(12, 15).trim().equals("CA")) - { - continue; - } - - Atom tmpatom = new Atom(line); - - tmpchain = findChain(tmpatom.chain); - if (tmpchain != null) - { - tmpchain.atoms.addElement(tmpatom); - } - else - { - tmpchain = new PDBChain(tmpatom.chain); - chains.addElement(tmpchain); - tmpchain.atoms.addElement(tmpatom); - } - - } - } - - makeResidueList(); - makeCaBondList(); - } - - public void makeResidueList() { - for (int i = 0; i < chains.size(); i++) { - ((PDBChain) chains.elementAt(i)).makeResidueList(); - } - } - - public void makeCaBondList() { - for (int i = 0; i < chains.size(); i++) { - ((PDBChain) chains.elementAt(i)).makeCaBondList(); - } - } - - public PDBChain findChain(String id) { - for (int i = 0; i < chains.size(); i++) { - if (((PDBChain) chains.elementAt(i)).id.equals(id)) { - return (PDBChain) chains.elementAt(i); - } - } - - return null; - } - - public void setChargeColours() { - for (int i = 0; i < chains.size(); i++) { - ((PDBChain) chains.elementAt(i)).setChargeColours(); - } - } - - public void setColours(jalview.schemes.ColourSchemeI cs) { - for (int i = 0; i < chains.size(); i++) { - ((PDBChain) chains.elementAt(i)).setChainColours(cs); - } - } - - public void setChainColours() - { - for (int i = 0; i < chains.size(); i++) - { - ((PDBChain) chains.elementAt(i)).setChainColours( - Color.getHSBColor(1.0f / (float)i, .4f, 1.0f) - ); - } - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import jalview.datamodel.*; + +import java.io.*; + +import java.util.*; +import java.awt.Color; + + +public class PDBfile extends jalview.io.AlignFile { + public Vector chains; + public String id; + + public PDBfile(String inFile, String inType) throws IOException + { + super(inFile, inType); + } + + public String print() + { + return null; + } + + public void parse() throws IOException + { + chains = new Vector(); + + PDBChain tmpchain; + String line; + boolean modelFlag = false; + boolean terFlag = false; + + + int index = 0; + while((line = nextLine())!=null) + { + if (line.indexOf("HEADER") == 0) + { + id = line.substring(62, 67).trim(); + continue; + } + + if(line.indexOf("MODEL")==0) + modelFlag = true; + + if(line.indexOf("TER")==0) + terFlag = true; + + if(modelFlag && line.indexOf("ENDMDL")==0) + break; + + if ( line.indexOf("ATOM")==0 + || (line.indexOf("HETATM")==0 && !terFlag) + ) + { + terFlag = false; + + + //Jalview is only interested in CA bonds???? + if (!line.substring(12, 15).trim().equals("CA")) + { + continue; + } + + Atom tmpatom = new Atom(line); + tmpchain = findChain(tmpatom.chain); + if (tmpchain != null) + { + tmpchain.atoms.addElement(tmpatom); + } + else + { + tmpchain = new PDBChain(tmpatom.chain); + chains.addElement(tmpchain); + tmpchain.atoms.addElement(tmpatom); + } + } + index ++; + } + + makeResidueList(); + makeCaBondList(); + + if(id==null) + { + id = inFile.getName(); + } + for (int i = 0; i < chains.size(); i++) + { + SequenceI seq = ( (PDBChain) chains.elementAt(i)). + sequence; + seq.setName(id + "|" + seq.getName()); + Sequence dataset = new Sequence(seq. + getName(), + seq.getSequence().toString(), seq.getStart(), seq.getEnd()); + + PDBEntry entry = new PDBEntry(); + entry.setId(id); + if(inFile!=null) + entry.setFile(inFile.getAbsolutePath()); + + seq.setDatasetSequence(dataset); + dataset.addPDBId(entry); + + getSeqs().addElement(seq); + } + } + + public void makeResidueList() { + for (int i = 0; i < chains.size(); i++) { + ((PDBChain) chains.elementAt(i)).makeResidueList(); + } + } + + public void makeCaBondList() { + for (int i = 0; i < chains.size(); i++) { + ((PDBChain) chains.elementAt(i)).makeCaBondList(); + } + } + + public PDBChain findChain(String id) { + for (int i = 0; i < chains.size(); i++) { + if (((PDBChain) chains.elementAt(i)).id.equals(id)) { + return (PDBChain) chains.elementAt(i); + } + } + + return null; + } + + public void setChargeColours() { + for (int i = 0; i < chains.size(); i++) { + ((PDBChain) chains.elementAt(i)).setChargeColours(); + } + } + + public void setColours(jalview.schemes.ColourSchemeI cs) { + for (int i = 0; i < chains.size(); i++) { + ((PDBChain) chains.elementAt(i)).setChainColours(cs); + } + } + + public void setChainColours() + { + for (int i = 0; i < chains.size(); i++) + { + ((PDBChain) chains.elementAt(i)).setChainColours( + Color.getHSBColor(1.0f / (float)i, .4f, 1.0f) + ); + } + } +} diff --git a/src/MCview/Residue.java b/src/MCview/Residue.java index 0f24137..39e7112 100755 --- a/src/MCview/Residue.java +++ b/src/MCview/Residue.java @@ -1,48 +1,48 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import java.util.*; - - -public class Residue { - Vector atoms = new Vector(); - int number; - int count; - int seqnumber; - - public Residue(Vector atoms, int number, int count) { - this.atoms = atoms; - this.number = number; - this.count = count; - } - - public Atom findAtom(String name) - { - for (int i = 0; i < atoms.size(); i++) - { - if (((Atom) atoms.elementAt(i)).name.equals(name)) - { - return (Atom) atoms.elementAt(i); - } - } - - return null; - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import java.util.*; + + +public class Residue { + Vector atoms = new Vector(); + int number; + int count; + int seqnumber; + + public Residue(Vector atoms, int number, int count) { + this.atoms = atoms; + this.number = number; + this.count = count; + } + + public Atom findAtom(String name) + { + for (int i = 0; i < atoms.size(); i++) + { + if (((Atom) atoms.elementAt(i)).name.equals(name)) + { + return (Atom) atoms.elementAt(i); + } + } + + return null; + } +} diff --git a/src/MCview/Zsort.java b/src/MCview/Zsort.java index c54a3ff..383958d 100755 --- a/src/MCview/Zsort.java +++ b/src/MCview/Zsort.java @@ -1,63 +1,63 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package MCview; - -import java.util.*; - - -public class Zsort { - public void Zsort(Vector bonds) { - sort(bonds, 0, bonds.size() - 1); - } - - public void sort(Vector bonds, int p, int r) { - int q; - - if (p < r) { - q = partition(bonds, p, r); - sort(bonds, p, q); - sort(bonds, q + 1, r); - } - } - - private int partition(Vector bonds, int p, int r) { - float x = ((Bond) bonds.elementAt(p)).start[2]; - int i = p - 1; - int j = r + 1; - Bond tmp; - while (true) { - do { - j = j - 1; - } while ((j >= 0) && (((Bond) bonds.elementAt(j)).start[2] > x)); - - do { - i = i + 1; - } while ((i < bonds.size()) && - (((Bond) bonds.elementAt(i)).start[2] < x)); - - if (i < j) { - tmp = (Bond) bonds.elementAt(i); - bonds.setElementAt(bonds.elementAt(j), i); - bonds.setElementAt(tmp, j); - } else { - return j; - } - } - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package MCview; + +import java.util.*; + + +public class Zsort { + public void Zsort(Vector bonds) { + sort(bonds, 0, bonds.size() - 1); + } + + public void sort(Vector bonds, int p, int r) { + int q; + + if (p < r) { + q = partition(bonds, p, r); + sort(bonds, p, q); + sort(bonds, q + 1, r); + } + } + + private int partition(Vector bonds, int p, int r) { + float x = ((Bond) bonds.elementAt(p)).start[2]; + int i = p - 1; + int j = r + 1; + Bond tmp; + while (true) { + do { + j --; + } while ((j >= 0) && (((Bond) bonds.elementAt(j)).start[2] > x)); + + do { + i ++; + } while ((i < bonds.size()) && + (((Bond) bonds.elementAt(i)).start[2] < x)); + + if (i < j) { + tmp = (Bond) bonds.elementAt(i); + bonds.setElementAt(bonds.elementAt(j), i); + bonds.setElementAt(tmp, j); + } else { + return j; + } + } + } +} diff --git a/src/ext/vamsas/MuscleWS.java b/src/ext/vamsas/MuscleWS.java index ffbe5cb..2b9d19b 100755 --- a/src/ext/vamsas/MuscleWS.java +++ b/src/ext/vamsas/MuscleWS.java @@ -3,11 +3,11 @@ * * This file was auto-generated from WSDL * by the Apache Axis 1.2RC2 Nov 16, 2004 (12:19:44 EST) WSDL2Java emitter. - */ - + */ + /* * Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -22,20 +22,20 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package ext.vamsas; - -public interface MuscleWS extends java.rmi.Remote { - public vamsas.objects.simple.WsJobId align( - vamsas.objects.simple.SequenceSet seqSet) - throws java.rmi.RemoteException; - - public vamsas.objects.simple.Alignment getalign(java.lang.String job_id) - throws java.rmi.RemoteException; - - public vamsas.objects.simple.MsaResult getResult(java.lang.String job_id) - throws java.rmi.RemoteException; - - public vamsas.objects.simple.WsJobId cancel(java.lang.String jobId) - throws java.rmi.RemoteException; -} +*/ +package ext.vamsas; + +public interface MuscleWS extends java.rmi.Remote { + public vamsas.objects.simple.WsJobId align( + vamsas.objects.simple.SequenceSet seqSet) + throws java.rmi.RemoteException; + + public vamsas.objects.simple.Alignment getalign(java.lang.String job_id) + throws java.rmi.RemoteException; + + public vamsas.objects.simple.MsaResult getResult(java.lang.String job_id) + throws java.rmi.RemoteException; + + public vamsas.objects.simple.WsJobId cancel(java.lang.String jobId) + throws java.rmi.RemoteException; +} diff --git a/src/ext/vamsas/MuscleWSService.java b/src/ext/vamsas/MuscleWSService.java index ffc4abc..f4984e3 100755 --- a/src/ext/vamsas/MuscleWSService.java +++ b/src/ext/vamsas/MuscleWSService.java @@ -3,11 +3,11 @@ * * This file was auto-generated from WSDL * by the Apache Axis 1.2RC2 Nov 16, 2004 (12:19:44 EST) WSDL2Java emitter. - */ - + */ + /* * Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -22,15 +22,15 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package ext.vamsas; - -public interface MuscleWSService extends javax.xml.rpc.Service { - public java.lang.String getMuscleWSAddress(); - - public ext.vamsas.MuscleWS getMuscleWS() - throws javax.xml.rpc.ServiceException; - - public ext.vamsas.MuscleWS getMuscleWS(java.net.URL portAddress) - throws javax.xml.rpc.ServiceException; -} +*/ +package ext.vamsas; + +public interface MuscleWSService extends javax.xml.rpc.Service { + public java.lang.String getMuscleWSAddress(); + + public ext.vamsas.MuscleWS getMuscleWS() + throws javax.xml.rpc.ServiceException; + + public ext.vamsas.MuscleWS getMuscleWS(java.net.URL portAddress) + throws javax.xml.rpc.ServiceException; +} diff --git a/src/ext/vamsas/MuscleWSServiceLocator.java b/src/ext/vamsas/MuscleWSServiceLocator.java index 96ef074..565b73e 100755 --- a/src/ext/vamsas/MuscleWSServiceLocator.java +++ b/src/ext/vamsas/MuscleWSServiceLocator.java @@ -3,11 +3,11 @@ * * This file was auto-generated from WSDL * by the Apache Axis 1.2RC2 Nov 16, 2004 (12:19:44 EST) WSDL2Java emitter. - */ - + */ + /* * Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -22,147 +22,147 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package ext.vamsas; - -public class MuscleWSServiceLocator extends org.apache.axis.client.Service - implements ext.vamsas.MuscleWSService { - // Use to get a proxy class for MuscleWS - private java.lang.String MuscleWS_address = "http://anaplog.compbio.dundee.ac.uk:8080/axis/services/MuscleWS"; - - // The WSDD service name defaults to the port name. - private java.lang.String MuscleWSWSDDServiceName = "MuscleWS"; - private java.util.HashSet ports = null; - - public MuscleWSServiceLocator() { - } - - public MuscleWSServiceLocator(org.apache.axis.EngineConfiguration config) { - super(config); - } - - public java.lang.String getMuscleWSAddress() { - return MuscleWS_address; - } - - public java.lang.String getMuscleWSWSDDServiceName() { - return MuscleWSWSDDServiceName; - } - - public void setMuscleWSWSDDServiceName(java.lang.String name) { - MuscleWSWSDDServiceName = name; - } - - public ext.vamsas.MuscleWS getMuscleWS() - throws javax.xml.rpc.ServiceException { - java.net.URL endpoint; - - try { - endpoint = new java.net.URL(MuscleWS_address); - } catch (java.net.MalformedURLException e) { - throw new javax.xml.rpc.ServiceException(e); - } - - return getMuscleWS(endpoint); - } - - public ext.vamsas.MuscleWS getMuscleWS(java.net.URL portAddress) - throws javax.xml.rpc.ServiceException { - try { - ext.vamsas.MuscleWSSoapBindingStub _stub = new ext.vamsas.MuscleWSSoapBindingStub(portAddress, - this); - _stub.setPortName(getMuscleWSWSDDServiceName()); - - return _stub; - } catch (org.apache.axis.AxisFault e) { - return null; - } - } - - public void setMuscleWSEndpointAddress(java.lang.String address) { - MuscleWS_address = address; - } - +*/ +package ext.vamsas; + +public class MuscleWSServiceLocator extends org.apache.axis.client.Service + implements ext.vamsas.MuscleWSService { + // Use to get a proxy class for MuscleWS + private java.lang.String MuscleWS_address = "http://anaplog.compbio.dundee.ac.uk:8080/axis/services/MuscleWS"; + + // The WSDD service name defaults to the port name. + private java.lang.String MuscleWSWSDDServiceName = "MuscleWS"; + private java.util.HashSet ports = null; + + public MuscleWSServiceLocator() { + } + + public MuscleWSServiceLocator(org.apache.axis.EngineConfiguration config) { + super(config); + } + + public java.lang.String getMuscleWSAddress() { + return MuscleWS_address; + } + + public java.lang.String getMuscleWSWSDDServiceName() { + return MuscleWSWSDDServiceName; + } + + public void setMuscleWSWSDDServiceName(java.lang.String name) { + MuscleWSWSDDServiceName = name; + } + + public ext.vamsas.MuscleWS getMuscleWS() + throws javax.xml.rpc.ServiceException { + java.net.URL endpoint; + + try { + endpoint = new java.net.URL(MuscleWS_address); + } catch (java.net.MalformedURLException e) { + throw new javax.xml.rpc.ServiceException(e); + } + + return getMuscleWS(endpoint); + } + + public ext.vamsas.MuscleWS getMuscleWS(java.net.URL portAddress) + throws javax.xml.rpc.ServiceException { + try { + ext.vamsas.MuscleWSSoapBindingStub _stub = new ext.vamsas.MuscleWSSoapBindingStub(portAddress, + this); + _stub.setPortName(getMuscleWSWSDDServiceName()); + + return _stub; + } catch (org.apache.axis.AxisFault e) { + return null; + } + } + + public void setMuscleWSEndpointAddress(java.lang.String address) { + MuscleWS_address = address; + } + /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. - */ - public java.rmi.Remote getPort(Class serviceEndpointInterface) - throws javax.xml.rpc.ServiceException { - try { - if (ext.vamsas.MuscleWS.class.isAssignableFrom( - serviceEndpointInterface)) { - ext.vamsas.MuscleWSSoapBindingStub _stub = new ext.vamsas.MuscleWSSoapBindingStub(new java.net.URL( - MuscleWS_address), this); - _stub.setPortName(getMuscleWSWSDDServiceName()); - - return _stub; - } - } catch (java.lang.Throwable t) { - throw new javax.xml.rpc.ServiceException(t); - } - - throw new javax.xml.rpc.ServiceException( - "There is no stub implementation for the interface: " + - ((serviceEndpointInterface == null) ? "null" - : serviceEndpointInterface.getName())); - } - + */ + public java.rmi.Remote getPort(Class serviceEndpointInterface) + throws javax.xml.rpc.ServiceException { + try { + if (ext.vamsas.MuscleWS.class.isAssignableFrom( + serviceEndpointInterface)) { + ext.vamsas.MuscleWSSoapBindingStub _stub = new ext.vamsas.MuscleWSSoapBindingStub(new java.net.URL( + MuscleWS_address), this); + _stub.setPortName(getMuscleWSWSDDServiceName()); + + return _stub; + } + } catch (java.lang.Throwable t) { + throw new javax.xml.rpc.ServiceException(t); + } + + throw new javax.xml.rpc.ServiceException( + "There is no stub implementation for the interface: " + + ((serviceEndpointInterface == null) ? "null" + : serviceEndpointInterface.getName())); + } + /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. - */ - public java.rmi.Remote getPort(javax.xml.namespace.QName portName, - Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { - if (portName == null) { - return getPort(serviceEndpointInterface); - } - - java.lang.String inputPortName = portName.getLocalPart(); - - if ("MuscleWS".equals(inputPortName)) { - return getMuscleWS(); - } else { - java.rmi.Remote _stub = getPort(serviceEndpointInterface); - ((org.apache.axis.client.Stub) _stub).setPortName(portName); - - return _stub; - } - } - - public javax.xml.namespace.QName getServiceName() { - return new javax.xml.namespace.QName("vamsas", "MuscleWSService"); - } - - public java.util.Iterator getPorts() { - if (ports == null) { - ports = new java.util.HashSet(); - ports.add(new javax.xml.namespace.QName("vamsas", "MuscleWS")); - } - - return ports.iterator(); - } - + */ + public java.rmi.Remote getPort(javax.xml.namespace.QName portName, + Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { + if (portName == null) { + return getPort(serviceEndpointInterface); + } + + java.lang.String inputPortName = portName.getLocalPart(); + + if ("MuscleWS".equals(inputPortName)) { + return getMuscleWS(); + } else { + java.rmi.Remote _stub = getPort(serviceEndpointInterface); + ((org.apache.axis.client.Stub) _stub).setPortName(portName); + + return _stub; + } + } + + public javax.xml.namespace.QName getServiceName() { + return new javax.xml.namespace.QName("vamsas", "MuscleWSService"); + } + + public java.util.Iterator getPorts() { + if (ports == null) { + ports = new java.util.HashSet(); + ports.add(new javax.xml.namespace.QName("vamsas", "MuscleWS")); + } + + return ports.iterator(); + } + /** * Set the endpoint address for the specified port name. -*/ - public void setEndpointAddress(java.lang.String portName, - java.lang.String address) throws javax.xml.rpc.ServiceException { - if ("MuscleWS".equals(portName)) { - setMuscleWSEndpointAddress(address); - } else { // Unknown Port Name - throw new javax.xml.rpc.ServiceException( - " Cannot set Endpoint Address for Unknown Port" + portName); - } - } - +*/ + public void setEndpointAddress(java.lang.String portName, + java.lang.String address) throws javax.xml.rpc.ServiceException { + if ("MuscleWS".equals(portName)) { + setMuscleWSEndpointAddress(address); + } else { // Unknown Port Name + throw new javax.xml.rpc.ServiceException( + " Cannot set Endpoint Address for Unknown Port" + portName); + } + } + /** * Set the endpoint address for the specified port name. -*/ - public void setEndpointAddress(javax.xml.namespace.QName portName, - java.lang.String address) throws javax.xml.rpc.ServiceException { - setEndpointAddress(portName.getLocalPart(), address); - } -} +*/ + public void setEndpointAddress(javax.xml.namespace.QName portName, + java.lang.String address) throws javax.xml.rpc.ServiceException { + setEndpointAddress(portName.getLocalPart(), address); + } +} diff --git a/src/ext/vamsas/MuscleWSSoapBindingStub.java b/src/ext/vamsas/MuscleWSSoapBindingStub.java index c56432d..b1f8065 100755 --- a/src/ext/vamsas/MuscleWSSoapBindingStub.java +++ b/src/ext/vamsas/MuscleWSSoapBindingStub.java @@ -3,11 +3,11 @@ * * This file was auto-generated from WSDL * by the Apache Axis 1.2RC2 Nov 16, 2004 (12:19:44 EST) WSDL2Java emitter. - */ - + */ + /* * Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -22,373 +22,373 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package ext.vamsas; - -public class MuscleWSSoapBindingStub extends org.apache.axis.client.Stub - implements ext.vamsas.MuscleWS { - static org.apache.axis.description.OperationDesc[] _operations; - - static { - _operations = new org.apache.axis.description.OperationDesc[4]; - _initOperationDesc1(); - } - - private java.util.Vector cachedSerClasses = new java.util.Vector(); - private java.util.Vector cachedSerQNames = new java.util.Vector(); - private java.util.Vector cachedSerFactories = new java.util.Vector(); - private java.util.Vector cachedDeserFactories = new java.util.Vector(); - - public MuscleWSSoapBindingStub() throws org.apache.axis.AxisFault { - this(null); - } - - public MuscleWSSoapBindingStub(java.net.URL endpointURL, - javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { - this(service); - super.cachedEndpoint = endpointURL; - } - - public MuscleWSSoapBindingStub(javax.xml.rpc.Service service) - throws org.apache.axis.AxisFault { - if (service == null) { - super.service = new org.apache.axis.client.Service(); - } else { - super.service = service; - } - - java.lang.Class cls; - javax.xml.namespace.QName qName; - java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class; - java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class; - //java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class; - //java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class; - java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class; - java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class; - //java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class; - // java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class; - //java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class; - //java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class; - qName = new javax.xml.namespace.QName("simple.objects.vamsas", - "Sequence"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.Sequence.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("vamsas", "ArrayOf_tns1_Sequence"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.Sequence[].class; - cachedSerClasses.add(cls); - cachedSerFactories.add(arraysf); - cachedDeserFactories.add(arraydf); - - qName = new javax.xml.namespace.QName("simple.objects.vamsas", - "MsaResult"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.MsaResult.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("simple.objects.vamsas", - "SequenceSet"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.SequenceSet.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("http://simple.objects.vamsas", - "Object"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.Object.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("simple.objects.vamsas", - "Alignment"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.Alignment.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("simple.objects.vamsas", "WsJobId"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.WsJobId.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - - qName = new javax.xml.namespace.QName("vamsas", "ArrayOf_xsd_string"); - cachedSerQNames.add(qName); - cls = java.lang.String[].class; - cachedSerClasses.add(cls); - cachedSerFactories.add(arraysf); - cachedDeserFactories.add(arraydf); - - qName = new javax.xml.namespace.QName("simple.objects.vamsas", "Result"); - cachedSerQNames.add(qName); - cls = vamsas.objects.simple.Result.class; - cachedSerClasses.add(cls); - cachedSerFactories.add(beansf); - cachedDeserFactories.add(beandf); - } - - private static void _initOperationDesc1() { - org.apache.axis.description.OperationDesc oper; - oper = new org.apache.axis.description.OperationDesc(); - oper.setName("align"); - oper.addParameter(new javax.xml.namespace.QName("", "seqSet"), - new javax.xml.namespace.QName("simple.objects.vamsas", "SequenceSet"), - vamsas.objects.simple.SequenceSet.class, - org.apache.axis.description.ParameterDesc.IN, false, false); - oper.setReturnType(new javax.xml.namespace.QName( - "simple.objects.vamsas", "WsJobId")); - oper.setReturnClass(vamsas.objects.simple.WsJobId.class); - oper.setReturnQName(new javax.xml.namespace.QName("", "alignReturn")); - oper.setStyle(org.apache.axis.constants.Style.RPC); - oper.setUse(org.apache.axis.constants.Use.ENCODED); - _operations[0] = oper; - - oper = new org.apache.axis.description.OperationDesc(); - oper.setName("getalign"); - oper.addParameter(new javax.xml.namespace.QName("", "job_id"), - new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", - "string"), java.lang.String.class, - org.apache.axis.description.ParameterDesc.IN, false, false); - oper.setReturnType(new javax.xml.namespace.QName( - "simple.objects.vamsas", "Alignment")); - oper.setReturnClass(vamsas.objects.simple.Alignment.class); - oper.setReturnQName(new javax.xml.namespace.QName("", "getalignReturn")); - oper.setStyle(org.apache.axis.constants.Style.RPC); - oper.setUse(org.apache.axis.constants.Use.ENCODED); - _operations[1] = oper; - - oper = new org.apache.axis.description.OperationDesc(); - oper.setName("getResult"); - oper.addParameter(new javax.xml.namespace.QName("", "job_id"), - new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", - "string"), java.lang.String.class, - org.apache.axis.description.ParameterDesc.IN, false, false); - oper.setReturnType(new javax.xml.namespace.QName( - "simple.objects.vamsas", "MsaResult")); - oper.setReturnClass(vamsas.objects.simple.MsaResult.class); - oper.setReturnQName(new javax.xml.namespace.QName("", "getResultReturn")); - oper.setStyle(org.apache.axis.constants.Style.RPC); - oper.setUse(org.apache.axis.constants.Use.ENCODED); - _operations[2] = oper; - - oper = new org.apache.axis.description.OperationDesc(); - oper.setName("cancel"); - oper.addParameter(new javax.xml.namespace.QName("", "jobId"), - new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", - "string"), java.lang.String.class, - org.apache.axis.description.ParameterDesc.IN, false, false); - oper.setReturnType(new javax.xml.namespace.QName( - "simple.objects.vamsas", "WsJobId")); - oper.setReturnClass(vamsas.objects.simple.WsJobId.class); - oper.setReturnQName(new javax.xml.namespace.QName("", "cancelReturn")); - oper.setStyle(org.apache.axis.constants.Style.RPC); - oper.setUse(org.apache.axis.constants.Use.ENCODED); - _operations[3] = oper; - } - - protected org.apache.axis.client.Call createCall() - throws java.rmi.RemoteException { - try { - org.apache.axis.client.Call _call = (org.apache.axis.client.Call) super.service.createCall(); - - if (super.maintainSessionSet) { - _call.setMaintainSession(super.maintainSession); - } - - if (super.cachedUsername != null) { - _call.setUsername(super.cachedUsername); - } - - if (super.cachedPassword != null) { - _call.setPassword(super.cachedPassword); - } - - if (super.cachedEndpoint != null) { - _call.setTargetEndpointAddress(super.cachedEndpoint); - } - - if (super.cachedTimeout != null) { - _call.setTimeout(super.cachedTimeout); - } - - if (super.cachedPortName != null) { - _call.setPortName(super.cachedPortName); - } - - java.util.Enumeration keys = super.cachedProperties.keys(); - - while (keys.hasMoreElements()) { - java.lang.String key = (java.lang.String) keys.nextElement(); - _call.setProperty(key, super.cachedProperties.get(key)); - } - - // All the type mapping information is registered - // when the first call is made. - // The type mapping information is actually registered in - // the TypeMappingRegistry of the service, which - // is the reason why registration is only needed for the first call. - synchronized (this) { - if (firstCall()) { - // must set encoding style before registering serializers - _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); - _call.setEncodingStyle(org.apache.axis.Constants.URI_SOAP11_ENC); - - for (int i = 0; i < cachedSerFactories.size(); ++i) { - java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i); - javax.xml.namespace.QName qName = (javax.xml.namespace.QName) cachedSerQNames.get(i); - java.lang.Class sf = (java.lang.Class) cachedSerFactories.get(i); - java.lang.Class df = (java.lang.Class) cachedDeserFactories.get(i); - _call.registerTypeMapping(cls, qName, sf, df, false); - } - } - } - - return _call; - } catch (java.lang.Throwable _t) { - throw new org.apache.axis.AxisFault("Failure trying to get the Call object", - _t); - } - } - - public vamsas.objects.simple.WsJobId align( - vamsas.objects.simple.SequenceSet seqSet) - throws java.rmi.RemoteException { - if (super.cachedEndpoint == null) { - throw new org.apache.axis.NoEndPointException(); - } - - org.apache.axis.client.Call _call = createCall(); - _call.setOperation(_operations[0]); - _call.setUseSOAPAction(true); - _call.setSOAPActionURI(""); - _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); - _call.setOperationName(new javax.xml.namespace.QName("vamsas", "align")); - - setRequestHeaders(_call); - setAttachments(_call); - - java.lang.Object _resp = _call.invoke(new java.lang.Object[] { seqSet }); - - if (_resp instanceof java.rmi.RemoteException) { - throw (java.rmi.RemoteException) _resp; - } else { - extractAttachments(_call); - - try { - return (vamsas.objects.simple.WsJobId) _resp; - } catch (java.lang.Exception _exception) { - return (vamsas.objects.simple.WsJobId) org.apache.axis.utils.JavaUtils.convert(_resp, - vamsas.objects.simple.WsJobId.class); - } - } - } - - public vamsas.objects.simple.Alignment getalign(java.lang.String job_id) - throws java.rmi.RemoteException { - if (super.cachedEndpoint == null) { - throw new org.apache.axis.NoEndPointException(); - } - - org.apache.axis.client.Call _call = createCall(); - _call.setOperation(_operations[1]); - _call.setUseSOAPAction(true); - _call.setSOAPActionURI(""); - _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); - _call.setOperationName(new javax.xml.namespace.QName("vamsas", - "getalign")); - - setRequestHeaders(_call); - setAttachments(_call); - - java.lang.Object _resp = _call.invoke(new java.lang.Object[] { job_id }); - - if (_resp instanceof java.rmi.RemoteException) { - throw (java.rmi.RemoteException) _resp; - } else { - extractAttachments(_call); - - try { - return (vamsas.objects.simple.Alignment) _resp; - } catch (java.lang.Exception _exception) { - return (vamsas.objects.simple.Alignment) org.apache.axis.utils.JavaUtils.convert(_resp, - vamsas.objects.simple.Alignment.class); - } - } - } - - public vamsas.objects.simple.MsaResult getResult(java.lang.String job_id) - throws java.rmi.RemoteException { - if (super.cachedEndpoint == null) { - throw new org.apache.axis.NoEndPointException(); - } - - org.apache.axis.client.Call _call = createCall(); - _call.setOperation(_operations[2]); - _call.setUseSOAPAction(true); - _call.setSOAPActionURI(""); - _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); - _call.setOperationName(new javax.xml.namespace.QName("vamsas", - "getResult")); - - setRequestHeaders(_call); - setAttachments(_call); - - java.lang.Object _resp = _call.invoke(new java.lang.Object[] { job_id }); - - if (_resp instanceof java.rmi.RemoteException) { - throw (java.rmi.RemoteException) _resp; - } else { - extractAttachments(_call); - - try { - return (vamsas.objects.simple.MsaResult) _resp; - } catch (java.lang.Exception _exception) { - return (vamsas.objects.simple.MsaResult) org.apache.axis.utils.JavaUtils.convert(_resp, - vamsas.objects.simple.MsaResult.class); - } - } - } - - public vamsas.objects.simple.WsJobId cancel(java.lang.String jobId) - throws java.rmi.RemoteException { - if (super.cachedEndpoint == null) { - throw new org.apache.axis.NoEndPointException(); - } - - org.apache.axis.client.Call _call = createCall(); - _call.setOperation(_operations[3]); - _call.setUseSOAPAction(true); - _call.setSOAPActionURI(""); - _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); - _call.setOperationName(new javax.xml.namespace.QName("vamsas", "cancel")); - - setRequestHeaders(_call); - setAttachments(_call); - - java.lang.Object _resp = _call.invoke(new java.lang.Object[] { jobId }); - - if (_resp instanceof java.rmi.RemoteException) { - throw (java.rmi.RemoteException) _resp; - } else { - extractAttachments(_call); - - try { - return (vamsas.objects.simple.WsJobId) _resp; - } catch (java.lang.Exception _exception) { - return (vamsas.objects.simple.WsJobId) org.apache.axis.utils.JavaUtils.convert(_resp, - vamsas.objects.simple.WsJobId.class); - } - } - } -} +*/ +package ext.vamsas; + +public class MuscleWSSoapBindingStub extends org.apache.axis.client.Stub + implements ext.vamsas.MuscleWS { + static org.apache.axis.description.OperationDesc[] _operations; + + static { + _operations = new org.apache.axis.description.OperationDesc[4]; + _initOperationDesc1(); + } + + private java.util.Vector cachedSerClasses = new java.util.Vector(); + private java.util.Vector cachedSerQNames = new java.util.Vector(); + private java.util.Vector cachedSerFactories = new java.util.Vector(); + private java.util.Vector cachedDeserFactories = new java.util.Vector(); + + public MuscleWSSoapBindingStub() throws org.apache.axis.AxisFault { + this(null); + } + + public MuscleWSSoapBindingStub(java.net.URL endpointURL, + javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { + this(service); + super.cachedEndpoint = endpointURL; + } + + public MuscleWSSoapBindingStub(javax.xml.rpc.Service service) + throws org.apache.axis.AxisFault { + if (service == null) { + super.service = new org.apache.axis.client.Service(); + } else { + super.service = service; + } + + java.lang.Class cls; + javax.xml.namespace.QName qName; + java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class; + java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class; + //java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class; + //java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class; + java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class; + java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class; + //java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class; + // java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class; + //java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class; + //java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class; + qName = new javax.xml.namespace.QName("simple.objects.vamsas", + "Sequence"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.Sequence.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("vamsas", "ArrayOf_tns1_Sequence"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.Sequence[].class; + cachedSerClasses.add(cls); + cachedSerFactories.add(arraysf); + cachedDeserFactories.add(arraydf); + + qName = new javax.xml.namespace.QName("simple.objects.vamsas", + "MsaResult"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.MsaResult.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("simple.objects.vamsas", + "SequenceSet"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.SequenceSet.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("http://simple.objects.vamsas", + "Object"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.Object.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("simple.objects.vamsas", + "Alignment"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.Alignment.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("simple.objects.vamsas", "WsJobId"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.WsJobId.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + + qName = new javax.xml.namespace.QName("vamsas", "ArrayOf_xsd_string"); + cachedSerQNames.add(qName); + cls = java.lang.String[].class; + cachedSerClasses.add(cls); + cachedSerFactories.add(arraysf); + cachedDeserFactories.add(arraydf); + + qName = new javax.xml.namespace.QName("simple.objects.vamsas", "Result"); + cachedSerQNames.add(qName); + cls = vamsas.objects.simple.Result.class; + cachedSerClasses.add(cls); + cachedSerFactories.add(beansf); + cachedDeserFactories.add(beandf); + } + + private static void _initOperationDesc1() { + org.apache.axis.description.OperationDesc oper; + oper = new org.apache.axis.description.OperationDesc(); + oper.setName("align"); + oper.addParameter(new javax.xml.namespace.QName("", "seqSet"), + new javax.xml.namespace.QName("simple.objects.vamsas", "SequenceSet"), + vamsas.objects.simple.SequenceSet.class, + org.apache.axis.description.ParameterDesc.IN, false, false); + oper.setReturnType(new javax.xml.namespace.QName( + "simple.objects.vamsas", "WsJobId")); + oper.setReturnClass(vamsas.objects.simple.WsJobId.class); + oper.setReturnQName(new javax.xml.namespace.QName("", "alignReturn")); + oper.setStyle(org.apache.axis.constants.Style.RPC); + oper.setUse(org.apache.axis.constants.Use.ENCODED); + _operations[0] = oper; + + oper = new org.apache.axis.description.OperationDesc(); + oper.setName("getalign"); + oper.addParameter(new javax.xml.namespace.QName("", "job_id"), + new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", + "string"), java.lang.String.class, + org.apache.axis.description.ParameterDesc.IN, false, false); + oper.setReturnType(new javax.xml.namespace.QName( + "simple.objects.vamsas", "Alignment")); + oper.setReturnClass(vamsas.objects.simple.Alignment.class); + oper.setReturnQName(new javax.xml.namespace.QName("", "getalignReturn")); + oper.setStyle(org.apache.axis.constants.Style.RPC); + oper.setUse(org.apache.axis.constants.Use.ENCODED); + _operations[1] = oper; + + oper = new org.apache.axis.description.OperationDesc(); + oper.setName("getResult"); + oper.addParameter(new javax.xml.namespace.QName("", "job_id"), + new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", + "string"), java.lang.String.class, + org.apache.axis.description.ParameterDesc.IN, false, false); + oper.setReturnType(new javax.xml.namespace.QName( + "simple.objects.vamsas", "MsaResult")); + oper.setReturnClass(vamsas.objects.simple.MsaResult.class); + oper.setReturnQName(new javax.xml.namespace.QName("", "getResultReturn")); + oper.setStyle(org.apache.axis.constants.Style.RPC); + oper.setUse(org.apache.axis.constants.Use.ENCODED); + _operations[2] = oper; + + oper = new org.apache.axis.description.OperationDesc(); + oper.setName("cancel"); + oper.addParameter(new javax.xml.namespace.QName("", "jobId"), + new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", + "string"), java.lang.String.class, + org.apache.axis.description.ParameterDesc.IN, false, false); + oper.setReturnType(new javax.xml.namespace.QName( + "simple.objects.vamsas", "WsJobId")); + oper.setReturnClass(vamsas.objects.simple.WsJobId.class); + oper.setReturnQName(new javax.xml.namespace.QName("", "cancelReturn")); + oper.setStyle(org.apache.axis.constants.Style.RPC); + oper.setUse(org.apache.axis.constants.Use.ENCODED); + _operations[3] = oper; + } + + protected org.apache.axis.client.Call createCall() + throws java.rmi.RemoteException { + try { + org.apache.axis.client.Call _call = (org.apache.axis.client.Call) super.service.createCall(); + + if (super.maintainSessionSet) { + _call.setMaintainSession(super.maintainSession); + } + + if (super.cachedUsername != null) { + _call.setUsername(super.cachedUsername); + } + + if (super.cachedPassword != null) { + _call.setPassword(super.cachedPassword); + } + + if (super.cachedEndpoint != null) { + _call.setTargetEndpointAddress(super.cachedEndpoint); + } + + if (super.cachedTimeout != null) { + _call.setTimeout(super.cachedTimeout); + } + + if (super.cachedPortName != null) { + _call.setPortName(super.cachedPortName); + } + + java.util.Enumeration keys = super.cachedProperties.keys(); + + while (keys.hasMoreElements()) { + java.lang.String key = (java.lang.String) keys.nextElement(); + _call.setProperty(key, super.cachedProperties.get(key)); + } + + // All the type mapping information is registered + // when the first call is made. + // The type mapping information is actually registered in + // the TypeMappingRegistry of the service, which + // is the reason why registration is only needed for the first call. + synchronized (this) { + if (firstCall()) { + // must set encoding style before registering serializers + _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); + _call.setEncodingStyle(org.apache.axis.Constants.URI_SOAP11_ENC); + + for (int i = 0; i < cachedSerFactories.size(); ++i) { + java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i); + javax.xml.namespace.QName qName = (javax.xml.namespace.QName) cachedSerQNames.get(i); + java.lang.Class sf = (java.lang.Class) cachedSerFactories.get(i); + java.lang.Class df = (java.lang.Class) cachedDeserFactories.get(i); + _call.registerTypeMapping(cls, qName, sf, df, false); + } + } + } + + return _call; + } catch (java.lang.Throwable _t) { + throw new org.apache.axis.AxisFault("Failure trying to get the Call object", + _t); + } + } + + public vamsas.objects.simple.WsJobId align( + vamsas.objects.simple.SequenceSet seqSet) + throws java.rmi.RemoteException { + if (super.cachedEndpoint == null) { + throw new org.apache.axis.NoEndPointException(); + } + + org.apache.axis.client.Call _call = createCall(); + _call.setOperation(_operations[0]); + _call.setUseSOAPAction(true); + _call.setSOAPActionURI(""); + _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); + _call.setOperationName(new javax.xml.namespace.QName("vamsas", "align")); + + setRequestHeaders(_call); + setAttachments(_call); + + java.lang.Object _resp = _call.invoke(new java.lang.Object[] { seqSet }); + + if (_resp instanceof java.rmi.RemoteException) { + throw (java.rmi.RemoteException) _resp; + } else { + extractAttachments(_call); + + try { + return (vamsas.objects.simple.WsJobId) _resp; + } catch (java.lang.Exception _exception) { + return (vamsas.objects.simple.WsJobId) org.apache.axis.utils.JavaUtils.convert(_resp, + vamsas.objects.simple.WsJobId.class); + } + } + } + + public vamsas.objects.simple.Alignment getalign(java.lang.String job_id) + throws java.rmi.RemoteException { + if (super.cachedEndpoint == null) { + throw new org.apache.axis.NoEndPointException(); + } + + org.apache.axis.client.Call _call = createCall(); + _call.setOperation(_operations[1]); + _call.setUseSOAPAction(true); + _call.setSOAPActionURI(""); + _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); + _call.setOperationName(new javax.xml.namespace.QName("vamsas", + "getalign")); + + setRequestHeaders(_call); + setAttachments(_call); + + java.lang.Object _resp = _call.invoke(new java.lang.Object[] { job_id }); + + if (_resp instanceof java.rmi.RemoteException) { + throw (java.rmi.RemoteException) _resp; + } else { + extractAttachments(_call); + + try { + return (vamsas.objects.simple.Alignment) _resp; + } catch (java.lang.Exception _exception) { + return (vamsas.objects.simple.Alignment) org.apache.axis.utils.JavaUtils.convert(_resp, + vamsas.objects.simple.Alignment.class); + } + } + } + + public vamsas.objects.simple.MsaResult getResult(java.lang.String job_id) + throws java.rmi.RemoteException { + if (super.cachedEndpoint == null) { + throw new org.apache.axis.NoEndPointException(); + } + + org.apache.axis.client.Call _call = createCall(); + _call.setOperation(_operations[2]); + _call.setUseSOAPAction(true); + _call.setSOAPActionURI(""); + _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); + _call.setOperationName(new javax.xml.namespace.QName("vamsas", + "getResult")); + + setRequestHeaders(_call); + setAttachments(_call); + + java.lang.Object _resp = _call.invoke(new java.lang.Object[] { job_id }); + + if (_resp instanceof java.rmi.RemoteException) { + throw (java.rmi.RemoteException) _resp; + } else { + extractAttachments(_call); + + try { + return (vamsas.objects.simple.MsaResult) _resp; + } catch (java.lang.Exception _exception) { + return (vamsas.objects.simple.MsaResult) org.apache.axis.utils.JavaUtils.convert(_resp, + vamsas.objects.simple.MsaResult.class); + } + } + } + + public vamsas.objects.simple.WsJobId cancel(java.lang.String jobId) + throws java.rmi.RemoteException { + if (super.cachedEndpoint == null) { + throw new org.apache.axis.NoEndPointException(); + } + + org.apache.axis.client.Call _call = createCall(); + _call.setOperation(_operations[3]); + _call.setUseSOAPAction(true); + _call.setSOAPActionURI(""); + _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); + _call.setOperationName(new javax.xml.namespace.QName("vamsas", "cancel")); + + setRequestHeaders(_call); + setAttachments(_call); + + java.lang.Object _resp = _call.invoke(new java.lang.Object[] { jobId }); + + if (_resp instanceof java.rmi.RemoteException) { + throw (java.rmi.RemoteException) _resp; + } else { + extractAttachments(_call); + + try { + return (vamsas.objects.simple.WsJobId) _resp; + } catch (java.lang.Exception _exception) { + return (vamsas.objects.simple.WsJobId) org.apache.axis.utils.JavaUtils.convert(_resp, + vamsas.objects.simple.WsJobId.class); + } + } + } +} diff --git a/src/jalview/analysis/AAFrequency.java b/src/jalview/analysis/AAFrequency.java index ad1fe4e..1f43788 100755 --- a/src/jalview/analysis/AAFrequency.java +++ b/src/jalview/analysis/AAFrequency.java @@ -1,139 +1,139 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package jalview.analysis; - -import jalview.datamodel.*; - -import java.util.*; - - -/** - * Takes in a vector of sequences and column start and column end - * and returns a vector of size (end-start+1). Each element of the - * vector contains a hashtable with the keys being residues and - * the values being the count of each residue in that column. - * This class is used extensively in calculating alignment colourschemes - * that depend on the amount of conservation in each alignment column. - * @author $author$ - * @version $Revision$ - */ -public class AAFrequency -{ - /** Takes in a vector of sequences and column start and column end - * and returns a vector of size (end-start+1). Each element of the - * vector contains a hashtable with the keys being residues and - * the values being the count of each residue in that column. - * This class is used extensively in calculating alignment colourschemes - * that depend on the amount of conservation in each alignment column. */ - public static final Vector calculate(Vector sequences, int start, int end) - { - Vector result = new Vector(); - Hashtable residueHash; - int count, maxCount, nongap, i, j, jSize = sequences.size(); - String maxResidue, sequence, res; - float percentage; - - for (i = start; i <= end; i++) - { - residueHash = new Hashtable(); - maxCount = 0; - maxResidue = "-"; - nongap = 0; - - for (j = 0; j < jSize; j++) - { - if (sequences.elementAt(j) instanceof Sequence) - { - sequence = ((Sequence) sequences.elementAt(j)).getSequence(); - - if (sequence.length() > i) - { - res = String.valueOf(Character.toUpperCase(sequence.charAt(i))); - - if (jalview.util.Comparison.isGap(res.charAt(0))) - { - res = "-"; // we always use this for gaps in the property vectors - } - else - { nongap++; } - - if (residueHash.containsKey(res)) - { - count = ((Integer) residueHash.get(res)).intValue(); - count++; - - if (!jalview.util.Comparison.isGap(res.charAt(0)) && - (count >= maxCount)) - { - if (count > maxCount) - { - maxResidue = res; - } - else if (maxResidue.indexOf(res) == -1) - { - maxResidue += res; - } - - maxCount = count; - } - - residueHash.put(res, new Integer(count)); - } - else - { - residueHash.put(res, new Integer(1)); - } - } - else - { - if (residueHash.containsKey("-")) - { - count = ((Integer) residueHash.get("-")).intValue(); - count++; - residueHash.put("-", new Integer(count)); - } - else - { - residueHash.put("-", new Integer(1)); - } - } - } - } - - residueHash.put("maxCount", new Integer(maxCount)); - residueHash.put("maxResidue", maxResidue); - - - //Size is redundant at present if we calculate percentage here - //residueHash.put("size", new Integer(jSize)); - //residueHash.put("nogaps", new Integer(nongap)); - - percentage = ((float)maxCount*100) / (float)jSize; - residueHash.put("pid_gaps", new Float(percentage) ); - - percentage = ((float)maxCount*100) / (float)nongap; - residueHash.put("pid_nogaps", new Float(percentage) ); - result.addElement(residueHash); - } - - - - return result; - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package jalview.analysis; + +import jalview.datamodel.*; + +import java.util.*; + + +/** + * Takes in a vector of sequences and column start and column end + * and returns a vector of size (end-start+1). Each element of the + * vector contains a hashtable with the keys being residues and + * the values being the count of each residue in that column. + * This class is used extensively in calculating alignment colourschemes + * that depend on the amount of conservation in each alignment column. + * @author $author$ + * @version $Revision$ + */ +public class AAFrequency +{ + /** Takes in a vector of sequences and column start and column end + * and returns a vector of size (end-start+1). Each element of the + * vector contains a hashtable with the keys being residues and + * the values being the count of each residue in that column. + * This class is used extensively in calculating alignment colourschemes + * that depend on the amount of conservation in each alignment column. */ + public static final Vector calculate(Vector sequences, int start, int end) + { + Vector result = new Vector(); + Hashtable residueHash; + int count, maxCount, nongap, i, j, jSize = sequences.size(); + String maxResidue, sequence, res; + float percentage; + + for (i = start; i <= end; i++) + { + residueHash = new Hashtable(); + maxCount = 0; + maxResidue = "-"; + nongap = 0; + + for (j = 0; j < jSize; j++) + { + if (sequences.elementAt(j) instanceof Sequence) + { + sequence = ((Sequence) sequences.elementAt(j)).getSequence(); + + if (sequence.length() > i) + { + res = String.valueOf(Character.toUpperCase(sequence.charAt(i))); + + if (jalview.util.Comparison.isGap(res.charAt(0))) + { + res = "-"; // we always use this for gaps in the property vectors + } + else + { nongap++; } + + if (residueHash.containsKey(res)) + { + count = ((Integer) residueHash.get(res)).intValue(); + count++; + + if (!jalview.util.Comparison.isGap(res.charAt(0)) && + (count >= maxCount)) + { + if (count > maxCount) + { + maxResidue = res; + } + else if (maxResidue.indexOf(res) == -1) + { + maxResidue += res; + } + + maxCount = count; + } + + residueHash.put(res, new Integer(count)); + } + else + { + residueHash.put(res, new Integer(1)); + } + } + else + { + if (residueHash.containsKey("-")) + { + count = ((Integer) residueHash.get("-")).intValue(); + count++; + residueHash.put("-", new Integer(count)); + } + else + { + residueHash.put("-", new Integer(1)); + } + } + } + } + + residueHash.put("maxCount", new Integer(maxCount)); + residueHash.put("maxResidue", maxResidue); + + + //Size is redundant at present if we calculate percentage here + //residueHash.put("size", new Integer(jSize)); + //residueHash.put("nogaps", new Integer(nongap)); + + percentage = ((float)maxCount*100) / (float)jSize; + residueHash.put("pid_gaps", new Float(percentage) ); + + percentage = ((float)maxCount*100) / (float)nongap; + residueHash.put("pid_nogaps", new Float(percentage) ); + result.addElement(residueHash); + } + + + + return result; + } +} diff --git a/src/jalview/analysis/AlignSeq.java b/src/jalview/analysis/AlignSeq.java index 401ad01..f743dd2 100755 --- a/src/jalview/analysis/AlignSeq.java +++ b/src/jalview/analysis/AlignSeq.java @@ -1,811 +1,837 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package jalview.analysis; - -import jalview.datamodel.SequenceI; - -import jalview.schemes.*; - -import jalview.util.*; - -import java.awt.*; - -import java.util.*; - - -/** - * - * - * @author $author$ - * @version $Revision$ - */ -public class AlignSeq -{ - /** DOCUMENT ME!! */ - public static java.util.Hashtable dnaHash = new java.util.Hashtable(); - - static - { - dnaHash.put("C", new Integer(0)); - dnaHash.put("T", new Integer(1)); - dnaHash.put("A", new Integer(2)); - dnaHash.put("G", new Integer(3)); - dnaHash.put("-", new Integer(4)); - } - - static String[] dna = { "C", "T", "A", "G", "-" }; - static String[] pep = - { - "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", - "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" - }; - int[][] score; - int[][] E; - int[][] F; - int[][] traceback; - int[] seq1; - int[] seq2; - SequenceI s1; - SequenceI s2; - String s1str; - String s2str; - int maxi; - int maxj; - int[] aseq1; - int[] aseq2; - public String astr1 = ""; - public String astr2 = ""; - - /** DOCUMENT ME!! */ - public int seq1start; - - /** DOCUMENT ME!! */ - public int seq1end; - - /** DOCUMENT ME!! */ - public int seq2start; - - /** DOCUMENT ME!! */ - public int seq2end; - int count; - - /** DOCUMENT ME!! */ - public int maxscore; - float pid; - int prev = 0; - int gapOpen = 120; - int gapExtend = 20; - int[][] lookup = ResidueProperties.getBLOSUM62(); - String[] intToStr = pep; - int defInt = 23; - StringBuffer output = new StringBuffer(); - String type; - Runtime rt; - - - /** - * Creates a new AlignSeq object. - * - * @param s1 DOCUMENT ME! - * @param s2 DOCUMENT ME! - * @param type DOCUMENT ME! - */ - public AlignSeq(SequenceI s1, SequenceI s2, String type) - { - rt = Runtime.getRuntime(); - SeqInit(s1, s2, type); - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int getMaxScore() - { - return maxscore; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int getSeq2Start() - { - return seq2start; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int getSeq2End() - { - return seq2end; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int getSeq1Start() - { - return seq1start; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int getSeq1End() - { - return seq1end; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public String getOutput() - { - return output.toString(); - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public String getAStr1() - { - return astr1; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public String getAStr2() - { - return astr2; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int[] getASeq1() - { - return aseq1; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int[] getASeq2() - { - return aseq2; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public SequenceI getS1() - { - return s1; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public SequenceI getS2() - { - return s2; - } - - /** - * DOCUMENT ME! - * - * @param s1 DOCUMENT ME! - * @param s2 DOCUMENT ME! - * @param type DOCUMENT ME! - */ - public void SeqInit(SequenceI s1, SequenceI s2, String type) - { - s1str = extractGaps(jalview.util.Comparison.GapChars, s1.getSequence()); - s2str = extractGaps(jalview.util.Comparison.GapChars, s2.getSequence()); - - this.s1 = s1; - this.s2 = s2; - - this.type = type; - - if (type.equals("pep")) - { - lookup = ResidueProperties.getBLOSUM62(); - intToStr = pep; - defInt = 23; - } - else if (type.equals("dna")) - { - lookup = ResidueProperties.getDNA(); - intToStr = dna; - defInt = 4; - } - else - { - output.append("Wrong type = dna or pep only"); - System.exit(0); - } - - //System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory()); - seq1 = new int[s1str.length()]; - - //System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory()); - seq2 = new int[s2str.length()]; - - //System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory()); - score = new int[s1str.length()][s2str.length()]; - - //System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory()); - E = new int[s1str.length()][s2str.length()]; - - //System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory()); - F = new int[s1str.length()][s2str.length()]; - traceback = new int[s1str.length()][s2str.length()]; - - //System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory()); - seq1 = stringToInt(s1str, type); - - //System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory()); - seq2 = stringToInt(s2str, type); - - //System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory()); - // long tstart = System.currentTimeMillis(); - // calcScoreMatrix(); - //long tend = System.currentTimeMillis(); - //System.out.println("Time take to calculate score matrix = " + (tend-tstart) + " ms"); - // printScoreMatrix(score); - //System.out.println(); - //printScoreMatrix(traceback); - //System.out.println(); - // printScoreMatrix(E); - //System.out.println(); - ///printScoreMatrix(F); - //System.out.println(); - // tstart = System.currentTimeMillis(); - //traceAlignment(); - //tend = System.currentTimeMillis(); - //System.out.println("Time take to traceback alignment = " + (tend-tstart) + " ms"); - } - - /** - * DOCUMENT ME! - */ - public void traceAlignment() - { - // Find the maximum score along the rhs or bottom row - int max = -9999; - - for (int i = 0; i < seq1.length; i++) - { - if (score[i][seq2.length - 1] > max) - { - max = score[i][seq2.length - 1]; - maxi = i; - maxj = seq2.length - 1; - } - } - - for (int j = 0; j < seq2.length; j++) - { - if (score[seq1.length - 1][j] > max) - { - max = score[seq1.length - 1][j]; - maxi = seq1.length - 1; - maxj = j; - } - } - - // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]); - int i = maxi; - int j = maxj; - int trace; - maxscore = score[i][j] / 10; - - seq1end = maxi + 1; - seq2end = maxj + 1; - - aseq1 = new int[seq1.length + seq2.length]; - aseq2 = new int[seq1.length + seq2.length]; - - count = (seq1.length + seq2.length) - 1; - - while ((i > 0) && (j > 0)) - { - if ((aseq1[count] != defInt) && (i >= 0)) - { - aseq1[count] = seq1[i]; - astr1 = intToStr[seq1[i]] + astr1; - } - - if ((aseq2[count] != defInt) && (j > 0)) - { - aseq2[count] = seq2[j]; - astr2 = intToStr[seq2[j]] + astr2; - } - - trace = findTrace(i, j); - - if (trace == 0) - { - i--; - j--; - } - else if (trace == 1) - { - j--; - aseq1[count] = defInt; - astr1 = "-" + astr1.substring(1); - } - else if (trace == -1) - { - i--; - aseq2[count] = defInt; - astr2 = "-" + astr2.substring(1); - } - - count--; - } - - seq1start = i + 1; - seq2start = j + 1; - - if (aseq1[count] != defInt) - { - aseq1[count] = seq1[i]; - astr1 = intToStr[seq1[i]] + astr1; - } - - if (aseq2[count] != defInt) - { - aseq2[count] = seq2[j]; - astr2 = intToStr[seq2[j]] + astr2; - } - } - - /** - * DOCUMENT ME! - */ - public void printAlignment(java.io.PrintStream os) - { - // Find the biggest id length for formatting purposes - int maxid = s1.getName().length(); - - if (s2.getName().length() > maxid) - { - maxid = s2.getName().length(); - } - - int len = 72 - maxid - 1; - int nochunks = ((aseq1.length - count) / len) + 1; - pid = 0; - - output.append("Score = " + score[maxi][maxj] + "\n"); - output.append("Length of alignment = " + (aseq1.length - count) + "\n"); - output.append("Sequence "); - output.append(new Format("%" + maxid + "s").form(s1.getName())); - output.append(" : " + seq1start + " - " + seq1end + " (Sequence length = " + - s1str.length() + ")\n"); - output .append("Sequence "); - output.append(new Format("%" + maxid + "s").form(s2.getName())); - output .append(" : " + seq2start + " - " + seq2end + " (Sequence length = " + - s2str.length() + ")\n\n"); - - for (int j = 0; j < nochunks; j++) - { - // Print the first aligned sequence - output.append(new Format("%" + (maxid) + "s").form(s1.getName()) + " "); - - for (int i = 0; i < len; i++) - { - if ((count + i + (j * len)) < aseq1.length) - { - output.append(new Format("%s").form(intToStr[aseq1[count + i + - (j * len)]])); - } - } - - output.append("\n"); - output.append(new Format("%" + (maxid) + "s").form(" ") + " "); - - // Print out the matching chars - for (int i = 0; i < len; i++) - { - if ((count + i + (j * len)) < aseq1.length) - { - if (intToStr[aseq1[count + i + (j * len)]].equals( - intToStr[aseq2[count + i + (j * len)]]) && - !intToStr[aseq1[count + i + (j * len)]].equals("-")) - { - pid++; - output.append("|"); - } - else if (type.equals("pep")) - { - if (ResidueProperties.getPAM250( - intToStr[aseq1[count + i + (j * len)]], - intToStr[aseq2[count + i + (j * len)]]) > 0) - { - output.append("."); - } - else - { - output.append(" "); - } - } - else - { - output.append(" "); - } - } - } - - // Now print the second aligned sequence - output = output.append("\n"); - output = output.append(new Format("%" + (maxid) + "s").form(s2.getName()) + " "); - - for (int i = 0; i < len; i++) - { - if ((count + i + (j * len)) < aseq1.length) - { - output .append(new Format("%s").form(intToStr[aseq2[count + i + - (j * len)]])); - } - } - - output = output .append("\n\n"); - } - - pid = pid / (float) (aseq1.length - count) * 100; - output = output.append(new Format("Percentage ID = %2.2f\n\n").form(pid)); - - try{ - os.print(output.toString()); - }catch(Exception ex){} - } - - /** - * DOCUMENT ME! - * - * @param mat DOCUMENT ME! - */ - public void printScoreMatrix(int[][] mat) - { - int n = seq1.length; - int m = seq2.length; - - for (int i = 0; i < n; i++) - { - // Print the top sequence - if (i == 0) - { - Format.print(System.out, "%8s", s2str.substring(0, 1)); - - for (int jj = 1; jj < m; jj++) - { - Format.print(System.out, "%5s", s2str.substring(jj, jj + 1)); - } - - System.out.println(); - } - - for (int j = 0; j < m; j++) - { - if (j == 0) - { - Format.print(System.out, "%3s", s1str.substring(i, i + 1)); - } - - Format.print(System.out, "%3d ", mat[i][j] / 10); - } - - System.out.println(); - } - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - * @param j DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int findTrace(int i, int j) - { - int t = 0; - int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10); - - if (F[i][j] > max) - { - max = F[i][j]; - t = -1; - } - else if (F[i][j] == max) - { - if (prev == -1) - { - max = F[i][j]; - t = -1; - } - } - - if (E[i][j] >= max) - { - max = E[i][j]; - t = 1; - } - else if (E[i][j] == max) - { - if (prev == 1) - { - max = E[i][j]; - t = 1; - } - } - - prev = t; - - return t; - } - - /** - * DOCUMENT ME! - */ - public void calcScoreMatrix() - { - int n = seq1.length; - int m = seq2.length; - - // top left hand element - score[0][0] = lookup[seq1[0]][seq2[0]] * 10; - E[0][0] = -gapExtend; - F[0][0] = 0; - - // Calculate the top row first - for (int j = 1; j < m; j++) - { - // What should these values be? 0 maybe - E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend); - F[0][j] = -gapExtend; - - score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, - -gapExtend); - - traceback[0][j] = 1; - } - - // Now do the left hand column - for (int i = 1; i < n; i++) - { - E[i][0] = -gapOpen; - F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend); - - score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]); - traceback[i][0] = -1; - } - - // Now do all the other rows - for (int i = 1; i < n; i++) - { - for (int j = 1; j < m; j++) - { - E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - - gapExtend); - F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - - gapExtend); - - score[i][j] = max(score[i - 1][j - 1] + - (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]); - traceback[i][j] = findTrace(i, j); - } - } - } - - - - /** - * DOCUMENT ME! - * - * @param gapChar DOCUMENT ME! - * @param seq DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public static String extractGaps(String gapChar, String seq) - { - StringTokenizer str = new StringTokenizer(seq, gapChar); - StringBuffer newString = new StringBuffer(); - - while (str.hasMoreTokens()) - { - newString.append( str.nextToken() ); - } - - return newString.toString(); - } - - /** - * DOCUMENT ME! - * - * @param i1 DOCUMENT ME! - * @param i2 DOCUMENT ME! - * @param i3 DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int max(int i1, int i2, int i3) - { - int max = i1; - - if (i2 > i1) - { - max = i2; - } - - if (i3 > max) - { - max = i3; - } - - return max; - } - - /** - * DOCUMENT ME! - * - * @param i1 DOCUMENT ME! - * @param i2 DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int max(int i1, int i2) - { - int max = i1; - - if (i2 > i1) - { - max = i2; - } - - return max; - } - - /** - * DOCUMENT ME! - * - * @param s DOCUMENT ME! - * @param type DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public int[] stringToInt(String s, String type) - { - int[] seq1 = new int[s.length()]; - - for (int i = 0; i < s.length(); i++) - { - String ss = s.substring(i, i + 1).toUpperCase(); - - try - { - if (type.equals("pep")) - { - seq1[i] = ((Integer) ResidueProperties.aaHash.get(ss)).intValue(); - } - else if (type.equals("dna")) - { - seq1[i] = ((Integer) dnaHash.get(ss)).intValue(); - } - - if (seq1[i] > 23) - { - seq1[i] = 23; - } - } - catch (Exception e) - { - if (type.equals("dna")) - { - seq1[i] = 4; - } - else - { - seq1[i] = 23; - } - } - } - - return seq1; - } - - /** - * DOCUMENT ME! - * - * @param g DOCUMENT ME! - * @param mat DOCUMENT ME! - * @param n DOCUMENT ME! - * @param m DOCUMENT ME! - * @param psize DOCUMENT ME! - */ - public static void displayMatrix(Graphics g, int[][] mat, int n, int m, - int psize) - { - int max = -1000; - int min = 1000; - - for (int i = 0; i < n; i++) - { - for (int j = 0; j < m; j++) - { - if (mat[i][j] >= max) - { - max = mat[i][j]; - } - - if (mat[i][j] <= min) - { - min = mat[i][j]; - } - } - } - - System.out.println(max + " " + min); - - for (int i = 0; i < n; i++) - { - for (int j = 0; j < m; j++) - { - int x = psize * i; - int y = psize * j; - - // System.out.println(mat[i][j]); - float score = (float) (mat[i][j] - min) / (float) (max - min); - g.setColor(new Color(score, 0, 0)); - g.fillRect(x, y, psize, psize); - - // System.out.println(x + " " + y + " " + score); - } - } - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package jalview.analysis; + +import jalview.datamodel.SequenceI; + +import jalview.schemes.*; + +import jalview.util.*; + +import java.awt.*; + +import java.util.*; + + +/** + * + * + * @author $author$ + * @version $Revision$ + */ +public class AlignSeq +{ + /** DOCUMENT ME!! */ + public static java.util.Hashtable dnaHash = new java.util.Hashtable(); + + static + { + dnaHash.put("C", new Integer(0)); + dnaHash.put("T", new Integer(1)); + dnaHash.put("A", new Integer(2)); + dnaHash.put("G", new Integer(3)); + dnaHash.put("-", new Integer(4)); + } + + static String[] dna = { "C", "T", "A", "G", "-" }; + static String[] pep = + { + "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", + "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" + }; + int[][] score; + int[][] E; + int[][] F; + int[][] traceback; + int[] seq1; + int[] seq2; + SequenceI s1; + SequenceI s2; + public String s1str; + public String s2str; + int maxi; + int maxj; + int[] aseq1; + int[] aseq2; + public String astr1=""; + public String astr2=""; + + /** DOCUMENT ME!! */ + public int seq1start; + + /** DOCUMENT ME!! */ + public int seq1end; + + /** DOCUMENT ME!! */ + public int seq2start; + + /** DOCUMENT ME!! */ + public int seq2end; + int count; + + /** DOCUMENT ME!! */ + public int maxscore; + float pid; + int prev = 0; + int gapOpen = 120; + int gapExtend = 20; + int[][] lookup = ResidueProperties.getBLOSUM62(); + String[] intToStr = pep; + int defInt = 23; + StringBuffer output = new StringBuffer(); + String type; + + /** + * Creates a new AlignSeq object. + * + * @param s1 DOCUMENT ME! + * @param s2 DOCUMENT ME! + * @param type DOCUMENT ME! + */ + public AlignSeq(SequenceI s1, SequenceI s2, String type) + { + SeqInit(s1, s1.getSequence(), s2, s2.getSequence(), type); + } + + /** + * Creates a new AlignSeq object. + * + * @param s1 DOCUMENT ME! + * @param s2 DOCUMENT ME! + * @param type DOCUMENT ME! + */ + public AlignSeq(SequenceI s1, + String string1, + SequenceI s2, + String string2, + String type) + { + SeqInit(s1, string1, s2, string2, type); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getMaxScore() + { + return maxscore; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getSeq2Start() + { + return seq2start; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getSeq2End() + { + return seq2end; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getSeq1Start() + { + return seq1start; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getSeq1End() + { + return seq1end; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getOutput() + { + return output.toString(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getAStr1() + { + return astr1; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getAStr2() + { + return astr2; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int[] getASeq1() + { + return aseq1; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int[] getASeq2() + { + return aseq2; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public SequenceI getS1() + { + return s1; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public SequenceI getS2() + { + return s2; + } + + /** + * DOCUMENT ME! + * + * @param s1 DOCUMENT ME! + * @param s2 DOCUMENT ME! + * @param type DOCUMENT ME! + */ + public void SeqInit(SequenceI s1, + String string1, + SequenceI s2, + String string2, + String type) + { + + s1str = extractGaps(jalview.util.Comparison.GapChars, string1); + s2str = extractGaps(jalview.util.Comparison.GapChars, string2); + + if(s1str.length()==0 || s2str.length()==0) + { + System.out.println("ALL GAPS: " + + (s1str.length()==0?s1.getName():" ") + +(s2str.length()==0?s2.getName():"")); + return; + } + + this.s1 = s1; + this.s2 = s2; + + this.type = type; + + if (type.equals("pep")) + { + lookup = ResidueProperties.getBLOSUM62(); + intToStr = pep; + defInt = 23; + } + else if (type.equals("dna")) + { + lookup = ResidueProperties.getDNA(); + intToStr = dna; + defInt = 4; + } + else + { + output.append("Wrong type = dna or pep only"); + System.exit(0); + } + + //System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory()); + seq1 = new int[s1str.length()]; + + //System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory()); + seq2 = new int[s2str.length()]; + + //System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory()); + score = new int[s1str.length()][s2str.length()]; + + //System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory()); + E = new int[s1str.length()][s2str.length()]; + + //System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory()); + F = new int[s1str.length()][s2str.length()]; + traceback = new int[s1str.length()][s2str.length()]; + + //System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory()); + seq1 = stringToInt(s1str, type); + + //System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory()); + seq2 = stringToInt(s2str, type); + + //System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory()); + // long tstart = System.currentTimeMillis(); + // calcScoreMatrix(); + //long tend = System.currentTimeMillis(); + //System.out.println("Time take to calculate score matrix = " + (tend-tstart) + " ms"); + // printScoreMatrix(score); + //System.out.println(); + //printScoreMatrix(traceback); + //System.out.println(); + // printScoreMatrix(E); + //System.out.println(); + ///printScoreMatrix(F); + //System.out.println(); + // tstart = System.currentTimeMillis(); + //traceAlignment(); + //tend = System.currentTimeMillis(); + //System.out.println("Time take to traceback alignment = " + (tend-tstart) + " ms"); + } + + /** + * DOCUMENT ME! + */ + public void traceAlignment() + { + // Find the maximum score along the rhs or bottom row + int max = -9999; + + for (int i = 0; i < seq1.length; i++) + { + if (score[i][seq2.length - 1] > max) + { + max = score[i][seq2.length - 1]; + maxi = i; + maxj = seq2.length - 1; + } + } + + for (int j = 0; j < seq2.length; j++) + { + if (score[seq1.length - 1][j] > max) + { + max = score[seq1.length - 1][j]; + maxi = seq1.length - 1; + maxj = j; + } + } + + // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]); + int i = maxi; + int j = maxj; + int trace; + maxscore = score[i][j] / 10; + + seq1end = maxi + 1; + seq2end = maxj + 1; + + aseq1 = new int[seq1.length + seq2.length]; + aseq2 = new int[seq1.length + seq2.length]; + + count = (seq1.length + seq2.length) - 1; + + while ((i > 0) && (j > 0)) + { + if ((aseq1[count] != defInt) && (i >= 0)) + { + aseq1[count] = seq1[i]; + astr1 = intToStr[seq1[i]] + astr1; + } + + if ((aseq2[count] != defInt) && (j > 0)) + { + aseq2[count] = seq2[j]; + astr2 = intToStr[seq2[j]] + astr2; + } + + trace = findTrace(i, j); + + if (trace == 0) + { + i--; + j--; + } + else if (trace == 1) + { + j--; + aseq1[count] = defInt; + astr1 = "-" + astr1.substring(1); + } + else if (trace == -1) + { + i--; + aseq2[count] = defInt; + astr2 = "-" + astr2.substring(1); + } + + count--; + } + + seq1start = i + 1; + seq2start = j + 1; + + if (aseq1[count] != defInt) + { + aseq1[count] = seq1[i]; + astr1 = intToStr[seq1[i]] + astr1; + } + + if (aseq2[count] != defInt) + { + aseq2[count] = seq2[j]; + astr2 = intToStr[seq2[j]] + astr2; + } + } + + /** + * DOCUMENT ME! + */ + public void printAlignment(java.io.PrintStream os) + { + // Find the biggest id length for formatting purposes + int maxid = s1.getName().length(); + + if (s2.getName().length() > maxid) + { + maxid = s2.getName().length(); + } + + int len = 72 - maxid - 1; + int nochunks = ((aseq1.length - count) / len) + 1; + pid = 0; + + output.append("Score = " + score[maxi][maxj] + "\n"); + output.append("Length of alignment = " + (aseq1.length - count) + "\n"); + output.append("Sequence "); + output.append(new Format("%" + maxid + "s").form(s1.getName())); + output.append(" : " + s1.getStart() + " - " + s1.getEnd() + " (Sequence length = " + + s1str.length() + ")\n"); + output .append("Sequence "); + output.append(new Format("%" + maxid + "s").form(s2.getName())); + output.append(" : " + s2.getStart() + " - " + s2.getEnd() + " (Sequence length = " + + s2str.length() + ")\n\n"); + + for (int j = 0; j < nochunks; j++) + { + // Print the first aligned sequence + output.append(new Format("%" + (maxid) + "s").form(s1.getName()) + " "); + + for (int i = 0; i < len; i++) + { + if ((count + i + (j * len)) < aseq1.length) + { + output.append(new Format("%s").form(intToStr[aseq1[count + i + + (j * len)]])); + } + } + + output.append("\n"); + output.append(new Format("%" + (maxid) + "s").form(" ") + " "); + + // Print out the matching chars + for (int i = 0; i < len; i++) + { + if ((count + i + (j * len)) < aseq1.length) + { + if (intToStr[aseq1[count + i + (j * len)]].equals( + intToStr[aseq2[count + i + (j * len)]]) && + !intToStr[aseq1[count + i + (j * len)]].equals("-")) + { + pid++; + output.append("|"); + } + else if (type.equals("pep")) + { + if (ResidueProperties.getPAM250( + intToStr[aseq1[count + i + (j * len)]], + intToStr[aseq2[count + i + (j * len)]]) > 0) + { + output.append("."); + } + else + { + output.append(" "); + } + } + else + { + output.append(" "); + } + } + } + + // Now print the second aligned sequence + output = output.append("\n"); + output = output.append(new Format("%" + (maxid) + "s").form(s2.getName()) + " "); + + for (int i = 0; i < len; i++) + { + if ((count + i + (j * len)) < aseq1.length) + { + output .append(new Format("%s").form(intToStr[aseq2[count + i + + (j * len)]])); + } + } + + output = output .append("\n\n"); + } + + pid = pid / (float) (aseq1.length - count) * 100; + output = output.append(new Format("Percentage ID = %2.2f\n\n").form(pid)); + + try{ + os.print(output.toString()); + }catch(Exception ex){} + } + + /** + * DOCUMENT ME! + * + * @param mat DOCUMENT ME! + */ + public void printScoreMatrix(int[][] mat) + { + int n = seq1.length; + int m = seq2.length; + + for (int i = 0; i < n; i++) + { + // Print the top sequence + if (i == 0) + { + Format.print(System.out, "%8s", s2str.substring(0, 1)); + + for (int jj = 1; jj < m; jj++) + { + Format.print(System.out, "%5s", s2str.substring(jj, jj + 1)); + } + + System.out.println(); + } + + for (int j = 0; j < m; j++) + { + if (j == 0) + { + Format.print(System.out, "%3s", s1str.substring(i, i + 1)); + } + + Format.print(System.out, "%3d ", mat[i][j] / 10); + } + + System.out.println(); + } + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + * @param j DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int findTrace(int i, int j) + { + int t = 0; + int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10); + + if (F[i][j] > max) + { + max = F[i][j]; + t = -1; + } + else if (F[i][j] == max) + { + if (prev == -1) + { + max = F[i][j]; + t = -1; + } + } + + if (E[i][j] >= max) + { + max = E[i][j]; + t = 1; + } + else if (E[i][j] == max) + { + if (prev == 1) + { + max = E[i][j]; + t = 1; + } + } + + prev = t; + + return t; + } + + /** + * DOCUMENT ME! + */ + public void calcScoreMatrix() + { + int n = seq1.length; + int m = seq2.length; + + // top left hand element + score[0][0] = lookup[seq1[0]][seq2[0]] * 10; + E[0][0] = -gapExtend; + F[0][0] = 0; + + // Calculate the top row first + for (int j = 1; j < m; j++) + { + // What should these values be? 0 maybe + E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend); + F[0][j] = -gapExtend; + + score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, + -gapExtend); + + traceback[0][j] = 1; + } + + // Now do the left hand column + for (int i = 1; i < n; i++) + { + E[i][0] = -gapOpen; + F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend); + + score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]); + traceback[i][0] = -1; + } + + // Now do all the other rows + for (int i = 1; i < n; i++) + { + for (int j = 1; j < m; j++) + { + E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - + gapExtend); + F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - + gapExtend); + + score[i][j] = max(score[i - 1][j - 1] + + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]); + traceback[i][j] = findTrace(i, j); + } + } + } + + + + /** + * DOCUMENT ME! + * + * @param gapChar DOCUMENT ME! + * @param seq DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public static String extractGaps(String gapChar, String seq) + { + StringTokenizer str = new StringTokenizer(seq, gapChar); + StringBuffer newString = new StringBuffer(); + + while (str.hasMoreTokens()) + { + newString.append( str.nextToken() ); + } + + return newString.toString(); + } + + /** + * DOCUMENT ME! + * + * @param i1 DOCUMENT ME! + * @param i2 DOCUMENT ME! + * @param i3 DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int max(int i1, int i2, int i3) + { + int max = i1; + + if (i2 > i1) + { + max = i2; + } + + if (i3 > max) + { + max = i3; + } + + return max; + } + + /** + * DOCUMENT ME! + * + * @param i1 DOCUMENT ME! + * @param i2 DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int max(int i1, int i2) + { + int max = i1; + + if (i2 > i1) + { + max = i2; + } + + return max; + } + + /** + * DOCUMENT ME! + * + * @param s DOCUMENT ME! + * @param type DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int[] stringToInt(String s, String type) + { + int[] seq1 = new int[s.length()]; + + for (int i = 0; i < s.length(); i++) + { + String ss = s.substring(i, i + 1).toUpperCase(); + + try + { + if (type.equals("pep")) + { + seq1[i] = ((Integer) ResidueProperties.aaHash.get(ss)).intValue(); + } + else if (type.equals("dna")) + { + seq1[i] = ((Integer) dnaHash.get(ss)).intValue(); + } + + if (seq1[i] > 23) + { + seq1[i] = 23; + } + } + catch (Exception e) + { + if (type.equals("dna")) + { + seq1[i] = 4; + } + else + { + seq1[i] = 23; + } + } + } + + return seq1; + } + + /** + * DOCUMENT ME! + * + * @param g DOCUMENT ME! + * @param mat DOCUMENT ME! + * @param n DOCUMENT ME! + * @param m DOCUMENT ME! + * @param psize DOCUMENT ME! + */ + public static void displayMatrix(Graphics g, int[][] mat, int n, int m, + int psize) + { + int max = -1000; + int min = 1000; + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (mat[i][j] >= max) + { + max = mat[i][j]; + } + + if (mat[i][j] <= min) + { + min = mat[i][j]; + } + } + } + + System.out.println(max + " " + min); + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + int x = psize * i; + int y = psize * j; + + // System.out.println(mat[i][j]); + float score = (float) (mat[i][j] - min) / (float) (max - min); + g.setColor(new Color(score, 0, 0)); + g.fillRect(x, y, psize, psize); + + // System.out.println(x + " " + y + " " + score); + } + } + } +} diff --git a/src/jalview/analysis/AlignmentSorter.java b/src/jalview/analysis/AlignmentSorter.java index 20101dc..507d38b 100755 --- a/src/jalview/analysis/AlignmentSorter.java +++ b/src/jalview/analysis/AlignmentSorter.java @@ -1,469 +1,470 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package jalview.analysis; - -import jalview.datamodel.*; - -import jalview.util.*; - -import java.util.*; - - -/** Data structure to hold and manipulate a multiple sequence alignment - */ -public class AlignmentSorter -{ - static boolean sortIdAscending = true; - static int lastGroupHash = 0; - static boolean sortGroupAscending = true; - static AlignmentOrder lastOrder = null; - static boolean sortOrderAscending = true; - static NJTree lastTree = null; - static boolean sortTreeAscending = true; - - /** - * Sort by Percentage Identity - * - * @param align AlignmentI - * @param s SequenceI - */ - public static void sortByPID(AlignmentI align, SequenceI s) - { - int nSeq = align.getHeight(); - - float[] scores = new float[nSeq]; - SequenceI[] seqs = new SequenceI[nSeq]; - - for (int i = 0; i < nSeq; i++) - { - scores[i] = Comparison.PID(align.getSequenceAt(i), s); - seqs[i] = align.getSequenceAt(i); - } - - QuickSort.sort(scores, 0, scores.length - 1, seqs); - - setReverseOrder(align, seqs); - } - - /** - * Reverse the order of the sort - * - * @param align DOCUMENT ME! - * @param seqs DOCUMENT ME! - */ - private static void setReverseOrder(AlignmentI align, SequenceI[] seqs) - { - int nSeq = seqs.length; - - int len = 0; - - if ((nSeq % 2) == 0) - { - len = nSeq / 2; - } - else - { - len = (nSeq + 1) / 2; - } - - // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work - for (int i = 0; i < len; i++) - { - //SequenceI tmp = seqs[i]; - align.getSequences().setElementAt(seqs[nSeq - i - 1], i); - align.getSequences().setElementAt(seqs[i], nSeq - i - 1); - } - } - - /** - * Sets the Alignment object with the given sequences - * - * @param align Alignment object to be updated - * @param tmp sequences as a vector - */ - private static void setOrder(AlignmentI align, Vector tmp) - { - setOrder(align, vectorSubsetToArray(tmp, align.getSequences())); - } - - /** - * Sets the Alignment object with the given sequences - * - * @param align DOCUMENT ME! - * @param seqs sequences as an array - */ - private static void setOrder(AlignmentI align, SequenceI[] seqs) - { - // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work - Vector algn = align.getSequences(); - - for (int i = 0; i < seqs.length; i++) - { - algn.setElementAt(seqs[i], i); - } - } - - /** - * Sorts by ID. Numbers are sorted before letters. - * - * @param align The alignment object to sort - */ - public static void sortByID(AlignmentI align) - { - int nSeq = align.getHeight(); - - String[] ids = new String[nSeq]; - SequenceI[] seqs = new SequenceI[nSeq]; - - for (int i = 0; i < nSeq; i++) - { - ids[i] = align.getSequenceAt(i).getName(); - seqs[i] = align.getSequenceAt(i); - } - - QuickSort.sort(ids, seqs); - - if (sortIdAscending) - { - setReverseOrder(align, seqs); - } - else - { - setOrder(align, seqs); - } - - sortIdAscending = !sortIdAscending; - } - - /** - * Sorts the alignment by size of group. - *
Maintains the order of sequences in each group - * by order in given alignment object. - * - * @param align sorts the given alignment object by group - */ - public static void sortByGroup(AlignmentI align) - { - //MAINTAINS ORIGNAL SEQUENCE ORDER, - //ORDERS BY GROUP SIZE - Vector groups = new Vector(); - - if (groups.hashCode() != lastGroupHash) - { - sortGroupAscending = true; - lastGroupHash = groups.hashCode(); - } - else - { - sortGroupAscending = !sortGroupAscending; - } - - //SORTS GROUPS BY SIZE - ////////////////////// - for (int i = 0; i < align.getGroups().size(); i++) - { - SequenceGroup sg = (SequenceGroup) align.getGroups().elementAt(i); - - for (int j = 0; j < groups.size(); j++) - { - SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j); - - if (sg.getSize() > sg2.getSize()) - { - groups.insertElementAt(sg, j); - - break; - } - } - - if (!groups.contains(sg)) - { - groups.addElement(sg); - } - } - - //NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER - /////////////////////////////////////////////// - Vector seqs = new Vector(); - - for (int i = 0; i < groups.size(); i++) - { - SequenceGroup sg = (SequenceGroup) groups.elementAt(i); - SequenceI[] orderedseqs = sg.getSequencesInOrder(align); - - for (int j = 0; j < orderedseqs.length; j++) - { - seqs.addElement(orderedseqs[j]); - } - } - - if (sortGroupAscending) - { - setOrder(align, seqs); - } - else - { - setReverseOrder(align, - vectorSubsetToArray(seqs, align.getSequences())); - } - } - - /** - * Converts Vector to array. - * java 1.18 does not have Vector.toArray() - * - * @param tmp Vector of SequenceI objects - * - * @return array of Sequence[] - */ - private static SequenceI[] vectorToArray(Vector tmp) - { - SequenceI[] seqs = new SequenceI[tmp.size()]; - - for (int i = 0; i < tmp.size(); i++) - { - seqs[i] = (SequenceI) tmp.elementAt(i); - } - - return seqs; - } - - /** - * DOCUMENT ME! - * - * @param tmp DOCUMENT ME! - * @param mask DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - private static SequenceI[] vectorSubsetToArray(Vector tmp, Vector mask) - { - Vector seqs = new Vector(); - int i; - boolean[] tmask = new boolean[mask.size()]; - - for (i = 0; i < mask.size(); i++) - tmask[i] = true; - - for (i = 0; i < tmp.size(); i++) - { - Object sq = tmp.elementAt(i); - - if (mask.contains(sq) && tmask[mask.indexOf(sq)]) - { - tmask[mask.indexOf(sq)] = false; - seqs.addElement(sq); - } - } - - for (i = 0; i < tmask.length; i++) - if (tmask[i]) - { - seqs.addElement(mask.elementAt(i)); - } - - return vectorToArray(seqs); - } - - /** - * Sorts by a given AlignmentOrder object - * - * @param align Alignment to order - * @param order specified order for alignment - */ - public static void sortBy(AlignmentI align, AlignmentOrder order) - { - // Get an ordered vector of sequences which may also be present in align - Vector tmp = order.getOrder(); - - if (lastOrder == order) - { - sortOrderAscending = !sortOrderAscending; - } - else - { - sortOrderAscending = true; - } - - if (sortOrderAscending) - { - setOrder(align, tmp); - } - else - { - setReverseOrder(align, - vectorSubsetToArray(tmp, align.getSequences())); - } - } - - /** - * DOCUMENT ME! - * - * @param align alignment to order - * @param tree tree which has - * - * @return DOCUMENT ME! - */ - private static Vector getOrderByTree(AlignmentI align, NJTree tree) - { - int nSeq = align.getHeight(); - - Vector tmp = new Vector(); - - tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences()); - - if (tmp.size() != nSeq) - { - // TODO: JBPNote - decide if this is always an error - // (eg. not when a tree is associated to another alignment which has more - // sequences) - if (tmp.size() < nSeq) - { - addStrays(align, tmp); - } - - if (tmp.size() != nSeq) - { - System.err.println("ERROR: tmp.size()=" + tmp.size() + - " != nseq=" + nSeq + " in getOrderByTree"); - } - } - - return tmp; - } - - /** - * Sorts the alignment by a given tree - * - * @param align alignment to order - * @param tree tree which has - */ - public static void sortByTree(AlignmentI align, NJTree tree) - { - Vector tmp = getOrderByTree(align, tree); - - // tmp should properly permute align with tree. - if (lastTree != tree) - { - sortTreeAscending = true; - lastTree = tree; - } - else - { - sortTreeAscending = !sortTreeAscending; - } - - if (sortTreeAscending) - { - setOrder(align, tmp); - } - else - { - setReverseOrder(align, - vectorSubsetToArray(tmp, align.getSequences())); - } - } - - /** - * DOCUMENT ME! - * - * @param align DOCUMENT ME! - * @param seqs DOCUMENT ME! - */ - private static void addStrays(AlignmentI align, Vector seqs) - { - int nSeq = align.getHeight(); - - for (int i = 0; i < nSeq; i++) - { - if (!seqs.contains(align.getSequenceAt(i))) - { - seqs.addElement(align.getSequenceAt(i)); - } - } - - if (nSeq != seqs.size()) - { - System.err.println( - "ERROR: Size still not right even after addStrays"); - } - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param tmp DOCUMENT ME! - * @param seqset DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - private static Vector _sortByTree(SequenceNode node, Vector tmp, - Vector seqset) - { - if (node == null) - { - return tmp; - } - - SequenceNode left = (SequenceNode) node.left(); - SequenceNode right = (SequenceNode) node.right(); - - if ((left == null) && (right == null)) - { - if (!node.isPlaceholder() && (node.element() != null)) - { - if (node.element() instanceof SequenceI) - { - if (!tmp.contains(node.element())) - { - tmp.addElement((SequenceI) node.element()); - } - } - } - - return tmp; - } - else - { - _sortByTree(left, tmp, seqset); - _sortByTree(right, tmp, seqset); - } - - return tmp; - } - - // Ordering Objects - // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in appropriate order - // - - /** - * recover the order of sequences given by the safe numbering scheme introducd - * SeqsetUtils.uniquify. - */ - public static void recoverOrder(SequenceI[] alignment) - { - float[] ids = new float[alignment.length]; - - for (int i = 0; i < alignment.length; i++) - ids[i] = (new Float(alignment[i].getName().substring(8))).floatValue(); - - jalview.util.QuickSort.sort(ids, alignment); - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package jalview.analysis; + +import jalview.datamodel.*; + +import jalview.util.*; + +import java.util.*; + + +/** Data structure to hold and manipulate a multiple sequence alignment + */ +public class AlignmentSorter +{ + static boolean sortIdAscending = true; + static int lastGroupHash = 0; + static boolean sortGroupAscending = true; + static AlignmentOrder lastOrder = null; + static boolean sortOrderAscending = true; + static NJTree lastTree = null; + static boolean sortTreeAscending = true; + + /** + * Sort by Percentage Identity + * + * @param align AlignmentI + * @param s SequenceI + */ + public static void sortByPID(AlignmentI align, SequenceI s) + { + int nSeq = align.getHeight(); + + float[] scores = new float[nSeq]; + SequenceI[] seqs = new SequenceI[nSeq]; + + for (int i = 0; i < nSeq; i++) + { + scores[i] = Comparison.PID(align.getSequenceAt(i).getSequence(), + s.getSequence()); + seqs[i] = align.getSequenceAt(i); + } + + QuickSort.sort(scores, 0, scores.length - 1, seqs); + + setReverseOrder(align, seqs); + } + + /** + * Reverse the order of the sort + * + * @param align DOCUMENT ME! + * @param seqs DOCUMENT ME! + */ + private static void setReverseOrder(AlignmentI align, SequenceI[] seqs) + { + int nSeq = seqs.length; + + int len = 0; + + if ((nSeq % 2) == 0) + { + len = nSeq / 2; + } + else + { + len = (nSeq + 1) / 2; + } + + // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work + for (int i = 0; i < len; i++) + { + //SequenceI tmp = seqs[i]; + align.getSequences().setElementAt(seqs[nSeq - i - 1], i); + align.getSequences().setElementAt(seqs[i], nSeq - i - 1); + } + } + + /** + * Sets the Alignment object with the given sequences + * + * @param align Alignment object to be updated + * @param tmp sequences as a vector + */ + private static void setOrder(AlignmentI align, Vector tmp) + { + setOrder(align, vectorSubsetToArray(tmp, align.getSequences())); + } + + /** + * Sets the Alignment object with the given sequences + * + * @param align DOCUMENT ME! + * @param seqs sequences as an array + */ + private static void setOrder(AlignmentI align, SequenceI[] seqs) + { + // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work + Vector algn = align.getSequences(); + + for (int i = 0; i < seqs.length; i++) + { + algn.setElementAt(seqs[i], i); + } + } + + /** + * Sorts by ID. Numbers are sorted before letters. + * + * @param align The alignment object to sort + */ + public static void sortByID(AlignmentI align) + { + int nSeq = align.getHeight(); + + String[] ids = new String[nSeq]; + SequenceI[] seqs = new SequenceI[nSeq]; + + for (int i = 0; i < nSeq; i++) + { + ids[i] = align.getSequenceAt(i).getName(); + seqs[i] = align.getSequenceAt(i); + } + + QuickSort.sort(ids, seqs); + + if (sortIdAscending) + { + setReverseOrder(align, seqs); + } + else + { + setOrder(align, seqs); + } + + sortIdAscending = !sortIdAscending; + } + + /** + * Sorts the alignment by size of group. + *
Maintains the order of sequences in each group + * by order in given alignment object. + * + * @param align sorts the given alignment object by group + */ + public static void sortByGroup(AlignmentI align) + { + //MAINTAINS ORIGNAL SEQUENCE ORDER, + //ORDERS BY GROUP SIZE + Vector groups = new Vector(); + + if (groups.hashCode() != lastGroupHash) + { + sortGroupAscending = true; + lastGroupHash = groups.hashCode(); + } + else + { + sortGroupAscending = !sortGroupAscending; + } + + //SORTS GROUPS BY SIZE + ////////////////////// + for (int i = 0; i < align.getGroups().size(); i++) + { + SequenceGroup sg = (SequenceGroup) align.getGroups().elementAt(i); + + for (int j = 0; j < groups.size(); j++) + { + SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j); + + if (sg.getSize(false) > sg2.getSize(false)) + { + groups.insertElementAt(sg, j); + + break; + } + } + + if (!groups.contains(sg)) + { + groups.addElement(sg); + } + } + + //NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER + /////////////////////////////////////////////// + Vector seqs = new Vector(); + + for (int i = 0; i < groups.size(); i++) + { + SequenceGroup sg = (SequenceGroup) groups.elementAt(i); + SequenceI[] orderedseqs = sg.getSequencesInOrder(align); + + for (int j = 0; j < orderedseqs.length; j++) + { + seqs.addElement(orderedseqs[j]); + } + } + + if (sortGroupAscending) + { + setOrder(align, seqs); + } + else + { + setReverseOrder(align, + vectorSubsetToArray(seqs, align.getSequences())); + } + } + + /** + * Converts Vector to array. + * java 1.18 does not have Vector.toArray() + * + * @param tmp Vector of SequenceI objects + * + * @return array of Sequence[] + */ + private static SequenceI[] vectorToArray(Vector tmp) + { + SequenceI[] seqs = new SequenceI[tmp.size()]; + + for (int i = 0; i < tmp.size(); i++) + { + seqs[i] = (SequenceI) tmp.elementAt(i); + } + + return seqs; + } + + /** + * DOCUMENT ME! + * + * @param tmp DOCUMENT ME! + * @param mask DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static SequenceI[] vectorSubsetToArray(Vector tmp, Vector mask) + { + Vector seqs = new Vector(); + int i; + boolean[] tmask = new boolean[mask.size()]; + + for (i = 0; i < mask.size(); i++) + tmask[i] = true; + + for (i = 0; i < tmp.size(); i++) + { + Object sq = tmp.elementAt(i); + + if (mask.contains(sq) && tmask[mask.indexOf(sq)]) + { + tmask[mask.indexOf(sq)] = false; + seqs.addElement(sq); + } + } + + for (i = 0; i < tmask.length; i++) + if (tmask[i]) + { + seqs.addElement(mask.elementAt(i)); + } + + return vectorToArray(seqs); + } + + /** + * Sorts by a given AlignmentOrder object + * + * @param align Alignment to order + * @param order specified order for alignment + */ + public static void sortBy(AlignmentI align, AlignmentOrder order) + { + // Get an ordered vector of sequences which may also be present in align + Vector tmp = order.getOrder(); + + if (lastOrder == order) + { + sortOrderAscending = !sortOrderAscending; + } + else + { + sortOrderAscending = true; + } + + if (sortOrderAscending) + { + setOrder(align, tmp); + } + else + { + setReverseOrder(align, + vectorSubsetToArray(tmp, align.getSequences())); + } + } + + /** + * DOCUMENT ME! + * + * @param align alignment to order + * @param tree tree which has + * + * @return DOCUMENT ME! + */ + private static Vector getOrderByTree(AlignmentI align, NJTree tree) + { + int nSeq = align.getHeight(); + + Vector tmp = new Vector(); + + tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences()); + + if (tmp.size() != nSeq) + { + // TODO: JBPNote - decide if this is always an error + // (eg. not when a tree is associated to another alignment which has more + // sequences) + if (tmp.size() < nSeq) + { + addStrays(align, tmp); + } + + if (tmp.size() != nSeq) + { + System.err.println("ERROR: tmp.size()=" + tmp.size() + + " != nseq=" + nSeq + " in getOrderByTree"); + } + } + + return tmp; + } + + /** + * Sorts the alignment by a given tree + * + * @param align alignment to order + * @param tree tree which has + */ + public static void sortByTree(AlignmentI align, NJTree tree) + { + Vector tmp = getOrderByTree(align, tree); + + // tmp should properly permute align with tree. + if (lastTree != tree) + { + sortTreeAscending = true; + lastTree = tree; + } + else + { + sortTreeAscending = !sortTreeAscending; + } + + if (sortTreeAscending) + { + setOrder(align, tmp); + } + else + { + setReverseOrder(align, + vectorSubsetToArray(tmp, align.getSequences())); + } + } + + /** + * DOCUMENT ME! + * + * @param align DOCUMENT ME! + * @param seqs DOCUMENT ME! + */ + private static void addStrays(AlignmentI align, Vector seqs) + { + int nSeq = align.getHeight(); + + for (int i = 0; i < nSeq; i++) + { + if (!seqs.contains(align.getSequenceAt(i))) + { + seqs.addElement(align.getSequenceAt(i)); + } + } + + if (nSeq != seqs.size()) + { + System.err.println( + "ERROR: Size still not right even after addStrays"); + } + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * @param tmp DOCUMENT ME! + * @param seqset DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static Vector _sortByTree(SequenceNode node, Vector tmp, + Vector seqset) + { + if (node == null) + { + return tmp; + } + + SequenceNode left = (SequenceNode) node.left(); + SequenceNode right = (SequenceNode) node.right(); + + if ((left == null) && (right == null)) + { + if (!node.isPlaceholder() && (node.element() != null)) + { + if (node.element() instanceof SequenceI) + { + if (!tmp.contains(node.element())) + { + tmp.addElement((SequenceI) node.element()); + } + } + } + + return tmp; + } + else + { + _sortByTree(left, tmp, seqset); + _sortByTree(right, tmp, seqset); + } + + return tmp; + } + + // Ordering Objects + // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in appropriate order + // + + /** + * recover the order of sequences given by the safe numbering scheme introducd + * SeqsetUtils.uniquify. + */ + public static void recoverOrder(SequenceI[] alignment) + { + float[] ids = new float[alignment.length]; + + for (int i = 0; i < alignment.length; i++) + ids[i] = (new Float(alignment[i].getName().substring(8))).floatValue(); + + jalview.util.QuickSort.sort(ids, alignment); + } +} diff --git a/src/jalview/analysis/Conservation.java b/src/jalview/analysis/Conservation.java index b9b68ce..7d831e8 100755 --- a/src/jalview/analysis/Conservation.java +++ b/src/jalview/analysis/Conservation.java @@ -1,563 +1,576 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package jalview.analysis; - -import jalview.datamodel.*; - -import java.util.*; - - -/** - * Calculates conservation values for a given set of sequences - * - * @author $author$ - * @version $Revision$ - */ -public class Conservation -{ - Vector sequences; - int start; - int end; - Vector seqNums; // vector of int vectors where first is sequence checksum - int maxLength = 0; // used by quality calcs - boolean seqNumsChanged = false; // updated after any change via calcSeqNum; - Vector total = new Vector(); - - /** Stores calculated quality values */ - public Vector quality; - - /** Stores maximum and minimum values of quality values */ - public Double[] qualityRange = new Double[2]; - String consString = ""; - Sequence consSequence; - Hashtable propHash; - int threshold; - String name = ""; - int[][] cons2; - - /** - * Creates a new Conservation object. - * - * @param name Name of conservation - * @param propHash DOCUMENT ME! - * @param threshold to count the residues in residueHash(). commonly used value is 3 - * @param sequences sequences to be used in calculation - * @param start start residue position - * @param end end residue position - */ - public Conservation(String name, Hashtable propHash, int threshold, - Vector sequences, int start, int end) - { - this.name = name; - this.propHash = propHash; - this.threshold = threshold; - this.sequences = sequences; - this.start = start; - this.end = end; - seqNums = new Vector(sequences.size()); - calcSeqNums(); - } - - /** - * DOCUMENT ME! - */ - private void calcSeqNums() - { - int i=0, iSize=sequences.size(); - for (i=0; i < iSize; i++) - { - calcSeqNum(i); - } - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - */ - private void calcSeqNum(int i) - { - String sq = null; // for dumb jbuilder not-inited exception warning - int[] sqnum = null; - - if ((i > -1) && (i < sequences.size())) - { - sq = ((SequenceI) sequences.elementAt(i)).getSequence(); - - if (seqNums.size() <= i) - { - seqNums.addElement(new int[sq.length() + 1]); - } - - if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0]) - { - int j; - int len; - seqNumsChanged = true; - sq = ((SequenceI) sequences.elementAt(i)).getSequence(); - len = sq.length(); - - if (maxLength < len) - { - maxLength = len; - } - - sqnum = new int[len + 1]; // better to always make a new array - sequence can change its length - sqnum[0] = sq.hashCode(); - - for (j = 1; j <= len; j++) - { - sqnum[j] = ((Integer) jalview.schemes.ResidueProperties.aaHash.get(String.valueOf( - sq.charAt(j - 1)))).intValue(); // yuk - JBPNote - case taken care of in aaHash - } - - seqNums.setElementAt(sqnum, i); - } - } - else - { - // JBPNote INFO level debug - System.err.println( - "ERROR: calcSeqNum called with out of range sequence index for Alignment\n"); - } - } - - /** - * Calculates the conservation values for given set of sequences - */ - public void calculate() - { - Hashtable resultHash, residueHash, ht; - int count, thresh, j, jSize = sequences.size(); - String sequence, res, type; - Enumeration enumeration, enumeration2; - - for (int i = start; i <= end; i++) - { - resultHash = new Hashtable(); - residueHash = new Hashtable(); - - for (j = 0; j < jSize; j++) - { - // JBPNote - have to make sure elements of the sequences vector - // are tested like this everywhere... - if (sequences.elementAt(j) instanceof Sequence) - { - sequence = ((Sequence) sequences.elementAt(j)).getSequence(); - - if (sequence.length() > i) - { - res = String.valueOf(Character.toUpperCase(sequence.charAt(i))); - - if (residueHash.containsKey(res)) - { - count = ((Integer) residueHash.get(res)).intValue(); - count++; - residueHash.put(res, new Integer(count)); - } - else - { - residueHash.put(res, new Integer(1)); - } - } - else - { - if (residueHash.containsKey("-")) - { - count = ((Integer) residueHash.get("-")).intValue(); - count++; - residueHash.put("-", new Integer(count)); - } - else - { - residueHash.put("-", new Integer(1)); - } - } - } - } - - //What is the count threshold to count the residues in residueHash() - thresh = (threshold * (sequences.size())) / 100; - - //loop over all the found residues - enumeration = residueHash.keys(); - - while (enumeration.hasMoreElements()) - { - res = (String) enumeration.nextElement(); - - if (((Integer) residueHash.get(res)).intValue() > thresh) - { - //Now loop over the properties - enumeration2 = propHash.keys(); - - while (enumeration2.hasMoreElements()) - { - type = (String) enumeration2.nextElement(); - ht = (Hashtable) propHash.get(type); - - //Have we ticked this before? - if (!resultHash.containsKey(type)) - { - if (ht.containsKey(res)) - { - resultHash.put(type, ht.get(res)); - } - else - { - resultHash.put(type, ht.get("-")); - } - } - else if (((Integer) resultHash.get(type)).equals( - (Integer) ht.get(res)) == false) - { - resultHash.put(type, new Integer(-1)); - } - } - } - } - - total.addElement(resultHash); - } - } - - - /*** - * countConsNGaps - * returns gap count in int[0], and conserved residue count in int[1] - */ - public int[] countConsNGaps(int j) - { - int count = 0; - int cons = 0; - int nres = 0; - int[] r = new int[2]; - char f = '$'; - int i, iSize = sequences.size(); - char c; - - for (i = 0; i < iSize; i++) - { - if (j >= ((Sequence) sequences.elementAt(i)).getLength()) - { - count++; - continue; - } - - c = ((Sequence) sequences.elementAt(i)).getCharAt(j); // gaps do not have upper/lower case - - if (jalview.util.Comparison.isGap((c))) - { - count++; - } - else - { - nres++; - - if (nres == 1) - { - f = c; - cons++; - } - else if (f == c) - { - cons++; - } - } - } - - r[0] = (nres == cons) ? 1 : 0; - r[1] = count; - - return r; - } - - /** - * Calculates the conservation sequence - * - * @param consflag if true, poitiveve conservation; false calculates negative conservation - * @param percentageGaps commonly used value is 25 - */ - public void verdict(boolean consflag, float percentageGaps) - { - StringBuffer consString = new StringBuffer(); - String type; - Integer result; - int[] gapcons; - int totGaps, count; - float pgaps; - Hashtable resultHash ; - Enumeration enumeration; - - - for (int i = start; i <= end; i++) - { - gapcons = countConsNGaps(i); - totGaps = gapcons[1]; - pgaps = ((float) totGaps * 100) / (float) sequences.size(); - - if (percentageGaps > pgaps) - { - resultHash = (Hashtable) total.elementAt(i - start); - - //Now find the verdict - count = 0; - enumeration = resultHash.keys(); - - while (enumeration.hasMoreElements()) - { - type = (String) enumeration.nextElement(); - result = (Integer) resultHash.get(type); - - //Do we want to count +ve conservation or +ve and -ve cons.? - if (consflag) - { - if (result.intValue() == 1) - { - count++; - } - } - else - { - if (result.intValue() != -1) - { - count++; - } - } - } - - if (count < 10) - { - consString.append(count); // Conserved props!=Identity - } - else - { - consString.append((gapcons[0] == 1) ? "*" : "+"); - } - } - else - { - consString.append("-"); - } - } - - consSequence = new Sequence(name, consString.toString(), start, end); - } - - /** - * - * - * @return Conservation sequence - */ - public Sequence getConsSequence() - { - return consSequence; - } - - // From Alignment.java in jalview118 - public void findQuality() - { - findQuality(0, maxLength - 1); - } - - /** - * DOCUMENT ME! - */ - private void percentIdentity2() - { - calcSeqNums(); // updates maxLength, too. - - if ((cons2 == null) || seqNumsChanged) - { - cons2 = new int[maxLength][24]; - - // Initialize the array - for (int j = 0; j < 24; j++) - { - for (int i = 0; i < maxLength; i++) - { - cons2[i][j] = 0; - } - } - - int[] sqnum; - int j = 0; - - while (j < sequences.size()) - { - sqnum = (int[]) seqNums.elementAt(j); - - for (int i = 1; i < sqnum.length; i++) - { - cons2[i - 1][sqnum[i]]++; - } - - for (int i = sqnum.length - 1; i < maxLength; i++) - { - cons2[i][23]++; // gap count - } - - j++; - } - - // unnecessary ? - - /* for (int i=start; i <= end; i++) { - int max = -1000; - int maxi = -1; - int maxj = -1; - - for (int j=0;j<24;j++) { - if (cons2[i][j] > max) { - max = cons2[i][j]; - maxi = i; - maxj = j; - } - - } - } */ - } - } - - /** - * Calculates the quality of the set of sequences - * - * @param start Start residue - * @param end End residue - */ - public void findQuality(int start, int end) - { - quality = new Vector(); - - double max = -10000; - int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62(); - - //Loop over columns // JBPNote Profiling info - // long ts = System.currentTimeMillis(); - //long te = System.currentTimeMillis(); - percentIdentity2(); - - int size = seqNums.size(); - int[] lengths = new int[size]; - double tot, bigtot, sr, tmp; - double [] x, xx; - int l, j, i, ii, seqNum; - - for (l = 0; l < size; l++) - lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1; - - - for (j = start; j <= end; j++) - { - bigtot = 0; - - // First Xr = depends on column only - x = new double[24]; - - for (ii = 0; ii < 24; ii++) - { - x[ii] = 0; - - try - { - for (int i2 = 0; i2 < 24; i2++) - { - x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + - 4); - } - } - catch (Exception e) - { - System.err.println("Exception during quality calculation."); - e.printStackTrace(); - } - - //System.out.println("X " + ii + " " + x[ii]); - x[ii] /= (size); - - //System.out.println("X " + ii + " " + x[ii]); - } - - // Now calculate D for each position and sum - for (int k = 0; k < size; k++) - { - tot = 0; - xx = new double[24]; - seqNum = (j < lengths[k]) - ? ((int[]) seqNums.elementAt(k))[j + 1] : 23; // Sequence, or gap at the end - - // This is a loop over r - for (i = 0; i < 23; i++) - { - sr = 0; - - try - { - sr = (double) BLOSUM62[i][seqNum] + 4; - } - catch (Exception e) - { - System.out.println("Exception in sr: " + e); - e.printStackTrace(); - } - - //Calculate X with another loop over residues - // System.out.println("Xi " + i + " " + x[i] + " " + sr); - xx[i] = x[i] - sr; - - tot += (xx[i] * xx[i]); - } - - bigtot += Math.sqrt(tot); - } - - // This is the quality for one column - if (max < bigtot) - { - max = bigtot; - } - - // bigtot = bigtot * (size-cons2[j][23])/size; - quality.addElement(new Double(bigtot)); - - - // Need to normalize by gaps - } - - double newmax = -10000; - - for (j = start; j <= end; j++) - { - tmp = ((Double) quality.elementAt(j)).doubleValue(); - tmp = ((max - tmp) * (size - cons2[j][23])) / size; - - // System.out.println(tmp+ " " + j); - quality.setElementAt(new Double(tmp), j); - - if (tmp > newmax) - { - newmax = tmp; - } - } - - // System.out.println("Quality " + s); - qualityRange[0] = new Double(0); - qualityRange[1] = new Double(newmax); - } -} +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package jalview.analysis; + +import jalview.datamodel.*; + +import java.util.*; + + +/** + * Calculates conservation values for a given set of sequences + * + * @author $author$ + * @version $Revision$ + */ +public class Conservation +{ + Vector sequences; + int start; + int end; + Vector seqNums; // vector of int vectors where first is sequence checksum + int maxLength = 0; // used by quality calcs + boolean seqNumsChanged = false; // updated after any change via calcSeqNum; + Vector total = new Vector(); + + /** Stores calculated quality values */ + public Vector quality; + + /** Stores maximum and minimum values of quality values */ + public Double[] qualityRange = new Double[2]; + String consString = ""; + Sequence consSequence; + Hashtable propHash; + int threshold; + String name = ""; + int[][] cons2; + + /** + * Creates a new Conservation object. + * + * @param name Name of conservation + * @param propHash DOCUMENT ME! + * @param threshold to count the residues in residueHash(). commonly used value is 3 + * @param sequences sequences to be used in calculation + * @param start start residue position + * @param end end residue position + */ + public Conservation(String name, Hashtable propHash, int threshold, + Vector sequences, int start, int end) + { + this.name = name; + this.propHash = propHash; + this.threshold = threshold; + this.sequences = sequences; + this.start = start; + this.end = end; + seqNums = new Vector(sequences.size()); + calcSeqNums(); + } + + /** + * DOCUMENT ME! + */ + private void calcSeqNums() + { + int i=0, iSize=sequences.size(); + for (i=0; i < iSize; i++) + { + calcSeqNum(i); + } + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + */ + private void calcSeqNum(int i) + { + String sq = null; // for dumb jbuilder not-inited exception warning + int[] sqnum = null; + + if ((i > -1) && (i < sequences.size())) + { + sq = ((SequenceI) sequences.elementAt(i)).getSequence(); + + if (seqNums.size() <= i) + { + seqNums.addElement(new int[sq.length() + 1]); + } + + if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0]) + { + int j; + int len; + seqNumsChanged = true; + sq = ((SequenceI) sequences.elementAt(i)).getSequence(); + len = sq.length(); + + if (maxLength < len) + { + maxLength = len; + } + + sqnum = new int[len + 1]; // better to always make a new array - sequence can change its length + sqnum[0] = sq.hashCode(); + + for (j = 1; j <= len; j++) + { + sqnum[j] = ((Integer) jalview.schemes.ResidueProperties.aaHash.get(String.valueOf( + sq.charAt(j - 1)))).intValue(); // yuk - JBPNote - case taken care of in aaHash + } + + seqNums.setElementAt(sqnum, i); + } + } + else + { + // JBPNote INFO level debug + System.err.println( + "ERROR: calcSeqNum called with out of range sequence index for Alignment\n"); + } + } + + /** + * Calculates the conservation values for given set of sequences + */ + public void calculate() + { + Hashtable resultHash, residueHash, ht; + int count, thresh, j, jSize = sequences.size(); + String type, res=null; + SequenceI sequence; + char c; + Enumeration enumeration, enumeration2; + + for (int i = start; i <= end; i++) + { + resultHash = new Hashtable(); + residueHash = new Hashtable(); + + for (j = 0; j < jSize; j++) + { + // JBPNote - have to make sure elements of the sequences vector + // are tested like this everywhere... + sequence = (Sequence) sequences.elementAt(j); + + if (sequence.getLength() > i) + { + c = sequence.getCharAt(i); + + // No need to check if its a '-' + if(c == '.' || c==' ') + c = '-'; + + if ('a' <= c && c <= 'z') + { + // TO UPPERCASE !!! + //Faster than toUpperCase + c -= ('a' - 'A') ; + } + + res = String.valueOf( c ); + + + if (residueHash.containsKey(res)) + { + count = ((Integer) residueHash.get(res)).intValue(); + count++; + residueHash.put(res, new Integer(count)); + } + else + { + residueHash.put(res, new Integer(1)); + } + } + else + { + if (residueHash.containsKey("-")) + { + count = ((Integer) residueHash.get("-")).intValue(); + count++; + residueHash.put("-", new Integer(count)); + } + else + { + residueHash.put("-", new Integer(1)); + } + } + } + + //What is the count threshold to count the residues in residueHash() + thresh = (threshold * (sequences.size())) / 100; + + //loop over all the found residues + enumeration = residueHash.keys(); + + while (enumeration.hasMoreElements()) + { + res = (String) enumeration.nextElement(); + + if (((Integer) residueHash.get(res)).intValue() > thresh) + { + //Now loop over the properties + enumeration2 = propHash.keys(); + + while (enumeration2.hasMoreElements()) + { + type = (String) enumeration2.nextElement(); + ht = (Hashtable) propHash.get(type); + + //Have we ticked this before? + if (!resultHash.containsKey(type)) + { + if (ht.containsKey(res)) + { + resultHash.put(type, ht.get(res)); + } + else + { + resultHash.put(type, ht.get("-")); + } + } + else if (((Integer) resultHash.get(type)).equals( + (Integer) ht.get(res)) == false) + { + resultHash.put(type, new Integer(-1)); + } + } + } + } + + total.addElement(resultHash); + } + } + + + /*** + * countConsNGaps + * returns gap count in int[0], and conserved residue count in int[1] + */ + public int[] countConsNGaps(int j) + { + int count = 0; + int cons = 0; + int nres = 0; + int[] r = new int[2]; + char f = '$'; + int i, iSize = sequences.size(); + char c; + + for (i = 0; i < iSize; i++) + { + if (j >= ((Sequence) sequences.elementAt(i)).getLength()) + { + count++; + continue; + } + + c = ((Sequence) sequences.elementAt(i)).getCharAt(j); // gaps do not have upper/lower case + + if (jalview.util.Comparison.isGap((c))) + { + count++; + } + else + { + nres++; + + if (nres == 1) + { + f = c; + cons++; + } + else if (f == c) + { + cons++; + } + } + } + + r[0] = (nres == cons) ? 1 : 0; + r[1] = count; + + return r; + } + + /** + * Calculates the conservation sequence + * + * @param consflag if true, poitiveve conservation; false calculates negative conservation + * @param percentageGaps commonly used value is 25 + */ + public void verdict(boolean consflag, float percentageGaps) + { + StringBuffer consString = new StringBuffer(); + String type; + Integer result; + int[] gapcons; + int totGaps, count; + float pgaps; + Hashtable resultHash ; + Enumeration enumeration; + + + for (int i = start; i <= end; i++) + { + gapcons = countConsNGaps(i); + totGaps = gapcons[1]; + pgaps = ((float) totGaps * 100) / (float) sequences.size(); + + if (percentageGaps > pgaps) + { + resultHash = (Hashtable) total.elementAt(i - start); + + //Now find the verdict + count = 0; + enumeration = resultHash.keys(); + + while (enumeration.hasMoreElements()) + { + type = (String) enumeration.nextElement(); + result = (Integer) resultHash.get(type); + + //Do we want to count +ve conservation or +ve and -ve cons.? + if (consflag) + { + if (result.intValue() == 1) + { + count++; + } + } + else + { + if (result.intValue() != -1) + { + count++; + } + } + } + + if (count < 10) + { + consString.append(count); // Conserved props!=Identity + } + else + { + consString.append((gapcons[0] == 1) ? "*" : "+"); + } + } + else + { + consString.append("-"); + } + } + + consSequence = new Sequence(name, consString.toString(), start, end); + } + + /** + * + * + * @return Conservation sequence + */ + public Sequence getConsSequence() + { + return consSequence; + } + + // From Alignment.java in jalview118 + public void findQuality() + { + findQuality(0, maxLength - 1); + } + + /** + * DOCUMENT ME! + */ + private void percentIdentity2() + { + calcSeqNums(); // updates maxLength, too. + + if ((cons2 == null) || seqNumsChanged) + { + cons2 = new int[maxLength][24]; + + // Initialize the array + for (int j = 0; j < 24; j++) + { + for (int i = 0; i < maxLength; i++) + { + cons2[i][j] = 0; + } + } + + int[] sqnum; + int j = 0; + + while (j < sequences.size()) + { + sqnum = (int[]) seqNums.elementAt(j); + + for (int i = 1; i < sqnum.length; i++) + { + cons2[i - 1][sqnum[i]]++; + } + + for (int i = sqnum.length - 1; i < maxLength; i++) + { + cons2[i][23]++; // gap count + } + + j++; + } + + // unnecessary ? + + /* for (int i=start; i <= end; i++) { + int max = -1000; + int maxi = -1; + int maxj = -1; + + for (int j=0;j<24;j++) { + if (cons2[i][j] > max) { + max = cons2[i][j]; + maxi = i; + maxj = j; + } + + } + } */ + } + } + + /** + * Calculates the quality of the set of sequences + * + * @param start Start residue + * @param end End residue + */ + public void findQuality(int start, int end) + { + quality = new Vector(); + + double max = -10000; + int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62(); + + //Loop over columns // JBPNote Profiling info + // long ts = System.currentTimeMillis(); + //long te = System.currentTimeMillis(); + percentIdentity2(); + + int size = seqNums.size(); + int[] lengths = new int[size]; + double tot, bigtot, sr, tmp; + double [] x, xx; + int l, j, i, ii, seqNum; + + for (l = 0; l < size; l++) + lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1; + + + for (j = start; j <= end; j++) + { + bigtot = 0; + + // First Xr = depends on column only + x = new double[24]; + + for (ii = 0; ii < 24; ii++) + { + x[ii] = 0; + + try + { + for (int i2 = 0; i2 < 24; i2++) + { + x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + + 4); + } + } + catch (Exception e) + { + System.err.println("Exception during quality calculation."); + e.printStackTrace(); + } + + //System.out.println("X " + ii + " " + x[ii]); + x[ii] /= (size); + + //System.out.println("X " + ii + " " + x[ii]); + } + + // Now calculate D for each position and sum + for (int k = 0; k < size; k++) + { + tot = 0; + xx = new double[24]; + seqNum = (j < lengths[k]) + ? ((int[]) seqNums.elementAt(k))[j + 1] : 23; // Sequence, or gap at the end + + // This is a loop over r + for (i = 0; i < 23; i++) + { + sr = 0; + + try + { + sr = (double) BLOSUM62[i][seqNum] + 4; + } + catch (Exception e) + { + System.out.println("Exception in sr: " + e); + e.printStackTrace(); + } + + //Calculate X with another loop over residues + // System.out.println("Xi " + i + " " + x[i] + " " + sr); + xx[i] = x[i] - sr; + + tot += (xx[i] * xx[i]); + } + + bigtot += Math.sqrt(tot); + } + + // This is the quality for one column + if (max < bigtot) + { + max = bigtot; + } + + // bigtot = bigtot * (size-cons2[j][23])/size; + quality.addElement(new Double(bigtot)); + + + // Need to normalize by gaps + } + + double newmax = -10000; + + for (j = start; j <= end; j++) + { + tmp = ((Double) quality.elementAt(j)).doubleValue(); + tmp = ((max - tmp) * (size - cons2[j][23])) / size; + + // System.out.println(tmp+ " " + j); + quality.setElementAt(new Double(tmp), j); + + if (tmp > newmax) + { + newmax = tmp; + } + } + + // System.out.println("Quality " + s); + qualityRange[0] = new Double(0); + qualityRange[1] = new Double(newmax); + } +} diff --git a/src/jalview/analysis/NJTree.java b/src/jalview/analysis/NJTree.java index 40dfc9b..e029771 100755 --- a/src/jalview/analysis/NJTree.java +++ b/src/jalview/analysis/NJTree.java @@ -1,1190 +1,1248 @@ -/* -* Jalview - A Sequence Alignment Editor and Viewer -* Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 -* of the License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ -package jalview.analysis; - -import jalview.datamodel.*; - -import jalview.io.NewickFile; - -import jalview.schemes.ResidueProperties; - -import jalview.util.*; - -import java.util.*; - - -/** - * DOCUMENT ME! - * - * @author $author$ - * @version $Revision$ - */ -public class NJTree -{ - Vector cluster; - SequenceI[] sequence; - int[] done; - int noseqs; - int noClus; - float[][] distance; - int mini; - int minj; - float ri; - float rj; - Vector groups = new Vector(); - SequenceNode maxdist; - SequenceNode top; - float maxDistValue; - float maxheight; - int ycount; - Vector node; - String type; - String pwtype; - Object found = null; - Object leaves = null; - int start; - int end; - boolean hasDistances = true; // normal case for jalview trees - boolean hasBootstrap = false; // normal case for jalview trees - - private boolean hasRootDistance = true; - - /** - * Creates a new NJTree object. - * - * @param node DOCUMENT ME! - */ - public NJTree(SequenceNode node) - { - top = node; - maxheight = findHeight(top); - } - - /** - * Creates a new NJTree object. - * - * @param seqs DOCUMENT ME! - * @param treefile DOCUMENT ME! - */ - public NJTree(SequenceI[] seqs, NewickFile treefile) - { - top = treefile.getTree(); - - hasDistances = treefile.HasDistances(); - hasBootstrap = treefile.HasBootstrap(); - hasRootDistance = treefile.HasRootDistance(); - - maxheight = findHeight(top); - - SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs); - - Vector leaves = new Vector(); - findLeaves(top, leaves); - - int i = 0; - int namesleft = seqs.length; - - SequenceNode j; - SequenceI nam; - String realnam; - - while (i < leaves.size()) - { - j = (SequenceNode) leaves.elementAt(i++); - realnam = j.getName(); - nam = null; - - if (namesleft > -1) - { - nam = algnIds.findIdMatch(realnam); - } - - if (nam != null) - { - j.setElement(nam); - namesleft--; - } - else - { - j.setElement(new Sequence(realnam, "THISISAPLACEHLDER")); - j.setPlaceholder(true); - } - } - } - - /** - * Creates a new NJTree object. - * - * @param sequence DOCUMENT ME! - * @param start DOCUMENT ME! - * @param end DOCUMENT ME! - */ - public NJTree(SequenceI[] sequence, int start, int end) - { - this(sequence, "NJ", "BL", start, end); - } - - /** - * Creates a new NJTree object. - * - * @param sequence DOCUMENT ME! - * @param type DOCUMENT ME! - * @param pwtype DOCUMENT ME! - * @param start DOCUMENT ME! - * @param end DOCUMENT ME! - */ - public NJTree(SequenceI[] sequence, String type, String pwtype, int start, - int end) - { - this.sequence = sequence; - this.node = new Vector(); - this.type = type; - this.pwtype = pwtype; - this.start = start; - this.end = end; - - if (!(type.equals("NJ"))) - { - type = "AV"; - } - - if (!(pwtype.equals("PID"))) - { - type = "BL"; - } - - int i = 0; - - done = new int[sequence.length]; - - while ((i < sequence.length) && (sequence[i] != null)) - { - done[i] = 0; - i++; - } - - noseqs = i++; - - distance = findDistances(); - - makeLeaves(); - - noClus = cluster.size(); - - cluster(); - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public String toString() - { - jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode()); - - return fout.print(false, true); // distances only - } - - /** - * - * used when the alignment associated to a tree has changed. - * - * @param alignment Vector - */ - public void UpdatePlaceHolders(Vector alignment) - { - Vector leaves = new Vector(); - findLeaves(top, leaves); - - int sz = leaves.size(); - SequenceIdMatcher seqmatcher = null; - int i = 0; - - while (i < sz) - { - SequenceNode leaf = (SequenceNode) leaves.elementAt(i++); - - if (alignment.contains(leaf.element())) - { - leaf.setPlaceholder(false); - } - else - { - if (seqmatcher == null) - { - // Only create this the first time we need it - SequenceI[] seqs = new SequenceI[alignment.size()]; - - for (int j = 0; j < seqs.length; j++) - seqs[j] = (SequenceI) alignment.elementAt(j); - - seqmatcher = new SequenceIdMatcher(seqs); - } - - SequenceI nam = seqmatcher.findIdMatch(leaf.getName()); - - if (nam != null) - { - leaf.setPlaceholder(false); - leaf.setElement(nam); - } - else - { - leaf.setPlaceholder(true); - } - } - } - } - - /** - * DOCUMENT ME! - */ - public void cluster() - { - while (noClus > 2) - { - if (type.equals("NJ")) - { - findMinNJDistance(); - } - else - { - findMinDistance(); - } - - Cluster c = joinClusters(mini, minj); - - done[minj] = 1; - - cluster.setElementAt(null, minj); - cluster.setElementAt(c, mini); - - noClus--; - } - - boolean onefound = false; - - int one = -1; - int two = -1; - - for (int i = 0; i < noseqs; i++) - { - if (done[i] != 1) - { - if (onefound == false) - { - two = i; - onefound = true; - } - else - { - one = i; - } - } - } - - joinClusters(one, two); - top = (SequenceNode) (node.elementAt(one)); - - reCount(top); - findHeight(top); - findMaxDist(top); - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - * @param j DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public Cluster joinClusters(int i, int j) - { - float dist = distance[i][j]; - - int noi = ((Cluster) cluster.elementAt(i)).value.length; - int noj = ((Cluster) cluster.elementAt(j)).value.length; - - int[] value = new int[noi + noj]; - - for (int ii = 0; ii < noi; ii++) - { - value[ii] = ((Cluster) cluster.elementAt(i)).value[ii]; - } - - for (int ii = noi; ii < (noi + noj); ii++) - { - value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi]; - } - - Cluster c = new Cluster(value); - - ri = findr(i, j); - rj = findr(j, i); - - if (type.equals("NJ")) - { - findClusterNJDistance(i, j); - } - else - { - findClusterDistance(i, j); - } - - SequenceNode sn = new SequenceNode(); - - sn.setLeft((SequenceNode) (node.elementAt(i))); - sn.setRight((SequenceNode) (node.elementAt(j))); - - SequenceNode tmpi = (SequenceNode) (node.elementAt(i)); - SequenceNode tmpj = (SequenceNode) (node.elementAt(j)); - - if (type.equals("NJ")) - { - findNewNJDistances(tmpi, tmpj, dist); - } - else - { - findNewDistances(tmpi, tmpj, dist); - } - - tmpi.setParent(sn); - tmpj.setParent(sn); - - node.setElementAt(sn, i); - - return c; - } - - /** - * DOCUMENT ME! - * - * @param tmpi DOCUMENT ME! - * @param tmpj DOCUMENT ME! - * @param dist DOCUMENT ME! - */ - public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj, - float dist) - { - - tmpi.dist = ((dist + ri) - rj) / 2; - tmpj.dist = (dist - tmpi.dist); - - if (tmpi.dist < 0) - { - tmpi.dist = 0; - } - - if (tmpj.dist < 0) - { - tmpj.dist = 0; - } - } - - /** - * DOCUMENT ME! - * - * @param tmpi DOCUMENT ME! - * @param tmpj DOCUMENT ME! - * @param dist DOCUMENT ME! - */ - public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj, - float dist) - { - float ih = 0; - float jh = 0; - - SequenceNode sni = tmpi; - SequenceNode snj = tmpj; - - while (sni != null) - { - ih = ih + sni.dist; - sni = (SequenceNode) sni.left(); - } - - while (snj != null) - { - jh = jh + snj.dist; - snj = (SequenceNode) snj.left(); - } - - tmpi.dist = ((dist / 2) - ih); - tmpj.dist = ((dist / 2) - jh); - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - * @param j DOCUMENT ME! - */ - public void findClusterDistance(int i, int j) - { - int noi = ((Cluster) cluster.elementAt(i)).value.length; - int noj = ((Cluster) cluster.elementAt(j)).value.length; - - // New distances from cluster to others - float[] newdist = new float[noseqs]; - - for (int l = 0; l < noseqs; l++) - { - if ((l != i) && (l != j)) - { - newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj)) / (noi + - noj); - } - else - { - newdist[l] = 0; - } - } - - for (int ii = 0; ii < noseqs; ii++) - { - distance[i][ii] = newdist[ii]; - distance[ii][i] = newdist[ii]; - } - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - * @param j DOCUMENT ME! - */ - public void findClusterNJDistance(int i, int j) - { - - // New distances from cluster to others - float[] newdist = new float[noseqs]; - - for (int l = 0; l < noseqs; l++) - { - if ((l != i) && (l != j)) - { - newdist[l] = ((distance[i][l] + distance[j][l]) - - distance[i][j]) / 2; - } - else - { - newdist[l] = 0; - } - } - - for (int ii = 0; ii < noseqs; ii++) - { - distance[i][ii] = newdist[ii]; - distance[ii][i] = newdist[ii]; - } - } - - /** - * DOCUMENT ME! - * - * @param i DOCUMENT ME! - * @param j DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float findr(int i, int j) - { - float tmp = 1; - - for (int k = 0; k < noseqs; k++) - { - if ((k != i) && (k != j) && (done[k] != 1)) - { - tmp = tmp + distance[i][k]; - } - } - - if (noClus > 2) - { - tmp = tmp / (noClus - 2); - } - - return tmp; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float findMinNJDistance() - { - float min = 100000; - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i + 1; j < noseqs; j++) - { - if ((done[i] != 1) && (done[j] != 1)) - { - float tmp = distance[i][j] - (findr(i, j) + findr(j, i)); - - if (tmp < min) - { - mini = i; - minj = j; - - min = tmp; - } - } - } - } - - return min; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float findMinDistance() - { - float min = 100000; - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i + 1; j < noseqs; j++) - { - if ((done[i] != 1) && (done[j] != 1)) - { - if (distance[i][j] < min) - { - mini = i; - minj = j; - - min = distance[i][j]; - } - } - } - } - - return min; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float[][] findDistances() - { - float[][] distance = new float[noseqs][noseqs]; - - if (pwtype.equals("PID")) - { - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i; j < noseqs; j++) - { - if (j == i) - { - distance[i][i] = 0; - } - else - { - distance[i][j] = 100 - - Comparison.PID(sequence[i], sequence[j], start, end); - distance[j][i] = distance[i][j]; - } - } - } - } - else if (pwtype.equals("BL")) - { - int maxscore = 0; - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i; j < noseqs; j++) - { - int score = 0; - - for (int k = start; k < end; k++) - { - try - { - score += ResidueProperties.getBLOSUM62(sequence[i].getSequence( - k, k + 1), sequence[j].getSequence(k, k + - 1)); - } - catch (Exception ex) - { - System.err.println("err creating BLOSUM62 tree"); - ex.printStackTrace(); - } - } - - distance[i][j] = (float) score; - - if (score > maxscore) - { - maxscore = score; - } - } - } - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i; j < noseqs; j++) - { - distance[i][j] = (float) maxscore - distance[i][j]; - distance[j][i] = distance[i][j]; - } - } - } - else if (pwtype.equals("SW")) - { - float max = -1; - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i; j < noseqs; j++) - { - AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep"); - as.calcScoreMatrix(); - as.traceAlignment(); - as.printAlignment(System.out); - distance[i][j] = (float) as.maxscore; - - if (max < distance[i][j]) - { - max = distance[i][j]; - } - } - } - - for (int i = 0; i < (noseqs - 1); i++) - { - for (int j = i; j < noseqs; j++) - { - distance[i][j] = max - distance[i][j]; - distance[j][i] = distance[i][j]; - } - } - } - - return distance; - } - - /** - * DOCUMENT ME! - */ - public void makeLeaves() - { - cluster = new Vector(); - - for (int i = 0; i < noseqs; i++) - { - SequenceNode sn = new SequenceNode(); - - sn.setElement(sequence[i]); - sn.setName(sequence[i].getName()); - node.addElement(sn); - - int[] value = new int[1]; - value[0] = i; - - Cluster c = new Cluster(value); - cluster.addElement(c); - } - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param leaves DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public Vector findLeaves(SequenceNode node, Vector leaves) - { - if (node == null) - { - return leaves; - } - - if ((node.left() == null) && (node.right() == null)) - { - leaves.addElement(node); - - return leaves; - } - else - { - findLeaves((SequenceNode) node.left(), leaves); - findLeaves((SequenceNode) node.right(), leaves); - } - - return leaves; - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param count DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public Object findLeaf(SequenceNode node, int count) - { - found = _findLeaf(node, count); - - return found; - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param count DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public Object _findLeaf(SequenceNode node, int count) - { - if (node == null) - { - return null; - } - - if (node.ycount == count) - { - found = node.element(); - - return found; - } - else - { - _findLeaf((SequenceNode) node.left(), count); - _findLeaf((SequenceNode) node.right(), count); - } - - return found; - } - - /** - * printNode is mainly for debugging purposes. - * - * @param node SequenceNode - */ - public void printNode(SequenceNode node) - { - if (node == null) - { - return; - } - - if ((node.left() == null) && (node.right() == null)) - { - System.out.println("Leaf = " + - ((SequenceI) node.element()).getName()); - System.out.println("Dist " + ((SequenceNode) node).dist); - System.out.println("Boot " + node.getBootstrap()); - } - else - { - System.out.println("Dist " + ((SequenceNode) node).dist); - printNode((SequenceNode) node.left()); - printNode((SequenceNode) node.right()); - } - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - */ - public void findMaxDist(SequenceNode node) - { - if (node == null) - { - return; - } - - if ((node.left() == null) && (node.right() == null)) - { - float dist = ((SequenceNode) node).dist; - - if (dist > maxDistValue) - { - maxdist = (SequenceNode) node; - maxDistValue = dist; - } - } - else - { - findMaxDist((SequenceNode) node.left()); - findMaxDist((SequenceNode) node.right()); - } - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public Vector getGroups() - { - return groups; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float getMaxHeight() - { - return maxheight; - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param threshold DOCUMENT ME! - */ - public void groupNodes(SequenceNode node, float threshold) - { - if (node == null) - { - return; - } - - if ((node.height / maxheight) > threshold) - { - groups.addElement(node); - } - else - { - groupNodes((SequenceNode) node.left(), threshold); - groupNodes((SequenceNode) node.right(), threshold); - } - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public float findHeight(SequenceNode node) - { - if (node == null) - { - return maxheight; - } - - if ((node.left() == null) && (node.right() == null)) - { - node.height = ((SequenceNode) node.parent()).height + node.dist; - - if (node.height > maxheight) - { - return node.height; - } - else - { - return maxheight; - } - } - else - { - if (node.parent() != null) - { - node.height = ((SequenceNode) node.parent()).height + - node.dist; - } - else - { - maxheight = 0; - node.height = (float) 0.0; - } - - maxheight = findHeight((SequenceNode) (node.left())); - maxheight = findHeight((SequenceNode) (node.right())); - } - - return maxheight; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public SequenceNode reRoot() - { - if (maxdist != null) - { - ycount = 0; - - float tmpdist = maxdist.dist; - - // New top - SequenceNode sn = new SequenceNode(); - sn.setParent(null); - - // New right hand of top - SequenceNode snr = (SequenceNode) maxdist.parent(); - changeDirection(snr, maxdist); - System.out.println("Printing reversed tree"); - printN(snr); - snr.dist = tmpdist / 2; - maxdist.dist = tmpdist / 2; - - snr.setParent(sn); - maxdist.setParent(sn); - - sn.setRight(snr); - sn.setLeft(maxdist); - - top = sn; - - ycount = 0; - reCount(top); - findHeight(top); - } - - return top; - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - */ - public static void printN(SequenceNode node) - { - if (node == null) - { - return; - } - - if ((node.left() != null) && (node.right() != null)) - { - printN((SequenceNode) node.left()); - printN((SequenceNode) node.right()); - } - else - { - System.out.println(" name = " + - ((SequenceI) node.element()).getName()); - } - - System.out.println(" dist = " + ((SequenceNode) node).dist + " " + - ((SequenceNode) node).count + " " + ((SequenceNode) node).height); - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - */ - public void reCount(SequenceNode node) - { - ycount = 0; - _reCount(node); - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - */ - public void _reCount(SequenceNode node) - { - if (node == null) - { - return; - } - - if ((node.left() != null) && (node.right() != null)) - { - _reCount((SequenceNode) node.left()); - _reCount((SequenceNode) node.right()); - - SequenceNode l = (SequenceNode) node.left(); - SequenceNode r = (SequenceNode) node.right(); - - ((SequenceNode) node).count = l.count + r.count; - ((SequenceNode) node).ycount = (l.ycount + r.ycount) / 2; - } - else - { - ((SequenceNode) node).count = 1; - ((SequenceNode) node).ycount = ycount++; - } - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - */ - public void swapNodes(SequenceNode node) - { - if (node == null) - { - return; - } - - SequenceNode tmp = (SequenceNode) node.left(); - - node.setLeft(node.right()); - node.setRight(tmp); - } - - /** - * DOCUMENT ME! - * - * @param node DOCUMENT ME! - * @param dir DOCUMENT ME! - */ - public void changeDirection(SequenceNode node, SequenceNode dir) - { - if (node == null) - { - return; - } - - if (node.parent() != top) - { - changeDirection((SequenceNode) node.parent(), node); - - SequenceNode tmp = (SequenceNode) node.parent(); - - if (dir == node.left()) - { - node.setParent(dir); - node.setLeft(tmp); - } - else if (dir == node.right()) - { - node.setParent(dir); - node.setRight(tmp); - } - } - else - { - if (dir == node.left()) - { - node.setParent(node.left()); - - if (top.left() == node) - { - node.setRight(top.right()); - } - else - { - node.setRight(top.left()); - } - } - else - { - node.setParent(node.right()); - - if (top.left() == node) - { - node.setLeft(top.right()); - } - else - { - node.setLeft(top.left()); - } - } - } - } - - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public SequenceNode getMaxDist() - { - return maxdist; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - public SequenceNode getTopNode() - { - return top; - } - /** - * - * @return true if tree has real distances - */ - public boolean isHasDistances() { - return hasDistances; - } - - /** - * - * @return true if tree has real bootstrap values - */ - public boolean isHasBootstrap() { - return hasBootstrap; - } - - public boolean isHasRootDistance() - { - return hasRootDistance; - } - -} - - -/** - * DOCUMENT ME! - * - * @author $author$ - * @version $Revision$ - */ -class Cluster -{ - int[] value; - - /** - * Creates a new Cluster object. - * - * @param value DOCUMENT ME! - */ - public Cluster(int[] value) - { - this.value = value; - } -} - +/* +* Jalview - A Sequence Alignment Editor and Viewer +* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +package jalview.analysis; + +import jalview.datamodel.*; + +import jalview.io.NewickFile; + +import jalview.schemes.ResidueProperties; + +import jalview.util.*; + +import java.util.*; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class NJTree +{ + Vector cluster; + SequenceI[] sequence; + + //SequenceData is a string representation of what the user + //sees. The display may contain hidden columns. + public AlignmentView seqData=null; + + int[] done; + int noseqs; + int noClus; + float[][] distance; + int mini; + int minj; + float ri; + float rj; + Vector groups = new Vector(); + SequenceNode maxdist; + SequenceNode top; + float maxDistValue; + float maxheight; + int ycount; + Vector node; + String type; + String pwtype; + Object found = null; + Object leaves = null; + + boolean hasDistances = true; // normal case for jalview trees + boolean hasBootstrap = false; // normal case for jalview trees + + private boolean hasRootDistance = true; + + /** + * Create a new NJTree object with leaves associated with sequences in seqs, + * and original alignment data represented by Cigar strings. + * @param seqs SequenceI[] + * @param odata Cigar[] + * @param treefile NewickFile + */ + public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile) { + this(seqs, treefile); + if (odata!=null) + seqData = odata; + /* + sequenceString = new String[odata.length]; + char gapChar = jalview.util.Comparison.GapChars.charAt(0); + for (int i = 0; i < odata.length; i++) + { + SequenceI oseq_aligned = odata[i].getSeq(gapChar); + sequenceString[i] = oseq_aligned.getSequence(); + } */ + } + + /** + * Creates a new NJTree object from a tree from an external source + * + * @param seqs SequenceI which should be associated with leafs of treefile + * @param treefile A parsed tree + */ + public NJTree(SequenceI[] seqs, NewickFile treefile) + { + this.sequence = seqs; + top = treefile.getTree(); + + /** + * There is no dependent alignment to be recovered from an + * imported tree. + * + if (sequenceString == null) + { + sequenceString = new String[seqs.length]; + for (int i = 0; i < seqs.length; i++) + { + sequenceString[i] = seqs[i].getSequence(); + } + } + */ + + hasDistances = treefile.HasDistances(); + hasBootstrap = treefile.HasBootstrap(); + hasRootDistance = treefile.HasRootDistance(); + + maxheight = findHeight(top); + + SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs); + + Vector leaves = new Vector(); + findLeaves(top, leaves); + + int i = 0; + int namesleft = seqs.length; + + SequenceNode j; + SequenceI nam; + String realnam; + + while (i < leaves.size()) + { + j = (SequenceNode) leaves.elementAt(i++); + realnam = j.getName(); + nam = null; + + if (namesleft > -1) + { + nam = algnIds.findIdMatch(realnam); + } + + if (nam != null) + { + j.setElement(nam); + namesleft--; + } + else + { + j.setElement(new Sequence(realnam, "THISISAPLACEHLDER")); + j.setPlaceholder(true); + } + } + } + + /** + * Creates a new NJTree object. + * + * @param sequence DOCUMENT ME! + * @param type DOCUMENT ME! + * @param pwtype DOCUMENT ME! + * @param start DOCUMENT ME! + * @param end DOCUMENT ME! + */ + public NJTree(SequenceI[] sequence, + AlignmentView seqData, + String type, + String pwtype, + int start, int end) + { + this.sequence = sequence; + this.node = new Vector(); + this.type = type; + this.pwtype = pwtype; + if (seqData!=null) { + this.seqData = seqData; + } else { + SeqCigar[] seqs = new SeqCigar[sequence.length]; + for(int i=0; i 2) + { + if (type.equals("NJ")) + { + findMinNJDistance(); + } + else + { + findMinDistance(); + } + + Cluster c = joinClusters(mini, minj); + + done[minj] = 1; + + cluster.setElementAt(null, minj); + cluster.setElementAt(c, mini); + + noClus--; + } + + boolean onefound = false; + + int one = -1; + int two = -1; + + for (int i = 0; i < noseqs; i++) + { + if (done[i] != 1) + { + if (onefound == false) + { + two = i; + onefound = true; + } + else + { + one = i; + } + } + } + + joinClusters(one, two); + top = (SequenceNode) (node.elementAt(one)); + + reCount(top); + findHeight(top); + findMaxDist(top); + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + * @param j DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Cluster joinClusters(int i, int j) + { + float dist = distance[i][j]; + + int noi = ((Cluster) cluster.elementAt(i)).value.length; + int noj = ((Cluster) cluster.elementAt(j)).value.length; + + int[] value = new int[noi + noj]; + + for (int ii = 0; ii < noi; ii++) + { + value[ii] = ((Cluster) cluster.elementAt(i)).value[ii]; + } + + for (int ii = noi; ii < (noi + noj); ii++) + { + value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi]; + } + + Cluster c = new Cluster(value); + + ri = findr(i, j); + rj = findr(j, i); + + if (type.equals("NJ")) + { + findClusterNJDistance(i, j); + } + else + { + findClusterDistance(i, j); + } + + SequenceNode sn = new SequenceNode(); + + sn.setLeft((SequenceNode) (node.elementAt(i))); + sn.setRight((SequenceNode) (node.elementAt(j))); + + SequenceNode tmpi = (SequenceNode) (node.elementAt(i)); + SequenceNode tmpj = (SequenceNode) (node.elementAt(j)); + + if (type.equals("NJ")) + { + findNewNJDistances(tmpi, tmpj, dist); + } + else + { + findNewDistances(tmpi, tmpj, dist); + } + + tmpi.setParent(sn); + tmpj.setParent(sn); + + node.setElementAt(sn, i); + + return c; + } + + /** + * DOCUMENT ME! + * + * @param tmpi DOCUMENT ME! + * @param tmpj DOCUMENT ME! + * @param dist DOCUMENT ME! + */ + public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj, + float dist) + { + + tmpi.dist = ((dist + ri) - rj) / 2; + tmpj.dist = (dist - tmpi.dist); + + if (tmpi.dist < 0) + { + tmpi.dist = 0; + } + + if (tmpj.dist < 0) + { + tmpj.dist = 0; + } + } + + /** + * DOCUMENT ME! + * + * @param tmpi DOCUMENT ME! + * @param tmpj DOCUMENT ME! + * @param dist DOCUMENT ME! + */ + public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj, + float dist) + { + float ih = 0; + float jh = 0; + + SequenceNode sni = tmpi; + SequenceNode snj = tmpj; + + while (sni != null) + { + ih = ih + sni.dist; + sni = (SequenceNode) sni.left(); + } + + while (snj != null) + { + jh = jh + snj.dist; + snj = (SequenceNode) snj.left(); + } + + tmpi.dist = ((dist / 2) - ih); + tmpj.dist = ((dist / 2) - jh); + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + * @param j DOCUMENT ME! + */ + public void findClusterDistance(int i, int j) + { + int noi = ((Cluster) cluster.elementAt(i)).value.length; + int noj = ((Cluster) cluster.elementAt(j)).value.length; + + // New distances from cluster to others + float[] newdist = new float[noseqs]; + + for (int l = 0; l < noseqs; l++) + { + if ((l != i) && (l != j)) + { + newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj)) / (noi + + noj); + } + else + { + newdist[l] = 0; + } + } + + for (int ii = 0; ii < noseqs; ii++) + { + distance[i][ii] = newdist[ii]; + distance[ii][i] = newdist[ii]; + } + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + * @param j DOCUMENT ME! + */ + public void findClusterNJDistance(int i, int j) + { + + // New distances from cluster to others + float[] newdist = new float[noseqs]; + + for (int l = 0; l < noseqs; l++) + { + if ((l != i) && (l != j)) + { + newdist[l] = ((distance[i][l] + distance[j][l]) - + distance[i][j]) / 2; + } + else + { + newdist[l] = 0; + } + } + + for (int ii = 0; ii < noseqs; ii++) + { + distance[i][ii] = newdist[ii]; + distance[ii][i] = newdist[ii]; + } + } + + /** + * DOCUMENT ME! + * + * @param i DOCUMENT ME! + * @param j DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float findr(int i, int j) + { + float tmp = 1; + + for (int k = 0; k < noseqs; k++) + { + if ((k != i) && (k != j) && (done[k] != 1)) + { + tmp = tmp + distance[i][k]; + } + } + + if (noClus > 2) + { + tmp = tmp / (noClus - 2); + } + + return tmp; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float findMinNJDistance() + { + float min = 100000; + + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i + 1; j < noseqs; j++) + { + if ((done[i] != 1) && (done[j] != 1)) + { + float tmp = distance[i][j] - (findr(i, j) + findr(j, i)); + + if (tmp < min) + { + mini = i; + minj = j; + + min = tmp; + } + } + } + } + + return min; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float findMinDistance() + { + float min = 100000; + + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i + 1; j < noseqs; j++) + { + if ((done[i] != 1) && (done[j] != 1)) + { + if (distance[i][j] < min) + { + mini = i; + minj = j; + + min = distance[i][j]; + } + } + } + } + + return min; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float[][] findDistances(String[] sequenceString) + { + float[][] distance = new float[noseqs][noseqs]; + + if (pwtype.equals("PID")) + { + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i; j < noseqs; j++) + { + if (j == i) + { + distance[i][i] = 0; + } + else + { + distance[i][j] = 100 - + Comparison.PID(sequenceString[i], sequenceString[j]); + + distance[j][i] = distance[i][j]; + } + } + } + } + else if (pwtype.equals("BL")) + { + int maxscore = 0; + int end = sequenceString[0].length(); + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i; j < noseqs; j++) + { + int score = 0; + + for (int k = 0; k < end; k++) + { + try + { + score += ResidueProperties.getBLOSUM62( + sequenceString[i].substring(k, k + 1), + sequenceString[j].substring(k, k + 1)); + } + catch (Exception ex) + { + System.err.println("err creating BLOSUM62 tree"); + ex.printStackTrace(); + } + } + + distance[i][j] = (float) score; + + if (score > maxscore) + { + maxscore = score; + } + } + } + + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i; j < noseqs; j++) + { + distance[i][j] = (float) maxscore - distance[i][j]; + distance[j][i] = distance[i][j]; + } + } + } + /* else if (pwtype.equals("SW")) + { + float max = -1; + + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i; j < noseqs; j++) + { + AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep"); + as.calcScoreMatrix(); + as.traceAlignment(); + as.printAlignment(System.out); + distance[i][j] = (float) as.maxscore; + + if (max < distance[i][j]) + { + max = distance[i][j]; + } + } + } + + for (int i = 0; i < (noseqs - 1); i++) + { + for (int j = i; j < noseqs; j++) + { + distance[i][j] = max - distance[i][j]; + distance[j][i] = distance[i][j]; + } + } + }/*/ + + return distance; + } + + /** + * DOCUMENT ME! + */ + public void makeLeaves() + { + cluster = new Vector(); + + for (int i = 0; i < noseqs; i++) + { + SequenceNode sn = new SequenceNode(); + + sn.setElement(sequence[i]); + sn.setName(sequence[i].getName()); + node.addElement(sn); + + int[] value = new int[1]; + value[0] = i; + + Cluster c = new Cluster(value); + cluster.addElement(c); + } + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * @param leaves DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Vector findLeaves(SequenceNode node, Vector leaves) + { + if (node == null) + { + return leaves; + } + + if ((node.left() == null) && (node.right() == null)) + { + leaves.addElement(node); + + return leaves; + } + else + { + findLeaves((SequenceNode) node.left(), leaves); + findLeaves((SequenceNode) node.right(), leaves); + } + + return leaves; + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * @param count DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Object findLeaf(SequenceNode node, int count) + { + found = _findLeaf(node, count); + + return found; + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * @param count DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Object _findLeaf(SequenceNode node, int count) + { + if (node == null) + { + return null; + } + + if (node.ycount == count) + { + found = node.element(); + + return found; + } + else + { + _findLeaf((SequenceNode) node.left(), count); + _findLeaf((SequenceNode) node.right(), count); + } + + return found; + } + + /** + * printNode is mainly for debugging purposes. + * + * @param node SequenceNode + */ + public void printNode(SequenceNode node) + { + if (node == null) + { + return; + } + + if ((node.left() == null) && (node.right() == null)) + { + System.out.println("Leaf = " + + ((SequenceI) node.element()).getName()); + System.out.println("Dist " + ((SequenceNode) node).dist); + System.out.println("Boot " + node.getBootstrap()); + } + else + { + System.out.println("Dist " + ((SequenceNode) node).dist); + printNode((SequenceNode) node.left()); + printNode((SequenceNode) node.right()); + } + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + */ + public void findMaxDist(SequenceNode node) + { + if (node == null) + { + return; + } + + if ((node.left() == null) && (node.right() == null)) + { + float dist = ((SequenceNode) node).dist; + + if (dist > maxDistValue) + { + maxdist = (SequenceNode) node; + maxDistValue = dist; + } + } + else + { + findMaxDist((SequenceNode) node.left()); + findMaxDist((SequenceNode) node.right()); + } + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Vector getGroups() + { + return groups; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float getMaxHeight() + { + return maxheight; + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * @param threshold DOCUMENT ME! + */ + public void groupNodes(SequenceNode node, float threshold) + { + if (node == null) + { + return; + } + + if ((node.height / maxheight) > threshold) + { + groups.addElement(node); + } + else + { + groupNodes((SequenceNode) node.left(), threshold); + groupNodes((SequenceNode) node.right(), threshold); + } + } + + /** + * DOCUMENT ME! + * + * @param node DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public float findHeight(SequenceNode node) + { + if (node == null) + { + return maxheight; + } + + if ((node.left() == null) && (node.right() == null)) + { + node.height = ((SequenceNode) node.parent()).height + node.dist; + + if (node.height > maxheight) + { + return node.height; + } + else + { + return maxheight; + } + } + else + { + if (node.parent() != null) + { + node.height = ((SequenceNode) node.parent()).height + + node.dist; + } + else + { + maxheight = 0; + node.height = (float) 0.0; + } + + maxheight = findHeight((SequenceNode) (node.left())); + maxheight = findHeight((SequenceNode) (node.right())); + } + + return maxheight; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public SequenceNode reRoot() + { + if (maxdist != null) + { + ycount = 0; + + float tmpdist = maxdist.dist; + + // New top + SequenceNode sn = new SequenceNode(); + sn.setParent(null); + + // New right hand of top + SequenceNode snr = (SequenceNode) maxdist.parent(); + changeDirection(snr, maxdist); + System.out.println("Printing reversed tree"); + printN(snr); + snr.dist = tmpdist / 2; + maxdist.dist = tmpdist / 2; + + snr.setParent(sn); + maxdist.setParent(sn); + + sn.setRight(snr); + sn.setLeft(maxdist); + + top = sn; + + ycount = 0; + reCount(top); + findHeight(top); + } + + return top; + } + /** + * + * @return true if original sequence data can be recovered + */ + public boolean hasOriginalSequenceData() { + return seqData!=null; + } + /** + * Returns original alignment data used for calculation - or null where + * not available. + * + * @return null or cut'n'pasteable alignment + */ + public String printOriginalSequenceData(char gapChar) + { + if (seqData==null) + return null; + + StringBuffer sb = new StringBuffer(); + String[] seqdatas = seqData.getSequenceStrings(gapChar); + for(int i=0; i0) { - for (int i=0;i0) - { - sq.setPDBId(pdbid); - } - - if ( (start != null) && (end != null)) - { - sq.setStart(start.intValue()); - sq.setEnd(end.intValue()); - } - - if ((sfeatures != null) && (sfeatures.size()>0)) - { - SequenceFeature[] sfarray = (SequenceFeature[]) sfeatures.toArray(); - sq.setSequenceFeatures(sfarray); - } - - if ((seqds!=null) && !(seqds.getName().equals("THISISAPLACEHOLDER") && seqds.getLength()==0)) { - sq.setDatasetSequence(seqds); - } - - return namePresent; - } - - /** - * Form of the unique name used in uniquify for the i'th sequence in an ordered vector of sequences. - * @param i int - * @return String - */ - public static String unique_name(int i) - { - return new String("Sequence" + i); - } - - /** - * Generates a hash of SeqCharacterHash properties for each sequence - * in a sequence set, and optionally renames the sequences to an - * unambiguous 'safe' name. - * @param sequences SequenceI[] - * @param write_names boolean set this to rename each of the sequences to its unique_name(index) name - * @return Hashtable to be passed to @see deuniquify to recover original names (and properties) for renamed sequences - */ - public static Hashtable uniquify(SequenceI[] sequences, boolean write_names) - { - // Generate a safely named sequence set and a hash to recover the sequence names - Hashtable map = new Hashtable(); - //String[] un_names = new String[sequences.length]; - - for (int i = 0; i < sequences.length; i++) - { - String safename = unique_name(i); - map.put(safename, SeqCharacterHash(sequences[i])); - - if (write_names) - { - sequences[i].setName(safename); - } - } - - - return map; - } - /** - * recover unsafe sequence names and original properties for a sequence - * set using a map generated by @see uniquify(sequences,true) - * @param map Hashtable - * @param sequences SequenceI[] - * @return boolean - */ - public static boolean deuniquify(Hashtable map, SequenceI[] sequences) - { - jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(sequences); - SequenceI msq = null; - Enumeration keys = map.keys(); - Vector unmatched = new Vector(); - for (int i=0, j=sequences.length; i0) { - System.err.println("Did not find matches for :"); - for (Enumeration i = unmatched.elements(); i.hasMoreElements(); System.out.println(((SequenceI) i.nextElement()).getName())) - ; - return false; - } - - return true; - } - /** - * returns a subset of the sequenceI seuqences, - * including only those that contain at least one residue. - * @param sequences SequenceI[] - * @return SequenceI[] - */ - public static SequenceI[] getNonEmptySequenceSet(SequenceI[] sequences) { - // Identify first row of alignment with residues for prediction - boolean ungapped[] = new boolean[sequences.length]; - int msflen=0; - for (int i=0,j=sequences.length; iTitle:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2004

+ * + *

Company: Dundee University

+ * + * @author not attributable + * @version 1.0 + */ +public class SeqsetUtils +{ + + /** + * Store essential properties of a sequence in a hashtable for later recovery + * Keys are Name, Start, End, SeqFeatures, PdbId + * @param seq SequenceI + * @return Hashtable + */ + public static Hashtable SeqCharacterHash(SequenceI seq) + { + Hashtable sqinfo = new Hashtable(); + sqinfo.put("Name", seq.getName()); + sqinfo.put("Start", new Integer(seq.getStart())); + sqinfo.put("End", new Integer(seq.getEnd())); + Vector sfeat = new Vector(); + jalview.datamodel.SequenceFeature[] sfarray=seq.getSequenceFeatures(); + if (sfarray!=null && sfarray.length>0) { + for (int i=0;i0) + { + sq.setPDBId(pdbid); + } + + if ( (start != null) && (end != null)) + { + sq.setStart(start.intValue()); + sq.setEnd(end.intValue()); + } + + if ((sfeatures != null) && (sfeatures.size()>0)) + { + SequenceFeature[] sfarray = (SequenceFeature[]) sfeatures.toArray(); + sq.setSequenceFeatures(sfarray); + } + + if ((seqds!=null) && !(seqds.getName().equals("THISISAPLACEHOLDER") && seqds.getLength()==0)) { + sq.setDatasetSequence(seqds); + } + + return namePresent; + } + + /** + * Form of the unique name used in uniquify for the i'th sequence in an ordered vector of sequences. + * @param i int + * @return String + */ + public static String unique_name(int i) + { + return new String("Sequence" + i); + } + + /** + * Generates a hash of SeqCharacterHash properties for each sequence + * in a sequence set, and optionally renames the sequences to an + * unambiguous 'safe' name. + * @param sequences SequenceI[] + * @param write_names boolean set this to rename each of the sequences to its unique_name(index) name + * @return Hashtable to be passed to @see deuniquify to recover original names (and properties) for renamed sequences + */ + public static Hashtable uniquify(SequenceI[] sequences, boolean write_names) + { + // Generate a safely named sequence set and a hash to recover the sequence names + Hashtable map = new Hashtable(); + //String[] un_names = new String[sequences.length]; + + for (int i = 0; i < sequences.length; i++) + { + String safename = unique_name(i); + map.put(safename, SeqCharacterHash(sequences[i])); + + if (write_names) + { + sequences[i].setName(safename); + } + } + + + return map; + } + /** + * recover unsafe sequence names and original properties for a sequence + * set using a map generated by @see uniquify(sequences,true) + * @param map Hashtable + * @param sequences SequenceI[] + * @return boolean + */ + public static boolean deuniquify(Hashtable map, SequenceI[] sequences) + { + jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(sequences); + SequenceI msq = null; + Enumeration keys = map.keys(); + Vector unmatched = new Vector(); + for (int i=0, j=sequences.length; i0) { + System.err.println("Did not find matches for :"); + for (Enumeration i = unmatched.elements(); i.hasMoreElements(); System.out.println(((SequenceI) i.nextElement()).getName())) + ; + return false; + } + + return true; + } + /** + * returns a subset of the sequenceI seuqences, + * including only those that contain at least one residue. + * @param sequences SequenceI[] + * @return SequenceI[] + */ + public static SequenceI[] getNonEmptySequenceSet(SequenceI[] sequences) { + // Identify first row of alignment with residues for prediction + boolean ungapped[] = new boolean[sequences.length]; + int msflen=0; + for (int i=0,j=sequences.length; iTitle:

- * SequenceIdMatcher - *

Description:

- * Routine which does approximate Sequence Id resolution by name using - * string containment (on word boundaries) rather than equivalence - *

Copyright: Copyright (c) 2004

- * - *

Company: Dundee University

- * - * @author not attributable - * @version 1.0 - */ -public class SequenceIdMatcher -{ - private Hashtable names; - - public SequenceIdMatcher(SequenceI[] seqs) - { - names = new Hashtable(); - for (int i = 0; i < seqs.length; i++) - { - names.put(new SeqIdName(seqs[i].getName()), seqs[i]); - } - } - - SequenceI findIdMatch(SequenceI seq) - { - SeqIdName nam = new SeqIdName(seq.getName()); - - if (names.containsKey(nam)) - { - return (SequenceI) names.get(nam); - } - - return null; - } - - SequenceI findIdMatch(String seqnam) - { - SeqIdName nam = new SeqIdName(seqnam); - - if (names.containsKey(nam)) - { - return (SequenceI) names.get(nam); - } - - return null; - } - - /** - * findIdMatch - * - * Return pointers to sequences (or sequence object containers) - * which have same Id as a given set of different sequence objects - * - * @param seqs SequenceI[] - * @return SequenceI[] - */ - SequenceI[] findIdMatch(SequenceI[] seqs) - { - SequenceI[] namedseqs = null; - int i = 0; - SeqIdName nam; - - if (seqs.length > 0) - { - namedseqs = new SequenceI[seqs.length]; - do - { - nam = new SeqIdName(seqs[i].getName()); - - if (names.containsKey(nam)) - { - namedseqs[i] = (SequenceI) names.get(nam); - } - else - { - namedseqs[i] = null; - } - } - while (++i < seqs.length); - } - - return namedseqs; - } - - private class SeqIdName - { - String id; - - SeqIdName(String s) - { - if (s!=null) - id = new String(s); - else - id = ""; - } - - public int hashCode() - { - return ((id.length()>=4) ? id.substring(0, 4).hashCode() : id.hashCode()); - } - - public boolean equals(Object s) - { - if (s instanceof SeqIdName) - { - return this.equals( (SeqIdName) s); - } - else - { - if (s instanceof String) - { - return this.equals( (String) s); - } - } - - return false; - } - - /** - * Characters that define the end of a unique sequence ID at - * the beginning of an arbitrary ID string - * JBPNote: This is a heuristic that will fail for arbritrarily extended sequence id's - * (like portions of an aligned set of repeats from one sequence) - */ - private String WORD_SEP="~. |#\\/<>!\"£$%^*)}[@',?"; - - /** - * matches if one ID properly contains another at a whitespace boundary. - * TODO: (JBPNote) These are not efficient. should use char[] for speed - * todo: (JBPNote) Set separator characters appropriately - * @param s SeqIdName - * @return boolean - */ - public boolean equals(SeqIdName s) - { - if (id.length()>s.id.length()) { - return id.startsWith(s.id) ? - (WORD_SEP.indexOf(id.charAt(s.id.length()))>-1) - : false; - } else - return s.id.startsWith(id) ? - (s.id.equals(id) ? true : - (WORD_SEP.indexOf(s.id.charAt(id.length()))>-1)) - : false; - } - - public boolean equals(String s) - { - if (id.length()>s.length()) { - return id.startsWith(s) ? - (WORD_SEP.indexOf(id.charAt(s.length()))>-1) - : false; - } else - return s.startsWith(id) ? - (s.equals(id) ? true : - (WORD_SEP.indexOf(s.charAt(id.length()))>-1)) - : false; - } - } -} +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ +package jalview.analysis; + +import java.util.*; + +import jalview.datamodel.*; + +/** + *

Title:

+ * SequenceIdMatcher + *

Description:

+ * Routine which does approximate Sequence Id resolution by name using + * string containment (on word boundaries) rather than equivalence + *

Copyright: Copyright (c) 2004

+ * + *

Company: Dundee University

+ * + * @author not attributable + * @version 1.0 + */ +public class SequenceIdMatcher +{ + private Hashtable names; + + public SequenceIdMatcher(SequenceI[] seqs) + { + names = new Hashtable(); + for (int i = 0; i < seqs.length; i++) + { + names.put(new SeqIdName(seqs[i].getName()), seqs[i]); + } + } + + SequenceI findIdMatch(SequenceI seq) + { + SeqIdName nam = new SeqIdName(seq.getName()); + + if (names.containsKey(nam)) + { + return (SequenceI) names.get(nam); + } + + return null; + } + + SequenceI findIdMatch(String seqnam) + { + SeqIdName nam = new SeqIdName(seqnam); + + if (names.containsKey(nam)) + { + return (SequenceI) names.get(nam); + } + + return null; + } + + /** + * findIdMatch + * + * Return pointers to sequences (or sequence object containers) + * which have same Id as a given set of different sequence objects + * + * @param seqs SequenceI[] + * @return SequenceI[] + */ + SequenceI[] findIdMatch(SequenceI[] seqs) + { + SequenceI[] namedseqs = null; + int i = 0; + SeqIdName nam; + + if (seqs.length > 0) + { + namedseqs = new SequenceI[seqs.length]; + do + { + nam = new SeqIdName(seqs[i].getName()); + + if (names.containsKey(nam)) + { + namedseqs[i] = (SequenceI) names.get(nam); + } + else + { + namedseqs[i] = null; + } + } + while (++i < seqs.length); + } + + return namedseqs; + } + + private class SeqIdName + { + String id; + + SeqIdName(String s) + { + if (s!=null) + id = new String(s); + else + id = ""; + } + + public int hashCode() + { + return ((id.length()>=4) ? id.substring(0, 4).hashCode() : id.hashCode()); + } + + public boolean equals(Object s) + { + if (s instanceof SeqIdName) + { + return this.equals( (SeqIdName) s); + } + else + { + if (s instanceof String) + { + return this.equals( (String) s); + } + } + + return false; + } + + /** + * Characters that define the end of a unique sequence ID at + * the beginning of an arbitrary ID string + * JBPNote: This is a heuristic that will fail for arbritrarily extended sequence id's + * (like portions of an aligned set of repeats from one sequence) + */ + private String WORD_SEP="~. |#\\/<>!\"£$%^*)}[@',?"; + + /** + * matches if one ID properly contains another at a whitespace boundary. + * TODO: (JBPNote) These are not efficient. should use char[] for speed + * todo: (JBPNote) Set separator characters appropriately + * @param s SeqIdName + * @return boolean + */ + public boolean equals(SeqIdName s) + { + if (id.length()>s.id.length()) { + return id.startsWith(s.id) ? + (WORD_SEP.indexOf(id.charAt(s.id.length()))>-1) + : false; + } else + return s.id.startsWith(id) ? + (s.id.equals(id) ? true : + (WORD_SEP.indexOf(s.id.charAt(id.length()))>-1)) + : false; + } + + public boolean equals(String s) + { + if (id.length()>s.length()) { + return id.startsWith(s) ? + (WORD_SEP.indexOf(id.charAt(s.length()))>-1) + : false; + } else + return s.startsWith(id) ? + (s.equals(id) ? true : + (WORD_SEP.indexOf(s.charAt(id.length()))>-1)) + : false; + } + } +} diff --git a/src/jalview/appletgui/APopupMenu.java b/src/jalview/appletgui/APopupMenu.java index b85c7d2..3e25d44 100755 --- a/src/jalview/appletgui/APopupMenu.java +++ b/src/jalview/appletgui/APopupMenu.java @@ -1,459 +1,645 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer - * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -package jalview.appletgui; - -import java.awt.*; -import java.awt.event.*; -import java.util.Vector; - -import jalview.analysis.*; -import jalview.datamodel.*; -import jalview.schemes.*; - -public class APopupMenu - extends java.awt.PopupMenu implements ActionListener, ItemListener -{ - Menu groupMenu = new Menu(); - protected MenuItem clustalColour = new MenuItem(); - protected MenuItem zappoColour = new MenuItem(); - protected MenuItem taylorColour = new MenuItem(); - protected MenuItem hydrophobicityColour = new MenuItem(); - protected MenuItem helixColour = new MenuItem(); - protected MenuItem strandColour = new MenuItem(); - protected MenuItem turnColour = new MenuItem(); - protected MenuItem buriedColour = new MenuItem(); - protected CheckboxMenuItem abovePIDColour = new CheckboxMenuItem(); - protected MenuItem userDefinedColour = new MenuItem(); - protected MenuItem PIDColour = new MenuItem(); - protected MenuItem BLOSUM62Colour = new MenuItem(); - MenuItem noColourmenuItem = new MenuItem(); - protected CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem(); - - final AlignmentPanel ap; - MenuItem unGroupMenuItem = new MenuItem(); - MenuItem nucleotideMenuItem = new MenuItem(); - Menu colourMenu = new Menu(); - CheckboxMenuItem showBoxes = new CheckboxMenuItem(); - CheckboxMenuItem showText = new CheckboxMenuItem(); - CheckboxMenuItem showColourText = new CheckboxMenuItem(); - - public APopupMenu(AlignmentPanel apanel, final Sequence seq, Vector links) - { - /////////////////////////////////////////////////////////// - // If this is activated from the sequence panel, the user may want to - // edit or annotate a particular residue. Therefore display the residue menu - // - // If from the IDPanel, we must display the sequence menu - ////////////////////////////////////////////////////////// - - this.ap = apanel; - - try - { - jbInit(); - } - catch (Exception e) - { - e.printStackTrace(); - } - - SequenceGroup sg = ap.av.getSelectionGroup(); - if (sg != null) - { - showText.setState(sg.getDisplayText()); - showColourText.setState(sg.getColourText()); - showBoxes.setState(sg.getDisplayBoxes()); - } - - if (!ap.av.alignment.getGroups().contains(sg)) - { - groupMenu.remove(unGroupMenuItem); - } - - if (seq != null && links!=null) - { - Menu linkMenu = new Menu("Link"); - MenuItem item; - String link; - for(int i=0; i-1) - id = id.substring(id.lastIndexOf("|")+1); - - final String url = link.substring(link.indexOf("|")+1, link.indexOf("$SEQUENCE_ID$")) - + id + - link.substring(link.indexOf("$SEQUENCE_ID$") + 13); - - item.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - ap.alignFrame.showURL(url, target); - } - }); - linkMenu.add(item); - } - add(linkMenu); - - item = new MenuItem("Show PDB Structure"); - item.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - addPDB(seq); - } - }); - - add(item); - - - } - } - - public void itemStateChanged(ItemEvent evt) - { - if(evt.getSource()==abovePIDColour) - abovePIDColour_itemStateChanged(); - else if(evt.getSource()==showColourText) - showColourText_itemStateChanged(); - else if(evt.getSource()==showText) - showText_itemStateChanged(); - else if(evt.getSource()==showBoxes) - showBoxes_itemStateChanged() ; - } - - public void actionPerformed(ActionEvent evt) - { - if(evt.getSource()==clustalColour) - clustalColour_actionPerformed(); - else if(evt.getSource()==zappoColour) - zappoColour_actionPerformed(); - else if(evt.getSource()==taylorColour) - taylorColour_actionPerformed(); - else if(evt.getSource()==hydrophobicityColour) - hydrophobicityColour_actionPerformed(); - else if(evt.getSource()==helixColour) - helixColour_actionPerformed(); - else if(evt.getSource()==strandColour) - strandColour_actionPerformed(); - else if(evt.getSource()==clustalColour) - turnColour_actionPerformed(); - else if(evt.getSource()==buriedColour) - buriedColour_actionPerformed(); - else if(evt.getSource()==nucleotideMenuItem) - nucleotideMenuItem_actionPerformed(); - - else if(evt.getSource()==userDefinedColour) - userDefinedColour_actionPerformed(); - else if(evt.getSource()==PIDColour) - PIDColour_actionPerformed(); - else if(evt.getSource()==BLOSUM62Colour) - BLOSUM62Colour_actionPerformed(); - else if(evt.getSource()==noColourmenuItem) - noColourmenuItem_actionPerformed(); - else if(evt.getSource()==conservationMenuItem) - conservationMenuItem_itemStateChanged(); - else if(evt.getSource()==unGroupMenuItem) - unGroupMenuItem_actionPerformed(); - - } - - void addPDB(Sequence seq) - { - CutAndPasteTransfer cap = new CutAndPasteTransfer(true, ap.alignFrame); - cap.setText("Paste your PDB file here."); - cap.setPDBImport(seq); - Frame frame = new Frame(); - frame.add(cap); - jalview.bin.JalviewLite.addFrame(frame, "Paste PDB file ", 400, 300); - } - - private void jbInit() - throws Exception - { - groupMenu.setLabel("Group"); - groupMenu.setLabel("Define"); - - unGroupMenuItem.setLabel("Remove Group"); - unGroupMenuItem.addActionListener(this); - - nucleotideMenuItem.setLabel("Nucleotide"); - nucleotideMenuItem.addActionListener(this); - conservationMenuItem.addItemListener(this); - abovePIDColour.addItemListener(this); - colourMenu.setLabel("Group Colour"); - showBoxes.setLabel("Boxes"); - showBoxes.setState(true); - showBoxes.addItemListener(this); - - showText.setLabel("Text"); - showText.addItemListener(this); - showColourText.setLabel("Colour Text"); - showColourText.addItemListener(this); - - add(groupMenu); - groupMenu.add(unGroupMenuItem); - groupMenu.add(colourMenu); - groupMenu.addSeparator(); - groupMenu.add(showBoxes); - groupMenu.add(showText); - groupMenu.add(showColourText); - colourMenu.add(noColourmenuItem); - colourMenu.add(clustalColour); - colourMenu.add(BLOSUM62Colour); - colourMenu.add(PIDColour); - colourMenu.add(zappoColour); - colourMenu.add(taylorColour); - colourMenu.add(hydrophobicityColour); - colourMenu.add(helixColour); - colourMenu.add(strandColour); - colourMenu.add(turnColour); - colourMenu.add(buriedColour); - colourMenu.add(nucleotideMenuItem); - colourMenu.add(userDefinedColour); - colourMenu.addSeparator(); - colourMenu.add(abovePIDColour); - colourMenu.add(conservationMenuItem); - - noColourmenuItem.setLabel("None"); - noColourmenuItem.addActionListener(this); - - clustalColour.setLabel("Clustalx colours"); - clustalColour.addActionListener(this); - zappoColour.setLabel("Zappo"); - zappoColour.addActionListener(this); - taylorColour.setLabel("Taylor"); - taylorColour.addActionListener(this); - hydrophobicityColour.setLabel("Hydrophobicity"); - hydrophobicityColour.addActionListener(this); - helixColour.setLabel("Helix propensity"); - helixColour.addActionListener(this); - strandColour.setLabel("Strand propensity"); - strandColour.addActionListener(this); - turnColour.setLabel("Turn propensity"); - turnColour.addActionListener(this); - buriedColour.setLabel("Buried Index"); - buriedColour.addActionListener(this); - abovePIDColour.setLabel("Above % Identity"); - - userDefinedColour.setLabel("User Defined"); - userDefinedColour.addActionListener(this); - PIDColour.setLabel("Percentage Identity"); - PIDColour.addActionListener(this); - BLOSUM62Colour.setLabel("BLOSUM62"); - BLOSUM62Colour.addActionListener(this); - conservationMenuItem.setLabel("Conservation"); - - } - - void refresh() - { - ap.seqPanel.seqCanvas.repaint(); - if(ap.overviewPanel!=null) - ap.overviewPanel.updateOverviewImage(); - } - - protected void clustalColour_actionPerformed() - { - SequenceGroup sg = getGroup(); - sg.cs = new ClustalxColourScheme(sg.sequences, ap.av.alignment.getWidth()); - refresh(); - } - - protected void zappoColour_actionPerformed() - { - getGroup().cs = new ZappoColourScheme(); - refresh(); - } - - protected void taylorColour_actionPerformed() - { - getGroup().cs = new TaylorColourScheme(); - refresh(); - } - - protected void hydrophobicityColour_actionPerformed() - { - getGroup().cs = new HydrophobicColourScheme(); - refresh(); - } - - protected void helixColour_actionPerformed() - { - getGroup().cs = new HelixColourScheme(); - refresh(); - } - - protected void strandColour_actionPerformed() - { - getGroup().cs = new StrandColourScheme(); - refresh(); - } - - protected void turnColour_actionPerformed() - { - getGroup().cs = new TurnColourScheme(); - refresh(); - } - - protected void buriedColour_actionPerformed() - { - getGroup().cs = new BuriedColourScheme(); - refresh(); - } - - public void nucleotideMenuItem_actionPerformed() - { - getGroup().cs = new NucleotideColourScheme(); - refresh(); - } - - protected void abovePIDColour_itemStateChanged() - { - SequenceGroup sg = getGroup(); - if(sg.cs==null) - return; - - if (abovePIDColour.getState()) - { - sg.cs.setConsensus(AAFrequency.calculate(sg.sequences, 0, - ap.av.alignment.getWidth())); - int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, - getGroup().getName()); - - sg.cs.setThreshold(threshold, ap.av.getIgnoreGapsConsensus()); - - SliderPanel.showPIDSlider(); - - } - else // remove PIDColouring - { - sg.cs.setThreshold(0, ap.av.getIgnoreGapsConsensus()); - } - - refresh(); - - } - - protected void userDefinedColour_actionPerformed() - { - new UserDefinedColours(ap, getGroup()); - } - - protected void PIDColour_actionPerformed() - { - SequenceGroup sg = getGroup(); - sg.cs = new PIDColourScheme(); - sg.cs.setConsensus(AAFrequency.calculate(sg.sequences, 0, - ap.av.alignment.getWidth())); - refresh(); - } - - protected void BLOSUM62Colour_actionPerformed() - { - SequenceGroup sg = getGroup(); - - sg.cs = new Blosum62ColourScheme(); - - sg.cs.setConsensus(AAFrequency.calculate(sg.sequences, 0, - ap.av.alignment.getWidth())); - - refresh(); - } - - protected void noColourmenuItem_actionPerformed() - { - getGroup().cs = null; - refresh(); - } - - protected void conservationMenuItem_itemStateChanged() - { - SequenceGroup sg = getGroup(); - if(sg.cs==null) - return; - - if (conservationMenuItem.getState()) - { - - Conservation c = new Conservation("Group", - ResidueProperties.propHash, 3, - sg.sequences, 0, - ap.av.alignment.getWidth()); - - c.calculate(); - c.verdict(false, ap.av.ConsPercGaps); - - sg.cs.setConservation(c); - - SliderPanel.setConservationSlider(ap, sg.cs, sg.getName()); - SliderPanel.showConservationSlider(); - } - else // remove ConservationColouring - { - sg.cs.setConservation(null); - } - - refresh(); - } - - - SequenceGroup getGroup() - { - SequenceGroup sg = ap.av.getSelectionGroup(); - - // this method won't add a new group if it already exists - if(sg!=null) - ap.av.alignment.addGroup(sg); - - return sg; - } - - void unGroupMenuItem_actionPerformed() - { - SequenceGroup sg = ap.av.getSelectionGroup(); - ap.av.alignment.deleteGroup(sg); - ap.av.setSelectionGroup(null); - ap.repaint(); - } - - public void showColourText_itemStateChanged() - { - getGroup().setColourText(showColourText.getState()); - refresh(); - } - - public void showText_itemStateChanged() - { - getGroup().setDisplayText(showText.getState()); - refresh(); - } - - public void showBoxes_itemStateChanged() - { - getGroup().setDisplayBoxes(showBoxes.getState()); - refresh(); - } - -} +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +package jalview.appletgui; + +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; + +import jalview.analysis.*; +import jalview.datamodel.*; +import jalview.schemes.*; + +public class APopupMenu + extends java.awt.PopupMenu implements ActionListener, ItemListener +{ + Menu groupMenu = new Menu(); + protected MenuItem clustalColour = new MenuItem(); + protected MenuItem zappoColour = new MenuItem(); + protected MenuItem taylorColour = new MenuItem(); + protected MenuItem hydrophobicityColour = new MenuItem(); + protected MenuItem helixColour = new MenuItem(); + protected MenuItem strandColour = new MenuItem(); + protected MenuItem turnColour = new MenuItem(); + protected MenuItem buriedColour = new MenuItem(); + protected CheckboxMenuItem abovePIDColour = new CheckboxMenuItem(); + protected MenuItem userDefinedColour = new MenuItem(); + protected MenuItem PIDColour = new MenuItem(); + protected MenuItem BLOSUM62Colour = new MenuItem(); + MenuItem noColourmenuItem = new MenuItem(); + protected CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem(); + + final AlignmentPanel ap; + MenuItem unGroupMenuItem = new MenuItem(); + MenuItem nucleotideMenuItem = new MenuItem(); + Menu colourMenu = new Menu(); + CheckboxMenuItem showBoxes = new CheckboxMenuItem(); + CheckboxMenuItem showText = new CheckboxMenuItem(); + CheckboxMenuItem showColourText = new CheckboxMenuItem(); + Menu editMenu = new Menu("Edit"); + MenuItem copy = new MenuItem("Copy (Jalview Only)"); + MenuItem cut = new MenuItem("Cut (Jalview Only)"); + MenuItem toUpper = new MenuItem("To Upper Case"); + MenuItem toLower = new MenuItem("To Lower Case"); + MenuItem toggleCase = new MenuItem("Toggle Case"); + Menu outputmenu = new Menu(); + Menu seqMenu = new Menu(); + MenuItem pdb = new MenuItem(); + MenuItem hideSeqs = new MenuItem(); + MenuItem repGroup = new MenuItem(); + + Sequence seq; + MenuItem revealAll = new MenuItem(); + + public APopupMenu(AlignmentPanel apanel, final Sequence seq, Vector links) + { + /////////////////////////////////////////////////////////// + // If this is activated from the sequence panel, the user may want to + // edit or annotate a particular residue. Therefore display the residue menu + // + // If from the IDPanel, we must display the sequence menu + ////////////////////////////////////////////////////////// + + this.ap = apanel; + this.seq = seq; + + try + { + jbInit(); + } + catch (Exception e) + { + e.printStackTrace(); + } + + for (int i = 0; i < jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS.length; i++) + { + MenuItem item = new MenuItem( jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS[i] ); + + item.addActionListener(this); + outputmenu.add(item); + } + + SequenceGroup sg = ap.av.getSelectionGroup(); + + if (sg != null && sg.getSize(false)>0) + { + showText.setState(sg.getDisplayText()); + showColourText.setState(sg.getColourText()); + showBoxes.setState(sg.getDisplayBoxes()); + if (!ap.av.alignment.getGroups().contains(sg)) + { + groupMenu.remove(unGroupMenuItem); + } + + } + else + { + remove(hideSeqs); + remove(groupMenu); + } + + if (links!=null) + { + Menu linkMenu = new Menu("Link"); + MenuItem item; + String link; + for(int i=0; i -1) + { + String id = seq.getName(); + if (id.indexOf("|") > -1) + id = id.substring(id.lastIndexOf("|") + 1); + + url = link.substring(link.indexOf("|") + 1, + link.indexOf("$SEQUENCE_ID$")) + + id + + link.substring(link.indexOf("$SEQUENCE_ID$") + 13); + } + else + url = link.substring(link.lastIndexOf("|")+1); + + System.out.println("add "+url +" "+target); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + ap.alignFrame.showURL(url, target); + } + }); + linkMenu.add(item); + } + if(seq!=null) + seqMenu.add(linkMenu); + else + add(linkMenu); + } + if(seq!=null) + { + seqMenu.setLabel(seq.getName()); + repGroup.setLabel("Represent Group with " + seq.getName()); + } + else + remove(seqMenu); + + if(!ap.av.hasHiddenRows) + remove(revealAll); + } + + public void itemStateChanged(ItemEvent evt) + { + if(evt.getSource()==abovePIDColour) + abovePIDColour_itemStateChanged(); + else if(evt.getSource()==showColourText) + showColourText_itemStateChanged(); + else if(evt.getSource()==showText) + showText_itemStateChanged(); + else if(evt.getSource()==showBoxes) + showBoxes_itemStateChanged() ; + } + + public void actionPerformed(ActionEvent evt) + { + Object source = evt.getSource(); + if(source==clustalColour) + clustalColour_actionPerformed(); + else if(source==zappoColour) + zappoColour_actionPerformed(); + else if(source==taylorColour) + taylorColour_actionPerformed(); + else if(source==hydrophobicityColour) + hydrophobicityColour_actionPerformed(); + else if(source==helixColour) + helixColour_actionPerformed(); + else if(source==strandColour) + strandColour_actionPerformed(); + else if(source==clustalColour) + turnColour_actionPerformed(); + else if(source==buriedColour) + buriedColour_actionPerformed(); + else if(source==nucleotideMenuItem) + nucleotideMenuItem_actionPerformed(); + + else if (source == userDefinedColour) + userDefinedColour_actionPerformed(); + else if (source == PIDColour) + PIDColour_actionPerformed(); + else if (source == BLOSUM62Colour) + BLOSUM62Colour_actionPerformed(); + else if (source == noColourmenuItem) + noColourmenuItem_actionPerformed(); + else if (source == conservationMenuItem) + conservationMenuItem_itemStateChanged(); + else if (source == unGroupMenuItem) + unGroupMenuItem_actionPerformed(); + + else if(source == pdb) + addPDB(); + else if(source == hideSeqs) + hideSequences(false); + else if(source == repGroup) + hideSequences(true); + else if(source == revealAll) + { + ap.av.showAllHiddenSeqs(); + } + + else if(source==copy) + ap.alignFrame.copy_actionPerformed(); + else if(source==cut) + ap.alignFrame.cut_actionPerformed(); + else if(source==toUpper || source==toLower || source==toggleCase) + { + SequenceGroup sg = ap.av.getSelectionGroup(); + if (sg != null) + { + for (int g = 0; g < sg.getSize(true); g++) + { + int start = sg.getStartRes(); + int end = sg.getEndRes() + 1; + + do + { + if (ap.av.hasHiddenColumns) + { + end = ap.av.colSel.getHiddenBoundaryRight(start); + if (start == end) + end = sg.getEndRes() + 1; + if (end > sg.getEndRes()) + end = sg.getEndRes() + 1; + } + + if (source == toggleCase) + ( (SequenceI) sg.getSequences(true).elementAt(g)) + .toggleCase(start, end); + else + ( (SequenceI) sg.getSequences(true).elementAt(g)) + .changeCase(source == toUpper, start, end); + + if (ap.av.hasHiddenColumns) + { + start = ap.av.colSel.adjustForHiddenColumns(end); + start = ap.av.colSel.getHiddenBoundaryLeft(start) + 1; + } + + } + while (end < sg.getEndRes()); + } + ap.seqPanel.seqCanvas.repaint(); + } + } + else + outputText(evt); + + } + + void outputText(ActionEvent e) + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(false, ap.alignFrame); + Vector vseqs = new Vector(); + + String [] selection = ap.av.getViewAsString(true); + SequenceI [] seqs = ap.av.getSelectionAsNewSequence(); + if (selection != null) + { + for (int i = 0; i < selection.length; i++) + { + Sequence seq = new Sequence( + seqs[i].getName(), + selection[i], + seqs[i].getStart(), seqs[i].getEnd()); + seq.setDescription(seqs[i].getDescription()); + vseqs.addElement( seq ); + } + } + + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, + "Selection output - " + e.getActionCommand(), + 600, 500); + + cap.setText(new jalview.io.AppletFormatAdapter().formatSequences( + e.getActionCommand(), + vseqs, + ap.av.showJVSuffix)); + + } + + void addPDB() + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(true, ap.alignFrame); + cap.setText("Paste your PDB file here."); + cap.setPDBImport(seq); + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, "Paste PDB file ", 400, 300); + } + + private void jbInit() + throws Exception + { + groupMenu.setLabel("Group"); + groupMenu.setLabel("Selection"); + + unGroupMenuItem.setLabel("Remove Group"); + unGroupMenuItem.addActionListener(this); + + nucleotideMenuItem.setLabel("Nucleotide"); + nucleotideMenuItem.addActionListener(this); + conservationMenuItem.addItemListener(this); + abovePIDColour.addItemListener(this); + colourMenu.setLabel("Group Colour"); + showBoxes.setLabel("Boxes"); + showBoxes.setState(true); + showBoxes.addItemListener(this); + + showText.setLabel("Text"); + showText.addItemListener(this); + showColourText.setLabel("Colour Text"); + showColourText.addItemListener(this); + outputmenu.setLabel("Output to Textbox..."); + seqMenu.setLabel("Sequence"); + pdb.setLabel("View PDB Structure"); + hideSeqs.setLabel("Hide Sequences"); + repGroup.setLabel("Represent Group with"); + revealAll.setLabel("Reveal All"); + + add(groupMenu); + this.add(seqMenu); + this.add(hideSeqs); + this.add(revealAll); + groupMenu.add(editMenu); + groupMenu.add(outputmenu); + groupMenu.addSeparator(); + groupMenu.add(unGroupMenuItem); + groupMenu.add(colourMenu); + groupMenu.add(showBoxes); + groupMenu.add(showText); + groupMenu.add(showColourText); + colourMenu.add(noColourmenuItem); + colourMenu.add(clustalColour); + colourMenu.add(BLOSUM62Colour); + colourMenu.add(PIDColour); + colourMenu.add(zappoColour); + colourMenu.add(taylorColour); + colourMenu.add(hydrophobicityColour); + colourMenu.add(helixColour); + colourMenu.add(strandColour); + colourMenu.add(turnColour); + colourMenu.add(buriedColour); + colourMenu.add(nucleotideMenuItem); + colourMenu.add(userDefinedColour); + colourMenu.addSeparator(); + colourMenu.add(abovePIDColour); + colourMenu.add(conservationMenuItem); + + noColourmenuItem.setLabel("None"); + noColourmenuItem.addActionListener(this); + + clustalColour.setLabel("Clustalx colours"); + clustalColour.addActionListener(this); + zappoColour.setLabel("Zappo"); + zappoColour.addActionListener(this); + taylorColour.setLabel("Taylor"); + taylorColour.addActionListener(this); + hydrophobicityColour.setLabel("Hydrophobicity"); + hydrophobicityColour.addActionListener(this); + helixColour.setLabel("Helix propensity"); + helixColour.addActionListener(this); + strandColour.setLabel("Strand propensity"); + strandColour.addActionListener(this); + turnColour.setLabel("Turn propensity"); + turnColour.addActionListener(this); + buriedColour.setLabel("Buried Index"); + buriedColour.addActionListener(this); + abovePIDColour.setLabel("Above % Identity"); + + userDefinedColour.setLabel("User Defined"); + userDefinedColour.addActionListener(this); + PIDColour.setLabel("Percentage Identity"); + PIDColour.addActionListener(this); + BLOSUM62Colour.setLabel("BLOSUM62"); + BLOSUM62Colour.addActionListener(this); + conservationMenuItem.setLabel("Conservation"); + + editMenu.add(copy); + copy.addActionListener(this); + editMenu.add(cut); + cut.addActionListener(this); + editMenu.add(toUpper); + toUpper.addActionListener(this); + editMenu.add(toLower); + toLower.addActionListener(this); + editMenu.add(toggleCase); + seqMenu.add(pdb); + seqMenu.add(repGroup); + toggleCase.addActionListener(this); + pdb.addActionListener(this); + hideSeqs.addActionListener(this); + repGroup.addActionListener(this); + revealAll.addActionListener(this); + + } + + void refresh() + { + ap.seqPanel.seqCanvas.repaint(); + if(ap.overviewPanel!=null) + ap.overviewPanel.updateOverviewImage(); + } + + protected void clustalColour_actionPerformed() + { + SequenceGroup sg = getGroup(); + sg.cs = new ClustalxColourScheme(sg.getSequences(true), ap.av.alignment.getWidth()); + refresh(); + } + + protected void zappoColour_actionPerformed() + { + getGroup().cs = new ZappoColourScheme(); + refresh(); + } + + protected void taylorColour_actionPerformed() + { + getGroup().cs = new TaylorColourScheme(); + refresh(); + } + + protected void hydrophobicityColour_actionPerformed() + { + getGroup().cs = new HydrophobicColourScheme(); + refresh(); + } + + protected void helixColour_actionPerformed() + { + getGroup().cs = new HelixColourScheme(); + refresh(); + } + + protected void strandColour_actionPerformed() + { + getGroup().cs = new StrandColourScheme(); + refresh(); + } + + protected void turnColour_actionPerformed() + { + getGroup().cs = new TurnColourScheme(); + refresh(); + } + + protected void buriedColour_actionPerformed() + { + getGroup().cs = new BuriedColourScheme(); + refresh(); + } + + public void nucleotideMenuItem_actionPerformed() + { + getGroup().cs = new NucleotideColourScheme(); + refresh(); + } + + protected void abovePIDColour_itemStateChanged() + { + SequenceGroup sg = getGroup(); + if(sg.cs==null) + return; + + if (abovePIDColour.getState()) + { + sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(true), 0, + ap.av.alignment.getWidth())); + int threshold = SliderPanel.setPIDSliderSource(ap, sg.cs, + getGroup().getName()); + + sg.cs.setThreshold(threshold, ap.av.getIgnoreGapsConsensus()); + + SliderPanel.showPIDSlider(); + + } + else // remove PIDColouring + { + sg.cs.setThreshold(0, ap.av.getIgnoreGapsConsensus()); + } + + refresh(); + + } + + protected void userDefinedColour_actionPerformed() + { + new UserDefinedColours(ap, getGroup()); + } + + protected void PIDColour_actionPerformed() + { + SequenceGroup sg = getGroup(); + sg.cs = new PIDColourScheme(); + sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(true), 0, + ap.av.alignment.getWidth())); + refresh(); + } + + protected void BLOSUM62Colour_actionPerformed() + { + SequenceGroup sg = getGroup(); + + sg.cs = new Blosum62ColourScheme(); + + sg.cs.setConsensus(AAFrequency.calculate(sg.getSequences(true), 0, + ap.av.alignment.getWidth())); + + refresh(); + } + + protected void noColourmenuItem_actionPerformed() + { + getGroup().cs = null; + refresh(); + } + + protected void conservationMenuItem_itemStateChanged() + { + SequenceGroup sg = getGroup(); + if(sg.cs==null) + return; + + if (conservationMenuItem.getState()) + { + + Conservation c = new Conservation("Group", + ResidueProperties.propHash, 3, + sg.getSequences(true), 0, + ap.av.alignment.getWidth()); + + c.calculate(); + c.verdict(false, ap.av.ConsPercGaps); + + sg.cs.setConservation(c); + + SliderPanel.setConservationSlider(ap, sg.cs, sg.getName()); + SliderPanel.showConservationSlider(); + } + else // remove ConservationColouring + { + sg.cs.setConservation(null); + } + + refresh(); + } + + + SequenceGroup getGroup() + { + SequenceGroup sg = ap.av.getSelectionGroup(); + + // this method won't add a new group if it already exists + if(sg!=null) + ap.av.alignment.addGroup(sg); + + return sg; + } + + void unGroupMenuItem_actionPerformed() + { + SequenceGroup sg = ap.av.getSelectionGroup(); + ap.av.alignment.deleteGroup(sg); + ap.av.setSelectionGroup(null); + ap.repaint(); + } + + public void showColourText_itemStateChanged() + { + getGroup().setColourText(showColourText.getState()); + refresh(); + } + + public void showText_itemStateChanged() + { + getGroup().setDisplayText(showText.getState()); + refresh(); + } + + public void showBoxes_itemStateChanged() + { + getGroup().setDisplayBoxes(showBoxes.getState()); + refresh(); + } + + void hideSequences(boolean representGroup) + { + SequenceGroup sg = ap.av.getSelectionGroup(); + if(sg==null || sg.getSize(false)<1) + { + ap.av.hideSequence(seq); + return; + } + + int index = 0; + while(index < sg.getSize(false)) + { + if(representGroup && sg.getSequenceAt(index)!=seq) + { + seq.addHiddenSequence(sg.getSequenceAt(index)); + ap.av.hideSequence(sg.getSequenceAt(index)); + } + else if(!representGroup) + { + ap.av.hideSequence(sg.getSequenceAt(index)); + } + index ++; + } + + ap.av.setSelectionGroup(null); + } + +} diff --git a/src/jalview/appletgui/AlignFrame.java b/src/jalview/appletgui/AlignFrame.java index 189a36d..e37061a 100755 --- a/src/jalview/appletgui/AlignFrame.java +++ b/src/jalview/appletgui/AlignFrame.java @@ -1,2176 +1,2406 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer - * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -package jalview.appletgui; - -import jalview.schemes.*; -import jalview.datamodel.*; -import jalview.analysis.*; -import jalview.io.*; -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import java.io.InputStreamReader; -import java.io.BufferedReader; -import java.net.URL; - - -public class AlignFrame extends Frame implements ActionListener, - ItemListener, KeyListener, MouseListener -{ - public AlignmentPanel alignPanel; - public AlignViewport viewport; - int NEW_WINDOW_WIDTH = 700; - int NEW_WINDOW_HEIGHT = 500; - jalview.bin.JalviewLite applet; - - - public AlignFrame(AlignmentI al, - jalview.bin.JalviewLite applet, - String title, - boolean embedded) - { - try{ - jbInit(); - }catch(Exception ex) - { - ex.printStackTrace(); - } - - this.applet = applet; - viewport = new AlignViewport(al, applet); - alignPanel = new AlignmentPanel(this, viewport); - - annotationPanelMenuItem.setState(viewport.showAnnotation); - - if(applet!=null) - { - String param = applet.getParameter("sortBy"); - if (param != null) - { - if (param.equalsIgnoreCase("Id")) - sortIDMenuItem_actionPerformed(); - else if (param.equalsIgnoreCase("Pairwise Identity")) - sortPairwiseMenuItem_actionPerformed(); - } - - param = applet.getParameter("wrap"); - if (param != null) - { - if (param.equalsIgnoreCase("true")) - { - wrapMenuItem.setState(true); - wrapMenuItem_actionPerformed(); - } - } - - try - { - param = applet.getParameter("windowWidth"); - if (param != null) - { - int width = Integer.parseInt(param); - NEW_WINDOW_WIDTH = width; - } - param = applet.getParameter("windowHeight"); - if (param != null) - { - int height = Integer.parseInt(param); - NEW_WINDOW_HEIGHT = height; - } - } - catch (Exception ex) - {} - - } - - //Some JVMS send keyevents to Top frame or lowest panel, - //Havent worked out why yet. So add to both this frame and seqCanvas for now - this.addKeyListener(this); - alignPanel.seqPanel.seqCanvas.addKeyListener(this); - alignPanel.idPanel.idCanvas.addKeyListener(this); - - viewport.addPropertyChangeListener(new java.beans.PropertyChangeListener() - { - public void propertyChange(java.beans.PropertyChangeEvent evt) - { - if (evt.getPropertyName().equals("alignment")) - { - alignmentChanged(); - } - } - }); - - - if(embedded) - { - setEmbedded(); - } - else - { - add(alignPanel, BorderLayout.CENTER); - jalview.bin.JalviewLite.addFrame(this, title, NEW_WINDOW_WIDTH, - NEW_WINDOW_HEIGHT); - } - alignPanel.validate(); - alignPanel.repaint(); - } - public AlignViewport getAlignViewport() - { - return viewport; - } - - public SeqCanvas getSeqcanvas() - { - return alignPanel.seqPanel.seqCanvas; - } - - - /** - * DOCUMENT ME! - * - * @param String DOCUMENT ME! - */ - - public void parseFeaturesFile(String file) - { - String line = null; - try - { - BufferedReader in = null; - java.io.InputStream is = getClass().getResourceAsStream("/" + file); - if (is != null) - { - in = new BufferedReader(new java.io.InputStreamReader(is)); - } - else - { - URL url = new URL(file); - in = new BufferedReader(new InputStreamReader(url.openStream())); - } - - SequenceI seq = null; - String type, desc, token; - - int index, start, end; - StringTokenizer st; - SequenceFeature sf; - FeatureRenderer fr = alignPanel.seqPanel.seqCanvas.getFeatureRenderer(); - int lineNo = 0; - String featureGroup = null; - while ( (line = in.readLine()) != null) - { - lineNo++; - st = new StringTokenizer(line, "\t"); - if (st.countTokens() == 2) - { - type = st.nextToken(); - if(type.equalsIgnoreCase("startgroup")) - { - featureGroup = st.nextToken(); - } - else if(type.equalsIgnoreCase("endgroup")) - { - //We should check whether this is the current group, - //but at present theres no way of showing more than 1 group - st.nextToken(); - featureGroup = null; - } - else - { - UserColourScheme ucs = new UserColourScheme(st.nextToken()); - fr.setColour(type, ucs.findColour("A")); - } - continue; - } - - while (st.hasMoreElements()) - { - desc = st.nextToken(); - token = st.nextToken(); - if (!token.equals("ID_NOT_SPECIFIED")) - { - index = viewport.alignment.findIndex(viewport.alignment.findName( - token)); - st.nextToken(); - } - else - { - index = Integer.parseInt(st.nextToken()); - } - - start = Integer.parseInt(st.nextToken()); - end = Integer.parseInt(st.nextToken()); - - seq = viewport.alignment.getSequenceAt(index); - - type = st.nextToken(); - - if(fr.getColour(type)==null) - { - // Probably the old style groups file - UserColourScheme ucs = new UserColourScheme(type); - fr.setColour(type, ucs.findColour("A")); - } - - sf = new SequenceFeature(type, desc, "", start, end, featureGroup); - - seq.addSequenceFeature(sf); - } - } - - viewport.showSequenceFeatures = true; - sequenceFeatures.setState(true); - - alignPanel.repaint(); - - } - catch (Exception ex) - { - ex.printStackTrace(); - System.out.println("Error parsing groups file: " + ex +"\n"+line); - } - } - - public void keyPressed(KeyEvent evt) - { - switch (evt.getKeyCode()) - { - case 27: // escape key - deselectAllSequenceMenuItem_actionPerformed(); - break; - case KeyEvent.VK_X: - if (evt.isControlDown() || evt.isMetaDown()) - { - cut_actionPerformed(); - } - break; - case KeyEvent.VK_C: - if (evt.isControlDown() || evt.isMetaDown()) - { - copy_actionPerformed(); - } - break; - case KeyEvent.VK_V: - if (evt.isControlDown() || evt.isMetaDown()) - { - paste(true); - } - break; - case KeyEvent.VK_A: - if (evt.isControlDown() || evt.isMetaDown()) - { - selectAllSequenceMenuItem_actionPerformed(); - } - break; - case KeyEvent.VK_DOWN: - moveSelectedSequences(false); - break; - case KeyEvent.VK_UP: - moveSelectedSequences(true); - break; - case KeyEvent.VK_F: - if (evt.isControlDown()) - { - findMenuItem_actionPerformed(); - } - break; - case KeyEvent.VK_BACK_SPACE: - case KeyEvent.VK_DELETE: - cut_actionPerformed(); - break; - } - } - public void keyReleased(KeyEvent evt) - {} - public void keyTyped(KeyEvent evt) - {} - -public void itemStateChanged(ItemEvent evt) - { - if(evt.getSource()==colourTextMenuItem) - colourTextMenuItem_actionPerformed(); - else if(evt.getSource()==wrapMenuItem) - wrapMenuItem_actionPerformed(); - else if(evt.getSource()==scaleAbove) - scaleAbove_actionPerformed(); - else if(evt.getSource()==scaleLeft) - scaleLeft_actionPerformed(); - else if(evt.getSource()==scaleRight) - scaleRight_actionPerformed(); - else if(evt.getSource()==seqLimits) - seqLimits_itemStateChanged(); - else if(evt.getSource()==viewBoxesMenuItem) - viewBoxesMenuItem_actionPerformed(); - else if(evt.getSource()==viewTextMenuItem) - viewTextMenuItem_actionPerformed(); - else if(evt.getSource()==renderGapsMenuItem) - renderGapsMenuItem_actionPerformed(); - else if(evt.getSource()==annotationPanelMenuItem) - annotationPanelMenuItem_actionPerformed(); - else if(evt.getSource()==sequenceFeatures) - { - viewport.showSequenceFeatures(sequenceFeatures.getState()); - alignPanel.seqPanel.seqCanvas.repaint(); - } - else if(evt.getSource()==conservationMenuItem) - conservationMenuItem_actionPerformed(); - else if(evt.getSource()==abovePIDThreshold) - abovePIDThreshold_actionPerformed(); - else if(evt.getSource()==applyToAllGroups) - applyToAllGroups_actionPerformed(); - } - public void actionPerformed(ActionEvent evt) - { - if(evt.getSource()==inputText) - inputText_actionPerformed(); - else if(evt.getSource()==loadTree) - loadTree_actionPerformed(); - else if(evt.getSource()==closeMenuItem) - closeMenuItem_actionPerformed(); - else if(evt.getSource()==copy) - copy_actionPerformed(); - else if(evt.getSource()==undoMenuItem) - undoMenuItem_actionPerformed(); - else if(evt.getSource()==redoMenuItem) - redoMenuItem_actionPerformed(); - else if(evt.getSource()==inputText) - inputText_actionPerformed(); - else if(evt.getSource()==closeMenuItem) - closeMenuItem_actionPerformed(); - else if(evt.getSource()==undoMenuItem) - undoMenuItem_actionPerformed(); - else if(evt.getSource()==redoMenuItem) - redoMenuItem_actionPerformed(); - else if(evt.getSource()==copy) - copy_actionPerformed(); - else if(evt.getSource()==pasteNew) - pasteNew_actionPerformed(); - else if(evt.getSource()==pasteThis) - pasteThis_actionPerformed(); - else if(evt.getSource()==cut) - cut_actionPerformed(); - else if(evt.getSource()==delete) - delete_actionPerformed(); - else if(evt.getSource()==deleteGroups) - deleteGroups_actionPerformed(); - else if(evt.getSource()==selectAllSequenceMenuItem) - selectAllSequenceMenuItem_actionPerformed(); - else if(evt.getSource()==deselectAllSequenceMenuItem) - deselectAllSequenceMenuItem_actionPerformed(); - else if(evt.getSource()==invertSequenceMenuItem) - invertSequenceMenuItem_actionPerformed(); - else if(evt.getSource()==remove2LeftMenuItem) - remove2LeftMenuItem_actionPerformed(); - else if(evt.getSource()==remove2RightMenuItem) - remove2RightMenuItem_actionPerformed(); - else if(evt.getSource()==removeGappedColumnMenuItem) - removeGappedColumnMenuItem_actionPerformed(); - else if(evt.getSource()==removeAllGapsMenuItem) - removeAllGapsMenuItem_actionPerformed(); - else if(evt.getSource()==findMenuItem) - findMenuItem_actionPerformed(); - else if(evt.getSource()==font) - font_actionPerformed(); - else if(evt.getSource()==featureSettings) - featureSettings_actionPerformed(); - else if(evt.getSource()==overviewMenuItem) - overviewMenuItem_actionPerformed(); - else if(evt.getSource()==noColourmenuItem) - noColourmenuItem_actionPerformed(); - else if(evt.getSource()==clustalColour) - clustalColour_actionPerformed(); - else if(evt.getSource()==zappoColour) - zappoColour_actionPerformed(); - else if(evt.getSource()==taylorColour) - taylorColour_actionPerformed(); - else if(evt.getSource()==hydrophobicityColour) - hydrophobicityColour_actionPerformed(); - else if(evt.getSource()==helixColour) - helixColour_actionPerformed(); - else if(evt.getSource()==strandColour) - strandColour_actionPerformed(); - else if(evt.getSource()==turnColour) - turnColour_actionPerformed(); - else if(evt.getSource()==buriedColour) - buriedColour_actionPerformed(); - else if(evt.getSource()==nucleotideColour) - nucleotideColour_actionPerformed(); - else if(evt.getSource()==modifyPID) - modifyPID_actionPerformed(); - else if(evt.getSource()==modifyConservation) - modifyConservation_actionPerformed(); - else if(evt.getSource()==userDefinedColour) - userDefinedColour_actionPerformed(); - else if(evt.getSource()==PIDColour) - PIDColour_actionPerformed(); - else if(evt.getSource()==BLOSUM62Colour) - BLOSUM62Colour_actionPerformed(); - else if(evt.getSource()==annotationColour) - new AnnotationColourChooser(viewport, alignPanel); - else if(evt.getSource()==sortPairwiseMenuItem) - sortPairwiseMenuItem_actionPerformed(); - else if(evt.getSource()==sortIDMenuItem) - sortIDMenuItem_actionPerformed(); - else if(evt.getSource()==sortGroupMenuItem) - sortGroupMenuItem_actionPerformed(); - else if(evt.getSource()==removeRedundancyMenuItem) - removeRedundancyMenuItem_actionPerformed(); - else if(evt.getSource()==pairwiseAlignmentMenuItem) - pairwiseAlignmentMenuItem_actionPerformed(); - else if(evt.getSource()==PCAMenuItem) - PCAMenuItem_actionPerformed(); - else if(evt.getSource()==averageDistanceTreeMenuItem) - averageDistanceTreeMenuItem_actionPerformed(); - else if(evt.getSource()==neighbourTreeMenuItem) - neighbourTreeMenuItem_actionPerformed(); - else if(evt.getSource()==njTreeBlosumMenuItem) - njTreeBlosumMenuItem_actionPerformed(); - else if(evt.getSource()==avDistanceTreeBlosumMenuItem) - avTreeBlosumMenuItem_actionPerformed(); - else if(evt.getSource()==documentation) - documentation_actionPerformed(); - else if(evt.getSource()==about) - about_actionPerformed(); - - } - - public void inputText_actionPerformed() - { - CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this); - Frame frame = new Frame(); - frame.add(cap); - jalview.bin.JalviewLite.addFrame(frame, "Cut & Paste Input", 500, 500); - } - - protected void outputText_actionPerformed(ActionEvent e) - { - CutAndPasteTransfer cap = new CutAndPasteTransfer(false, this); - Frame frame = new Frame(); - frame.add(cap); - jalview.bin.JalviewLite.addFrame(frame, - "Alignment output - " + e.getActionCommand(), - 600, 500); - cap.setText(new AppletFormatAdapter().formatSequences(e.getActionCommand(), - viewport.getAlignment().getSequences(), - viewport.showJVSuffix)); - } - - public void closeMenuItem_actionPerformed() - { - PaintRefresher.components.remove(viewport.alignment); - if(PaintRefresher.components.size()==0 && applet==null) - System.exit(0); - - this.dispose(); - } - - Stack historyList = new Stack(); - Stack redoList = new Stack(); - - void updateEditMenuBar() - { - if (historyList.size() > 0) - { - undoMenuItem.setEnabled(true); - HistoryItem hi = (HistoryItem) historyList.peek(); - undoMenuItem.setLabel("Undo " + hi.getDescription()); - } - else - { - undoMenuItem.setEnabled(false); - undoMenuItem.setLabel("Undo"); - } - - if (redoList.size() > 0) - { - redoMenuItem.setEnabled(true); - HistoryItem hi = (HistoryItem) redoList.peek(); - redoMenuItem.setLabel("Redo " + hi.getDescription()); - } - else - { - redoMenuItem.setEnabled(false); - redoMenuItem.setLabel("Redo"); - } - } - - public void addHistoryItem(HistoryItem hi) - { - historyList.push(hi); - updateEditMenuBar(); - } - - protected void undoMenuItem_actionPerformed() - { - HistoryItem hi = (HistoryItem) historyList.pop(); - redoList.push(new HistoryItem(hi.getDescription(), viewport.alignment, - HistoryItem.HIDE)); - restoreHistoryItem(hi); - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - protected void redoMenuItem_actionPerformed() - { - HistoryItem hi = (HistoryItem) redoList.pop(); - restoreHistoryItem(hi); - updateEditMenuBar(); - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - // used by undo and redo - void restoreHistoryItem(HistoryItem hi) - { - hi.restore(); - - updateEditMenuBar(); - - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - public void moveSelectedSequences(boolean up) - { - SequenceGroup sg = viewport.getSelectionGroup(); - if (sg == null) - { - return; - } - - if (up) - { - for (int i = 1; i < viewport.alignment.getHeight(); i++) - { - SequenceI seq = viewport.alignment.getSequenceAt(i); - if (!sg.sequences.contains(seq)) - { - continue; - } - - SequenceI temp = viewport.alignment.getSequenceAt(i - 1); - if (sg.sequences.contains(temp)) - { - continue; - } - - viewport.alignment.getSequences().setElementAt(temp, i); - viewport.alignment.getSequences().setElementAt(seq, i - 1); - } - } - else - { - for (int i = viewport.alignment.getHeight() - 2; i > -1; i--) - { - SequenceI seq = viewport.alignment.getSequenceAt(i); - if (!sg.sequences.contains(seq)) - { - continue; - } - - SequenceI temp = viewport.alignment.getSequenceAt(i + 1); - if (sg.sequences.contains(temp)) - { - continue; - } - - viewport.alignment.getSequences().setElementAt(temp, i); - viewport.alignment.getSequences().setElementAt(seq, i + 1); - } - } - - alignPanel.repaint(); - } - - StringBuffer copiedSequences; - protected void copy_actionPerformed() - { - if (viewport.getSelectionGroup() == null) - { - return; - } - - SequenceGroup sg = viewport.getSelectionGroup(); - copiedSequences = new StringBuffer(); - Hashtable orderedSeqs = new Hashtable(); - for (int i = 0; i < sg.getSize(); i++) - { - SequenceI seq = sg.getSequenceAt(i); - int index = viewport.alignment.findIndex(seq); - orderedSeqs.put(index + "", seq); - } - - int index = 0, startRes, endRes; - char ch; - - for (int i = 0; i < sg.getSize(); i++) - { - SequenceI seq = null; - - while (seq == null) - { - if (orderedSeqs.containsKey(index + "")) - { - seq = (SequenceI) orderedSeqs.get(index + ""); - index++; - - break; - } - else - { - index++; - } - } - - //FIND START RES - //Returns residue following index if gap - startRes = seq.findPosition(sg.getStartRes()); - - //FIND END RES - //Need to find the residue preceeding index if gap - endRes = 0; - - for (int j = 0; j < sg.getEndRes()+1 && j < seq.getLength(); j++) - { - ch = seq.getCharAt(j); - if (!jalview.util.Comparison.isGap( (ch))) - { - endRes++; - } - } - - if(endRes>0) - { - endRes += seq.getStart() -1; - } - - copiedSequences.append(seq.getName() + "\t" + - startRes + "\t" + - endRes + "\t" + - seq.getSequence(sg.getStartRes(), - sg.getEndRes() + 1) + "\n"); - } - - } - - protected void pasteNew_actionPerformed() - { - paste(true); - } - - protected void pasteThis_actionPerformed() - { - addHistoryItem(new HistoryItem("Paste Sequences", viewport.alignment, - HistoryItem.PASTE)); - paste(false); - } - - void paste(boolean newAlignment) - { - try - { - if (copiedSequences == null) - { - return; - } - - StringTokenizer st = new StringTokenizer(copiedSequences.toString()); - Vector seqs = new Vector(); - while (st.hasMoreElements()) - { - String name = st.nextToken(); - int start = Integer.parseInt(st.nextToken()); - int end = Integer.parseInt(st.nextToken()); - Sequence sequence = new Sequence(name, st.nextToken(), start, end); - - if (!newAlignment) - { - viewport.alignment.addSequence(sequence); - } - else - { - seqs.addElement(sequence); - } - } - - if (newAlignment) - { - SequenceI[] newSeqs = new SequenceI[seqs.size()]; - for (int i = 0; i < seqs.size(); i++) - { - newSeqs[i] = (SequenceI) seqs.elementAt(i); - } - - String newtitle = new String("Copied sequences"); - if (getTitle().startsWith("Copied sequences")) - { - newtitle = getTitle(); - } - else - { - newtitle = newtitle.concat("- from " + getTitle()); - } - AlignFrame af = new AlignFrame(new Alignment(newSeqs), - applet, - newtitle, - false); - - jalview.bin.JalviewLite.addFrame(af, newtitle, NEW_WINDOW_WIDTH, - NEW_WINDOW_HEIGHT); - } - else - { - viewport.setEndSeq(viewport.alignment.getHeight()); - viewport.alignment.getWidth(); - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - } - catch (Exception ex) - {} // could be anything being pasted in here - - } - - protected void cut_actionPerformed() - { - copy_actionPerformed(); - delete_actionPerformed(); - } - - protected void delete_actionPerformed() - { - addHistoryItem(new HistoryItem("Delete Sequences", viewport.alignment, - HistoryItem.HIDE)); - if (viewport.getSelectionGroup() == null) - { - return; - } - - - SequenceGroup sg = viewport.getSelectionGroup(); - boolean allSequences = false; - if(sg.sequences.size()==viewport.alignment.getHeight()) - allSequences = true; - - for (int i = 0; i < sg.sequences.size(); i++) - { - SequenceI seq = sg.getSequenceAt(i); - int index = viewport.getAlignment().findIndex(seq); - seq.deleteChars(sg.getStartRes(), sg.getEndRes() + 1); - - // If the cut affects all sequences, remove highlighted columns - if (allSequences) - { - viewport.getColumnSelection().removeElements(sg.getStartRes(), - sg.getEndRes() + 1); - } - - - if (seq.getSequence().length() < 1) - { - viewport.getAlignment().deleteSequence(seq); - } - else - { - viewport.getAlignment().getSequences().setElementAt(seq, index); - } - } - - viewport.setSelectionGroup(null); - viewport.alignment.deleteGroup(sg); - viewport.resetSeqLimits(alignPanel.seqPanel.seqCanvas.getSize().height); - if (viewport.getAlignment().getHeight() < 1) - { - try - { - this.setVisible(false); - } - catch (Exception ex) - {} - } - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - - } - - protected void deleteGroups_actionPerformed() - { - viewport.alignment.deleteAllGroups(); - viewport.setSelectionGroup(null); - - alignPanel.repaint(); - } - - public void selectAllSequenceMenuItem_actionPerformed() - { - SequenceGroup sg = new SequenceGroup(); - for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++) - { - sg.addSequence(viewport.getAlignment().getSequenceAt(i), false); - } - sg.setEndRes(viewport.alignment.getWidth()-1); - viewport.setSelectionGroup(sg); - alignPanel.repaint(); - PaintRefresher.Refresh(null, viewport.alignment); - } - - public void deselectAllSequenceMenuItem_actionPerformed() - { - viewport.setSelectionGroup(null); - viewport.getColumnSelection().clear(); - viewport.setSelectionGroup(null); - alignPanel.idPanel.idCanvas.searchResults = null; - alignPanel.seqPanel.seqCanvas.highlightSearchResults(null); - alignPanel.repaint(); - PaintRefresher.Refresh(null, viewport.alignment); - } - - public void invertSequenceMenuItem_actionPerformed() - { - SequenceGroup sg = viewport.getSelectionGroup(); - for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++) - { - sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false); - } - - PaintRefresher.Refresh(null, viewport.alignment); - } - - public void remove2LeftMenuItem_actionPerformed() - { - ColumnSelection colSel = viewport.getColumnSelection(); - if (colSel.size() > 0) - { - addHistoryItem(new HistoryItem("Remove Left", viewport.alignment, - HistoryItem.HIDE)); - int min = colSel.getMin(); - viewport.getAlignment().trimLeft(min); - colSel.compensateForEdit(0, min); - - if (viewport.getSelectionGroup() != null) - { - viewport.getSelectionGroup().adjustForRemoveLeft(min); - } - - Vector groups = viewport.alignment.getGroups(); - for (int i = 0; i < groups.size(); i++) - { - SequenceGroup sg = (SequenceGroup) groups.elementAt(i); - if (!sg.adjustForRemoveLeft(min)) - { - viewport.alignment.deleteGroup(sg); - } - } - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - } - - public void remove2RightMenuItem_actionPerformed() - { - ColumnSelection colSel = viewport.getColumnSelection(); - if (colSel.size() > 0) - { - addHistoryItem(new HistoryItem("Remove Right", viewport.alignment, - HistoryItem.HIDE)); - int max = colSel.getMax(); - viewport.getAlignment().trimRight(max); - if (viewport.getSelectionGroup() != null) - { - viewport.getSelectionGroup().adjustForRemoveRight(max); - } - - Vector groups = viewport.alignment.getGroups(); - for (int i = 0; i < groups.size(); i++) - { - SequenceGroup sg = (SequenceGroup) groups.elementAt(i); - if (!sg.adjustForRemoveRight(max)) - { - viewport.alignment.deleteGroup(sg); - } - } - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - } - - public void removeGappedColumnMenuItem_actionPerformed() - { - addHistoryItem(new HistoryItem("Remove Gapped Columns", - viewport.alignment, - HistoryItem.HIDE)); - - //This is to maintain viewport position on first residue - //of first sequence - SequenceI seq = viewport.alignment.getSequenceAt(0); - int startRes = seq.findPosition(viewport.startRes); - - viewport.getAlignment().removeGaps(); - - viewport.setStartRes(seq.findIndex(startRes)-1); - - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - public void removeAllGapsMenuItem_actionPerformed() - { - addHistoryItem(new HistoryItem("Remove Gaps", viewport.alignment, - HistoryItem.HIDE)); - - //This is to maintain viewport position on first residue - //of first sequence - SequenceI seq = viewport.alignment.getSequenceAt(0); - int startRes = seq.findPosition(viewport.startRes); - - SequenceI current; - int jSize; - - Vector seqs=null; - - int start=0, end = viewport.alignment.getWidth(); - - if (viewport.getSelectionGroup() != null - && viewport.getSelectionGroup().sequences != null - && viewport.getSelectionGroup().sequences.size()>0) - { - seqs = viewport.getSelectionGroup().sequences; - start = viewport.getSelectionGroup().getStartRes(); - end = viewport.getSelectionGroup().getEndRes()+1; - } - else - seqs = viewport.alignment.getSequences(); - - for (int i = 0; i < seqs.size(); i++) - { - current = (SequenceI) seqs.elementAt(i); - jSize = current.getLength(); - - // Removing a range is much quicker than removing gaps - // one by one for long sequences - int j = start; - int rangeStart=-1, rangeEnd=-1; - - do - { - if (jalview.util.Comparison.isGap(current.getCharAt(j))) - { - if(rangeStart==-1) - { - rangeStart = j; - rangeEnd = j+1; - } - else - { - rangeEnd++; - } - j++; - } - else - { - if(rangeStart>-1) - { - current.deleteChars(rangeStart, rangeEnd); - j-=rangeEnd-rangeStart; - jSize-=rangeEnd-rangeStart; - rangeStart = -1; - rangeEnd = -1; - } - else - j++; - } - } - while (j < end && j < jSize); - if(rangeStart>-1) - { - current.deleteChars(rangeStart, rangeEnd); - } - } - viewport.setStartRes(seq.findIndex(startRes)-1); - viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); - } - - public void alignmentChanged() - { - viewport.updateConsensus(); - viewport.updateConservation (); - resetAllColourSchemes(); - if(alignPanel.overviewPanel!=null) - alignPanel.overviewPanel.updateOverviewImage(); - - viewport.alignment.adjustSequenceAnnotations(); - alignPanel.repaint(); - } - - void resetAllColourSchemes() - { - ColourSchemeI cs = viewport.globalColourScheme; - if(cs!=null) - { - if (cs instanceof ClustalxColourScheme) - { - ( (ClustalxColourScheme) viewport.getGlobalColourScheme()). - resetClustalX(viewport.alignment.getSequences(), - viewport.alignment.getWidth()); - } - - cs.setConsensus(viewport.vconsensus); - if (cs.conservationApplied()) - { - Alignment al = (Alignment) viewport.alignment; - Conservation c = new Conservation("All", - ResidueProperties.propHash, 3, - al.getSequences(), 0, - al.getWidth() - 1); - c.calculate(); - c.verdict(false, viewport.ConsPercGaps); - - cs.setConservation(c); - } - } - - int s, sSize = viewport.alignment.getGroups().size(); - for(s=0; s 1) - { - Frame frame = new Frame(); - frame.add(new PairwiseAlignPanel(alignPanel)); - jalview.bin.JalviewLite.addFrame(frame, "Pairwise Alignment", 600, 500); - } - } - - public void PCAMenuItem_actionPerformed() - { - //are the sequences aligned? - if (!viewport.alignment.isAligned()) - { - SequenceI current; - int Width = viewport.getAlignment().getWidth(); - - for (int i = 0; i < viewport.getAlignment().getSequences().size(); - i++) - { - current = viewport.getAlignment().getSequenceAt(i); - - if (current.getLength() < Width) - { - current.insertCharAt(Width - 1, viewport.getGapCharacter()); - } - } - alignPanel.repaint(); - } - - if ( (viewport.getSelectionGroup() != null && - viewport.getSelectionGroup().getSize() < 4 && - viewport.getSelectionGroup().getSize() > 0) - || viewport.getAlignment().getHeight() < 4) - { - return; - } - - try - { - new PCAPanel(viewport); - } - catch (java.lang.OutOfMemoryError ex) - { - } - - } - - public void averageDistanceTreeMenuItem_actionPerformed() - { - NewTreePanel("AV", "PID", "Average distance tree using PID"); - } - - public void neighbourTreeMenuItem_actionPerformed() - { - NewTreePanel("NJ", "PID", "Neighbour joining tree using PID"); - } - - protected void njTreeBlosumMenuItem_actionPerformed() - { - NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62"); - } - - protected void avTreeBlosumMenuItem_actionPerformed() - { - NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62PID"); - } - - void NewTreePanel(String type, String pwType, String title) - { - //are the sequences aligned? - if (!viewport.alignment.isAligned()) - { - SequenceI current; - int Width = viewport.getAlignment().getWidth(); - - for (int i = 0; i < viewport.getAlignment().getSequences().size(); - i++) - { - current = viewport.getAlignment().getSequenceAt(i); - - if (current.getLength() < Width) - { - current.insertCharAt(Width - 1, viewport.getGapCharacter()); - } - } - alignPanel.repaint(); - - } - - final TreePanel tp; - if (viewport.getSelectionGroup() != null && - viewport.getSelectionGroup().getSize() > 3) - { - tp = new TreePanel(viewport, viewport.getSelectionGroup().sequences, type, - pwType, - 0, viewport.alignment.getWidth()); - } - else - { - tp = new TreePanel(viewport, viewport.getAlignment().getSequences(), - type, pwType, 0, viewport.alignment.getWidth()); - } - - addTreeMenuItem(tp, title); - - jalview.bin.JalviewLite.addFrame(tp, title, 600, 500); - } - - void loadTree_actionPerformed() - { - TreePanel tp = null; - - CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this); - cap.setText("Paste your Newick tree file here."); - cap.treeImport = true; - Frame frame = new Frame(); - frame.add(cap); - jalview.bin.JalviewLite.addFrame(frame, "Paste Newick file ", 400, 300); - } - - public void loadTree(jalview.io.NewickFile tree, String treeFile) - { - TreePanel tp = new TreePanel(viewport, - viewport.getAlignment().getSequences(), - tree, "From File - ", treeFile); - jalview.bin.JalviewLite.addFrame(tp, treeFile, 600, 500); - addTreeMenuItem(tp, treeFile); - } - - void addTreeMenuItem(final TreePanel treePanel, String title) - { - final MenuItem item = new MenuItem(title); - sortByTreeMenu.add(item); - item.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent evt) - { - addHistoryItem(new HistoryItem("Sort", viewport.alignment, - HistoryItem.SORT)); - AlignmentSorter.sortByTree(viewport.getAlignment(), treePanel.getTree()); - alignPanel.repaint(); - } - }); - - treePanel.addWindowListener(new WindowAdapter() - { - public void windowClosing(WindowEvent e) - { - sortByTreeMenu.remove(item); - }; - }); - } - - protected void documentation_actionPerformed() - { - showURL("http://www.jalview.org/help.html", "HELP"); - } - - protected void about_actionPerformed() - { - - class AboutPanel extends Canvas - { - String version; - public AboutPanel(String version) - { this.version = version; } - - public void paint(Graphics g) - { - g.setColor(Color.white); - g.fillRect(0, 0, getSize().width, getSize().height); - g.setFont(new Font("Helvetica", Font.PLAIN, 12)); - FontMetrics fm = g.getFontMetrics(); - int fh = fm.getHeight(); - int y = 5, x = 7; - g.setColor(Color.black); - g.setFont(new Font("Helvetica", Font.BOLD, 14)); - g.drawString("Jalview - Release "+version, 200, y += fh); - g.setFont(new Font("Helvetica", Font.PLAIN, 12)); - g.drawString("Authors: Michele Clamp, James Cuff, Steve Searle, Andrew Waterhouse, Jim Procter & Geoff Barton.", - x, y += fh * 2); - g.drawString("Current development managed by Andrew Waterhouse; Barton Group, University of Dundee.", - x, y += fh); - g.drawString( - "For any issues relating to Jalview, email help@jalview.org", x, - y += fh); - g.drawString("If you use JalView, please cite:", x, y += fh + 8); - g.drawString("\"Clamp, M., Cuff, J., Searle, S. M. and Barton, G. J. (2004), The Jalview Java Alignment Editor\"", - x, y += fh); - g.drawString("Bioinformatics, 2004 12;426-7.", x, y += fh); - } - } - - String version = "test"; - java.net.URL url = getClass().getResource("/.build_properties"); - if (url != null) - { - try - { - BufferedReader reader = new BufferedReader(new InputStreamReader( - url.openStream())); - String line; - while ( (line = reader.readLine()) != null) - { - if (line.indexOf("VERSION") > -1) - { - version = line.substring(line.indexOf("=") + 1); - } - } - } - catch (Exception ex) - { - ex.printStackTrace(); - } - } - - - Frame frame = new Frame(); - frame.add(new AboutPanel(version)); - jalview.bin.JalviewLite.addFrame(frame, "Jalview", 580, 200); - - } - - public void showURL(String url, String target) - { - if (applet == null) - { - System.out.println("Not running as applet - no browser available."); - } - else - { - try - { - applet.getAppletContext().showDocument(new java.net.URL(url), - target); - } - catch (Exception ex) - { - ex.printStackTrace(); - } - } - } - - - ////////////////////////////////////////////////////////////////////////////////// - //JBuilder Graphics here - - protected MenuBar alignFrameMenuBar = new MenuBar(); - protected Menu fileMenu = new Menu("File"); - protected MenuItem loadTree = new MenuItem("Load Associated Tree"); - protected MenuItem closeMenuItem = new MenuItem("Close"); - protected Menu editMenu = new Menu("Edit"); - protected Menu viewMenu = new Menu("View"); - protected Menu colourMenu = new Menu("Colour"); - protected Menu calculateMenu = new Menu("Calculate"); - protected MenuItem selectAllSequenceMenuItem = new MenuItem("Select all"); - protected MenuItem deselectAllSequenceMenuItem = new MenuItem("Deselect All"); - protected MenuItem invertSequenceMenuItem = new MenuItem("Invert Selection"); - protected MenuItem remove2LeftMenuItem = new MenuItem(); - protected MenuItem remove2RightMenuItem = new MenuItem(); - protected MenuItem removeGappedColumnMenuItem = new MenuItem(); - protected MenuItem removeAllGapsMenuItem = new MenuItem(); - protected CheckboxMenuItem viewBoxesMenuItem = new CheckboxMenuItem(); - protected CheckboxMenuItem viewTextMenuItem = new CheckboxMenuItem(); - protected MenuItem sortPairwiseMenuItem = new MenuItem(); - protected MenuItem sortIDMenuItem = new MenuItem(); - protected MenuItem sortGroupMenuItem = new MenuItem(); - protected MenuItem removeRedundancyMenuItem = new MenuItem(); - protected MenuItem pairwiseAlignmentMenuItem = new MenuItem(); - protected MenuItem PCAMenuItem = new MenuItem(); - protected MenuItem averageDistanceTreeMenuItem = new MenuItem(); - protected MenuItem neighbourTreeMenuItem = new MenuItem(); - BorderLayout borderLayout1 = new BorderLayout(); - public Label statusBar = new Label(); - protected Menu outputTextboxMenu = new Menu(); - protected MenuItem clustalColour = new MenuItem(); - protected MenuItem zappoColour = new MenuItem(); - protected MenuItem taylorColour = new MenuItem(); - protected MenuItem hydrophobicityColour = new MenuItem(); - protected MenuItem helixColour = new MenuItem(); - protected MenuItem strandColour = new MenuItem(); - protected MenuItem turnColour = new MenuItem(); - protected MenuItem buriedColour = new MenuItem(); - protected MenuItem userDefinedColour = new MenuItem(); - protected MenuItem PIDColour = new MenuItem(); - protected MenuItem BLOSUM62Colour = new MenuItem(); - MenuItem njTreeBlosumMenuItem = new MenuItem(); - MenuItem avDistanceTreeBlosumMenuItem = new MenuItem(); - protected CheckboxMenuItem annotationPanelMenuItem = new CheckboxMenuItem(); - protected CheckboxMenuItem colourTextMenuItem = new CheckboxMenuItem(); - MenuItem overviewMenuItem = new MenuItem(); - protected MenuItem undoMenuItem = new MenuItem(); - protected MenuItem redoMenuItem = new MenuItem(); - protected CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem(); - MenuItem noColourmenuItem = new MenuItem(); - protected CheckboxMenuItem wrapMenuItem = new CheckboxMenuItem(); - protected CheckboxMenuItem renderGapsMenuItem = new CheckboxMenuItem(); - MenuItem findMenuItem = new MenuItem(); - Menu searchMenu = new Menu(); - protected CheckboxMenuItem abovePIDThreshold = new CheckboxMenuItem(); - protected MenuItem nucleotideColour = new MenuItem(); - MenuItem deleteGroups = new MenuItem(); - MenuItem delete = new MenuItem(); - MenuItem copy = new MenuItem(); - MenuItem cut = new MenuItem(); - Menu pasteMenu = new Menu(); - MenuItem pasteNew = new MenuItem(); - MenuItem pasteThis = new MenuItem(); - protected CheckboxMenuItem applyToAllGroups = new CheckboxMenuItem(); - protected MenuItem font = new MenuItem(); - protected CheckboxMenuItem scaleAbove = new CheckboxMenuItem(); - protected CheckboxMenuItem scaleLeft = new CheckboxMenuItem(); - protected CheckboxMenuItem scaleRight = new CheckboxMenuItem(); - MenuItem modifyPID = new MenuItem(); - MenuItem modifyConservation = new MenuItem(); - protected Menu sortByTreeMenu = new Menu(); - Menu sort = new Menu(); - Menu calculate = new Menu(); - MenuItem inputText = new MenuItem(); - Menu helpMenu = new Menu(); - MenuItem documentation = new MenuItem(); - MenuItem about = new MenuItem(); - protected CheckboxMenuItem seqLimits = new CheckboxMenuItem(); - Panel embeddedMenu; - Label embeddedEdit; - Label embeddedSearch; - Label embeddedView; - Label embeddedColour; - Label embeddedFile; - Label embeddedHelp; - Label embeddedCalculate; - FlowLayout flowLayout1; - - private void jbInit() throws Exception { - - setMenuBar(alignFrameMenuBar); - - MenuItem item; - - // dynamically fill save as menu with available formats - for (int i = 0; i < jalview.io.AppletFormatAdapter.formats.size(); i++) - { - - item = new MenuItem( (String) jalview.io.AppletFormatAdapter.formats. - elementAt( - i)); - item.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - outputText_actionPerformed(e); - } - }); - - outputTextboxMenu.add(item); - } - closeMenuItem.addActionListener(this); - - loadTree.addActionListener(this); - selectAllSequenceMenuItem.addActionListener(this); - deselectAllSequenceMenuItem.addActionListener(this); - invertSequenceMenuItem.addActionListener(this); - remove2LeftMenuItem.setLabel("Remove Left"); - remove2LeftMenuItem.addActionListener(this); - remove2RightMenuItem.setLabel("Remove Right"); - remove2RightMenuItem.addActionListener(this); - removeGappedColumnMenuItem.setLabel("Remove Empty Columns"); - removeGappedColumnMenuItem.addActionListener(this); - removeAllGapsMenuItem.setLabel("Remove All Gaps"); - removeAllGapsMenuItem.addActionListener(this); - viewBoxesMenuItem.setLabel("Boxes"); - viewBoxesMenuItem.setState(true); - viewBoxesMenuItem.addItemListener(this); - viewTextMenuItem.setLabel("Text"); - viewTextMenuItem.setState(true); - viewTextMenuItem.addItemListener(this); - sortPairwiseMenuItem.setLabel("by Pairwise Identity"); - sortPairwiseMenuItem.addActionListener(this); - sortIDMenuItem.setLabel("by ID"); - sortIDMenuItem.addActionListener(this); - sortGroupMenuItem.setLabel("by Group"); - sortGroupMenuItem.addActionListener(this); - removeRedundancyMenuItem.setLabel("Remove Redundancy..."); - removeRedundancyMenuItem.addActionListener(this); - pairwiseAlignmentMenuItem.setLabel("Pairwise Alignments..."); - pairwiseAlignmentMenuItem.addActionListener(this); - PCAMenuItem.setLabel("Principal Component Analysis"); - PCAMenuItem.addActionListener(this); - averageDistanceTreeMenuItem.setLabel( - "Average Distance Using % Identity"); - averageDistanceTreeMenuItem.addActionListener(this); - neighbourTreeMenuItem.setLabel("Neighbour Joining Using % Identity"); - neighbourTreeMenuItem.addActionListener(this); - alignFrameMenuBar.setFont(new java.awt.Font("Verdana", 0, 11)); - statusBar.setBackground(Color.white); - statusBar.setFont(new java.awt.Font("Verdana", 0, 11)); - statusBar.setText("Status bar"); - outputTextboxMenu.setLabel("Output to Textbox"); - clustalColour.setLabel("Clustalx"); - - clustalColour.addActionListener(this); - zappoColour.setLabel("Zappo"); - zappoColour.addActionListener(this); - taylorColour.setLabel("Taylor"); - taylorColour.addActionListener(this); - hydrophobicityColour.setLabel("Hydrophobicity"); - hydrophobicityColour.addActionListener(this); - helixColour.setLabel("Helix Propensity"); - helixColour.addActionListener(this); - strandColour.setLabel("Strand Propensity"); - strandColour.addActionListener(this); - turnColour.setLabel("Turn Propensity"); - turnColour.addActionListener(this); - buriedColour.setLabel("Buried Index"); - buriedColour.addActionListener(this); - userDefinedColour.setLabel("User Defined..."); - userDefinedColour.addActionListener(this); - PIDColour.setLabel("Percentage Identity"); - PIDColour.addActionListener(this); - BLOSUM62Colour.setLabel("BLOSUM62 Score"); - BLOSUM62Colour.addActionListener(this); - avDistanceTreeBlosumMenuItem.setLabel( - "Average Distance Using BLOSUM62"); - avDistanceTreeBlosumMenuItem.addActionListener(this); - njTreeBlosumMenuItem.setLabel("Neighbour Joining Using BLOSUM62"); - njTreeBlosumMenuItem.addActionListener(this); - annotationPanelMenuItem.setLabel("Show Annotations"); - annotationPanelMenuItem.addItemListener(this); - colourTextMenuItem.setLabel("Colour Text"); - colourTextMenuItem.addItemListener(this); - overviewMenuItem.setLabel("Overview Window"); - overviewMenuItem.addActionListener(this); - undoMenuItem.setEnabled(false); - undoMenuItem.setLabel("Undo"); - undoMenuItem.addActionListener(this); - redoMenuItem.setEnabled(false); - redoMenuItem.setLabel("Redo"); - redoMenuItem.addActionListener(this); - conservationMenuItem.setLabel("by Conservation"); - conservationMenuItem.addItemListener(this); - noColourmenuItem.setLabel("None"); - noColourmenuItem.addActionListener(this); - wrapMenuItem.setLabel("Wrap"); - wrapMenuItem.addItemListener(this); - renderGapsMenuItem.setLabel("Show Gaps"); - renderGapsMenuItem.setState(true); - renderGapsMenuItem.addItemListener(this); - findMenuItem.setLabel("Find..."); - findMenuItem.addActionListener(this); - searchMenu.setLabel("Search"); - - abovePIDThreshold.setLabel("Above Identity Threshold"); - abovePIDThreshold.addItemListener(this); - nucleotideColour.setLabel("Nucleotide"); - nucleotideColour.addActionListener(this); - deleteGroups.setLabel("Undefine Groups"); - deleteGroups.addActionListener(this); - copy.setLabel("Copy"); - copy.addActionListener(this); - cut.setLabel("Cut"); - cut.addActionListener(this); - delete.setLabel("Delete"); - delete.addActionListener(this); - pasteMenu.setLabel("Paste"); - pasteNew.setLabel("To New Alignment"); - pasteNew.addActionListener(this); - pasteThis.setLabel("Add To This Alignment"); - pasteThis.addActionListener(this); - applyToAllGroups.setLabel("Apply Colour To All Groups"); - applyToAllGroups.setState(true); - applyToAllGroups.addItemListener(this); - font.setLabel("Font..."); - font.addActionListener(this); - scaleAbove.setLabel("Scale Above"); - scaleAbove.setState(true); - scaleAbove.setEnabled(false); - scaleAbove.addItemListener(this); - scaleLeft.setEnabled(false); - scaleLeft.setState(true); - scaleLeft.setLabel("Scale Left"); - scaleLeft.addItemListener(this); - scaleRight.setEnabled(false); - scaleRight.setState(true); - scaleRight.setLabel("Scale Right"); - scaleRight.addItemListener(this); - modifyPID.setLabel("Modify Identity Threshold..."); - modifyPID.addActionListener(this); - modifyConservation.setLabel("Modify Conservation Threshold..."); - modifyConservation.addActionListener(this); - sortByTreeMenu.setLabel("By Tree Order"); - sort.setLabel("Sort"); - calculate.setLabel("Calculate Tree"); - inputText.setLabel("Input from textbox"); - inputText.addActionListener(this); - - helpMenu.setLabel("Help"); - documentation.setLabel("Documentation"); - documentation.addActionListener(this); - - about.setLabel("About..."); - about.addActionListener(this); - seqLimits.setState(true); - seqLimits.setLabel("Show Sequence Limits"); - seqLimits.addItemListener(this); - featureSettings.setLabel("Feature Settings..."); - featureSettings.addActionListener(this); - sequenceFeatures.setLabel("Sequence Features"); - sequenceFeatures.addItemListener(this); - sequenceFeatures.setState(false); - annotationColour.setLabel("by Annotation..."); - annotationColour.addActionListener(this); - - alignFrameMenuBar.add(fileMenu); - alignFrameMenuBar.add(editMenu); - alignFrameMenuBar.add(searchMenu); - alignFrameMenuBar.add(viewMenu); - alignFrameMenuBar.add(colourMenu); - alignFrameMenuBar.add(calculateMenu); - alignFrameMenuBar.add(helpMenu); - fileMenu.add(inputText); - fileMenu.add(outputTextboxMenu); - fileMenu.addSeparator(); - fileMenu.add(loadTree); - fileMenu.add(closeMenuItem); - editMenu.add(undoMenuItem); - editMenu.add(redoMenuItem); - editMenu.add(cut); - editMenu.add(copy); - editMenu.add(pasteMenu); - editMenu.add(delete); - editMenu.addSeparator(); - editMenu.add(selectAllSequenceMenuItem); - editMenu.add(deselectAllSequenceMenuItem); - editMenu.add(invertSequenceMenuItem); - editMenu.add(deleteGroups); - editMenu.addSeparator(); - editMenu.add(remove2LeftMenuItem); - editMenu.add(remove2RightMenuItem); - editMenu.add(removeGappedColumnMenuItem); - editMenu.add(removeAllGapsMenuItem); - editMenu.add(removeRedundancyMenuItem); - searchMenu.add(findMenuItem); - viewMenu.add(font); - viewMenu.addSeparator(); - viewMenu.add(seqLimits); - viewMenu.addSeparator(); - viewMenu.add(wrapMenuItem); - viewMenu.add(scaleAbove); - viewMenu.add(scaleLeft); - viewMenu.add(scaleRight); - viewMenu.addSeparator(); - viewMenu.add(viewBoxesMenuItem); - viewMenu.add(viewTextMenuItem); - viewMenu.add(colourTextMenuItem); - viewMenu.add(renderGapsMenuItem); - viewMenu.add(annotationPanelMenuItem); - viewMenu.addSeparator(); - viewMenu.add(sequenceFeatures); - viewMenu.add(featureSettings); - viewMenu.addSeparator(); - viewMenu.add(overviewMenuItem); - colourMenu.add(applyToAllGroups); - colourMenu.addSeparator(); - colourMenu.add(noColourmenuItem); - colourMenu.add(clustalColour); - colourMenu.add(BLOSUM62Colour); - colourMenu.add(PIDColour); - colourMenu.add(zappoColour); - colourMenu.add(taylorColour); - colourMenu.add(hydrophobicityColour); - colourMenu.add(helixColour); - colourMenu.add(strandColour); - colourMenu.add(turnColour); - colourMenu.add(buriedColour); - colourMenu.add(nucleotideColour); - colourMenu.add(userDefinedColour); - colourMenu.addSeparator(); - colourMenu.add(conservationMenuItem); - colourMenu.add(modifyConservation); - colourMenu.add(abovePIDThreshold); - colourMenu.add(modifyPID); - colourMenu.add(annotationColour); - calculateMenu.add(sort); - calculateMenu.add(calculate); - calculateMenu.addSeparator(); - calculateMenu.add(pairwiseAlignmentMenuItem); - calculateMenu.add(PCAMenuItem); - this.add(statusBar, BorderLayout.SOUTH); - pasteMenu.add(pasteNew); - pasteMenu.add(pasteThis); - sort.add(sortIDMenuItem); - sort.add(sortByTreeMenu); - sort.add(sortGroupMenuItem); - sort.add(sortPairwiseMenuItem); - calculate.add(averageDistanceTreeMenuItem); - calculate.add(neighbourTreeMenuItem); - calculate.add(avDistanceTreeBlosumMenuItem); - calculate.add(njTreeBlosumMenuItem); - helpMenu.add(documentation); - helpMenu.add(about); - } - - public void setEmbedded() - { - - embeddedMenu = new Panel(); - embeddedEdit = new Label(); - embeddedSearch = new Label(); - embeddedView = new Label(); - embeddedColour = new Label(); - embeddedFile = new Label(); - embeddedHelp = new Label(); - embeddedCalculate = new Label(); - flowLayout1 = new FlowLayout(); - embeddedMenu.setBackground(Color.lightGray); - embeddedMenu.setLayout(flowLayout1); - embeddedEdit.setText("Edit"); - embeddedEdit.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedSearch.setText("Search"); - embeddedSearch.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedView.setText("View"); - embeddedView.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedColour.setText("Colour"); - embeddedColour.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedFile.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedFile.setText("File"); - embeddedHelp.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedHelp.setText("Help"); - embeddedCalculate.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); - embeddedCalculate.setText("Calculate"); - embeddedMenu.add(embeddedFile); - embeddedMenu.add(embeddedEdit); - embeddedMenu.add(embeddedSearch); - embeddedMenu.add(embeddedView); - embeddedMenu.add(embeddedColour); - embeddedMenu.add(embeddedCalculate); - embeddedMenu.add(embeddedHelp); - flowLayout1.setAlignment(FlowLayout.LEFT); - flowLayout1.setHgap(2); - flowLayout1.setVgap(0); - embeddedFile.addMouseListener(this); - embeddedEdit.addMouseListener(this); - embeddedSearch.addMouseListener(this); - embeddedView.addMouseListener(this); - embeddedColour.addMouseListener(this); - embeddedCalculate.addMouseListener(this); - embeddedHelp.addMouseListener(this); - - // setVisible(false); - fileMenu.remove(closeMenuItem); - fileMenu.remove(2); // Seperator - - applet.setLayout(new BorderLayout()); - applet.add(embeddedMenu, BorderLayout.NORTH); - applet.add(statusBar, BorderLayout.SOUTH); - // applet.validate(); - - alignPanel.setSize(applet.size().width, applet.size().height - - embeddedMenu.HEIGHT - statusBar.HEIGHT); - - applet.add(alignPanel, BorderLayout.CENTER); - applet.validate(); - - } - - - - PopupMenu filePopup, editPopup, searchPopup, - viewPopup, colourPopup, calculatePopup, helpPopup; - MenuItem featureSettings = new MenuItem(); - CheckboxMenuItem sequenceFeatures = new CheckboxMenuItem(); - MenuItem annotationColour = new MenuItem(); - - public void mousePressed(MouseEvent evt) - { - PopupMenu popup = null; - Label source = (Label)evt.getSource(); - if(source==embeddedFile) - { - popup = filePopup = genPopupMenu(filePopup, fileMenu); - } - else if(source==embeddedEdit) - { - popup = editPopup = genPopupMenu(editPopup, editMenu); - } - else if(source==embeddedSearch) - { - popup = searchPopup = genPopupMenu(searchPopup, searchMenu); - } - else if(source==embeddedView) - { - popup = viewPopup = genPopupMenu(viewPopup, viewMenu); - } - else if(source==embeddedColour) - { - popup = colourPopup = genPopupMenu(colourPopup, colourMenu); - } - else if(source==embeddedCalculate) - { - popup = calculatePopup = genPopupMenu(calculatePopup, calculateMenu); - } - else if(source==embeddedHelp) - { - popup = helpPopup = genPopupMenu(helpPopup, helpMenu); - } - - embeddedMenu.add(popup); - popup.show(embeddedMenu, - source.getBounds().x, - source.getBounds().y + source.getBounds().getSize().height); - } - - PopupMenu genPopupMenu(PopupMenu popup, Menu original) - { - if(popup!=null) - { - return popup; - } - popup = new PopupMenu(); - int m, mSize = original.getItemCount(); - for(m=0; m0) + alignPanel.seqPanel.seqCanvas + .getFeatureRenderer().featureLinks = featureLinks; + viewport.showSequenceFeatures = true; + sequenceFeatures.setState(true); + alignPanel.repaint(); + } + + } + + + public void keyPressed(KeyEvent evt) + { + if (viewport.cursorMode + && evt.getKeyCode() >= KeyEvent.VK_0 + && evt.getKeyCode() <= KeyEvent.VK_9) + { + alignPanel.seqPanel.numberPressed(evt.getKeyChar()); + } + + switch (evt.getKeyCode()) + { + case 27: // escape key + deselectAllSequenceMenuItem_actionPerformed(); + break; + case KeyEvent.VK_X: + if (evt.isControlDown() || evt.isMetaDown()) + { + cut_actionPerformed(); + } + break; + case KeyEvent.VK_C: + if (viewport.cursorMode && !evt.isControlDown()) + { + alignPanel.seqPanel.setCursorColumn(); + } + if (evt.isControlDown() || evt.isMetaDown()) + { + copy_actionPerformed(); + } + break; + case KeyEvent.VK_V: + if (evt.isControlDown() || evt.isMetaDown()) + { + paste(true); + } + break; + case KeyEvent.VK_A: + if (evt.isControlDown() || evt.isMetaDown()) + { + selectAllSequenceMenuItem_actionPerformed(); + } + break; + case KeyEvent.VK_DOWN: + if(viewport.cursorMode) + { + alignPanel.seqPanel.moveCursor(0,1); + } + else + moveSelectedSequences(false); + break; + + case KeyEvent.VK_UP: + if (viewport.cursorMode) + { + alignPanel.seqPanel.moveCursor(0,-1); + } + else + moveSelectedSequences(true); + break; + + case KeyEvent.VK_LEFT: + if(viewport.cursorMode) + { + alignPanel.seqPanel.moveCursor(-1,0); + } + break; + + case KeyEvent.VK_RIGHT: + if (viewport.cursorMode) + { + alignPanel.seqPanel.moveCursor(1,0); + } + break; + case KeyEvent.VK_SPACE: + if(viewport.cursorMode) + { + alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()); + } + break; + + case KeyEvent.VK_DELETE: + case KeyEvent.VK_BACK_SPACE: + if(viewport.cursorMode) + { + alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()); + } + else + { + cut_actionPerformed(); + alignPanel.seqPanel.seqCanvas.repaint(); + } + break; + + case KeyEvent.VK_S: + if(viewport.cursorMode) + { + alignPanel.seqPanel.setCursorRow(); + } + break; + case KeyEvent.VK_P: + if(viewport.cursorMode) + { + alignPanel.seqPanel.setCursorPosition(); + } + break; + + case KeyEvent.VK_ENTER: + case KeyEvent.VK_COMMA: + if(viewport.cursorMode) + { + alignPanel.seqPanel.setCursorRowAndColumn(); + } + break; + + case KeyEvent.VK_Q: + if(viewport.cursorMode) + { + alignPanel.seqPanel.setSelectionAreaAtCursor(true); + } + break; + case KeyEvent.VK_M: + if(viewport.cursorMode) + { + alignPanel.seqPanel.setSelectionAreaAtCursor(false); + } + break; + + case KeyEvent.VK_F2: + viewport.cursorMode = ! viewport.cursorMode; + statusBar.setText("Keyboard editing mode is "+ + (viewport.cursorMode ? "on" : "off")); + if(viewport.cursorMode) + { + alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes; + alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq; + } + alignPanel.seqPanel.seqCanvas.repaint(); + break; + + case KeyEvent.VK_F: + if (evt.isControlDown()) + { + findMenuItem_actionPerformed(); + } + break; + case KeyEvent.VK_H: + { + boolean toggleSeqs = !evt.isControlDown(); + boolean toggleCols = !evt.isShiftDown(); + boolean hide = false; + SequenceGroup sg = viewport.getSelectionGroup(); + + if(toggleSeqs) + { + if (sg != null && sg.getSize(false) != viewport.alignment.getHeight()) + { + hide = true; + viewport.hideAllSelectedSeqs(); + } + else if (!(toggleCols && viewport.colSel.getSelected().size() > 0)) + viewport.showAllHiddenSeqs(); + } + + if(toggleCols) + { + if (viewport.colSel.getSelected().size() > 0) + { + viewport.hideSelectedColumns(); + if(!toggleSeqs) + viewport.selectionGroup = sg; + } + else if (!hide) + viewport.showAllHiddenColumns(); + } + + alignPanel.repaint(); + break; + } + + } + } + public void keyReleased(KeyEvent evt) + {} + public void keyTyped(KeyEvent evt) + {} + +public void itemStateChanged(ItemEvent evt) + { + if(evt.getSource()==colourTextMenuItem) + colourTextMenuItem_actionPerformed(); + else if(evt.getSource()==wrapMenuItem) + wrapMenuItem_actionPerformed(); + else if(evt.getSource()==scaleAbove) + scaleAbove_actionPerformed(); + else if(evt.getSource()==scaleLeft) + scaleLeft_actionPerformed(); + else if(evt.getSource()==scaleRight) + scaleRight_actionPerformed(); + else if(evt.getSource()==seqLimits) + seqLimits_itemStateChanged(); + else if(evt.getSource()==viewBoxesMenuItem) + viewBoxesMenuItem_actionPerformed(); + else if(evt.getSource()==viewTextMenuItem) + viewTextMenuItem_actionPerformed(); + else if(evt.getSource()==renderGapsMenuItem) + renderGapsMenuItem_actionPerformed(); + else if(evt.getSource()==annotationPanelMenuItem) + annotationPanelMenuItem_actionPerformed(); + else if(evt.getSource()==sequenceFeatures) + { + viewport.showSequenceFeatures(sequenceFeatures.getState()); + alignPanel.seqPanel.seqCanvas.repaint(); + } + else if(evt.getSource()==conservationMenuItem) + conservationMenuItem_actionPerformed(); + else if(evt.getSource()==abovePIDThreshold) + abovePIDThreshold_actionPerformed(); + else if(evt.getSource()==applyToAllGroups) + applyToAllGroups_actionPerformed(); + else if(evt.getSource()==autoCalculate) + viewport.autocalculateConsensus = autoCalculate.getState(); + } + public void actionPerformed(ActionEvent evt) + { + Object source = evt.getSource(); + + if(source==inputText) + inputText_actionPerformed(); + else if(source==loadTree) + loadTree_actionPerformed(); + else if(source==loadApplication) + launchFullApplication(); + else if(source==closeMenuItem) + closeMenuItem_actionPerformed(); + else if(source==copy) + copy_actionPerformed(); + else if(source==undoMenuItem) + undoMenuItem_actionPerformed(); + else if(source==redoMenuItem) + redoMenuItem_actionPerformed(); + else if(source==inputText) + inputText_actionPerformed(); + else if(source==closeMenuItem) + closeMenuItem_actionPerformed(); + else if(source==undoMenuItem) + undoMenuItem_actionPerformed(); + else if(source==redoMenuItem) + redoMenuItem_actionPerformed(); + else if(source==copy) + copy_actionPerformed(); + else if(source==pasteNew) + pasteNew_actionPerformed(); + else if(source==pasteThis) + pasteThis_actionPerformed(); + else if(source==cut) + cut_actionPerformed(); + else if(source==delete) + delete_actionPerformed(); + else if(source==deleteGroups) + deleteGroups_actionPerformed(); + else if(source==selectAllSequenceMenuItem) + selectAllSequenceMenuItem_actionPerformed(); + else if(source==deselectAllSequenceMenuItem) + deselectAllSequenceMenuItem_actionPerformed(); + else if(source==invertSequenceMenuItem) + invertSequenceMenuItem_actionPerformed(); + else if(source==invertColSel) + { viewport.invertColumnSelection(); alignPanel.repaint(); } + else if(source==remove2LeftMenuItem) + remove2LeftMenuItem_actionPerformed(); + else if(source==remove2RightMenuItem) + remove2RightMenuItem_actionPerformed(); + else if(source==removeGappedColumnMenuItem) + removeGappedColumnMenuItem_actionPerformed(); + else if(source==removeAllGapsMenuItem) + removeAllGapsMenuItem_actionPerformed(); + else if(source==findMenuItem) + findMenuItem_actionPerformed(); + else if(source==font) + font_actionPerformed(); + else if(source==showColumns) + { + viewport.showAllHiddenColumns(); alignPanel.repaint(); + } + else if(source==showSeqs) + { + viewport.showAllHiddenSeqs(); + } + else if(source == hideColumns) + { + viewport.hideSelectedColumns(); alignPanel.repaint(); + } + else if(source == hideSequences && viewport.getSelectionGroup()!=null) + { + viewport.hideAllSelectedSeqs(); + } + else if(source==featureSettings) + featureSettings_actionPerformed(); + else if(source==overviewMenuItem) + overviewMenuItem_actionPerformed(); + else if(source==noColourmenuItem) + noColourmenuItem_actionPerformed(); + else if(source==clustalColour) + clustalColour_actionPerformed(); + else if(source==zappoColour) + zappoColour_actionPerformed(); + else if(source==taylorColour) + taylorColour_actionPerformed(); + else if(source==hydrophobicityColour) + hydrophobicityColour_actionPerformed(); + else if(source==helixColour) + helixColour_actionPerformed(); + else if(source==strandColour) + strandColour_actionPerformed(); + else if(source==turnColour) + turnColour_actionPerformed(); + else if(source==buriedColour) + buriedColour_actionPerformed(); + else if(source==nucleotideColour) + nucleotideColour_actionPerformed(); + else if(source==modifyPID) + modifyPID_actionPerformed(); + else if(source==modifyConservation) + modifyConservation_actionPerformed(); + else if(source==userDefinedColour) + userDefinedColour_actionPerformed(); + else if(source==PIDColour) + PIDColour_actionPerformed(); + else if(source==BLOSUM62Colour) + BLOSUM62Colour_actionPerformed(); + else if(source==annotationColour) + new AnnotationColourChooser(viewport, alignPanel); + else if(source==sortPairwiseMenuItem) + sortPairwiseMenuItem_actionPerformed(); + else if(source==sortIDMenuItem) + sortIDMenuItem_actionPerformed(); + else if(source==sortGroupMenuItem) + sortGroupMenuItem_actionPerformed(); + else if(source==removeRedundancyMenuItem) + removeRedundancyMenuItem_actionPerformed(); + else if(source==pairwiseAlignmentMenuItem) + pairwiseAlignmentMenuItem_actionPerformed(); + else if(source==PCAMenuItem) + PCAMenuItem_actionPerformed(); + else if(source==averageDistanceTreeMenuItem) + averageDistanceTreeMenuItem_actionPerformed(); + else if(source==neighbourTreeMenuItem) + neighbourTreeMenuItem_actionPerformed(); + else if(source==njTreeBlosumMenuItem) + njTreeBlosumMenuItem_actionPerformed(); + else if(source==avDistanceTreeBlosumMenuItem) + avTreeBlosumMenuItem_actionPerformed(); + else if(source==documentation) + documentation_actionPerformed(); + else if(source==about) + about_actionPerformed(); + + } + + public void inputText_actionPerformed() + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this); + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, "Cut & Paste Input", 500, 500); + } + + protected void outputText_actionPerformed(ActionEvent e) + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(false, this); + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, + "Alignment output - " + e.getActionCommand(), + 600, 500); + cap.setText(new AppletFormatAdapter().formatSequences(e.getActionCommand(), + viewport.getAlignment().getSequences(), + viewport.showJVSuffix)); + } + + void launchFullApplication() + { + StringBuffer url = new StringBuffer(jalviewServletURL); + + url.append("?open="+ + appendProtocol( viewport.applet.getParameter("file") ) ); + + if(viewport.applet.getParameter("features")!=null) + { + url.append( "&features=" ); + url.append( appendProtocol( viewport.applet.getParameter("features") ) ); + } + + if(viewport.applet.getParameter("annotations")!=null) + { + url.append( "&annotations=" ); + url.append( appendProtocol( viewport.applet.getParameter("annotations") ) ); + } + + if(viewport.applet.getParameter("jnetfile")!=null) + { + url.append( "&annotations=" ); + url.append( appendProtocol( viewport.applet.getParameter("jnetfile") ) ); + } + + if(viewport.applet.getParameter("defaultColour")!=null) + { + url.append("&colour=" + + removeWhiteSpace(viewport.applet.getParameter("defaultColour")) + ); + } + + if(viewport.applet.getParameter("userDefinedColour")!=null) + { + url.append( "&colour=" + + removeWhiteSpace( viewport.applet.getParameter("userDefinedColour") ) + ); + } + + showURL(url.toString(), "FULL_APP"); + } + + + String removeWhiteSpace(String colour) + { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < colour.length(); i++) + { + if (Character.isWhitespace(colour.charAt(i))) + sb.append("%20"); + else + sb.append(colour.charAt(i)); + } + + return sb.toString(); + } + + + String appendProtocol(String url) + { + try{ + new URL(url); + }catch(java.net.MalformedURLException ex) + { + url = viewport.applet.getCodeBase()+url; + } + return url; + } + + public void closeMenuItem_actionPerformed() + { + PaintRefresher.components.remove(viewport.alignment); + if(PaintRefresher.components.size()==0 && viewport.applet==null) + System.exit(0); + + this.dispose(); + } + + Stack historyList = new Stack(); + Stack redoList = new Stack(); + + void updateEditMenuBar() + { + if (historyList.size() > 0) + { + undoMenuItem.setEnabled(true); + HistoryItem hi = (HistoryItem) historyList.peek(); + undoMenuItem.setLabel("Undo " + hi.getDescription()); + } + else + { + undoMenuItem.setEnabled(false); + undoMenuItem.setLabel("Undo"); + } + + if (redoList.size() > 0) + { + redoMenuItem.setEnabled(true); + HistoryItem hi = (HistoryItem) redoList.peek(); + redoMenuItem.setLabel("Redo " + hi.getDescription()); + } + else + { + redoMenuItem.setEnabled(false); + redoMenuItem.setLabel("Redo"); + } + } + + public void addHistoryItem(HistoryItem hi) + { + historyList.push(hi); + redoList.removeAllElements(); + updateEditMenuBar(); + } + + protected void undoMenuItem_actionPerformed() + { + HistoryItem nh,hi = (HistoryItem) historyList.pop(); + redoList.push(nh=new HistoryItem(hi.getDescription(), viewport.alignment, + HistoryItem.HIDE)); + if (hi.alColumnChanges!=null) + nh.alColumnChanges=hi.alColumnChanges.getInverse(); + restoreHistoryItem(hi); + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + protected void redoMenuItem_actionPerformed() + { + HistoryItem nh,hi = (HistoryItem) redoList.pop(); + historyList.push(nh=new HistoryItem(hi.getDescription(), viewport.alignment, + HistoryItem.HIDE)); + if (hi.alColumnChanges!=null) + nh.alColumnChanges=hi.alColumnChanges.getInverse(); + restoreHistoryItem(hi); + updateEditMenuBar(); + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + // used by undo and redo + void restoreHistoryItem(HistoryItem hi) + { + hi.restore(viewport.getColumnSelection()); + updateEditMenuBar(); + + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + public void moveSelectedSequences(boolean up) + { + SequenceGroup sg = viewport.getSelectionGroup(); + if (sg == null) + { + return; + } + + if (up) + { + for (int i = 1; i < viewport.alignment.getHeight(); i++) + { + SequenceI seq = viewport.alignment.getSequenceAt(i); + if (!sg.getSequences(false).contains(seq)) + { + continue; + } + + SequenceI temp = viewport.alignment.getSequenceAt(i - 1); + if (sg.getSequences(false).contains(temp)) + { + continue; + } + + viewport.alignment.getSequences().setElementAt(temp, i); + viewport.alignment.getSequences().setElementAt(seq, i - 1); + } + } + else + { + for (int i = viewport.alignment.getHeight() - 2; i > -1; i--) + { + SequenceI seq = viewport.alignment.getSequenceAt(i); + if (!sg.getSequences(true).contains(seq)) + { + continue; + } + + SequenceI temp = viewport.alignment.getSequenceAt(i + 1); + if (sg.getSequences(true).contains(temp)) + { + continue; + } + + viewport.alignment.getSequences().setElementAt(temp, i); + viewport.alignment.getSequences().setElementAt(seq, i + 1); + } + } + + alignPanel.repaint(); + } + + static StringBuffer copiedSequences; + static Vector copiedHiddenColumns; + protected void copy_actionPerformed() + { + if (viewport.getSelectionGroup() == null) + { + return; + } + + SequenceGroup sg = viewport.getSelectionGroup(); + copiedSequences = new StringBuffer(); + Hashtable orderedSeqs = new Hashtable(); + for (int i = 0; i < sg.getSize(false); i++) + { + SequenceI seq = sg.getSequenceAt(i); + int index = viewport.alignment.findIndex(seq); + orderedSeqs.put(index + "", seq); + } + + int index = 0, startRes, endRes; + char ch; + + if (viewport.hasHiddenColumns && viewport.getSelectionGroup() != null) + { + copiedHiddenColumns = new Vector(); + int hiddenOffset = viewport.getSelectionGroup().getStartRes(); + for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size(); + i++) + { + int[] region = (int[]) + viewport.getColumnSelection().getHiddenColumns().elementAt(i); + + copiedHiddenColumns.addElement(new int[] + {region[0] - hiddenOffset, + region[1] - hiddenOffset}); + } + } + else + copiedHiddenColumns = null; + + + for (int i = 0; i < sg.getSize(false); i++) + { + SequenceI seq = null; + + while (seq == null) + { + if (orderedSeqs.containsKey(index + "")) + { + seq = (SequenceI) orderedSeqs.get(index + ""); + index++; + + break; + } + else + { + index++; + } + } + + //FIND START RES + //Returns residue following index if gap + startRes = seq.findPosition(sg.getStartRes()); + + //FIND END RES + //Need to find the residue preceeding index if gap + endRes = 0; + + for (int j = 0; j < sg.getEndRes()+1 && j < seq.getLength(); j++) + { + ch = seq.getCharAt(j); + if (!jalview.util.Comparison.isGap( (ch))) + { + endRes++; + } + } + + if(endRes>0) + { + endRes += seq.getStart() -1; + } + + copiedSequences.append(seq.getName() + "\t" + + startRes + "\t" + + endRes + "\t" + + seq.getSequence(sg.getStartRes(), + sg.getEndRes() + 1) + "\n"); + } + + } + + protected void pasteNew_actionPerformed() + { + paste(true); + } + + protected void pasteThis_actionPerformed() + { + addHistoryItem(new HistoryItem("Paste Sequences", viewport.alignment, + HistoryItem.PASTE)); + paste(false); + } + + void paste(boolean newAlignment) + { + try + { + if (copiedSequences == null) + { + return; + } + + StringTokenizer st = new StringTokenizer(copiedSequences.toString()); + Vector seqs = new Vector(); + while (st.hasMoreElements()) + { + String name = st.nextToken(); + int start = Integer.parseInt(st.nextToken()); + int end = Integer.parseInt(st.nextToken()); + Sequence sequence = new Sequence(name, st.nextToken(), start, end); + + if (!newAlignment) + { + viewport.alignment.addSequence(sequence); + } + else + { + seqs.addElement(sequence); + } + } + + if (newAlignment) + { + SequenceI[] newSeqs = new SequenceI[seqs.size()]; + for (int i = 0; i < seqs.size(); i++) + { + newSeqs[i] = (SequenceI) seqs.elementAt(i); + } + + String newtitle = new String("Copied sequences"); + if (getTitle().startsWith("Copied sequences")) + { + newtitle = getTitle(); + } + else + { + newtitle = newtitle.concat("- from " + getTitle()); + } + AlignFrame af = new AlignFrame(new Alignment(newSeqs), + viewport.applet, + newtitle, + false); + if (copiedHiddenColumns != null) + { + for (int i = 0; i < copiedHiddenColumns.size(); i++) + { + int[] region = (int[]) copiedHiddenColumns.elementAt(i); + af.viewport.hideColumns(region[0], region[1]); + } + } + + + jalview.bin.JalviewLite.addFrame(af, newtitle, NEW_WINDOW_WIDTH, + NEW_WINDOW_HEIGHT); + } + else + { + viewport.setEndSeq(viewport.alignment.getHeight()); + viewport.alignment.getWidth(); + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + } + catch (Exception ex) + {} // could be anything being pasted in here + + } + + protected void cut_actionPerformed() + { + copy_actionPerformed(); + delete_actionPerformed(); + } + + protected void delete_actionPerformed() + { + addHistoryItem(new HistoryItem("Delete Sequences", viewport.alignment, + HistoryItem.HIDE)); + if (viewport.getSelectionGroup() == null) + { + return; + } + + + SequenceGroup sg = viewport.getSelectionGroup(); + boolean allSequences = false; + if(sg.getSize(false)==viewport.alignment.getHeight()) + allSequences = true; + + for (int i = 0; i < sg.getSize(false); i++) + { + SequenceI seq = sg.getSequenceAt(i); + int index = viewport.getAlignment().findIndex(seq); + seq.deleteChars(sg.getStartRes(), sg.getEndRes() + 1); + + // If the cut affects all sequences, remove highlighted columns + if (allSequences) + { + viewport.getColumnSelection().removeElements(sg.getStartRes(), + sg.getEndRes() + 1); + } + + + if (seq.getSequence().length() < 1) + { + viewport.getAlignment().deleteSequence(seq); + } + else + { + viewport.getAlignment().getSequences().setElementAt(seq, index); + } + } + + viewport.setSelectionGroup(null); + viewport.alignment.deleteGroup(sg); + viewport.resetSeqLimits(alignPanel.seqPanel.seqCanvas.getSize().height); + if (viewport.getAlignment().getHeight() < 1) + { + try + { + this.setVisible(false); + } + catch (Exception ex) + {} + } + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + + } + + protected void deleteGroups_actionPerformed() + { + viewport.alignment.deleteAllGroups(); + viewport.setSelectionGroup(null); + + alignPanel.repaint(); + } + + public void selectAllSequenceMenuItem_actionPerformed() + { + SequenceGroup sg = new SequenceGroup(); + for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++) + { + sg.addSequence(viewport.getAlignment().getSequenceAt(i), false); + } + sg.setEndRes(viewport.alignment.getWidth()-1); + viewport.setSelectionGroup(sg); + alignPanel.repaint(); + PaintRefresher.Refresh(null, viewport.alignment); + } + + public void deselectAllSequenceMenuItem_actionPerformed() + { + if(viewport.cursorMode) + { + alignPanel.seqPanel.keyboardNo1=null; + alignPanel.seqPanel.keyboardNo2=null; + } + viewport.setSelectionGroup(null); + viewport.getColumnSelection().clear(); + viewport.setSelectionGroup(null); + alignPanel.idPanel.idCanvas.searchResults = null; + alignPanel.seqPanel.seqCanvas.highlightSearchResults(null); + alignPanel.repaint(); + PaintRefresher.Refresh(null, viewport.alignment); + } + + public void invertSequenceMenuItem_actionPerformed() + { + SequenceGroup sg = viewport.getSelectionGroup(); + for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++) + { + sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false); + } + + PaintRefresher.Refresh(null, viewport.alignment); + } + + public void remove2LeftMenuItem_actionPerformed() + { + ColumnSelection colSel = viewport.getColumnSelection(); + if (colSel.size() > 0) + { + HistoryItem edit; + addHistoryItem(edit=new HistoryItem("Remove Left", viewport.alignment, + HistoryItem.HIDE)); + int min = colSel.getMin(); + viewport.getAlignment().trimLeft(min); + colSel.compensateForEdit(0, min); + edit.addShift(0, min); + if (viewport.getSelectionGroup() != null) + { + viewport.getSelectionGroup().adjustForRemoveLeft(min); + } + + Vector groups = viewport.alignment.getGroups(); + for (int i = 0; i < groups.size(); i++) + { + SequenceGroup sg = (SequenceGroup) groups.elementAt(i); + if (!sg.adjustForRemoveLeft(min)) + { + viewport.alignment.deleteGroup(sg); + } + } + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + } + + public void remove2RightMenuItem_actionPerformed() + { + ColumnSelection colSel = viewport.getColumnSelection(); + if (colSel.size() > 0) + { + addHistoryItem(new HistoryItem("Remove Right", viewport.alignment, + HistoryItem.HIDE)); + int max = colSel.getMax(); + viewport.getAlignment().trimRight(max); + + if (viewport.getSelectionGroup() != null) + { + viewport.getSelectionGroup().adjustForRemoveRight(max); + } + + Vector groups = viewport.alignment.getGroups(); + for (int i = 0; i < groups.size(); i++) + { + SequenceGroup sg = (SequenceGroup) groups.elementAt(i); + if (!sg.adjustForRemoveRight(max)) + { + viewport.alignment.deleteGroup(sg); + } + } + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + } + + public void removeGappedColumnMenuItem_actionPerformed() + { + HistoryItem edit; + addHistoryItem(edit=new HistoryItem("Remove Gapped Columns", + viewport.alignment, + HistoryItem.HIDE)); + + //This is to maintain viewport position on first residue + //of first sequence + SequenceI seq = viewport.alignment.getSequenceAt(0); + int startRes = seq.findPosition(viewport.startRes); + + viewport.getAlignment().removeGaps(); + + viewport.setStartRes(seq.findIndex(startRes)-1); + + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + public void removeAllGapsMenuItem_actionPerformed() + { + // TODO: hidden regions should not be touched by removeAllGaps - a minimal number of gaps will remain in alignment segments containing uneven length subsequences + // TODO: columnSelection.compensateforedits should be called (and passed to history item) + HistoryItem editgaps; + addHistoryItem(editgaps=new HistoryItem("Remove Gaps", viewport.alignment, + HistoryItem.HIDE)); + + //This is to maintain viewport position on first residue + //of first sequence + SequenceI seq = viewport.alignment.getSequenceAt(0); + int startRes = seq.findPosition(viewport.startRes); + + SequenceI current; + Vector seqs=null; + + int start=0, end = viewport.alignment.getWidth(); + + if (viewport.getSelectionGroup() != null + && viewport.getSelectionGroup().getSequences(false) != null + && viewport.getSelectionGroup().getSize(false)>0) + { + seqs = viewport.getSelectionGroup().getSequences(true); + start = viewport.getSelectionGroup().getStartRes(); + end = viewport.getSelectionGroup().getEndRes()+1; + } + else + seqs = viewport.alignment.getSequences(); + + /* Commented out regions below are partial implementation of todo above. + * divide start,end into visible chunks, and for each: + int diff=end-start+1; + int diffmax=0; + int dr[] = new int[seqs.size()]; + */ + for (int i = 0; i < seqs.size(); i++) + { + current = (SequenceI) seqs.elementAt(i); + //dr[i]= + current.removeGaps(start, end); + /*if (d0) { + // record shift for history. + editgaps.addShift(start, diff); + if (viewport.hasHiddenColumns && diffmax>diff) { + // pad sequence + StringBuffer gaps=new StringBuffer(diffmax); + for (int i=0,j=diffmax-diff; i0) { + String sq = current.getSequence(); + current.setSequence(sq.substring(0, hcend-dr[i])+gaps.substring(0, dr[i]-diff)+sq.substring()); + } + } + } + }*/ + + viewport.setStartRes(seq.findIndex(startRes)-1); + viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences()); + } + + public void alignmentChanged() + { + viewport.alignment.padGaps(); + if(viewport.autocalculateConsensus) + { + viewport.updateConsensus(); + viewport.updateConservation(); + } + + resetAllColourSchemes(); + if(alignPanel.overviewPanel!=null) + alignPanel.overviewPanel.updateOverviewImage(); + + viewport.alignment.adjustSequenceAnnotations(); + alignPanel.repaint(); + } + + void resetAllColourSchemes() + { + ColourSchemeI cs = viewport.globalColourScheme; + if(cs!=null) + { + if (cs instanceof ClustalxColourScheme) + { + ( (ClustalxColourScheme) viewport.getGlobalColourScheme()). + resetClustalX(viewport.alignment.getSequences(), + viewport.alignment.getWidth()); + } + + cs.setConsensus(viewport.vconsensus); + if (cs.conservationApplied()) + { + Alignment al = (Alignment) viewport.alignment; + Conservation c = new Conservation("All", + ResidueProperties.propHash, 3, + al.getSequences(), 0, + al.getWidth() - 1); + c.calculate(); + c.verdict(false, viewport.ConsPercGaps); + + cs.setConservation(c); + } + } + + int s, sSize = viewport.alignment.getGroups().size(); + for(s=0; s 1) + { + Frame frame = new Frame(); + frame.add(new PairwiseAlignPanel(alignPanel)); + jalview.bin.JalviewLite.addFrame(frame, "Pairwise Alignment", 600, 500); + } + } + + public void PCAMenuItem_actionPerformed() + { + //are the sequences aligned? + if (!viewport.alignment.isAligned()) + { + SequenceI current; + int Width = viewport.getAlignment().getWidth(); + + for (int i = 0; i < viewport.getAlignment().getSequences().size(); + i++) + { + current = viewport.getAlignment().getSequenceAt(i); + + if (current.getLength() < Width) + { + current.insertCharAt(Width - 1, viewport.getGapCharacter()); + } + } + alignPanel.repaint(); + } + + if ( (viewport.getSelectionGroup() != null && + viewport.getSelectionGroup().getSize(false) < 4 && + viewport.getSelectionGroup().getSize(false) > 0) + || viewport.getAlignment().getHeight() < 4) + { + return; + } + + try + { + new PCAPanel(viewport); + } + catch (java.lang.OutOfMemoryError ex) + { + } + + } + + public void averageDistanceTreeMenuItem_actionPerformed() + { + NewTreePanel("AV", "PID", "Average distance tree using PID"); + } + + public void neighbourTreeMenuItem_actionPerformed() + { + NewTreePanel("NJ", "PID", "Neighbour joining tree using PID"); + } + + protected void njTreeBlosumMenuItem_actionPerformed() + { + NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62"); + } + + protected void avTreeBlosumMenuItem_actionPerformed() + { + NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62PID"); + } + + void NewTreePanel(String type, String pwType, String title) + { + //are the sequences aligned? + if (!viewport.alignment.isAligned()) + { + SequenceI current; + int Width = viewport.getAlignment().getWidth(); + + for (int i = 0; i < viewport.getAlignment().getSequences().size(); + i++) + { + current = viewport.getAlignment().getSequenceAt(i); + + if (current.getLength() < Width) + { + current.insertCharAt(Width - 1, viewport.getGapCharacter()); + } + } + alignPanel.repaint(); + + } + + if ( (viewport.getSelectionGroup() != null && + viewport.getSelectionGroup().getSize(false) > 1) + || (viewport.getSelectionGroup() == null + && viewport.alignment.getHeight() > 1)) + { + final TreePanel tp = new TreePanel(viewport, + type, + pwType); + + addTreeMenuItem(tp, title); + + jalview.bin.JalviewLite.addFrame(tp, title, 600, 500); + } + } + + void loadTree_actionPerformed() + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(true, this); + cap.setText("Paste your Newick tree file here."); + cap.treeImport = true; + Frame frame = new Frame(); + frame.add(cap); + jalview.bin.JalviewLite.addFrame(frame, "Paste Newick file ", 400, 300); + } + + public void loadTree(jalview.io.NewickFile tree, String treeFile) + { + TreePanel tp = new TreePanel(viewport, + treeFile, + "From File - ", + tree); + jalview.bin.JalviewLite.addFrame(tp, treeFile, 600, 500); + addTreeMenuItem(tp, treeFile); + } + + void addTreeMenuItem(final TreePanel treePanel, String title) + { + final MenuItem item = new MenuItem(title); + sortByTreeMenu.add(item); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent evt) + { + addHistoryItem(new HistoryItem("Sort", viewport.alignment, + HistoryItem.SORT)); + AlignmentSorter.sortByTree(viewport.getAlignment(), treePanel.getTree()); + alignPanel.repaint(); + } + }); + + treePanel.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + sortByTreeMenu.remove(item); + }; + }); + } + + protected void documentation_actionPerformed() + { + showURL("http://www.jalview.org/help.html", "HELP"); + } + + protected void about_actionPerformed() + { + + class AboutPanel extends Canvas + { + String version; + public AboutPanel(String version) + { this.version = version; } + + public void paint(Graphics g) + { + g.setColor(Color.white); + g.fillRect(0, 0, getSize().width, getSize().height); + g.setFont(new Font("Helvetica", Font.PLAIN, 12)); + FontMetrics fm = g.getFontMetrics(); + int fh = fm.getHeight(); + int y = 5, x = 7; + g.setColor(Color.black); + g.setFont(new Font("Helvetica", Font.BOLD, 14)); + g.drawString("Jalview - Release "+version, 200, y += fh); + g.setFont(new Font("Helvetica", Font.PLAIN, 12)); + g.drawString("Authors: Michele Clamp, James Cuff, Steve Searle, Andrew Waterhouse, Jim Procter & Geoff Barton.", + x, y += fh * 2); + g.drawString("Current development managed by Andrew Waterhouse; Barton Group, University of Dundee.", + x, y += fh); + g.drawString( + "For any issues relating to Jalview, email help@jalview.org", x, + y += fh); + g.drawString("If you use JalView, please cite:", x, y += fh + 8); + g.drawString("\"Clamp, M., Cuff, J., Searle, S. M. and Barton, G. J. (2004), The Jalview Java Alignment Editor\"", + x, y += fh); + g.drawString("Bioinformatics, 2004 20;426-7.", x, y += fh); + } + } + + String version = "test"; + java.net.URL url = getClass().getResource("/.build_properties"); + if (url != null) + { + try + { + BufferedReader reader = new BufferedReader(new InputStreamReader( + url.openStream())); + String line; + while ( (line = reader.readLine()) != null) + { + if (line.indexOf("VERSION") > -1) + { + version = line.substring(line.indexOf("=") + 1); + } + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + + Frame frame = new Frame(); + frame.add(new AboutPanel(version)); + jalview.bin.JalviewLite.addFrame(frame, "Jalview", 580, 200); + + } + + public void showURL(String url, String target) + { + if (viewport.applet == null) + { + System.out.println("Not running as applet - no browser available."); + } + else + { + try + { + System.out.println("Show url: "+url); + viewport.applet.getAppletContext().showDocument(new java.net.URL(url), + target); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + } + + + ////////////////////////////////////////////////////////////////////////////////// + //JBuilder Graphics here + + protected MenuBar alignFrameMenuBar = new MenuBar(); + protected Menu fileMenu = new Menu("File"); + protected MenuItem loadApplication = new MenuItem("View in Full Application"); + protected MenuItem loadTree = new MenuItem("Load Associated Tree"); + protected MenuItem closeMenuItem = new MenuItem("Close"); + protected Menu editMenu = new Menu("Edit"); + protected Menu viewMenu = new Menu("View"); + protected Menu colourMenu = new Menu("Colour"); + protected Menu calculateMenu = new Menu("Calculate"); + protected MenuItem selectAllSequenceMenuItem = new MenuItem("Select all"); + protected MenuItem deselectAllSequenceMenuItem = new MenuItem("Deselect All"); + protected MenuItem invertSequenceMenuItem = new MenuItem("Invert Selection"); + protected MenuItem remove2LeftMenuItem = new MenuItem(); + protected MenuItem remove2RightMenuItem = new MenuItem(); + protected MenuItem removeGappedColumnMenuItem = new MenuItem(); + protected MenuItem removeAllGapsMenuItem = new MenuItem(); + protected CheckboxMenuItem viewBoxesMenuItem = new CheckboxMenuItem(); + protected CheckboxMenuItem viewTextMenuItem = new CheckboxMenuItem(); + protected MenuItem sortPairwiseMenuItem = new MenuItem(); + protected MenuItem sortIDMenuItem = new MenuItem(); + protected MenuItem sortGroupMenuItem = new MenuItem(); + protected MenuItem removeRedundancyMenuItem = new MenuItem(); + protected MenuItem pairwiseAlignmentMenuItem = new MenuItem(); + protected MenuItem PCAMenuItem = new MenuItem(); + protected MenuItem averageDistanceTreeMenuItem = new MenuItem(); + protected MenuItem neighbourTreeMenuItem = new MenuItem(); + BorderLayout borderLayout1 = new BorderLayout(); + public Label statusBar = new Label(); + protected Menu outputTextboxMenu = new Menu(); + protected MenuItem clustalColour = new MenuItem(); + protected MenuItem zappoColour = new MenuItem(); + protected MenuItem taylorColour = new MenuItem(); + protected MenuItem hydrophobicityColour = new MenuItem(); + protected MenuItem helixColour = new MenuItem(); + protected MenuItem strandColour = new MenuItem(); + protected MenuItem turnColour = new MenuItem(); + protected MenuItem buriedColour = new MenuItem(); + protected MenuItem userDefinedColour = new MenuItem(); + protected MenuItem PIDColour = new MenuItem(); + protected MenuItem BLOSUM62Colour = new MenuItem(); + MenuItem njTreeBlosumMenuItem = new MenuItem(); + MenuItem avDistanceTreeBlosumMenuItem = new MenuItem(); + protected CheckboxMenuItem annotationPanelMenuItem = new CheckboxMenuItem(); + protected CheckboxMenuItem colourTextMenuItem = new CheckboxMenuItem(); + MenuItem overviewMenuItem = new MenuItem(); + protected MenuItem undoMenuItem = new MenuItem(); + protected MenuItem redoMenuItem = new MenuItem(); + protected CheckboxMenuItem conservationMenuItem = new CheckboxMenuItem(); + MenuItem noColourmenuItem = new MenuItem(); + protected CheckboxMenuItem wrapMenuItem = new CheckboxMenuItem(); + protected CheckboxMenuItem renderGapsMenuItem = new CheckboxMenuItem(); + MenuItem findMenuItem = new MenuItem(); + Menu searchMenu = new Menu(); + protected CheckboxMenuItem abovePIDThreshold = new CheckboxMenuItem(); + protected MenuItem nucleotideColour = new MenuItem(); + MenuItem deleteGroups = new MenuItem(); + MenuItem delete = new MenuItem(); + MenuItem copy = new MenuItem(); + MenuItem cut = new MenuItem(); + Menu pasteMenu = new Menu(); + MenuItem pasteNew = new MenuItem(); + MenuItem pasteThis = new MenuItem(); + protected CheckboxMenuItem applyToAllGroups = new CheckboxMenuItem(); + protected MenuItem font = new MenuItem(); + protected CheckboxMenuItem scaleAbove = new CheckboxMenuItem(); + protected CheckboxMenuItem scaleLeft = new CheckboxMenuItem(); + protected CheckboxMenuItem scaleRight = new CheckboxMenuItem(); + MenuItem modifyPID = new MenuItem(); + MenuItem modifyConservation = new MenuItem(); + protected CheckboxMenuItem autoCalculate + = new CheckboxMenuItem("Autocalculate Consensus", true); + protected Menu sortByTreeMenu = new Menu(); + Menu sort = new Menu(); + Menu calculate = new Menu(); + MenuItem inputText = new MenuItem(); + Menu helpMenu = new Menu(); + MenuItem documentation = new MenuItem(); + MenuItem about = new MenuItem(); + protected CheckboxMenuItem seqLimits = new CheckboxMenuItem(); + Panel embeddedMenu; + Label embeddedEdit; + Label embeddedSearch; + Label embeddedView; + Label embeddedColour; + Label embeddedFile; + Label embeddedHelp; + Label embeddedCalculate; + FlowLayout flowLayout1; + + private void jbInit() throws Exception { + + setMenuBar(alignFrameMenuBar); + + MenuItem item; + + // dynamically fill save as menu with available formats + for (int i = 0; i < jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS.length; i++) + { + + item = new MenuItem( jalview.io.AppletFormatAdapter.WRITEABLE_FORMATS[i]); + + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + outputText_actionPerformed(e); + } + }); + + outputTextboxMenu.add(item); + } + closeMenuItem.addActionListener(this); + loadApplication.addActionListener(this); + + loadTree.addActionListener(this); + selectAllSequenceMenuItem.addActionListener(this); + deselectAllSequenceMenuItem.addActionListener(this); + invertSequenceMenuItem.addActionListener(this); + remove2LeftMenuItem.setLabel("Remove Left"); + remove2LeftMenuItem.addActionListener(this); + remove2RightMenuItem.setLabel("Remove Right"); + remove2RightMenuItem.addActionListener(this); + removeGappedColumnMenuItem.setLabel("Remove Empty Columns"); + removeGappedColumnMenuItem.addActionListener(this); + removeAllGapsMenuItem.setLabel("Remove All Gaps"); + removeAllGapsMenuItem.addActionListener(this); + viewBoxesMenuItem.setLabel("Boxes"); + viewBoxesMenuItem.setState(true); + viewBoxesMenuItem.addItemListener(this); + viewTextMenuItem.setLabel("Text"); + viewTextMenuItem.setState(true); + viewTextMenuItem.addItemListener(this); + sortPairwiseMenuItem.setLabel("by Pairwise Identity"); + sortPairwiseMenuItem.addActionListener(this); + sortIDMenuItem.setLabel("by ID"); + sortIDMenuItem.addActionListener(this); + sortGroupMenuItem.setLabel("by Group"); + sortGroupMenuItem.addActionListener(this); + removeRedundancyMenuItem.setLabel("Remove Redundancy..."); + removeRedundancyMenuItem.addActionListener(this); + pairwiseAlignmentMenuItem.setLabel("Pairwise Alignments..."); + pairwiseAlignmentMenuItem.addActionListener(this); + PCAMenuItem.setLabel("Principal Component Analysis"); + PCAMenuItem.addActionListener(this); + averageDistanceTreeMenuItem.setLabel( + "Average Distance Using % Identity"); + averageDistanceTreeMenuItem.addActionListener(this); + neighbourTreeMenuItem.setLabel("Neighbour Joining Using % Identity"); + neighbourTreeMenuItem.addActionListener(this); + alignFrameMenuBar.setFont(new java.awt.Font("Verdana", 0, 11)); + statusBar.setBackground(Color.white); + statusBar.setFont(new java.awt.Font("Verdana", 0, 11)); + statusBar.setText("Status bar"); + outputTextboxMenu.setLabel("Output to Textbox"); + clustalColour.setLabel("Clustalx"); + + clustalColour.addActionListener(this); + zappoColour.setLabel("Zappo"); + zappoColour.addActionListener(this); + taylorColour.setLabel("Taylor"); + taylorColour.addActionListener(this); + hydrophobicityColour.setLabel("Hydrophobicity"); + hydrophobicityColour.addActionListener(this); + helixColour.setLabel("Helix Propensity"); + helixColour.addActionListener(this); + strandColour.setLabel("Strand Propensity"); + strandColour.addActionListener(this); + turnColour.setLabel("Turn Propensity"); + turnColour.addActionListener(this); + buriedColour.setLabel("Buried Index"); + buriedColour.addActionListener(this); + userDefinedColour.setLabel("User Defined..."); + userDefinedColour.addActionListener(this); + PIDColour.setLabel("Percentage Identity"); + PIDColour.addActionListener(this); + BLOSUM62Colour.setLabel("BLOSUM62 Score"); + BLOSUM62Colour.addActionListener(this); + avDistanceTreeBlosumMenuItem.setLabel( + "Average Distance Using BLOSUM62"); + avDistanceTreeBlosumMenuItem.addActionListener(this); + njTreeBlosumMenuItem.setLabel("Neighbour Joining Using BLOSUM62"); + njTreeBlosumMenuItem.addActionListener(this); + annotationPanelMenuItem.setLabel("Show Annotations"); + annotationPanelMenuItem.addItemListener(this); + colourTextMenuItem.setLabel("Colour Text"); + colourTextMenuItem.addItemListener(this); + overviewMenuItem.setLabel("Overview Window"); + overviewMenuItem.addActionListener(this); + undoMenuItem.setEnabled(false); + undoMenuItem.setLabel("Undo"); + undoMenuItem.addActionListener(this); + redoMenuItem.setEnabled(false); + redoMenuItem.setLabel("Redo"); + redoMenuItem.addActionListener(this); + conservationMenuItem.setLabel("by Conservation"); + conservationMenuItem.addItemListener(this); + noColourmenuItem.setLabel("None"); + noColourmenuItem.addActionListener(this); + wrapMenuItem.setLabel("Wrap"); + wrapMenuItem.addItemListener(this); + renderGapsMenuItem.setLabel("Show Gaps"); + renderGapsMenuItem.setState(true); + renderGapsMenuItem.addItemListener(this); + findMenuItem.setLabel("Find..."); + findMenuItem.addActionListener(this); + searchMenu.setLabel("Search"); + + abovePIDThreshold.setLabel("Above Identity Threshold"); + abovePIDThreshold.addItemListener(this); + nucleotideColour.setLabel("Nucleotide"); + nucleotideColour.addActionListener(this); + deleteGroups.setLabel("Undefine Groups"); + deleteGroups.addActionListener(this); + copy.setLabel("Copy"); + copy.addActionListener(this); + cut.setLabel("Cut"); + cut.addActionListener(this); + delete.setLabel("Delete"); + delete.addActionListener(this); + pasteMenu.setLabel("Paste"); + pasteNew.setLabel("To New Alignment"); + pasteNew.addActionListener(this); + pasteThis.setLabel("Add To This Alignment"); + pasteThis.addActionListener(this); + applyToAllGroups.setLabel("Apply Colour To All Groups"); + applyToAllGroups.setState(true); + applyToAllGroups.addItemListener(this); + font.setLabel("Font..."); + font.addActionListener(this); + scaleAbove.setLabel("Scale Above"); + scaleAbove.setState(true); + scaleAbove.setEnabled(false); + scaleAbove.addItemListener(this); + scaleLeft.setEnabled(false); + scaleLeft.setState(true); + scaleLeft.setLabel("Scale Left"); + scaleLeft.addItemListener(this); + scaleRight.setEnabled(false); + scaleRight.setState(true); + scaleRight.setLabel("Scale Right"); + scaleRight.addItemListener(this); + modifyPID.setLabel("Modify Identity Threshold..."); + modifyPID.addActionListener(this); + modifyConservation.setLabel("Modify Conservation Threshold..."); + modifyConservation.addActionListener(this); + sortByTreeMenu.setLabel("By Tree Order"); + sort.setLabel("Sort"); + calculate.setLabel("Calculate Tree"); + autoCalculate.addItemListener(this); + inputText.setLabel("Input from textbox"); + inputText.addActionListener(this); + + helpMenu.setLabel("Help"); + documentation.setLabel("Documentation"); + documentation.addActionListener(this); + + about.setLabel("About..."); + about.addActionListener(this); + seqLimits.setState(true); + seqLimits.setLabel("Show Sequence Limits"); + seqLimits.addItemListener(this); + featureSettings.setLabel("Feature Settings..."); + featureSettings.addActionListener(this); + sequenceFeatures.setLabel("Sequence Features"); + sequenceFeatures.addItemListener(this); + sequenceFeatures.setState(false); + annotationColour.setLabel("by Annotation..."); + annotationColour.addActionListener(this); + invertSequenceMenuItem.setLabel("Invert Sequence Selection"); + invertColSel.setLabel("Invert Column Selection"); + menu1.setLabel("Show"); + showColumns.setLabel("All Columns "); + showSeqs.setLabel("All Sequences"); + menu2.setLabel("Hide"); + hideColumns.setLabel("Selected Columns"); + hideSequences.setLabel("Selected Sequences"); + invertColSel.addActionListener(this); + showColumns.addActionListener(this); + showSeqs.addActionListener(this); + hideColumns.addActionListener(this); + hideSequences.addActionListener(this); + + + alignFrameMenuBar.add(fileMenu); + alignFrameMenuBar.add(editMenu); + alignFrameMenuBar.add(searchMenu); + alignFrameMenuBar.add(viewMenu); + alignFrameMenuBar.add(colourMenu); + alignFrameMenuBar.add(calculateMenu); + alignFrameMenuBar.add(helpMenu); + fileMenu.add(inputText); + fileMenu.add(outputTextboxMenu); + if(jalviewServletURL!=null) + fileMenu.add(loadApplication); + fileMenu.addSeparator(); + fileMenu.add(loadTree); + fileMenu.add(closeMenuItem); + editMenu.add(undoMenuItem); + editMenu.add(redoMenuItem); + editMenu.add(cut); + editMenu.add(copy); + editMenu.add(pasteMenu); + editMenu.add(delete); + editMenu.addSeparator(); + editMenu.add(selectAllSequenceMenuItem); + editMenu.add(deselectAllSequenceMenuItem); + editMenu.add(invertSequenceMenuItem); + editMenu.add(invertColSel); + editMenu.add(deleteGroups); + editMenu.addSeparator(); + editMenu.add(remove2LeftMenuItem); + editMenu.add(remove2RightMenuItem); + editMenu.add(removeGappedColumnMenuItem); + editMenu.add(removeAllGapsMenuItem); + editMenu.add(removeRedundancyMenuItem); + searchMenu.add(findMenuItem); + viewMenu.add(font); + viewMenu.addSeparator(); + viewMenu.add(menu1); + viewMenu.add(menu2); + viewMenu.addSeparator(); + viewMenu.add(wrapMenuItem); + viewMenu.add(scaleAbove); + viewMenu.add(scaleLeft); + viewMenu.add(scaleRight); + viewMenu.addSeparator(); + viewMenu.add(seqLimits); + viewMenu.add(viewBoxesMenuItem); + viewMenu.add(viewTextMenuItem); + viewMenu.add(colourTextMenuItem); + viewMenu.add(renderGapsMenuItem); + viewMenu.add(annotationPanelMenuItem); + viewMenu.addSeparator(); + viewMenu.add(sequenceFeatures); + viewMenu.add(featureSettings); + viewMenu.addSeparator(); + viewMenu.add(overviewMenuItem); + colourMenu.add(applyToAllGroups); + colourMenu.addSeparator(); + colourMenu.add(noColourmenuItem); + colourMenu.add(clustalColour); + colourMenu.add(BLOSUM62Colour); + colourMenu.add(PIDColour); + colourMenu.add(zappoColour); + colourMenu.add(taylorColour); + colourMenu.add(hydrophobicityColour); + colourMenu.add(helixColour); + colourMenu.add(strandColour); + colourMenu.add(turnColour); + colourMenu.add(buriedColour); + colourMenu.add(nucleotideColour); + colourMenu.add(userDefinedColour); + colourMenu.addSeparator(); + colourMenu.add(conservationMenuItem); + colourMenu.add(modifyConservation); + colourMenu.add(abovePIDThreshold); + colourMenu.add(modifyPID); + colourMenu.add(annotationColour); + calculateMenu.add(sort); + calculateMenu.add(calculate); + calculateMenu.addSeparator(); + calculateMenu.add(pairwiseAlignmentMenuItem); + calculateMenu.add(PCAMenuItem); + calculateMenu.add(autoCalculate); + this.add(statusBar, BorderLayout.SOUTH); + pasteMenu.add(pasteNew); + pasteMenu.add(pasteThis); + sort.add(sortIDMenuItem); + sort.add(sortByTreeMenu); + sort.add(sortGroupMenuItem); + sort.add(sortPairwiseMenuItem); + calculate.add(averageDistanceTreeMenuItem); + calculate.add(neighbourTreeMenuItem); + calculate.add(avDistanceTreeBlosumMenuItem); + calculate.add(njTreeBlosumMenuItem); + helpMenu.add(documentation); + helpMenu.add(about); + menu1.add(showColumns); + menu1.add(showSeqs); + menu2.add(hideColumns); + menu2.add(hideSequences); + } + + public void setEmbedded() + { + + embeddedMenu = new Panel(); + embeddedEdit = new Label(); + embeddedSearch = new Label(); + embeddedView = new Label(); + embeddedColour = new Label(); + embeddedFile = new Label(); + embeddedHelp = new Label(); + embeddedCalculate = new Label(); + flowLayout1 = new FlowLayout(); + embeddedMenu.setBackground(Color.lightGray); + embeddedMenu.setLayout(flowLayout1); + embeddedEdit.setText("Edit"); + embeddedEdit.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedSearch.setText("Search"); + embeddedSearch.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedView.setText("View"); + embeddedView.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedColour.setText("Colour"); + embeddedColour.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedFile.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedFile.setText("File"); + embeddedHelp.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedHelp.setText("Help"); + embeddedCalculate.setFont(new java.awt.Font("Arial", Font.PLAIN, 10)); + embeddedCalculate.setText("Calculate"); + embeddedMenu.add(embeddedFile); + embeddedMenu.add(embeddedEdit); + embeddedMenu.add(embeddedSearch); + embeddedMenu.add(embeddedView); + embeddedMenu.add(embeddedColour); + embeddedMenu.add(embeddedCalculate); + embeddedMenu.add(embeddedHelp); + flowLayout1.setAlignment(FlowLayout.LEFT); + flowLayout1.setHgap(2); + flowLayout1.setVgap(0); + embeddedFile.addMouseListener(this); + embeddedEdit.addMouseListener(this); + embeddedSearch.addMouseListener(this); + embeddedView.addMouseListener(this); + embeddedColour.addMouseListener(this); + embeddedCalculate.addMouseListener(this); + embeddedHelp.addMouseListener(this); + + // setVisible(false); + fileMenu.remove(closeMenuItem); + fileMenu.remove(3); // Seperator + + viewport.applet.setLayout(new BorderLayout()); + viewport.applet.add(embeddedMenu, BorderLayout.NORTH); + viewport.applet.add(statusBar, BorderLayout.SOUTH); + // viewport.applet.validate(); + + alignPanel.setSize(viewport.applet.size().width, viewport.applet.size().height + - embeddedMenu.HEIGHT - statusBar.HEIGHT); + + viewport.applet.add(alignPanel, BorderLayout.CENTER); + viewport.applet.validate(); + + } + + + + PopupMenu filePopup, editPopup, searchPopup, + viewPopup, colourPopup, calculatePopup, helpPopup; + MenuItem featureSettings = new MenuItem(); + CheckboxMenuItem sequenceFeatures = new CheckboxMenuItem(); + MenuItem annotationColour = new MenuItem(); + MenuItem invertColSel = new MenuItem(); + Menu menu1 = new Menu(); + MenuItem showColumns = new MenuItem(); + MenuItem showSeqs = new MenuItem(); + Menu menu2 = new Menu(); + MenuItem hideColumns = new MenuItem(); + MenuItem hideSequences = new MenuItem(); + + public void mousePressed(MouseEvent evt) + { + PopupMenu popup = null; + Label source = (Label)evt.getSource(); + if(source==embeddedFile) + { + popup = filePopup = genPopupMenu(filePopup, fileMenu); + } + else if(source==embeddedEdit) + { + popup = editPopup = genPopupMenu(editPopup, editMenu); + } + else if(source==embeddedSearch) + { + popup = searchPopup = genPopupMenu(searchPopup, searchMenu); + } + else if(source==embeddedView) + { + popup = viewPopup = genPopupMenu(viewPopup, viewMenu); + } + else if(source==embeddedColour) + { + popup = colourPopup = genPopupMenu(colourPopup, colourMenu); + } + else if(source==embeddedCalculate) + { + popup = calculatePopup = genPopupMenu(calculatePopup, calculateMenu); + } + else if(source==embeddedHelp) + { + popup = helpPopup = genPopupMenu(helpPopup, helpMenu); + } + + embeddedMenu.add(popup); + popup.show(embeddedMenu, + source.getBounds().x, + source.getBounds().y + source.getBounds().getSize().height); + } + + PopupMenu genPopupMenu(PopupMenu popup, Menu original) + { + if(popup!=null) + { + return popup; + } + popup = new PopupMenu(); + int m, mSize = original.getItemCount(); + for(m=0; m 1) - { - mouseOver = "[" + maxRes + "] "; - maxRes = "+"; - } - - - mouseOver += (int) value + "%"; - annotations[i] = new Annotation(maxRes, mouseOver, ' ', value); - - } - - if (consensus == null) - { - consensus = new AlignmentAnnotation("Consensus", - "PID", annotations, 0f, 100f, AlignmentAnnotation.BAR_GRAPH); - if (showConsensus) - { - alignment.addAnnotation(consensus); - } - } - else - { - consensus.annotations = annotations; - } - - if(globalColourScheme!=null) - globalColourScheme.setConsensus(vconsensus); - - } - - public SequenceGroup getSelectionGroup() - { - return selectionGroup; - } - - public void setSelectionGroup(SequenceGroup sg) - { - selectionGroup = sg; - } - - public boolean getConservationSelected() - { - return conservationColourSelected; - } - - public void setConservationSelected(boolean b) - { - conservationColourSelected = b; - } - - public boolean getAbovePIDThreshold() - { - return abovePIDThreshold; - } - - public void setAbovePIDThreshold(boolean b) - { - abovePIDThreshold = b; - } - - public int getStartRes() - { - return startRes; - } - - public int getEndRes() - { - return endRes; - } - - public int getStartSeq() - { - return startSeq; - } - - public void setGlobalColourScheme(ColourSchemeI cs) - { - globalColourScheme = cs; - } - - public ColourSchemeI getGlobalColourScheme() - { - return globalColourScheme; - } - - public void setStartRes(int res) - { - this.startRes = res; - } - - public void setStartSeq(int seq) - { - this.startSeq = seq; - } - - public void setEndRes(int res) - { - if (res > alignment.getWidth() - 1) - { - // log.System.out.println(" Corrected res from " + res + " to maximum " + (alignment.getWidth()-1)); - res = alignment.getWidth() - 1; - } - if (res < 0) - { - res = 0; - } - this.endRes = res; - } - - public void setEndSeq(int seq) - { - if (seq > alignment.getHeight()) - { - seq = alignment.getHeight(); - } - if (seq < 0) - { - seq = 0; - } - this.endSeq = seq; - } - - public int getEndSeq() - { - return endSeq; - } - - public void setFont(Font f) - { - font = f; - java.awt.Frame temp = new java.awt.Frame(); - temp.addNotify(); - java.awt.FontMetrics fm = temp.getGraphics().getFontMetrics(font); - setCharHeight(fm.getHeight()); - setCharWidth(fm.charWidth('M')); - } - - public Font getFont() - { - return font; - } - - public void setCharWidth(int w) - { - this.charWidth = w; - } - - public int getCharWidth() - { - return charWidth; - } - - public void setCharHeight(int h) - { - this.charHeight = h; - } - - public int getCharHeight() - { - return charHeight; - } - - public void setWrappedWidth(int w) - { - this.wrappedWidth = w; - } - - public int getwrappedWidth() - { - return wrappedWidth; - } - - public AlignmentI getAlignment() - { - return alignment; - } - - public void setAlignment(AlignmentI align) - { - this.alignment = align; - } - - public void setWrapAlignment(boolean state) - { - wrapAlignment = state; - } - - public void setShowText(boolean state) - { - showText = state; - } - - public void setRenderGaps(boolean state) - { - renderGaps = state; - } - - public boolean getColourText() - { - return showColourText; - } - - public void setColourText(boolean state) - { - showColourText = state; - } - - public void setShowBoxes(boolean state) - { - showBoxes = state; - } - - public boolean getWrapAlignment() - { - return wrapAlignment; - } - - public boolean getShowText() - { - return showText; - } - - public boolean getShowBoxes() - { - return showBoxes; - } - - public char getGapCharacter() - { - return getAlignment().getGapCharacter(); - } - - public void setGapCharacter(char gap) - { - if (getAlignment() != null) - { - getAlignment().setGapCharacter(gap); - } - } - - public void setThreshold(int thresh) - { - threshold = thresh; - } - - public int getThreshold() - { - return threshold; - } - - public void setIncrement(int inc) - { - increment = inc; - } - - public int getIncrement() - { - return increment; - } - - public int getIndex(int y) - { - int y1 = 0; - int starty = getStartSeq(); - int endy = getEndSeq(); - - for (int i = starty; i <= endy; i++) - { - if (i < alignment.getHeight() && alignment.getSequenceAt(i) != null) - { - int y2 = y1 + getCharHeight(); - - if (y >= y1 && y <= y2) - { - return i; - } - y1 = y2; - } - else - { - return -1; - } - } - return -1; - } - - public ColumnSelection getColumnSelection() - { - return colSel; - } - - public void resetSeqLimits(int height) - { - setEndSeq(height / getCharHeight()); - } - - public void setCurrentTree(NJTree tree) - { - currentTree = tree; - } - - public NJTree getCurrentTree() - { - return currentTree; - } - - public void setColourAppliesToAllGroups(boolean b) - { - colourAppliesToAllGroups = b; - } - - public boolean getColourAppliesToAllGroups() - { - return colourAppliesToAllGroups; - } - - public boolean getShowJVSuffix() - { - return showJVSuffix; - } - - public void setShowJVSuffix(boolean b) - { - showJVSuffix = b; - } - - public boolean getShowAnnotation() - { - return showAnnotation; - } - - public void setShowAnnotation(boolean b) - { - showAnnotation = b; - } - - public boolean getScaleAboveWrapped() - { - return scaleAboveWrapped; - } - - public boolean getScaleLeftWrapped() - { - return scaleLeftWrapped; - } - - public boolean getScaleRightWrapped() - { - return scaleRightWrapped; - } - - public void setScaleAboveWrapped(boolean b) - { - scaleAboveWrapped = b; - } - - public void setScaleLeftWrapped(boolean b) - { - scaleLeftWrapped = b; - } - - public void setScaleRightWrapped(boolean b) - { - scaleRightWrapped = b; - } - - public void setIgnoreGapsConsensus(boolean b) - { - ignoreGapsInConsensusCalculation = b; - updateConsensus(); - if (globalColourScheme!=null) - { - globalColourScheme.setThreshold(globalColourScheme.getThreshold(), - ignoreGapsInConsensusCalculation); - - } - } - - /** - * Property change listener for changes in alignment - * - * @param listener DOCUMENT ME! - */ - public void addPropertyChangeListener( - java.beans.PropertyChangeListener listener) - { - changeSupport.addPropertyChangeListener(listener); - } - - /** - * DOCUMENT ME! - * - * @param listener DOCUMENT ME! - */ - public void removePropertyChangeListener( - java.beans.PropertyChangeListener listener) - { - changeSupport.removePropertyChangeListener(listener); - } - - /** - * Property change listener for changes in alignment - * - * @param prop DOCUMENT ME! - * @param oldvalue DOCUMENT ME! - * @param newvalue DOCUMENT ME! - */ - public void firePropertyChange(String prop, Object oldvalue, Object newvalue) - { - changeSupport.firePropertyChange(prop, oldvalue, newvalue); - } - - - - public boolean getIgnoreGapsConsensus() - { - return ignoreGapsInConsensusCalculation; - } - - -} +/* + * Jalview - A Sequence Alignment Editor and Viewer + * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +package jalview.appletgui; + +import java.util.*; + +import java.awt.*; + +import jalview.analysis.*; +import jalview.bin.*; +import jalview.datamodel.*; +import jalview.schemes.*; + +public class AlignViewport +{ + int startRes; + int endRes; + + int startSeq; + int endSeq; + + + boolean cursorMode = false; + + boolean showJVSuffix = true; + boolean showText = true; + boolean showColourText = false; + boolean showBoxes = true; + boolean wrapAlignment = false; + boolean renderGaps = true; + boolean showSequenceFeatures = false; + boolean showAnnotation = true; + boolean showConservation = true; + boolean showQuality = true; + boolean showConsensus = true; + + boolean colourAppliesToAllGroups = true; + ColourSchemeI globalColourScheme = null; + boolean conservationColourSelected = false; + boolean abovePIDThreshold = false; + + SequenceGroup selectionGroup; + + int charHeight; + int charWidth; + int wrappedWidth; + + Font font = new Font("SansSerif", Font.PLAIN, 10); + boolean validCharWidth = true; + AlignmentI alignment; + + ColumnSelection colSel = new ColumnSelection(); + + int threshold; + int increment; + + NJTree currentTree = null; + + boolean scaleAboveWrapped = true; + boolean scaleLeftWrapped = true; + boolean scaleRightWrapped = true; + + // The following vector holds the features which are + // currently visible, in the correct order or rendering + Hashtable featuresDisplayed; + + boolean hasHiddenColumns = false; + boolean hasHiddenRows = false; + boolean showHiddenMarkers = true; + + + public Vector vconsensus; + AlignmentAnnotation consensus; + AlignmentAnnotation conservation; + AlignmentAnnotation quality; + + boolean autocalculateConsensus = true; + + public int ConsPercGaps = 25; // JBPNote : This should be a scalable property! + + private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(this); + + boolean ignoreGapsInConsensusCalculation = false; + + jalview.bin.JalviewLite applet; + + boolean MAC = false; + + public AlignViewport(AlignmentI al, JalviewLite applet) + { + this.applet = applet; + setAlignment(al); + this.startRes = 0; + this.endRes = al.getWidth() - 1; + this.startSeq = 0; + this.endSeq = al.getHeight() - 1; + setFont(font); + + if(System.getProperty("os.name").startsWith("Mac")) + MAC = true; + + if (applet != null) + { + String param = applet.getParameter("showFullId"); + if (param != null) + { + showJVSuffix = Boolean.valueOf(param).booleanValue(); + } + + param = applet.getParameter("showAnnotation"); + if (param != null) + { + showAnnotation = Boolean.valueOf(param).booleanValue(); + } + + param = applet.getParameter("showConservation"); + if (param != null) + { + showConservation = Boolean.valueOf(param).booleanValue(); + } + + param = applet.getParameter("showQuality"); + if (param != null) + { + showQuality = Boolean.valueOf(param).booleanValue(); + } + + param = applet.getParameter("showConsensus"); + if (param != null) + { + showConsensus = Boolean.valueOf(param).booleanValue(); + } + } + // We must set conservation and consensus before setting colour, + // as Blosum and Clustal require this to be done + updateConservation(); + updateConsensus(); + + + if (applet != null) + { + String colour = applet.getParameter("defaultColour"); + + if(colour == null) + { + colour = applet.getParameter("userDefinedColour"); + if(colour !=null) + colour = "User Defined"; + } + + if(colour != null) + { + globalColourScheme = ColourSchemeProperty.getColour(alignment, colour); + if (globalColourScheme != null) + { + globalColourScheme.setConsensus(vconsensus); + } + } + + if(applet.getParameter("userDefinedColour")!=null) + { + ((UserColourScheme)globalColourScheme).parseAppletParameter( + applet.getParameter("userDefinedColour")); + } + + + } + } + + public void showSequenceFeatures(boolean b) + { + showSequenceFeatures = b; + } + + public boolean getShowSequenceFeatures() + { + return showSequenceFeatures; + } + + + public void updateConservation() + { + if(alignment.isNucleotide()) + return; + + Conservation cons = new jalview.analysis.Conservation("All", + jalview.schemes.ResidueProperties.propHash, 3, + alignment.getSequences(), 0, + alignment.getWidth() - 1); + cons.calculate(); + cons.verdict(false, ConsPercGaps); + cons.findQuality(); + int alWidth = alignment.getWidth(); + Annotation[] annotations = new Annotation[alWidth]; + Annotation[] qannotations = new Annotation[alWidth]; + String sequence = cons.getConsSequence().getSequence(); + float minR, minG, minB, maxR, maxG, maxB; + minR = 0.3f; + minG = 0.0f; + minB = 0f; + maxR = 1.0f - minR; + maxG = 0.9f - minG; + maxB = 0f - minB; // scalable range for colouring both Conservation and Quality + float min = 0f; + float max = 11f; + float qmin = cons.qualityRange[0].floatValue(); + float qmax = cons.qualityRange[1].floatValue(); + + for (int i = 0; i < alWidth; i++) + { + float value = 0; + try + { + value = Integer.parseInt(sequence.charAt(i) + ""); + } + catch (Exception ex) + { + if (sequence.charAt(i) == '*') + { + value = 11; + } + if (sequence.charAt(i) == '+') + { + value = 10; + } + } + float vprop = value - min; + vprop /= max; + + annotations[i] = new Annotation(sequence.charAt(i) + "", + "", ' ', value, + new Color(minR + maxR * vprop, + minG + maxG * vprop, + minB + maxB * vprop)); + // Quality calc + value = ( (Double) cons.quality.elementAt(i)).floatValue(); + vprop = value - qmin; + vprop /= qmax; + qannotations[i] = new Annotation(" ", + String.valueOf(value), ' ', value, + new + Color(minR + maxR * vprop, + minG + maxG * vprop, + minB + maxB * vprop)); + } + + if (conservation == null) + { + conservation = new AlignmentAnnotation("Conservation", + "Conservation of total alignment less than " + + ConsPercGaps + "% gaps", + annotations, + 0f, // cons.qualityRange[0].floatValue(), + 11f, // cons.qualityRange[1].floatValue() + AlignmentAnnotation.BAR_GRAPH); + if (showConservation) + { + alignment.addAnnotation(conservation); + } + quality = new AlignmentAnnotation("Quality", + "Alignment Quality based on Blosum62 scores", + qannotations, + cons.qualityRange[0].floatValue(), + cons.qualityRange[1].floatValue(), + AlignmentAnnotation.BAR_GRAPH); + if (showQuality) + { + alignment.addAnnotation(quality); + } + } + else + { + conservation.annotations = annotations; + quality.annotations = qannotations; + quality.graphMax = cons.qualityRange[1].floatValue(); + } + + } + + public void updateConsensus() + { + Annotation[] annotations = new Annotation[alignment.getWidth()]; + + // this routine prevents vconsensus becoming a new object each time + // consenus is calculated. Important for speed of Blosum62 + // and PID colouring of alignment + if (vconsensus == null) + { + vconsensus = alignment.getAAFrequency(); + } + else + { + Vector temp = alignment.getAAFrequency(); + vconsensus.removeAllElements(); + Enumeration e = temp.elements(); + while (e.hasMoreElements()) + { + vconsensus.addElement(e.nextElement()); + } + } + Hashtable hash = null; + for (int i = 0; i < alignment.getWidth(); i++) + { + hash = (Hashtable) vconsensus.elementAt(i); + float value = 0; + if(ignoreGapsInConsensusCalculation) + value = ((Float)hash.get("pid_nogaps")).floatValue(); + else + value = ((Float)hash.get("pid_gaps")).floatValue(); + + String maxRes = hash.get("maxResidue").toString(); + String mouseOver = hash.get("maxResidue") + " "; + if (maxRes.length() > 1) + { + mouseOver = "[" + maxRes + "] "; + maxRes = "+"; + } + + + mouseOver += (int) value + "%"; + annotations[i] = new Annotation(maxRes, mouseOver, ' ', value); + + } + + if (consensus == null) + { + consensus = new AlignmentAnnotation("Consensus", + "PID", annotations, 0f, 100f, AlignmentAnnotation.BAR_GRAPH); + if (showConsensus) + { + alignment.addAnnotation(consensus); + } + } + else + { + consensus.annotations = annotations; + } + + if(globalColourScheme!=null) + globalColourScheme.setConsensus(vconsensus); + + } + /** + * get the consensus sequence as displayed under the PID consensus annotation row. + * @return consensus sequence as a new sequence object + */ + /** + * get the consensus sequence as displayed under the PID consensus annotation row. + * @return consensus sequence as a new sequence object + */ + public SequenceI getConsensusSeq() { + if (consensus==null) + updateConsensus(); + if (consensus==null) + return null; + StringBuffer seqs=new StringBuffer(); + for (int i=0; i alignment.getWidth() - 1) + { + // log.System.out.println(" Corrected res from " + res + " to maximum " + (alignment.getWidth()-1)); + res = alignment.getWidth() - 1; + } + if (res < 0) + { + res = 0; + } + this.endRes = res; + } + + public void setEndSeq(int seq) + { + if (seq > alignment.getHeight()) + { + seq = alignment.getHeight(); + } + if (seq < 0) + { + seq = 0; + } + this.endSeq = seq; + } + + public int getEndSeq() + { + return endSeq; + } + + java.awt.Frame nullFrame; + public void setFont(Font f) + { + font = f; + if(nullFrame == null) + { + nullFrame = new java.awt.Frame(); + nullFrame.addNotify(); + } + + java.awt.FontMetrics fm = nullFrame.getGraphics().getFontMetrics(font); + setCharHeight(fm.getHeight()); + charWidth = fm.charWidth('M'); + } + + public Font getFont() + { + return font; + } + + public int getCharWidth() + { + return charWidth; + } + + public void setCharHeight(int h) + { + this.charHeight = h; + } + + public int getCharHeight() + { + return charHeight; + } + + public void setWrappedWidth(int w) + { + this.wrappedWidth = w; + } + + public int getwrappedWidth() + { + return wrappedWidth; + } + + public AlignmentI getAlignment() + { + return alignment; + } + + public void setAlignment(AlignmentI align) + { + this.alignment = align; + } + + public void setWrapAlignment(boolean state) + { + wrapAlignment = state; + } + + public void setShowText(boolean state) + { + showText = state; + } + + public void setRenderGaps(boolean state) + { + renderGaps = state; + } + + public boolean getColourText() + { + return showColourText; + } + + public void setColourText(boolean state) + { + showColourText = state; + } + + public void setShowBoxes(boolean state) + { + showBoxes = state; + } + + public boolean getWrapAlignment() + { + return wrapAlignment; + } + + public boolean getShowText() + { + return showText; + } + + public boolean getShowBoxes() + { + return showBoxes; + } + + public char getGapCharacter() + { + return getAlignment().getGapCharacter(); + } + + public void setGapCharacter(char gap) + { + if (getAlignment() != null) + { + getAlignment().setGapCharacter(gap); + } + } + + public void setThreshold(int thresh) + { + threshold = thresh; + } + + public int getThreshold() + { + return threshold; + } + + public void setIncrement(int inc) + { + increment = inc; + } + + public int getIncrement() + { + return increment; + } + + public void setHiddenColumns(ColumnSelection colsel) + { + this.colSel = colsel; + if(colSel.getHiddenColumns()!=null) + hasHiddenColumns = true; + } + + public ColumnSelection getColumnSelection() + { + return colSel; + } + + public void resetSeqLimits(int height) + { + setEndSeq(height / getCharHeight()); + } + + public void setCurrentTree(NJTree tree) + { + currentTree = tree; + } + + public NJTree getCurrentTree() + { + return currentTree; + } + + public void setColourAppliesToAllGroups(boolean b) + { + colourAppliesToAllGroups = b; + } + + public boolean getColourAppliesToAllGroups() + { + return colourAppliesToAllGroups; + } + + public boolean getShowJVSuffix() + { + return showJVSuffix; + } + + public void setShowJVSuffix(boolean b) + { + showJVSuffix = b; + } + + public boolean getShowAnnotation() + { + return showAnnotation; + } + + public void setShowAnnotation(boolean b) + { + showAnnotation = b; + } + + public boolean getScaleAboveWrapped() + { + return scaleAboveWrapped; + } + + public boolean getScaleLeftWrapped() + { + return scaleLeftWrapped; + } + + public boolean getScaleRightWrapped() + { + return scaleRightWrapped; + } + + public void setScaleAboveWrapped(boolean b) + { + scaleAboveWrapped = b; + } + + public void setScaleLeftWrapped(boolean b) + { + scaleLeftWrapped = b; + } + + public void setScaleRightWrapped(boolean b) + { + scaleRightWrapped = b; + } + + public void setIgnoreGapsConsensus(boolean b) + { + ignoreGapsInConsensusCalculation = b; + updateConsensus(); + if (globalColourScheme!=null) + { + globalColourScheme.setThreshold(globalColourScheme.getThreshold(), + ignoreGapsInConsensusCalculation); + + } + } + + /** + * Property change listener for changes in alignment + * + * @param listener DOCUMENT ME! + */ + public void addPropertyChangeListener( + java.beans.PropertyChangeListener listener) + { + changeSupport.addPropertyChangeListener(listener); + } + + /** + * DOCUMENT ME! + * + * @param listener DOCUMENT ME! + */ + public void removePropertyChangeListener( + java.beans.PropertyChangeListener listener) + { + changeSupport.removePropertyChangeListener(listener); + } + + /** + * Property change listener for changes in alignment + * + * @param prop DOCUMENT ME! + * @param oldvalue DOCUMENT ME! + * @param newvalue DOCUMENT ME! + */ + public void firePropertyChange(String prop, Object oldvalue, Object newvalue) + { + changeSupport.firePropertyChange(prop, oldvalue, newvalue); + } + + + + public boolean getIgnoreGapsConsensus() + { + return ignoreGapsInConsensusCalculation; + } + public void hideSelectedColumns() + { + if (colSel.size() < 1) + return; + + colSel.hideSelectedColumns(); + setSelectionGroup(null); + + hasHiddenColumns = true; + } + + public void invertColumnSelection() + { + int column; + for (int i = 0; i < alignment.getWidth(); i++) + { + column = i; + + if (colSel.contains(column)) + colSel.removeElement(column); + else + colSel.addElement(column); + + } + } + + + public void hideColumns(int start, int end) + { + if(start==end) + colSel.hideColumns(start); + else + colSel.hideColumns(start, end); + + hasHiddenColumns = true; + } + + public void hideSequence(SequenceI seq) + { + if(seq!=null) + { + alignment.getHiddenSequences().hideSequence(seq); + hasHiddenRows = true; + firePropertyChange("alignment", null, alignment.getSequences()); + } + } + + public void hideAllSelectedSeqs() + { + if (selectionGroup == null) + return; + + SequenceI[] seqs = selectionGroup.getSequencesInOrder(alignment); + + for (int i = 0; i < seqs.length; i++) + { + alignment.getHiddenSequences().hideSequence(seqs[i]); + } + firePropertyChange("alignment", null, alignment.getSequences()); + hasHiddenRows = true; + setSelectionGroup(null); + } + + public void showColumn(int col) + { + colSel.revealHiddenColumns(col); + if(colSel.getHiddenColumns()==null) + hasHiddenColumns = false; + } + + public void showAllHiddenColumns() + { + colSel.revealAllHiddenColumns(); + hasHiddenColumns = false; + } + + public void showAllHiddenSeqs() + { + if(alignment.getHiddenSequences().getSize()>0) + { + if(selectionGroup==null) + { + selectionGroup = new SequenceGroup(); + selectionGroup.setEndRes(alignment.getWidth()-1); + } + Vector tmp = alignment.getHiddenSequences().showAll(); + for(int t=0; t