From: amwaterhouse Date: Tue, 2 Nov 2004 10:46:54 +0000 (+0000) Subject: Jalview Imported Sources X-Git-Tag: start X-Git-Url: http://source.jalview.org/gitweb/?a=commitdiff_plain;h=1ecf6419aba86993b3c223bf5ec0fa79427baf85;p=jalview.git Jalview Imported Sources --- 1ecf6419aba86993b3c223bf5ec0fa79427baf85 diff --git a/BartonGroupBanner.gif b/BartonGroupBanner.gif new file mode 100755 index 0000000..6b0b6e2 Binary files /dev/null and b/BartonGroupBanner.gif differ diff --git a/JalviewX.jpx b/JalviewX.jpx new file mode 100755 index 0000000..4179212 --- /dev/null +++ b/JalviewX.jpx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/jalview/analysis/AAFrequency.java b/src/jalview/analysis/AAFrequency.java new file mode 100755 index 0000000..c8e6388 --- /dev/null +++ b/src/jalview/analysis/AAFrequency.java @@ -0,0 +1,383 @@ +package jalview.analysis; + +import jalview.jbgui.*; +import jalview.datamodel.*; +import jalview.io.*; +import jalview.analysis.*; + +import java.awt.*; +import java.applet.Applet; +import java.util.*; +import java.net.*; +import java.io.*; + +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 Vector calculate(Vector sequences,int start,int end) { + + Vector result = new Vector(); + + for (int i = start;i <= end; i++) + { + + Hashtable residueHash = new Hashtable(); + int maxCount = -1; + String maxResidue = "-"; + int nongap = 0; + for (int j=0; j < sequences.size(); j++) + { + + if (sequences.elementAt(j) instanceof Sequence) + { + Sequence s = (Sequence)sequences.elementAt(j); + + if (s.getSequence().length() > i) + { + + String res = s.getSequence().substring(i,i+1); + + if (!res.equals("-")) + nongap++; + + if (residueHash.containsKey(res)) + { + + int count = ((Integer)residueHash.get(res)).intValue() ; + count++; + + if (!res.equals("-") && 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("-")) + { + int 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); + residueHash.put("size", new Integer(sequences.size())); + residueHash.put("nongap", new Integer(nongap)); + result.addElement(residueHash); + } + + return result; + } + + public static Vector calculatePID(SequenceI refseq,Vector sequences,int window,int start,int end) { + + Vector result = new Vector(); + + boolean init = true; + + + Vector prev = null; + + for (int i = start;i <= end; i++) { + Vector values = new Vector(); + + result.addElement(values); + + // If start < window/2 then set value to zero. + + if (i< window/2 || i >= refseq.getSequence().length()-window/2) { + for (int j = 0; j < sequences.size(); j++) { + values.addElement(new Integer(0)); + } + } else if (init == true) { + init = false; + + int winstart = i-window/2; + int winend = i+window/2; + + if (window%2 != 0) { + winend++; + } + + for (int j = 0; j < sequences.size(); j++) { + values.addElement(new Integer(0)); + } + + for (int k = winstart; k <= winend; k++) { + String refchar = refseq.getSequence().substring(k,k+1); + + for (int j = 0; j < sequences.size(); j++) { + + if (refchar.equals("-") == false) { + + Sequence s = (Sequence)sequences.elementAt(j); + + if (s.getSequence().length() > k) { + + String res = s.getSequence().substring(k,k+1); + + if (res.equals(refchar)) { + int val = ((Integer)values.elementAt(j)).intValue(); + val++; + values.setElementAt(new Integer(val),j); + } + } + } + } + } + prev = values; + } else { + int winstart = i-window/2; + int winend = i+window/2; + + if (window%2 != 0) { + winend++; + } + // We need to take the previous set of values + // subtract the pid at winstart-1 + // and add the pid at winend; + + String pre_refchar = refseq.getSequence().substring(winstart-1,winstart); + String pos_refchar = "-"; + + if (refseq.getSequence().length() > winend) { + pos_refchar = refseq.getSequence().substring(winend,winend+1); + } + + for (int j = 0; j < sequences.size(); j++) { + // First copy the pid value from i-1 + + int val = ((Integer)prev.elementAt(j)).intValue(); + + Sequence s = (Sequence)sequences.elementAt(j); + + String pre_char = s.getSequence().substring(winstart-1,winstart); + + String pos_char = "-"; + + if (s.getSequence().length() > winend) { + pos_char = s.getSequence().substring(winend,winend+1); + } + + // Now substract 1 if the chars at winstart-1 match + + if (pre_refchar.equals("-") == false && pre_char.equals(pre_refchar)) { + val--; + } + + if (pos_refchar.equals("-") == false && pos_char.equals(pos_refchar)) { + val++; + } + + values.addElement(new Integer(val)); + + + } + prev = values; + } + } + + return result; + } + + public static Hashtable findBlocks(Vector seqs, int start, int end,Vector exc) { + + // start and end are in real (not relative coords); + + // The coords in the hashtable that is returned are in relative coords + // i.e. start from 0 + + Hashtable blocks = new Hashtable(); + + boolean prev = false; + int bstart = -1; + + for (int i = start; i <= end ; i++) { + SequenceI seq = (SequenceI)seqs.elementAt(0); + + char c = seq.getCharAt(i); + + boolean found = true; + + int j = 1; + + while (j < seqs.size() && found == true) { + + SequenceI jseq = (SequenceI)seqs.elementAt(j); + + if (!exc.contains(jseq)) { + + char cc = jseq.getCharAt(i); + + if ( cc != c) { + found = false; + } + } + j++; + } + + + if (prev == false && found == true) { + bstart = i; + } else if (prev == true && found == false && bstart != -1) { + + int blockstart = bstart-start; + int blocklen = i-bstart; + + //System.out.println("Start len " + blockstart + " " + blocklen); + + for (int jj = blockstart; jj < blockstart + blocklen;jj++) { + blocks.put(new Integer(jj),new Integer(blocklen)); + } + + bstart = -1; + } + prev = found; + } + + if (bstart != -1) { + + int blockstart = bstart-start; + int blocklen = end-bstart; + + // System.out.println("Start len " + blockstart + " " + blocklen); + + for (int jj = blockstart; jj < blockstart + blocklen;jj++) { + blocks.put(new Integer(blockstart),new Integer(blocklen)); + } + + } + return blocks; + } + + + + public static Hashtable findKmerCount(SequenceI seq, int start, int end,int window, int step,Vector kmers) { + + int tmpstart = start; + Hashtable vals = new Hashtable(); + + while (tmpstart <= end) { + + String tmpstr = seq.getSequence().substring(tmpstart-window/2,tmpstart+window/2); + + int count = 0; + + //System.out.println("Str " + tmpstr); + + for (int ii = 0; ii < kmers.size(); ii++) { + String kmer = ((SequenceI)kmers.elementAt(ii)).getSequence(); + + int i = -1; + + while (tmpstr.indexOf(kmer,i) != -1) { + i = tmpstr.indexOf(kmer,i); + + i++; + count++; + } + ii++; + } + vals.put(new Integer(tmpstart),new Integer(count)); + tmpstart += step; + } + return vals; + } + + public static Hashtable findBlockStarts(Vector seqs, int start, int end,Vector exc) { + + // start and end are in real (not relative coords); + + // The coords in the hashtable that is returned are in relative coords + // i.e. start from 0 + + Hashtable blocks = new Hashtable(); + + boolean prev = false; + int bstart = -1; + + for (int i = start; i <= end ; i++) { + SequenceI seq = (SequenceI)seqs.elementAt(0); + + char c = seq.getCharAt(i); + + boolean found = true; + + int j = 1; + + while (j < seqs.size() && found == true) { + + SequenceI jseq = (SequenceI)seqs.elementAt(j); + + if (!exc.contains(jseq)) { + + char cc = jseq.getCharAt(i); + + if ( cc != c) { + found = false; + } + } + j++; + } + + + if (prev == false && found == true) { + bstart = i; + } else if (prev == true && found == false && bstart != -1) { + + int blockstart = bstart-start; + int blocklen = i-bstart; + + // System.out.println("Start len " + blockstart + " " + blocklen); + + //for (int jj = blockstart; jj < blockstart + blocklen;jj++) { + blocks.put(new Integer(blockstart),new Integer(blocklen)); + // } + + bstart = -1; + } + prev = found; + } + + if (bstart != -1) { + + int blockstart = bstart-start; + int blocklen = end-bstart; + + // System.out.println("Start len " + blockstart + " " + blocklen); + + //for (int jj = blockstart; jj < blockstart + blocklen;jj++) { + blocks.put(new Integer(blockstart),new Integer(blocklen)); + // } + + } + return blocks; + } + +} + diff --git a/src/jalview/analysis/AlignSeq.java b/src/jalview/analysis/AlignSeq.java new file mode 100755 index 0000000..81874e0 --- /dev/null +++ b/src/jalview/analysis/AlignSeq.java @@ -0,0 +1,541 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +package jalview.analysis; + +import jalview.schemes.*; +import jalview.datamodel.SequenceI; +import jalview.util.*; +import jalview.io.*; + +import java.util.*; +import java.io.*; +import java.awt.*; + +public class AlignSeq { + + 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; + + String astr1 = ""; + String astr2 = ""; + + int seq1start; + int seq1end; + int seq2start; + int seq2end; + + int count; + + int maxscore; + float pid; + int prev = 0; + + 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 gapOpen = 120; + int gapExtend = 20; + + int lookup[][] = ResidueProperties.getBLOSUM62(); + String intToStr[] = pep; + int defInt = 23; + + String output = ""; + + String type; + Runtime rt; + public AlignSeq() {} + + public AlignSeq(SequenceI s1, SequenceI s2,String type) { + rt = Runtime.getRuntime(); + SeqInit(s1,s2,type); + } + + public int getMaxScore() { + return maxscore; + } + + public int getSeq2Start() { + return seq2start; + } + + public int getSeq2End() { + return seq2end; + } + + public int getSeq1Start() { + return seq1start; + } + + public int getSeq1End() { + return seq1end; + } + + public String getOutput() { + return output; + } + + public String getAStr1() { + return astr1; + } + public String getAStr2() { + return astr2; + } + public int [] getASeq1() { + return aseq1; + } + public int [] getASeq2() { + return aseq2; + } + public SequenceI getS1() { + return s1; + } + public SequenceI getS2() { + return s2; + } + + public void SeqInit(SequenceI s1, SequenceI s2,String type) { + s1str = extractGaps(".",s1.getSequence()); + s2str = extractGaps(".",s2.getSequence()); + s1str = extractGaps("-",s1str); + s2str = extractGaps("-",s2str); + s1str = extractGaps(" ",s1str); + s2str = extractGaps(" ",s2str); + + 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 = output + ("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"); + } + + 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; + } + } + + public void printAlignment() { + // 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; + int overlap = 0; + + output = output + ("Score = " + score[maxi][maxj] + "\n"); + output = output + ("Length of alignment = " + (aseq1.length-count) + "\n"); + output = output + ("Sequence "); + output = output + (new Format("%" + maxid + "s").form(s1.getName())); + output = output + (" : " + seq1start + " - " + seq1end + " (Sequence length = " + s1str.length() + ")\n"); + output = output + ("Sequence "); + output = output + (new Format("%" + maxid + "s").form(s2.getName())); + output = output + (" : " + seq2start + " - " + seq2end + " (Sequence length = " + s2str.length() + ")\n\n"); + + for (int j = 0; j < nochunks; j++) { + // Print the first aligned sequence + output = output + (new Format("%" + (maxid) + "s").form(s1.getName()) + " "); + for (int i = 0; i < len ; i++) { + + if ((count + i + j*len) < aseq1.length) { + output = output + (new Format("%s").form(intToStr[aseq1[count + i + j*len]])); + } + } + + output = output + ("\n"); + output = output + (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 = output + ("|"); + } else if (type.equals("pep")) { + if (ResidueProperties.getPAM250(intToStr[aseq1[count+i+j*len]],intToStr[aseq2[count+i+j*len]]) > 0) { + output = output + ("."); + } else { + output = output + (" "); + } + } else { + output = output + (" "); + } + + } + } + // Now print the second aligned sequence + output = output + ("\n"); + output = output + (new Format("%" + (maxid) + "s").form(s2.getName()) + " " ); + for (int i = 0; i < len ; i++) { + if ((count + i + j*len) < aseq1.length) { + output = output + (new Format("%s").form(intToStr[aseq2[count + i + j*len]])); + } + } + output = output + ("\n\n"); + } + pid = pid/(float)(aseq1.length-count)*100; + output = output + (new Format("Percentage ID = %2.2f\n\n").form(pid)); + + } + + 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(); + } + } + + 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; + } + + 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); + } + } + + } + public static String extractChars(String chars, String seq) { + String out = seq; + for (int i=0; i < chars.length(); i++) { + String gap = chars.substring(i,i+1); + out = extractGaps(gap,out); + } + return out; + } + public static String extractGaps(String gapChar, String seq) { + StringTokenizer str = new StringTokenizer(seq,gapChar); + String newString = ""; + + while (str.hasMoreTokens()) { + newString = newString + str.nextToken(); + } + return newString; + } + + + public int max(int i1, int i2, int i3) { + int max = i1; + if (i2 > i1) { + max = i2; + } + if (i3 > max) { + max = i3; + } + return max; + } + + public int max(int i1, int i2) { + int max = i1; + if (i2 > i1) { + max = i2; + } + return max; + } + + 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; + } + + 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 new file mode 100755 index 0000000..3881266 --- /dev/null +++ b/src/jalview/analysis/AlignmentSorter.java @@ -0,0 +1,181 @@ +package jalview.analysis; + +import jalview.datamodel.*; +import jalview.util.*; +import jalview.io.*; + +import java.util.*; + +/** Data structure to hold and manipulate a multiple sequence alignment + */ +public class AlignmentSorter { + + private AlignmentSorter() { + } + + public static void sortGroups(AlignmentI align) { + Vector groups = align.getGroups(); + int nGroup = groups.size(); + + float[] arr = new float [nGroup]; + Object[] s = new Object[nGroup]; + + for (int i=0; i < nGroup; i++) { + arr[i] = ((SequenceGroup)groups.elementAt(i)).getSize(); + s[i] = groups.elementAt(i); + } + + QuickSort.sort(arr,s); + + Vector newg = new Vector(nGroup); + + for (int i=nGroup-1; i >= 0; i--) { + newg.addElement(s[i]); + } + + // align.setGroups(newg); + } + + /** */ + 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.compare(align.getSequenceAt(i),s); + seqs[i] = align.getSequenceAt(i); + } + + QuickSort.sort(scores,0,scores.length-1,seqs); + + setReverseOrder(align,seqs); + } + + 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); + } + } + + private static void setOrder(AlignmentI align, Vector tmp) { + setOrder(align,vectorToArray(tmp)); + } + + private static void setOrder(AlignmentI align, SequenceI [] seqs) { +// NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work + for (int i = 0; i < seqs.length; i++) { + align.getSequences().setElementAt(seqs[i],i); + } + } + + /** */ + 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); + + setReverseOrder(align,seqs); + } + + public static void sortByGroup(AlignmentI align) { + int nSeq = align.getHeight(); + Vector groups = align.getGroups(); + + Vector seqs = new Vector(); + + for (int i=0; i < groups.size(); i++) { + SequenceGroup sg = (SequenceGroup)groups.elementAt(i); + + for (int j = 0; j < sg.getSize(); j++) { + seqs.addElement(sg.getSequenceAt(j)); + } + } + + if (seqs.size() != nSeq) { + System.err.println("ERROR: tmp.size() != nseq in sortByGroups"); + if (seqs.size() < nSeq) { + addStrays(align,seqs); + } + } + + setOrder(align,seqs); + } + + 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; + } + + public static void sortByTree(AlignmentI align, NJTree tree) { + int nSeq = align.getHeight(); + + Vector tmp = new Vector(); + + tmp = _sortByTree(tree.getTopNode(),tmp); + + if (tmp.size() != nSeq) { + System.err.println("ERROR: tmp.size() != nseq in sortByTree"); + if (tmp.size() < nSeq) { + addStrays(align,tmp); + } + } + + setOrder(align,tmp); + } + + private static void addStrays(AlignmentI align, Vector seqs) { + int nSeq = align.getHeight(); + for (int i=0;i= 0 && + seqint[k][i] >= 0) { + counts[seqint[k][i]][seqint[j][i]]++; + + // print_matrix(counts,4,4); + tots[seqint[j][i]]++; + tot++; + } + if (seqint[j][i] != -1) { + fulltots[seqint[j][i]]++; + fulltot++; + } + } + } + + if (k != j) { + + System.out.println(); + + System.out.println("Sequence " + align.getSequenceAt(j).getName() + " " + align.getSequenceAt(k).getName()); + + System.out.println(); + print_matrix(counts,4,4); + System.out.println(); + + + + double[][] out = new double[4][4];// = constant_multiply_matrix(counts,1.0/tot,4,4); + + for (int i = 0; i < 4; i++) { + for (int jj = 0; jj < 4; jj++) { + out[i][jj] = (double)counts[i][jj]/tots[jj]; + } + } + + print_matrix(out,4,4); + System.out.println(); + + + System.out.print("RATES\t"); + System.out.print(align.getSequenceAt(j).getName() + "\t" + align.getSequenceAt(k).getName() + "\t"); + + for (int i = 0; i < 4; i++) { + for (int jj = 0; jj < 4; jj++) { + Format.print(System.out,"%4.3f\t",out[i][jj]); + } + } + System.out.println(); + + for (int i = 0; i < 4; i++) { + Format.print(System.out,"%4.3f\t",(double)fulltots[i]*1.0/fulltot); + } + + System.out.println(); + System.out.print("\nGC "); + + Format.print(System.out,"%4.3f\t",(double)(100*fulltots[1]+fulltots[3])/fulltot); + + System.out.print((fulltots[1]+fulltots[3]) + "\t" + fulltot); + + + System.out.println(); + + rates.addElement(out); + } + + } + } + return rates; + } + + public static double[][] constant_multiply_matrix(int[][] matrix, double c,int n, int m) { + double[][] out = new double[n][m]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + + out[i][j] = matrix[i][j]*c; + } + } + return out; + } + + + public static void print_matrix(int[][] matrix, int n, int m) { + + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + + System.out.print(matrix[i][j] + "\t"); + } + System.out.println(); + } + } + public static void print_matrix(double[][] matrix, int n, int m) { + + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + + Format.print(System.out,"%4.3f\t",matrix[i][j]); + + } + System.out.println(); + } + } + + public static Hashtable findKmers(SequenceI seq, int start, int end, Vector kmers) { + + Hashtable pos = new Hashtable(); + + for (int j = 0; j < kmers.size(); j++) { + + String kmer = ((Sequence)kmers.elementAt(j)).getSequence(); + Sequence kmerseq = (Sequence)kmers.elementAt(j); + + if (end < seq.getLength()) { + + String str = seq.getSequence(start,end); + + int i = 0; + + while (str.indexOf(kmer,i) != -1) { + + // System.out.println("STring " + str + " " + i); + int coord = str.indexOf(kmer,i); + + pos.put(new Integer(coord),new Integer(kmerseq.getLength())); + + i = coord + 1; + + } + } + } + return pos; + } + +} diff --git a/src/jalview/analysis/CompareAlignments.java b/src/jalview/analysis/CompareAlignments.java new file mode 100755 index 0000000..3cb8144 --- /dev/null +++ b/src/jalview/analysis/CompareAlignments.java @@ -0,0 +1,166 @@ +package jalview.analysis; + +import jalview.datamodel.*; +import jalview.io.*; + +import java.util.*; + +public class CompareAlignments { + + Vector align; + String refId; + Vector ids; + + public CompareAlignments(Vector align) { + + this.align = align; + + ids = new Vector(); + + Alignment al0 = (Alignment)align.elementAt(0); + + for (int i = 0; i < al0.getHeight(); i++) { + SequenceI seq = al0.getSequenceAt(i); + + ids.addElement(seq.getName()); + + if (i == 0) { + setReferenceId(seq.getName()); + } + } + + } + + public void compare() { + + Hashtable positions = new Hashtable(); + + for (int k = 0; k < ids.size(); k++) { + + String id = (String)ids.elementAt(k); + + System.out.println("Ids " + id + " " + refId); + + if (!id.equals(refId)) { + + Hashtable fullhash = new Hashtable(); + + for (int i = 0; i < align.size(); i++) { + System.out.println("Alignment " + i); + + Alignment al = (Alignment)align.elementAt(i); + + SequenceI refseq = null; + + for (int j = 0; j < al.getHeight(); j++) { + if (((SequenceI)al.getSequenceAt(j)).getName().equals(refId)) { + refseq = (SequenceI)al.getSequenceAt(j); + } + } + + if (refseq != null) { + + System.out.println("Refseq " + refseq.getName()); + + for (int jj = 0; jj < al.getHeight(); jj++) { + SequenceI seq = (SequenceI)al.getSequenceAt(jj); + + if (seq.getName().equals(id)) { + Hashtable hash = getAlignPositions(seq,refseq); + + Enumeration keys = hash.keys(); + + while (keys.hasMoreElements()) { + Integer key = (Integer)keys.nextElement(); + // System.out.println(key + " " + hash.get(key)); + if (fullhash.get(key) == null) { + fullhash.put(key,new Vector()); + } + + Vector tmp = (Vector)fullhash.get(key); + + tmp.addElement(hash.get(key)); + } + } + + } + } + } + + System.out.println ("\nId " + id); + + Enumeration keys = fullhash.keys(); + + + int totdiff = 0; + while (keys.hasMoreElements()) { + Integer key = (Integer)keys.nextElement(); + + Vector tmp = (Vector)fullhash.get(key); + + + + int diff0 = ((Integer)tmp.elementAt(0)).intValue();; + int diff = 0; + + for (int l = 1; l < tmp.size(); l++) { + diff += Math.abs(diff0 - ((Integer)tmp.elementAt(l)).intValue()); + + } + + if (diff > 0) { + totdiff++; + System.out.print(id + " Ref pos " + key + " : " + diff0 + " " + diff + " : "); + + for (int l = 1; l < tmp.size(); l++) { + System.out.print(diff0 - ((Integer)tmp.elementAt(l)).intValue() + " "); + } + System.out.println(); + } + } + + System.out.println("Total " + id + " " + totdiff); + + } + } + } + + + public void setReferenceId(String id) { + this.refId = id; + } + + public Hashtable getAlignPositions(SequenceI seq1, SequenceI seq2) { + + Hashtable hash = new Hashtable(); + + int i = 0; + + int pos1 = 0; + int pos2 = 0; + + while (i < seq1.getLength()) { + + char c1 = seq1.getCharAt(i); + char c2 = seq2.getCharAt(i); + + if (c1 != '-') { + pos1++; + } + + if (c2 != '-') { + pos2++; + } + + if (c1 != '-') { + hash.put(new Integer(pos1),new Integer(pos2)); + } + + i++; + } + return hash; + } + + + +} diff --git a/src/jalview/analysis/Conservation.java b/src/jalview/analysis/Conservation.java new file mode 100755 index 0000000..db572ac --- /dev/null +++ b/src/jalview/analysis/Conservation.java @@ -0,0 +1,185 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +package jalview.analysis; + + +import java.util.*; +import jalview.gui.*; +import jalview.datamodel.*; + + +public class Conservation { + Vector sequences; + int start; + int end; + + Vector total = new Vector(); + + String consString = ""; + + DrawableSequence consSequence; + Hashtable propHash; + int threshold; + Hashtable[] freqs; + + String name = ""; + + public Conservation(String name,Hashtable[] freqs,Hashtable propHash, int threshold, Vector sequences, int start, int end) { + this.name = name; + this.freqs = freqs; + this.propHash = propHash; + this.threshold = threshold; + this.sequences = sequences; + this.start = start; + this.end = end; + } + + + public void calculate() { + + for (int i = start;i <= end; i++) { + Hashtable resultHash = null; + Hashtable residueHash = null; + + resultHash = new Hashtable(); + residueHash = new Hashtable(); + + for (int j=0; j < sequences.size(); j++) { + + if (sequences.elementAt(j) instanceof Sequence) { + Sequence s = (Sequence)sequences.elementAt(j); + + if (s.getSequence().length() > i) { + String res = s.getSequence().substring(i,i+1); + + if (residueHash.containsKey(res)) { + int count = ((Integer)residueHash.get(res)).intValue() ; + count++; + residueHash.put(res,new Integer(count)); + } else { + residueHash.put(res,new Integer(1)); + } + } else { + if (residueHash.containsKey("-")) { + int 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() + int thresh = threshold*(sequences.size())/100; + + //loop over all the found residues + Enumeration e = residueHash.keys(); + + while (e.hasMoreElements()) { + + String res = (String)e.nextElement(); + if (((Integer)residueHash.get(res)).intValue() > thresh) { + + //Now loop over the properties + Enumeration e2 = propHash.keys(); + + while (e2.hasMoreElements()) { + String type = (String)e2.nextElement(); + Hashtable 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); + } + } + + public int countGaps(int j) { + int count = 0; + + for (int i = 0; i < sequences.size();i++) { + String tmp = ((Sequence)sequences.elementAt(i)).getSequence().substring(j,j+1); + if (tmp.equals(" ") || tmp.equals(".") || tmp.equals("-")) { + count++; + } + } + return count; + } + + public void verdict(boolean consflag, float percentageGaps) { + String consString = ""; + + for (int i=start; i <= end; i++) { + int totGaps = countGaps(i); + float pgaps = (float)totGaps*100/(float)sequences.size(); + + if (percentageGaps > pgaps) { + Hashtable resultHash = (Hashtable)total.elementAt(i); + + //Now find the verdict + int count = 0; + Enumeration e3 = resultHash.keys(); + + while (e3.hasMoreElements()) { + String type = (String)e3.nextElement(); + Integer 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 = consString + String.valueOf(count); + } else { + consString = consString + "*"; + } + } else { + consString = consString + "-"; + } + } + + consSequence = new DrawableSequence(name,consString,start,end); + + } + + public jalview.gui.DrawableSequence getConsSequence() { + return consSequence; + } + +} diff --git a/src/jalview/analysis/NJTree.java b/src/jalview/analysis/NJTree.java new file mode 100755 index 0000000..4aeee3d --- /dev/null +++ b/src/jalview/analysis/NJTree.java @@ -0,0 +1,667 @@ +package jalview.analysis; + +import jalview.datamodel.*; +import jalview.util.*; +import jalview.schemes.ResidueProperties; +import java.util.*; + +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; + + public NJTree(SequenceNode node) { + top = node; + maxheight = findHeight(top); + } + + public NJTree(SequenceI[] sequence,int start, int end) { + this(sequence,"NJ","BL",start,end); + } + + 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(); + + } + + + public void cluster() { + + while (noClus > 2) { + if (type.equals("NJ")) { + float mind = findMinNJDistance(); + } else { + float mind = 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; + } + } + } + + Cluster c = joinClusters(one,two); + top = (SequenceNode)(node.elementAt(one)); + + reCount(top); + findHeight(top); + findMaxDist(top); + + } + + 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; + } + + public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj, float dist) { + + float ih = 0; + float jh = 0; + + SequenceNode sni = tmpi; + SequenceNode snj = tmpj; + + 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; + } + } + + 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); + } + + + + 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]; + } + } + + public void findClusterNJDistance(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] + 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]; + } + } + + 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; + } + + 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; + } + + 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; + } + + 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.compare(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=0; k < sequence[i].getLength(); k++) { + try{ + score += + ResidueProperties.getBLOSUM62(sequence[i].getSequence(k, + k + 1), + sequence[j].getSequence(k, + k + 1)); + }catch(Exception ex){System.out.println("err creating BLOSUM62 tree");} + } + 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(); + 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; + } + + 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); + } + } + + 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; + } + + public Object findLeaf(SequenceNode node, int count) { + found = _findLeaf(node,count); + + return found; + } + 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; + } + + 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()); + } + } + 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()); + } + } + public Vector getGroups() { + return groups; + } + public float getMaxHeight() { + return maxheight; + } + 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); + } + } + + 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; + } + 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; + } + 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); + } + + public void reCount(SequenceNode node) { + ycount = 0; + _reCount(node); + } + 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++; + } + + } + public void swapNodes(SequenceNode node) { + if (node == null) { + return; + } + SequenceNode tmp = (SequenceNode)node.left(); + + node.setLeft(node.right()); + node.setRight(tmp); + } + 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()); + } + } + } + } + public void setMaxDist(SequenceNode node) { + this.maxdist = maxdist; + } + public SequenceNode getMaxDist() { + return maxdist; + } + public SequenceNode getTopNode() { + return top; + } + +} + + + +class Cluster { + + int[] value; + + public Cluster(int[] value) { + this.value = value; + } + +} + diff --git a/src/jalview/analysis/PCA.java b/src/jalview/analysis/PCA.java new file mode 100755 index 0000000..c14a1b8 --- /dev/null +++ b/src/jalview/analysis/PCA.java @@ -0,0 +1,189 @@ +package jalview.analysis; + +import jalview.math.*; +import jalview.datamodel.*; +import jalview.util.*; + +import java.awt.*; +import java.io.*; + +public class PCA implements Runnable { + Matrix m; + Matrix symm; + Matrix m2; + + double[] eigenvalue; + Matrix eigenvector; + + public PCA(Matrix m) { + this.m = m; + } + + public PCA(SequenceI[] s) { + Runtime rt = Runtime.getRuntime(); + + BinarySequence[] bs = new BinarySequence[s.length]; + int ii = 0; + while (ii < s.length && s[ii] != null) { + + bs[ii] = new BinarySequence(s[ii]); + bs[ii].encode(); + ii++; + } + + BinarySequence[] bs2 = new BinarySequence[s.length]; + ii = 0; + while (ii < s.length && s[ii] != null) { + + bs2[ii] = new BinarySequence(s[ii]); + bs2[ii].blosumEncode(); + ii++; + } + + + //System.out.println("Created binary encoding"); + //printMemory(rt); + + int count=0; + while (count < bs.length && bs[count] != null) { + count++; + } + double[][] seqmat = new double[count][bs[0].getDBinary().length]; + double[][] seqmat2 = new double[count][bs2[0].getDBinary().length]; + int i=0; + while (i < count) { + seqmat[i] = bs[i].getDBinary(); + seqmat2[i] = bs2[i].getDBinary(); + i++; + } + //System.out.println("Created array"); + //printMemory(rt); + // System.out.println(" --- Original matrix ---- "); + m = new Matrix(seqmat,count,bs[0].getDBinary().length); + m2 = new Matrix(seqmat2,count,bs2[0].getDBinary().length); + + //System.out.println("Created matrix"); + printMemory(rt); + } + + public static void printMemory(Runtime rt) { + System.out.println("Free memory = " + rt.freeMemory()); + } + + public Matrix getM() { + return m; + } + + public double[] getEigenvector(int i) { + return eigenvector.getColumn(i); + } + + public double getEigenvalue(int i) { + return eigenvector.d[i]; + } + public float[][] getComponents(int l, int n, int mm) { + return getComponents(l,n,mm,1); + } + public float[][] getComponents(int l, int n, int mm, float factor) { + float[][] out = new float[m.rows][3]; + + for (int i = 0; i < m.rows;i++) { + out[i][0] = (float)component(i,l)*factor; + out[i][1] = (float)component(i,n)*factor; + out[i][2] = (float)component(i,mm)*factor; + } + return out; + } + + public double[] component(int n) { + // n = index of eigenvector + double[] out = new double[m.rows]; + + for (int i=0; i < m.rows; i++) { + out[i] = component(i,n); + } + return out; + } + public double component(int row, int n) { + double out = 0.0; + + for (int i = 0; i < symm.cols; i++) { + out += symm.value[row][i] * eigenvector.value[i][n]; + } + return out/eigenvector.d[n]; + } + + public void checkEigenvector(int n,PrintStream ps) { + ps.println(" --- Eigenvector " + n + " --- "); + + double[] eigenv = eigenvector.getColumn(n); + + for (int i=0; i < eigenv.length;i++) { + Format.print(ps,"%15.4f",eigenv[i]); + } + + System.out.println(); + + double[] neigenv = symm.vectorPostMultiply(eigenv); + System.out.println(" --- symmat * eigenv / lambda --- "); + if (eigenvector.d[n] > 1e-4) { + for (int i=0; i < neigenv.length;i++) { + Format.print(System.out,"%15.4f",neigenv[i]/eigenvector.d[n]); + } + } + System.out.println(); + } + + public void run() { + Matrix mt = m.transpose(); + // System.out.println(" --- OrigT * Orig ---- "); + eigenvector = mt.preMultiply(m2); + // eigenvector.print(System.out); + symm = eigenvector.copy(); + + //TextArea ta = new TextArea(25,72); + //TextAreaPrintStream taps = new TextAreaPrintStream(System.out,ta); + //Frame f = new Frame("PCA output"); + //f.resize(500,500); + //f.setLayout(new BorderLayout()); + //f.add("Center",ta); + //f.show(); + //symm.print(taps); + long tstart = System.currentTimeMillis(); + eigenvector.tred(); + long tend = System.currentTimeMillis(); + //taps.println("Time take for tred = " + (tend-tstart) + "ms"); + //taps.println(" ---Tridiag transform matrix ---"); + + //taps.println(" --- D vector ---"); + //eigenvector.printD(taps); + //taps.println(); + //taps.println(" --- E vector ---"); + // eigenvector.printE(taps); + //taps.println(); + + // Now produce the diagonalization matrix + tstart = System.currentTimeMillis(); + eigenvector.tqli(); + tend = System.currentTimeMillis(); + //System.out.println("Time take for tqli = " + (tend-tstart) + " ms"); + + //System.out.println(" --- New diagonalization matrix ---"); + + //System.out.println(" --- Eigenvalues ---"); + //eigenvector.printD(taps); + + //System.out.println(); + + // for (int i=0; i < eigenvector.cols; i++) { + // checkEigenvector(i,taps); + // taps.println(); + // } + + // taps.println(); + // taps.println("Transformed sequences = "); + // Matrix trans = m.preMultiply(eigenvector); + // trans.print(System.out); + } + +} diff --git a/src/jalview/bin/Cache.java b/src/jalview/bin/Cache.java new file mode 100755 index 0000000..b054bc3 --- /dev/null +++ b/src/jalview/bin/Cache.java @@ -0,0 +1,15 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + + +package jalview.bin; + +public class Cache +{ + public static String LAST_DIRECTORY = "."; +} diff --git a/src/jalview/bin/Jalview.java b/src/jalview/bin/Jalview.java new file mode 100755 index 0000000..de8aa70 --- /dev/null +++ b/src/jalview/bin/Jalview.java @@ -0,0 +1,50 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + + +package jalview.bin; + +import jalview.gui.*; +import javax.swing.*; + +public class Jalview +{ + + public static void main(String[] args) { + try{ + UIManager.setLookAndFeel //("javax.swing.plaf.metal.MetalLookAndFeel"); + ( UIManager.getCrossPlatformLookAndFeelClassName() ); + + // ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + // ("com.sun.java.swing.plaf.motif.MotifLookAndFeel" ); + } + catch (Exception ex) + {} + + JFrame.setDefaultLookAndFeelDecorated(true); + Desktop frame = new Desktop(); + frame.setResizable(true); + frame.setVisible(true); + + + if(args!=null && args.length>0) + { + String file = args[0]; + jalview.bin.Cache.LAST_DIRECTORY = file; + String protocol = "File"; + if(file.indexOf("http:")>-1) + protocol = "URL"; + + String format = jalview.io.IdentifyFile.Identify(file, protocol); + + frame.LoadFile(file, protocol, format); + } + + } + +} diff --git a/src/jalview/datamodel/Alignment.java b/src/jalview/datamodel/Alignment.java new file mode 100755 index 0000000..69b66e0 --- /dev/null +++ b/src/jalview/datamodel/Alignment.java @@ -0,0 +1,453 @@ +package jalview.datamodel; + +import jalview.jbgui.*; +import jalview.schemes.*; +import jalview.analysis.*; +import jalview.util.*; +import java.util.*; + +/** Data structure to hold and manipulate a multiple sequence alignment + */ +public class Alignment implements AlignmentI +{ + + protected Vector sequences; + protected Vector groups = new Vector(); + public Hashtable[] cons; + protected String gapCharacter = "."; + + /** Make an alignment from an array of Sequences. + * + * @param sequences + */ + public Alignment(SequenceI[] seqs) { + sequences = new Vector(); + + for (int i=0; i < seqs.length; i++) { + sequences.addElement(seqs[i]); + } + + groups.addElement(new SequenceGroup()); + + int i = 0; + + while (i < seqs.length) { + addToGroup((SequenceGroup)groups.elementAt(0),seqs[i]); + i++; + } + + getWidth(); + } + + public Vector getSequences() { + return sequences; + } + + public SequenceI getSequenceAt(int i) { + if (i < sequences.size()) { + return (SequenceI)sequences.elementAt(i); + } + + return null; + } + + /** Adds a sequence to the alignment. Recalculates maxLength and size. + * Should put the new sequence in a sequence group!!! + * + * @param snew + */ + public void addSequence(SequenceI snew) { + sequences.addElement(snew); + + ((SequenceGroup)groups.lastElement()).addSequence(snew); + } + + public void addSequence(SequenceI[] seq) { + for (int i=0; i < seq.length; i++) { + addSequence(seq[i]); + } + } + + /** Adds a sequence to the alignment. Recalculates maxLength and size. + * Should put the new sequence in a sequence group!!! + * + * @param snew + */ + public void setSequenceAt(int i,SequenceI snew) { + SequenceI oldseq = getSequenceAt(i); + deleteSequence(oldseq); + + sequences.setElementAt(snew,i); + + ((SequenceGroup)groups.lastElement()).addSequence(snew); + } + + public Vector getGroups() { + return groups; + } + + /** Sorts the sequences by sequence group size - largest to smallest. + * Uses QuickSort. + */ + public void sortGroups() { + float[] arr = new float [groups.size()]; + Object[] s = new Object[groups.size()]; + + for (int i=0; i < groups.size(); i++) { + arr[i] = ((SequenceGroup)groups.elementAt(i)).sequences.size(); + s[i] = groups.elementAt(i); + } + + QuickSort.sort(arr,s); + + Vector newg = new Vector(groups.size()); + + for (int i=groups.size()-1; i >= 0; i--) { + newg.addElement(s[i]); + } + + groups = newg; + } + + /** Takes out columns consisting entirely of gaps (-,.," ") + */ + public void removeGaps() + { + + SequenceI current; + int iSize = getWidth(); + for (int i=0; i < iSize; i++) + { + boolean delete = true; + for (int j=0; j < getHeight(); j++) + { + current = getSequenceAt(j); + if (current.getLength() > i) + { + /* MC Should move this to a method somewhere */ + if (current.getCharAt(i)!='-' && current.getCharAt(i)!='.' && current.getCharAt(i)!=' ') + delete = false; + + } + } + + if ( delete ) + { + deleteColumns(i,i); + iSize--; + i--; + } + } + + + } + + /** Returns an array of Sequences containing columns + * start to end (inclusive) only. + * + * @param start start column to fetch + * @param end end column to fetch + * @return Array of Sequences, ready to put into a new Alignment + */ + public SequenceI[] getColumns(int start, int end) { + return getColumns(0,getHeight()-1,start,end); + } + + /** Removes a range of columns (start to end inclusive). + * + * @param start Start column in the alignment + * @param end End column in the alignment + */ + public void deleteColumns(int start, int end) { + deleteColumns(0,getHeight()-1,start,end); + } + + public void deleteColumns(int seq1, int seq2, int start, int end) { + + for (int i=0; i <= (end-start); i++) { + for (int j=seq1; j <= seq2; j++) { + getSequenceAt(j).deleteCharAt(start); + } + } + } + + public void insertColumns(SequenceI[] seqs, int pos) { + if (seqs.length == getHeight()) { + for (int i=0; i < getHeight();i++) { + String tmp = new String(getSequenceAt(i).getSequence()); + getSequenceAt(i).setSequence(tmp.substring(0,pos) + seqs[i].getSequence() + tmp.substring(pos)); + } + + } + } + + public SequenceI[] getColumns(int seq1, int seq2, int start, int end) { + SequenceI[] seqs = new Sequence[(seq2-seq1)+1]; + for (int i=seq1; i<= seq2; i++ ) { + seqs[i] = new Sequence(getSequenceAt(i).getName(), + getSequenceAt(i).getSequence().substring(start,end), + getSequenceAt(i).findPosition(start), + getSequenceAt(i).findPosition(end)); + } + return seqs; + } + + public void trimLeft(int i) { + for (int j = 0;j< getHeight();j++) { + + SequenceI s = getSequenceAt(j); + int newstart = s.findPosition(i); + + s.setStart(newstart); + s.setSequence(s.getSequence().substring(i)); + + } + } + + public void trimRight(int i) { + for (int j = 0;j< getHeight();j++) { + SequenceI s = getSequenceAt(j); + int newend = s.findPosition(i); + + s.setEnd(newend); + s.setSequence(s.getSequence().substring(0,i+1)); + } + } + + public void deleteSequence(SequenceI s) + { + for (int i=0; i < getHeight(); i++) + if (getSequenceAt(i) == s) + deleteSequence(i); + } + + public void deleteSequence(int i) + { + sequences.removeElementAt(i); + } + + + public Vector removeRedundancy(float threshold, Vector sel) { + Vector del = new Vector(); + + for (int i=1; i < sel.size(); i++) { + for (int j = 0; j < i; j++) { + // Only do the comparison if either have not been deleted + if (!del.contains((SequenceI)sel.elementAt(i)) || + !del.contains((SequenceI)sel.elementAt(j))) { + + float pid = Comparison.compare((SequenceI)sel.elementAt(j), + (SequenceI)sel.elementAt(i)); + + if (pid >= threshold) { + // Delete the shortest one + if (((SequenceI)sel.elementAt(j)).getSequence().length() > + ((SequenceI)sel.elementAt(i)).getSequence().length()) { + del.addElement(sel.elementAt(i)); + System.out.println("Deleting sequence " + ((SequenceI)sel.elementAt(i)).getName()); + } else { + del.addElement(sel.elementAt(i)); + System.out.println("Deleting sequence " + ((SequenceI)sel.elementAt(i)).getName()); + } + } + } + } + } + + // Now delete the sequences + for (int i=0; i < del.size(); i++) { + System.out.println("Deleting sequence " + ((SequenceI)del.elementAt(i)).getName()); + deleteSequence((SequenceI)del.elementAt(i)); + } + + return del; + } + + public void sortByPID(SequenceI s) { + + float scores[] = new float[getHeight()]; + SequenceI seqs[] = new SequenceI[getHeight()]; + + for (int i = 0; i < getHeight(); i++) { + scores[i] = Comparison.compare(getSequenceAt(i),s); + seqs[i] = getSequenceAt(i); + } + + QuickSort.sort(scores,0,scores.length-1,seqs); + + int len = 0; + + if (getHeight()%2 == 0) { + len = getHeight()/2; + } else { + len = (getHeight()+1)/2; + } + + for (int i = 0; i < len; i++) { + SequenceI tmp = seqs[i]; + sequences.setElementAt(seqs[getHeight()-i-1],i); + sequences.setElementAt(tmp,getHeight()-i-1); + } + } + + public void sortByID() { + String ids[] = new String[getHeight()]; + SequenceI seqs[] = new SequenceI[getHeight()]; + + for (int i = 0; i < getHeight(); i++) { + ids[i] = getSequenceAt(i).getName(); + seqs[i] = getSequenceAt(i); + } + + QuickSort.sort(ids,seqs); + + int len = 0; + + if (getHeight()%2 == 0) { + len = getHeight()/2; + } else { + len = (getHeight()+1)/2; + System.out.println("Sort len is odd = " + len); + } + for (int i = 0; i < len; i++) { + System.out.println("Swapping " + seqs[i].getName() + " and " + seqs[getHeight()-i-1].getName()); + SequenceI tmp = seqs[i]; + sequences.setElementAt(seqs[getHeight()-i-1],i); + sequences.setElementAt(tmp,getHeight()-i-1); + } + } + + /** */ + public SequenceGroup findGroup(int i) { + return findGroup(getSequenceAt(i)); + } + + /** */ + public SequenceGroup findGroup(SequenceI s) { + for (int i = 0; i < this.groups.size();i++) { + SequenceGroup sg = (SequenceGroup)groups.elementAt(i); + if (sg.sequences.contains(s)) { + return sg; + } + } + return null; + + } + /** */ + public void addToGroup(SequenceGroup g, SequenceI s) { + if (!(g.sequences.contains(s))) { + g.sequences.addElement(s); + } + } + /** */ + public void removeFromGroup(SequenceGroup g,SequenceI s) { + if (g != null && g.sequences != null) { + if (g.sequences.contains(s)) { + g.sequences.removeElement(s); + if (g.sequences.size() == 0) { + groups.removeElement(g); + } + } + } + } + + /** */ + public void addGroup(SequenceGroup sg) { + groups.addElement(sg); + } + + /** */ + public SequenceGroup addGroup() { + SequenceGroup sg = new SequenceGroup(); + groups.addElement(sg); + return sg; + } + + /** */ + public void deleteGroup(SequenceGroup g) { + if (groups.contains(g)) { + groups.removeElement(g); + } + } + + /** */ + public SequenceI findName(String name) { + int i = 0; + while (i < sequences.size()) { + SequenceI s = getSequenceAt(i); + if (s.getName().equals(name)) { + return s; + } + i++; + } + return null; + } + + /** */ + public int findIndex(SequenceI s) { + int i=0; + while (i < sequences.size()) { + if (s == getSequenceAt(i)) { + return i; + } + i++; + } + return -1; + } + + public int getHeight() { + return sequences.size(); + } + + + public int getWidth() + { + int maxLength = -1; + for (int i = 0; i < sequences.size(); i++) + { + if (getSequenceAt(i).getLength() > maxLength) + maxLength = getSequenceAt(i).getLength(); + } + + return maxLength; + } + + + public int getMaxIdLength() { + int max = 0; + int i = 0; + + while (i < sequences.size()) { + SequenceI seq = getSequenceAt(i); + String tmp = seq.getName() + "/" + seq.getStart() + "-" + seq.getEnd(); + + if (tmp.length() > max) { + max = tmp.length(); + } + + i++; + } + return max; + } + + public void setGapCharacter(String gc) { + gapCharacter = gc; + } + + public String getGapCharacter() { + return gapCharacter; + } + + public Vector getAAFrequency() + { + return AAFrequency.calculate(sequences, 0, getWidth()); + } +} + + + + + + + + diff --git a/src/jalview/datamodel/AlignmentI.java b/src/jalview/datamodel/AlignmentI.java new file mode 100755 index 0000000..6a1e026 --- /dev/null +++ b/src/jalview/datamodel/AlignmentI.java @@ -0,0 +1,64 @@ +package jalview.datamodel; + +import jalview.jbgui.*; +import java.util.*; + +/** Data structure to hold and manipulate a multiple sequence alignment + */ +public interface AlignmentI { + + public int getHeight() ; + public int getWidth() ; + public int getMaxIdLength() ; + + public Vector getSequences(); + public SequenceI getSequenceAt(int i); + + public void addSequence(SequenceI seq) ; + public void setSequenceAt(int i,SequenceI seq); + + public void deleteSequence(SequenceI s) ; + public void deleteSequence(int i) ; + + public SequenceI[] getColumns(int start, int end) ; + public SequenceI[] getColumns(int seq1, int seq2, int start, int end) ; + + public void deleteColumns(int start, int end) ; + public void deleteColumns(int seq1, int seq2, int start, int end) ; + + public void insertColumns(SequenceI[] seqs, int pos) ; + + public SequenceI findName(String name) ; + public int findIndex(SequenceI s) ; + + // Modifying + public void trimLeft(int i) ; + public void trimRight(int i) ; + + public void removeGaps() ; + public Vector removeRedundancy(float threshold, Vector sel) ; + + + // Grouping methods + public SequenceGroup findGroup(int i) ; + public SequenceGroup findGroup(SequenceI s) ; + public void addToGroup(SequenceGroup g, SequenceI s) ; + public void removeFromGroup(SequenceGroup g,SequenceI s) ; + public void addGroup(SequenceGroup sg) ; + public SequenceGroup addGroup() ; + public void deleteGroup(SequenceGroup g) ; + public Vector getGroups(); + + // Sorting + public void sortGroups() ; + public void sortByPID(SequenceI s) ; + public void sortByID() ; + + public void setGapCharacter(String gc); + public String getGapCharacter(); + + public Vector getAAFrequency(); +} + + + diff --git a/src/jalview/datamodel/BinaryNode.java b/src/jalview/datamodel/BinaryNode.java new file mode 100755 index 0000000..77b5971 --- /dev/null +++ b/src/jalview/datamodel/BinaryNode.java @@ -0,0 +1,73 @@ +package jalview.datamodel; + +public class BinaryNode { + + Object element; + String name; + BinaryNode left; + BinaryNode right; + BinaryNode parent; + public int bootstrap; + + public BinaryNode() { + left = right = parent = null; + } + + public BinaryNode(Object element, BinaryNode parent,String name) { + this.element = element; + this.parent = parent; + this.name = name; + + left=right=null; + } + + public Object element() { + return element; + } + + public Object setElement(Object v) { + return element=v; + } + + public BinaryNode left() { + return left; + } + + public BinaryNode setLeft(BinaryNode n) { + return left=n; + } + + public BinaryNode right() { + return right; + } + + public BinaryNode setRight(BinaryNode n) { + return right=n; + } + + public BinaryNode parent() { + return parent; + } + + public BinaryNode setParent(BinaryNode n) { + return parent=n; + } + + public boolean isLeaf() { + return (left == null) && (right == null); + } + + public void setName(String name) { + this.name = name; + } + public String getName() { + return this.name; + } + public void setBootstrap(int boot) { + this.bootstrap = boot; + } + public int getBootstrap() { + return bootstrap; + } +} + diff --git a/src/jalview/datamodel/BinarySequence.java b/src/jalview/datamodel/BinarySequence.java new file mode 100755 index 0000000..b029641 --- /dev/null +++ b/src/jalview/datamodel/BinarySequence.java @@ -0,0 +1,109 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +package jalview.datamodel; + +import jalview.io.*; +import jalview.analysis.PCA; +import jalview.jbgui.*; +import jalview.schemes.*; + +import java.awt.*; + +public class BinarySequence extends Sequence { + int[] binary; + double[] dbinary; + + public BinarySequence(SequenceI s) { + super(s.getName(),s.getSequence(),s.getStart(),s.getEnd()); + } + + public BinarySequence(String name, String sequence, int start, int end) { + super(name,sequence,start,end); + } + + public void encode() { + // Set all matrix to 0 + dbinary = new double[getSequence().length() * 21]; + int nores = 21; + for (int i = 0; i < dbinary.length; i++) { + dbinary[i] = 0.0; + } + + for (int i=0; i < getSequence().length(); i++ ) { + int aanum = 20; + try { + aanum = ((Integer)ResidueProperties.getAAHash().get(getSequence().substring(i,i+1))).intValue(); + } catch (NullPointerException e) { + aanum = 20; + } + if (aanum > 20) { + aanum = 20; + } + + dbinary[i* nores + aanum] = 1.0; + + } + } + + public void blosumEncode() { + + // Set all matrix to 0 + dbinary = new double[getSequence().length() * 21]; + int nores = 21; + //for (int i = 0; i < dbinary.length; i++) { + // dbinary[i] = 0.0; + //} + + for (int i=0; i < getSequence().length(); i++ ) { + int aanum = 20; + try { + aanum = ((Integer)ResidueProperties.getAAHash().get(getSequence().substring(i,i+1))).intValue(); + } catch (NullPointerException e) { + aanum = 20; + } + if (aanum > 20) { + aanum = 20; + } + + // Do the blosum thing + for (int j = 0;j < 20;j++) { + dbinary[i * nores + j] = ResidueProperties.getBLOSUM62()[aanum][j]; + } + + } + } + + public String toBinaryString() { + String out = ""; + for (int i=0; i < binary.length;i++) { + out += (new Integer(binary[i])).toString(); + if (i < binary.length-1) { + out += " "; + } + } + return out; + } + + public double[] getDBinary() { + return dbinary; + } + + public static void printMemory(Runtime rt) { + System.out.println("Free memory = " + rt.freeMemory()); + } +} diff --git a/src/jalview/datamodel/FeaturePair.java b/src/jalview/datamodel/FeaturePair.java new file mode 100755 index 0000000..025d2af --- /dev/null +++ b/src/jalview/datamodel/FeaturePair.java @@ -0,0 +1,118 @@ +package jalview.datamodel; + +import java.util.*; + +public class FeaturePair { + SequenceFeature f1; + SequenceFeature f2; + + public FeaturePair() { + this.f1 = new SequenceFeature(); + this.f2 = new SequenceFeature(); + } + public FeaturePair(SequenceFeature f1, SequenceFeature f2) { + this.f1 = f1; + this.f2 = f2; + } + public void setQueryFeature(SequenceFeature feature) { + this.f1 = feature; + } + public SequenceFeature getQueryFeature() { + return f1; + } + public void setHitFeature(SequenceFeature feature) { + this.f2 = feature; + } + public SequenceFeature getHitFeature() { + return f2; + } + public void setStart(int start) { + f1.setStart(start); + } + public int getStart() { + return f1.getStart(); + } + public void setEnd(int end) { + f1.setEnd(end); + } + public int getEnd() { + return f1.getEnd(); + } + public void setStrand(int strand) { + f1.setStrand(strand); + } + public int getStrand() { + return f1.getStrand(); + } + public String getId() { + return f1.getId(); + } + public void setId(String id) { + f1.setId(id); + } + public double getScore() { + return f1.getScore(); + } + public void setScore(double score) { + f1.setScore(score); + f2.setScore(score); + } + + public String getHitId() { + return f2.getId(); + } + public void setHitId(String name) { + f2.setId(name); + } + public int getHstart() { + return f2.getStart(); + } + public void setHstart(int start) { + f2.setStart(start); + } + public int getHend() { + return f2.getEnd(); + } + public void setHend(int end) { + f2.setEnd(end); + } + public void setHstrand(int strand) { + f2.setStrand(strand); + } + public int getHstrand() { + return f2.getStrand(); + } + + public double getPValue() { + return f1.getPValue(); + } + public void setPValue(double value) { + f1.setPValue(value); + f2.setPValue(value); + } + public double getPercentId() { + return f1.getPercentId(); + } + public void setPercentId(double pid) { + f1.setPercentId(pid); + f2.setPercentId(pid); + } + + public void invert() { + SequenceFeature tmp = f1; + f1 = f2; + f2 = tmp; + } + + public String toGFFString() { + String tmp = f1.toGFFString(); + + tmp = tmp + "\t" + getHitId() + "\t" + getHstart() + "\t" + getHend() + "\t" + getPValue() + "\t" + getPercentId(); + + return tmp; + } + + public static void main(String[] args) { + FeaturePair fp = new FeaturePair(); + } +} \ No newline at end of file diff --git a/src/jalview/datamodel/Sequence.java b/src/jalview/datamodel/Sequence.java new file mode 100755 index 0000000..1875557 --- /dev/null +++ b/src/jalview/datamodel/Sequence.java @@ -0,0 +1,157 @@ +package jalview.datamodel; + + +import java.awt.*; + +public class Sequence implements SequenceI { + protected String name; + protected String sequence; + protected int start; + protected int end; + protected String description; + protected int charHeight; + protected String displayId; + protected Color color = Color.black; + + public Sequence(String name, String sequence, int start, int end) + { + + this.name = name; + this.sequence = sequence; + this.start = start; + this.end = end; + + setDisplayId(); + + } + + public Sequence(String name,String sequence) { + this(name,sequence,1,sequence.length()); + } + public Sequence(SequenceI seq) { + this(seq.getName(),seq.getSequence(),seq.getStart(),seq.getEnd()); + } + public String getDisplayId() { + return displayId; + } + public void setDisplayId() { + displayId = name + "/" + start + "-" + end; + } + public void setName(String name) { + this.name = name; + setDisplayId(); + } + public String getName() { + return this.name; + } + public void setStart(int start) { + this.start = start; + setDisplayId(); + } + public int getStart() { + return this.start; + } + public void setEnd(int end) { + this.end = end; + setDisplayId(); + } + public int getEnd() { + return this.end; + } + public int getLength() { + return this.sequence.length(); + } + public void setSequence(String seq) { + this.sequence = seq; + } + public String getSequence() { + return this.sequence; + } + public String getSequence(int start,int end) { + return this.sequence.substring(start,end); + } + + public char getCharAt(int i) { + if (i < sequence.length()) { + return sequence.charAt(i); + } else { + return ' '; + } + } + public void setDescription(String desc) { + this.description = desc; + } + public String getDescription() { + return this.description; + } + + public int findIndex(int pos) { + // returns the alignment position for a residue + int j = start; + int i = 0; + + while (i< sequence.length() && j <= end && j <= pos) { + + String s = sequence.substring(i,i+1); + + if (!(s.equals(".") || s.equals("-") || s.equals(" "))) { + j++; + } + i++; + } + if (j == end && j < pos) { + return end+1; + } else { + + return i; + } + } + + public int findPosition(int i) { + // Returns the sequence position for an alignment position + int j = 0; + int pos = start; + + while (j < i) { + String s = sequence.substring(j,j+1); + + if (!(s.equals(".") || s.equals("-") || s.equals(" "))) { + pos++; + } + j++; + } + return pos; + } + public void deleteCharAt(int i) + { + StringBuffer sbuffer = new StringBuffer(sequence); + sbuffer.deleteCharAt(i); + sequence = sbuffer.toString(); + } + + public void insertCharAt(int i, char c) + { + insertCharAt(i,c,true); + } + + public void insertCharAt(int i,char c,boolean chop) { + + String tmp = new String(sequence); + + if (i < sequence.length()) { + sequence = tmp.substring(0,i) + String.valueOf(c) + tmp.substring(i); + } else { + sequence = tmp + String.valueOf(c); + } + + } + + public void setColor(Color c) { + this.color = c; + } + + public Color getColor() { + return color; + } + +} diff --git a/src/jalview/datamodel/SequenceFeature.java b/src/jalview/datamodel/SequenceFeature.java new file mode 100755 index 0000000..2512978 --- /dev/null +++ b/src/jalview/datamodel/SequenceFeature.java @@ -0,0 +1,197 @@ +package jalview.datamodel; + +import jalview.util.*; +import jalview.jbgui.*; +import jalview.schemes.*; +import java.awt.*; + +public class SequenceFeature { + int start; + int end; + String type; + String description; + Color color; + Sequence sequence; + String id; + double score; + int strand; + double pvalue; + double pid; + + public SequenceFeature() { + } + + public SequenceFeature(Sequence sequence,String type, int start, int end, String description) { + this.sequence = sequence; + this.type = type; + this.start = start; + this.end = end; + this.description = description; + + setColor(); + } + + + public String toGFFString() { + String gff = id + "\t" + type + "\tfeature\t" + start + "\t" + end + "\t" + score + "\t" + strand + "\t."; + return gff; + } + public double getScore() { + return score; + } + + public void setScore(double score) { + this.score = score; + } + + public String getId() { + return this.id; + } + public void setId(String id) { + this.id = id; + } + public void setSequence(Sequence seq) { + this.sequence = seq; + } + public void setStart(int start) { + this.start = start; + } + public void setEnd(int end) { + this.end = end; + } + public int getStrand() { + return strand; + } + public void setStrand(int strand) { + this.strand = strand; + } + public int getStart() { + return start; + } + + public int getEnd() { + return end; + } + + public String getType() { + return type; + } + + public String getDescription() { + return description; + } + + public double getPValue() { + return pvalue; + } + public void setPValue(double value) { + this.pvalue = value; + } + public double getPercentId() { + return pid; + } + public void setPercentId(double pid) { + this.pid = pid; + } + public Color getColor() { + return color; + } + + public void setColor() { + if (type.equals("CHAIN")) { + color = Color.white; + } else if (type.equals("DOMAIN")) { + color = Color.white; + } else if (type.equals("TRANSMEM")) { + color = Color.red.darker(); + } else if (type.equals("SIGNAL")) { + color = Color.cyan; + } else if (type.equals("HELIX")) { + color = Color.magenta; + } else if (type.equals("TURN")) { + color = Color.cyan; + } else if (type.equals("SHEET")) { + color = Color.yellow; + } else if (type.equals("STRAND")) { + color = Color.yellow; + } else if (type.equals("CARBOHYD")) { + color = Color.pink; + } else if (type.equals("ACT_SITE")) { + color = Color.red; + } else if (type.equals("TRANSIT")) { + color = Color.orange; + } else if (type.equals("VARIANT")) { + color = Color.orange.darker(); + } else if (type.equals("BINDING")) { + color = Color.blue; + } else if (type.equals("DISULFID")) { + color = Color.yellow.darker(); + } else if (type.equals("NP_BIND")) { + color = Color.red; + } else if (type.indexOf("BIND") > 0) { + color = Color.red; + } else { + color = Color.lightGray; + } + } + public String print() { + String tmp = new Format("%15s").form(type); + tmp = tmp + new Format("%6d").form(start); + tmp = tmp + new Format("%6d").form(end); + tmp = tmp + " " + description; + return tmp; + } + public void draw(Graphics g, int fstart, int fend, int x1, int y1, int width, int height) { + g.setColor(new Color((float)(Math.random()),(float)(Math.random()),(float)(Math.random()))); + + // int xstart = sequence.findIndex(start); + //int xend = sequence.findIndex(end); + int xstart = start; + int xend = end; + long tstart = System.currentTimeMillis(); + if (!(xend < fstart && xstart > fend)) { + + if (xstart > fstart) { + x1 = x1 + (xstart-fstart)*width; + fstart = xstart; + } + + if (xend < fend) { + fend = xend; + } + + for (int i = fstart; i <= fend; i++) { + String s = sequence.sequence.substring(i,i+1); + if (!(s.equals(".") || s.equals("-") || s.equals(" "))) { + g.fillRect(x1+(i-fstart)*width,y1,width,height); + } else { + g.drawString("-",x1+(i-fstart)*width,y1+height); + } + } + + } + long tend = System.currentTimeMillis(); + System.out.println("Time = " + (tend-tstart) + "ms"); + + } + + public static void main(String[] args) { + SequenceFeature sf = new SequenceFeature(); + + System.out.println("Feature " + sf); + } + public static int CHAIN = 0; + public static int DOMAIN = 1; + public static int TRANSMEM = 2; + public static int SIGNAL = 3; + public static int HELIX = 4; + public static int TURN = 5; + public static int SHEET = 6; + public static int CARBOHYD = 7; + public static int ACT_SITE = 8; + public static int TRANSIT = 9; + public static int VARIANT = 10; + public static int BINDING = 11; + +} + diff --git a/src/jalview/datamodel/SequenceGroup.java b/src/jalview/datamodel/SequenceGroup.java new file mode 100755 index 0000000..de746ba --- /dev/null +++ b/src/jalview/datamodel/SequenceGroup.java @@ -0,0 +1,107 @@ +package jalview.datamodel; + +import jalview.jbgui.*; +import jalview.schemes.*; +import jalview.analysis.*; +import jalview.datamodel.*; + +import java.util.Vector; +import java.awt.*; + +public class SequenceGroup { + boolean isSelected; + boolean displayBoxes; + boolean displayText; + boolean colourText; + boolean display; + Conservation conserve; + Vector aaFrequency; + boolean aaFrequencyValid = false; + Vector sequences = new Vector(); + int width = -1; + + + public SequenceGroup() { + this.isSelected = false; + this.displayBoxes = true; + this.displayText = true; + this.colourText = false; + this.display = true; + } + + public SequenceGroup( ColourSchemeI scheme, boolean isSelected, + boolean displayBoxes, boolean displayText, + boolean colourText, + boolean display) { + + this.isSelected = isSelected; + this.displayBoxes = displayBoxes; + this.displayText = displayText; + this.colourText = colourText; + this.display = display; + } + + public Conservation getConservation() { + return conserve; + } + public void addSequence(SequenceI s) { + sequences.addElement(s); + } + + public void deleteSequence(SequenceI s) { + sequences.removeElement(s); + } + + public void setColourText(boolean state) { + colourText = state; + } + public boolean getColourText() { + return colourText; + } + + public void setDisplayText(boolean state) { + displayText = state; + } + + public boolean getDisplayText() { + return displayText; + } + + public void setDisplayBoxes(boolean state) { + displayBoxes = state; + } + + public boolean getDisplayBoxes() { + return displayBoxes; + } + + public int getSize() { + return sequences.size(); + } + public SequenceI getSequenceAt(int i) { + return (SequenceI)sequences.elementAt(i); + } + + public Vector getAAFrequency() { + if (aaFrequency == null || aaFrequencyValid == false) { + aaFrequency = AAFrequency.calculate(sequences,1,getWidth()); + aaFrequencyValid = true; + } + return aaFrequency; + } + public int getWidth() { + // MC This needs to get reset when characters are inserted and deleted + if (width == -1) { + for (int i = 0; i < sequences.size(); i++) { + SequenceI seq = (SequenceI)sequences.elementAt(i); + if (seq.getLength() > width) { + width = seq.getLength(); + } + } + } + + return width; + } +} + + diff --git a/src/jalview/datamodel/SequenceI.java b/src/jalview/datamodel/SequenceI.java new file mode 100755 index 0000000..2183131 --- /dev/null +++ b/src/jalview/datamodel/SequenceI.java @@ -0,0 +1,50 @@ +package jalview.datamodel; + +import jalview.jbgui.*; +import java.awt.*; + +import java.util.Vector; + +public interface SequenceI { + public void setName(String name); + public String getName(); + + public void setStart(int start); + public int getStart(); + + public String getDisplayId(); + + public void setEnd(int end); + public int getEnd(); + + public int getLength(); + + public void setSequence(String sequence); + public String getSequence(); + public String getSequence(int start,int end); + public char getCharAt(int i); + + public void setDescription(String desc); + public String getDescription(); + + public int findIndex(int pos); + public int findPosition(int i); + + public void deleteCharAt(int i); + public void insertCharAt(int i, char c); + public void insertCharAt(int i,char c,boolean chop); + + public void setColor(Color c); + public Color getColor(); + } + + + + + + + + + + + diff --git a/src/jalview/datamodel/SequenceNode.java b/src/jalview/datamodel/SequenceNode.java new file mode 100755 index 0000000..6e35ee3 --- /dev/null +++ b/src/jalview/datamodel/SequenceNode.java @@ -0,0 +1,21 @@ +package jalview.datamodel; + +import java.awt.Color; + +public class SequenceNode extends BinaryNode { + + public float dist; + public int count; + public float height; + public float ycount; + public Color color = Color.black; + + public SequenceNode() { + super(); + } + + public SequenceNode(Object val, SequenceNode parent, float dist,String name) { + super(val,parent,name); + this.dist = dist; + } +} diff --git a/src/jalview/datamodel/SequencePoint.java b/src/jalview/datamodel/SequencePoint.java new file mode 100755 index 0000000..093c45a --- /dev/null +++ b/src/jalview/datamodel/SequencePoint.java @@ -0,0 +1,36 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +package jalview.datamodel; +import java.util.*; +import java.awt.*; + + +public class SequencePoint { + + // SMJS PUBLIC + public SequenceI sequence; + public float[] coord; + // SMJS ENDPUBLIC + + public SequencePoint(SequenceI sequence, float[] coord) { + this.sequence = sequence; + this.coord = coord; + } + +} diff --git a/src/jalview/gui/AlignFrame.java b/src/jalview/gui/AlignFrame.java new file mode 100755 index 0000000..af8a6c0 --- /dev/null +++ b/src/jalview/gui/AlignFrame.java @@ -0,0 +1,509 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + + + + +package jalview.gui; + +import jalview.jbgui.GAlignFrame; +import jalview.schemes.*; +import jalview.datamodel.*; +import jalview.analysis.*; +import jalview.io.*; +import java.awt.event.*; +import java.awt.*; +import javax.swing.*; + +public class AlignFrame extends GAlignFrame +{ + AlignmentPanel alignPanel; + AlignViewport viewport; + public AlignFrame(AlignmentI al) + { + super(); + viewport = new AlignViewport(al,true,true,true,false); + alignPanel = new AlignmentPanel(this, viewport); + getContentPane().add(alignPanel, java.awt.BorderLayout.CENTER); + fontNameMenuItem.setText(viewport.getFont().getName()); + fontSizeMenuItem.setText(viewport.getFont().getSize()+""); + } + + protected void saveAs_actionPerformed(ActionEvent e) + { + JFileChooser chooser = new JFileChooser(jalview.bin.Cache.LAST_DIRECTORY); + chooser.setDialogTitle("Save Alignment to file - "+e.getActionCommand() +" format."); + chooser.setToolTipText("Save"); + int value = chooser.showSaveDialog(this); + if(value == JFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.bin.Cache.LAST_DIRECTORY = choice; + String output = FormatAdapter.get(e.getActionCommand(), viewport.getAlignment().getSequences()); + try{ + java.io.PrintWriter out = new java.io.PrintWriter( new java.io.FileWriter( choice ) ); + out.println(output); + out.close(); + } + catch(Exception ex){} + } + + } + + protected void outputText_actionPerformed(ActionEvent e) + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(false); + JInternalFrame frame = new JInternalFrame(); + cap.formatForOutput(); + frame.setContentPane(cap); + Desktop.addInternalFrame(frame, "Alignment output - "+e.getActionCommand(), 600, 500); + cap.setText( FormatAdapter.get(e.getActionCommand(), viewport.getAlignment().getSequences())); + } + + protected void htmlMenuItem_actionPerformed(ActionEvent e) + { + HTMLOutput htmlOutput = new HTMLOutput(viewport.getAlignment(), alignPanel.seqPanel.getColourScheme()); + htmlOutput = null; + } + + public void saveAsPostscriptMenuItem_actionPerformed(ActionEvent e) + { + + } + + public void closeMenuItem_actionPerformed(ActionEvent e) + { + try{ + this.setClosed(true); + }catch(Exception ex){} + } + + public void groupsMenuItem_actionPerformed(ActionEvent e) + { + + } + + public void groupEditingMenuItem_actionPerformed(ActionEvent e) + { + + } + + public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e) + { + Selection sel = viewport.getSelection(); + for (int i=0; i500) + newHeight=500; + Desktop.addInternalFrame(af, "Copied sequences", 700,newHeight); + } + + public void deselectAllColumnsMenuItem_actionPerformed(ActionEvent e) + { + viewport.getColumnSelection().clear(); + repaint(); + } + + public void remove2LeftMenuItem_actionPerformed(ActionEvent e) + { + ColumnSelection colSel = viewport.getColumnSelection(); + if (colSel.size() > 0) + { + int min = colSel.getMin(); + viewport.getAlignment().trimLeft(min); + colSel.compensateForEdit(0,min); + alignPanel.RefreshPanels(); + } + } + + public void remove2RightMenuItem_actionPerformed(ActionEvent e) + { + ColumnSelection colSel = viewport.getColumnSelection(); + if (colSel.size() > 0) + { + int max = colSel.getMax(); + if(max>1) + viewport.getAlignment().trimRight(max); + + alignPanel.RefreshPanels(); + } + + } + + public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e) + { + viewport.getAlignment().removeGaps(); + alignPanel.RefreshPanels(); + } + + public void removeAllGapsMenuItem_actionPerformed(ActionEvent e) + { + SequenceI current; + int jSize; + for (int i=0; i < viewport.getAlignment().getSequences().size();i++) + { + current = viewport.getAlignment().getSequenceAt(i); + jSize = current.getLength(); + for (int j=0; j < jSize; j++) + if (current.getCharAt(j)=='-' || current.getCharAt(j)=='.' || current.getCharAt(j)==' ') + { + current.deleteCharAt(j); + j--; + jSize--; + } + } + + alignPanel.RefreshPanels(); + } + + public void setGapCharMenuItem_actionPerformed(ActionEvent e) + { + String thisChar = "-"; + String nextChar = "."; + if(viewport.getGapCharacter().equals("-")) + { + thisChar = "."; + nextChar = "-"; + } + setGapCharMenuItem.setText("Set gap character to \""+nextChar+"\""); + viewport.setGapCharacter(thisChar); + } + + + public void fontNameMenuItem_actionPerformed(ActionEvent e) + { + String fonts[] = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); + + + String selection = JOptionPane.showInputDialog(this, + "Select font", + "Font selection", + JOptionPane.QUESTION_MESSAGE, + null,fonts + ,fontNameMenuItem.getText()).toString(); + if(selection!=null) + { + fontNameMenuItem.setText(selection); + SetFont(); + } + + } + + public void fontSizeMenuItem_actionPerformed(ActionEvent e) + { + String selection = JOptionPane.showInputDialog(this, + "Select font size", + "Font size", + JOptionPane.QUESTION_MESSAGE, + null, new String[]{"1","2","4","6","8","10","12","14","16","18","20"} + ,fontSizeMenuItem.getText()).toString(); + if(selection!=null) + { + fontSizeMenuItem.setText(selection); + SetFont(); + } + } + + public void fontStyleMenuItem_actionPerformed(ActionEvent e) + { + String selection = JOptionPane.showInputDialog(this, + "Select font style", + "Font style", + JOptionPane.QUESTION_MESSAGE, + null, new String[]{"plain", "bold", "italic"} + ,fontStyleMenuItem.getText()).toString(); + if(selection!=null) + { + fontStyleMenuItem.setText(selection); + SetFont(); + } + + } + + protected void colourTextMenuItem_actionPerformed(ActionEvent e) + { + viewport.setColourText( colourTextMenuItem.isSelected() ); + alignPanel.RefreshPanels(); + } + + void SetFont() + { + int style = java.awt.Font.PLAIN; + if(fontStyleMenuItem.getText().equals("bold")) + style = java.awt.Font.BOLD; + else if(fontStyleMenuItem.getText().equals("italic")) + style = java.awt.Font.ITALIC; + + viewport.setFont(new java.awt.Font(fontNameMenuItem.getText(), + style, + Integer.parseInt(fontSizeMenuItem.getText()))); + alignPanel.RefreshPanels(); + } + + public void viewBoxesMenuItem_actionPerformed(ActionEvent e) + { + viewport.setShowBoxes( viewBoxesMenuItem.isSelected() ); + alignPanel.RefreshPanels(); + } + + public void viewTextMenuItem_actionPerformed(ActionEvent e) + { + viewport.setShowText( viewTextMenuItem.isSelected() ); + alignPanel.RefreshPanels(); + } + + + public void consensusGraphMenuItem_actionPerformed(ActionEvent e) + { + alignPanel.setGraphPanelVisible( consensusGraphMenuItem.isSelected() ); + } + + + public void clustalColour_actionPerformed(ActionEvent e) + { + // alignPanel.seqPanel.setColourScheme( new ClustalxColourScheme() ); + } + + public void zappoColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new ZappoColourScheme() ); + } + + public void taylorColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new TaylorColourScheme() ); + } + + + public void hydrophobicityColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new HydrophobicColourScheme() ); + } + + public void helixColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new HelixColourScheme() ); + } + + public void strandColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new StrandColourScheme() ); + } + + public void turnColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new TurnColourScheme() ); + } + + public void buriedColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new BuriedColourScheme() ); + } + + public void conservationColour_actionPerformed(ActionEvent e) + { + + } + + public void conservationColourIncMenuItem_actionPerformed(ActionEvent e) + { + + } + + + public void abovePIDColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new PIDColourScheme() ); + } + + + public void userDefinedColour_actionPerformed(ActionEvent e) + { + JInternalFrame frame = new JInternalFrame(); + UserDefinedColours chooser = new UserDefinedColours( frame, alignPanel.seqPanel ); + frame.setContentPane(chooser); + Desktop.addInternalFrame(frame,"User defined colours", 450,540 ); + frame.setResizable(false); + frame.setIconifiable(false); + frame.setMaximizable(false); + } + + public void PIDColour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new PIDColourScheme() ); + } + + public void BLOSUM62Colour_actionPerformed(ActionEvent e) + { + alignPanel.seqPanel.setColourScheme( new Blosum62ColourScheme(viewport) ); + } + + + protected void schemeKeyMenuItem_actionPerformed(ActionEvent e) + { + ColourKey colourKey = new ColourKey( alignPanel.seqPanel.getColourScheme() ); + Desktop.addInternalFrame(colourKey, "Colour scheme key", 400, 320); + } + + + public void sortPairwiseMenuItem_actionPerformed(ActionEvent e) + { + AlignmentSorter.sortByPID(viewport.getAlignment(), viewport.getAlignment().getSequenceAt(0)); + alignPanel.RefreshPanels(); + } + + public void sortIDMenuItem_actionPerformed(ActionEvent e) + { + AlignmentSorter.sortByID( viewport.getAlignment() ); + alignPanel.RefreshPanels(); + } + + public void sortGroupMenuItem_actionPerformed(ActionEvent e) + { + AlignmentSorter.sortGroups(viewport.getAlignment()); + AlignmentSorter.sortGroups(viewport.getAlignment()); + alignPanel.RefreshPanels(); + } + + public void sortTreeOrderMenuItem_actionPerformed(ActionEvent e) + { + if(viewport.getCurrentTree()==null) + return; + + AlignmentSorter.sortByTree(viewport.getAlignment(), viewport.getCurrentTree()); + alignPanel.RefreshPanels(); + } + + public void removeRedundancyMenuItem_actionPerformed(ActionEvent e) + { + + } + + public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e) + { + if(viewport.getSelection().size()<2) + JOptionPane.showMessageDialog(this, "You must select at least 2 sequences.", "Invalid Selection", JOptionPane.WARNING_MESSAGE); + else + { + JInternalFrame frame = new JInternalFrame(); + frame.setContentPane(new PairwiseAlignPanel(viewport)); + Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500); + } + } + + public void PCAMenuItem_actionPerformed(ActionEvent e) + { + PCAPanel pcaPanel = new PCAPanel(viewport, null); + JInternalFrame frame = new JInternalFrame(); + frame.setContentPane(pcaPanel); + Desktop.addInternalFrame(frame, "Principal component analysis", 400,400); + } + + public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e) + { + NewTreePanel("AV", "PID", "Average distance tree using PID"); + } + + public void neighbourTreeMenuItem_actionPerformed(ActionEvent e) + { + NewTreePanel("NJ", "PID", "Neighbour joining tree using PID"); + } + + + protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e) + { + NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62"); + } + + protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e) + { + NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62PID"); + } + + void NewTreePanel(String type, String pwType, String title) + { + JInternalFrame frame = new javax.swing.JInternalFrame(); + TreePanel tp=null; + if (viewport.getSelection() != null && viewport.getSelection().size() > 3) + { + tp = new TreePanel(viewport, viewport.getSelection().asVector(),type, pwType, + viewport.getStartRes(), viewport.getEndRes()); + } + else + { + tp = new TreePanel(viewport, viewport.getAlignment().getSequences(), + type, pwType, viewport.getStartRes(), + viewport.getEndRes()); + } + + frame.setContentPane(tp); + Desktop.addInternalFrame(frame, title, 600, 500); + } + + + + public void clustalAlignMenuItem_actionPerformed(ActionEvent e) + { + JOptionPane.showMessageDialog(this, "Jalview is currently being reengineered" + +"\nwithin the Barton Group, Dundee University." + +"\nThis will be available as a web service 2005", + "Web service", JOptionPane.INFORMATION_MESSAGE); + } + +} diff --git a/src/jalview/gui/AlignViewport.java b/src/jalview/gui/AlignViewport.java new file mode 100755 index 0000000..1324c1e --- /dev/null +++ b/src/jalview/gui/AlignViewport.java @@ -0,0 +1,346 @@ +package jalview.gui; + +import java.awt.*; +import jalview.io.*; +import jalview.analysis.NJTree; +import jalview.datamodel.*; +import java.util.*; + +public class AlignViewport +{ + int startRes; + int endRes; + + int startSeq; + int endSeq; + + boolean showScores; + boolean showText; + boolean showColourText; + boolean showBoxes; + boolean wrapAlignment; + + boolean groupEdit = false; + + RendererI renderer = new SequenceRenderer(); + + int charHeight; + double charWidth; + int chunkWidth; + int chunkHeight; + + Color backgroundColour; + + Font font = new Font("SansSerif",Font.PLAIN,10); + AlignmentI alignment; + + Selection sel = new Selection(); + ColumnSelection colSel = new ColumnSelection(); + + OutputGenerator og; + + String visibleConsensus; + + int threshold; + int increment; + + NJTree currentTree = null; + + int window = 50; + int baseline = 30; + + Vector kmers; + + public AlignViewport(AlignmentI da, + boolean showScores, + boolean showText, + boolean showBoxes, + boolean wrapAlignment) { + this(0,da.getWidth()-1,0,da.getHeight()-1,showScores, + showText, + showBoxes, + wrapAlignment); + + setAlignment(da); + } + + public AlignViewport(int startRes, int endRes, + int startSeq, int endSeq, + boolean showScores, + boolean showText, + boolean showBoxes, + boolean wrapAlignment) { + + this.startRes = startRes; + this.endRes = endRes; + this.startSeq = startSeq; + this.endSeq = endSeq; + + this.showScores = showScores; + this.showText = showText; + this.showBoxes = showBoxes; + this.wrapAlignment = wrapAlignment; + + // og = new AlignmentOutputGenerator(this); + + setFont( font ); + } + + public AlignViewport(int startRes, int endRes, + int startSeq, int endSeq, + boolean showScores, + boolean showText, + boolean showBoxes, + boolean wrapAlignment, + Color backgroundColour) { + this(startRes,endRes,startSeq,endSeq,showScores,showText,showBoxes,wrapAlignment); + + this.backgroundColour = backgroundColour; + } + + + public String getVisibleConsensus() + { + return visibleConsensus; + } + + Vector consensus = new Vector(); + + public Vector getConsensus(boolean recalculate) + { + if(recalculate || consensus.size()<1) + { + consensus = alignment.getAAFrequency(); + StringBuffer sb = new StringBuffer(); + Hashtable hash = null; + for (int i = 0; i < consensus.size(); i++) + { + hash = (Hashtable) consensus.elementAt(i); + sb.append(hash.get("maxResidue").toString().charAt(0)); + } + visibleConsensus = sb.toString(); + } + + + return consensus; + } + + + public int getStartRes() { + return startRes; + } + + public int getEndRes() { + return endRes; + } + + public int getStartSeq() { + return startSeq; + } + + + 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) { + 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; + javax.swing.JFrame temp = new javax.swing.JFrame(); + 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(double w) { + this.charWidth = w; + } + public double getCharWidth() { + return charWidth; + } + public void setCharHeight(int h) { + this.charHeight = h; + } + public int getCharHeight() { + return charHeight; + } + public void setChunkWidth(int w) { + this.chunkWidth = w; + } + public int getChunkWidth() { + return chunkWidth; + } + public void setChunkHeight(int h) { + this.chunkHeight = h; + } + public int getChunkHeight() { + return chunkHeight; + } + public AlignmentI getAlignment() { + return alignment; + } + public void setAlignment(AlignmentI align) { + this.alignment = align; + } + public void setShowScores(boolean state) { + showScores = state; + } + public void setWrapAlignment(boolean state) { + wrapAlignment = state; + } + public void setShowText(boolean state) { + showText = state; + } + + public boolean getColourText() + { + return showColourText; + } + + public void setColourText(boolean state) + { + showColourText = state; + } + + public void setShowBoxes(boolean state) { + showBoxes = state; + } + public boolean getShowScores() { + return showScores; + } + public boolean getWrapAlignment() { + return wrapAlignment; + } + public boolean getShowText() { + return showText; + } + public boolean getShowBoxes() { + return showBoxes; + } + // public CommandParser getCommandLog() { + /// return log; + // } + public boolean getGroupEdit() { + return groupEdit; + } + public void setGroupEdit(boolean state) { + groupEdit = state; + } + public String getGapCharacter() { + return getAlignment().getGapCharacter(); + } + public void setGapCharacter(String 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 Selection getSelection() { + return sel; + } + public ColumnSelection getColumnSelection() { + return colSel; + } + public OutputGenerator getOutputGenerator() { + return og; + } + public void resetSeqLimits(int height) { + setStartSeq(0); + setEndSeq(height/getCharHeight()); + } + public void setCurrentTree(NJTree tree) { + currentTree = tree; + } + public NJTree getCurrentTree() { + return currentTree; + } + + public void setRenderer(RendererI rend) { + this.renderer = rend; + } + + public RendererI getRenderer() { + return renderer; + } + public int getPIDWindow() { + return window; + } + public void setPIDWindow(int window) { + this.window = window; + } + + public int getPIDBaseline() { + return baseline; + } + public void setPIDBaseline(int baseline) { + this.baseline = baseline; + } + + public void setKmers(Vector kmers) { + this.kmers = kmers; + } + + public Vector getKmers() { + return this.kmers; + } + + +} diff --git a/src/jalview/gui/AlignmentPanel.java b/src/jalview/gui/AlignmentPanel.java new file mode 100755 index 0000000..cf3e3df --- /dev/null +++ b/src/jalview/gui/AlignmentPanel.java @@ -0,0 +1,136 @@ +package jalview.gui; + +import jalview.jbgui.GAlignmentPanel; +import java.awt.*; +import javax.swing.*; +import java.awt.event.*; + +public class AlignmentPanel extends GAlignmentPanel implements AdjustmentListener +{ + + AlignViewport av; + public SeqPanel seqPanel; + public IdPanel idPanel; + public AlignFrame alignFrame; + public ScalePanel scalePanel; + public ScorePanel scorePanel; + + public boolean groupEdit = false; + + public AlignmentPanel(AlignFrame af, AlignViewport av) + { + alignFrame = af; + this.av = av; + seqPanel = new SeqPanel (av, this); + idPanel = new IdPanel (av, this); + scalePanel = new ScalePanel(av); + scorePanel = new ScorePanel(av); + + idPanelHolder.add(idPanel, BorderLayout.CENTER); + scalePanelHolder.add(scalePanel, BorderLayout.CENTER); + scorePanelHolder.add(scorePanel, BorderLayout.CENTER); + seqPanelHolder.add(seqPanel, BorderLayout.CENTER); + setScrollValues(0,0); + + hscroll.addAdjustmentListener(this); + vscroll.addAdjustmentListener(this); + selectAll(false); + + addComponentListener(new ComponentAdapter() + { + public void componentResized(ComponentEvent evt) + { RefreshPanels(); } + }); + + } + + public int countSelected() + { + return av.getSelection().size(); + } + + public void selectAll(boolean flag) { + int i = 0; + if (flag) { + while (i < seqPanel.align.getHeight()) { + if (! av.getSelection().contains(av.getAlignment().getSequenceAt(i))) { + av.getSelection().addElement(av.getAlignment().getSequenceAt(i)); + } + i++; + } + } else { + av.getSelection().clear(); + } + } + + + + public void setGraphPanelVisible(boolean b) + { + scorePanelHolder.setVisible(b); + idSpaceFillerPanel.setVisible(b); + RefreshPanels(); + } + + + + public void RefreshPanels() + { + invalidate(); + idPanelHolder.setPreferredSize( idPanel.idCanvas.getPreferredSize() ); + validate(); + idPanel.idCanvas.paintFlag = true; + seqPanel.seqCanvas.paintFlag = true; + setScrollValues(av.getStartRes(), av.getStartSeq()); + av.getConsensus(true); + repaint(); + } + + int hextent = 0; + int vextent = 0; + + public void setScrollValues(int x, int y) + { + hextent = (int)(seqPanel.seqCanvas.getWidth()/av.getCharWidth()); + vextent = seqPanel.seqCanvas.getHeight()/av.getCharHeight(); + + if(hextent+x > av.getAlignment().getWidth()) + x = av.getAlignment().getWidth()- hextent; + + if(vextent+y > av.getAlignment().getHeight()) + y = av.getAlignment().getHeight() - vextent; + + if(y<0) + y = 0; + + if(x<0) + x=0; + + hscroll.setValues(x,hextent,0,av.getAlignment().getWidth()); + vscroll.setValues(y,vextent,0,av.getAlignment().getHeight() ); + + } + + + public void adjustmentValueChanged(AdjustmentEvent evt) { + + if (evt.getSource() == hscroll) + { + int x = hscroll.getValue(); + av.setStartRes(x); + av.setEndRes(x + (int)(seqPanel.seqCanvas.getWidth()/av.getCharWidth()-1)); + } + + if (evt.getSource() == vscroll) + { + int offy = vscroll.getValue(); + av.setStartSeq(offy); + av.setEndSeq(offy + seqPanel.seqCanvas.getHeight()/av.getCharHeight()); + } + + repaint(); + } + + + +} diff --git a/src/jalview/gui/BlockRenderer.java b/src/jalview/gui/BlockRenderer.java new file mode 100755 index 0000000..1dca1c4 --- /dev/null +++ b/src/jalview/gui/BlockRenderer.java @@ -0,0 +1,136 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; +import jalview.analysis.*; +import jalview.util.*; +import java.awt.*; +import java.util.*; + +public class BlockRenderer implements RendererI { + protected Color color = Color.black; + protected Color maroon = new Color(200,0,50); + protected Color purple = new Color(255,100,255); + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i) { + Color c = cs.findColour(seq,seq.getSequence(i,i+1),i,null); + return c; + } + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector pid, int seqnum,AlignViewport av) { + +/* int i = start; + int length = seq.getLength(); + + Color currentColor = Color.white; + Vector kmers = av.getKmers(); + + g.setColor(Color.black); + + int prev = -1; + + int seqno = -1; + + for (int ii = 0; ii < av.getAlignment().getHeight(); ii++) { + if (av.getSelection().contains(av.getAlignment().getSequenceAt(ii))) { + seqno = ii; + } + } + + int blstart = start - 20; + int blend = end + 20; + + if (blstart < 0) { + blstart = 0; + } + + if (blend > av.getAlignment().getWidth()) { + blend = av.getAlignment().getWidth(); + } + + Hashtable blocks = AAFrequency.findBlocks(av.getAlignment().getSequences(), + blstart, + blend, + av.getSelection().asVector()); + + Hashtable hkmer = AlignmentUtil.findKmers(seq,blstart,blend,kmers); + + boolean inblock = false; + + int bstart = -1; + int blen = -1; + int klen = -1; + int block_end = -1; + Color bc; + + // System.out.println("Rendering " + start + " " + end); + + while (i <= blend && i < length) { + boolean foundblock = false; + + if (blocks.get(new Integer(i-blstart)) != null) { + + blen = ((Integer)blocks.get(new Integer(i-blstart))).intValue(); + + foundblock = true; + + block_end = i + blen-1; + + g.setColor(getColor(blen)); + g.fillRect(x1+(int)(width*(i-start)),y1, + (int)width+1, height/2); + } + + boolean foundKmer = false; + + if (hkmer.get(new Integer(i-blstart)) != null) { + + + klen = ((Integer)hkmer.get(new Integer(i-blstart))).intValue(); + + // System.out.println("Got kmer " + i + " " + start + " kength " + klen); + + foundKmer = true; + + g.setColor(Color.lightGray); + + if ((int)width> 5) { + g.fillRect(x1+(int)(width*(i-start)),y1+height/2, + (int)(width*klen)+1, height/2); + } else { + g.fillRect(x1+(int)(width*(i-start)),y1+height/2, + (int)(width*klen)+1, height/2); + + } + + } + + if (width > 5) { + g.setColor(Color.black); + g.drawString(seq.getSequence().substring(i,i+1),x1+(int)(width*(i-start)),y1+height); + } + i++; + }*/ + } + + public Color getColor(int blen) { + + Color bc; + + if (blen > 20 ) { + bc = Color.yellow; + }else if (blen > 10) { + bc = Color.red; + } else if (blen > 5) { + bc = Color.blue; + } else if (blen > 2) { + bc = purple; + } else if (blen == 2) { + bc = Color.orange; + + } else { + bc = Color.lightGray; + } + return bc; + } +} diff --git a/src/jalview/gui/ColourKey.java b/src/jalview/gui/ColourKey.java new file mode 100755 index 0000000..4dd62a2 --- /dev/null +++ b/src/jalview/gui/ColourKey.java @@ -0,0 +1,240 @@ +package jalview.gui; + +import jalview.jbgui.GColourKey; +import jalview.schemes.*; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + +public class ColourKey extends GColourKey +{ + + Color midBlue = new Color(100,100,255); + public ColourKey(ColourSchemeI current) + { + if(current==null) + zappoMenuItem_actionPerformed(null); + + else if(current instanceof Blosum62ColourScheme) + blosumMenuItem_actionPerformed(null); + + else if(current instanceof BuriedColourScheme) + buriedMenuItem_actionPerformed(null); + +// else if(current instanceof ClustalxColourScheme) + // cl + else if(current instanceof HelixColourScheme) + helixMenuItem_actionPerformed(null); + + else if(current instanceof HydrophobicColourScheme) + hydroMenuItem_actionPerformed(null); + + else if(current instanceof StrandColourScheme) + strandMenuItem_actionPerformed(null); + + else if(current instanceof TaylorColourScheme) + taylorMenuItem_actionPerformed(null); + + else if(current instanceof TurnColourScheme) + turnMenuItem_actionPerformed(null); + + else // default + zappoMenuItem_actionPerformed(null); + } + + void displayKey(String [] residue, String [] description, Color [] colour, String comment) + { + this.getContentPane().removeAll(); + + for(int i=0; i 80 % Mid blue +> 60 % Light blue +> 40 % Light grey +<= 40% White +*/ + + + + + + + + + + + + + + diff --git a/src/jalview/gui/ColumnSelection.java b/src/jalview/gui/ColumnSelection.java new file mode 100755 index 0000000..d6eae09 --- /dev/null +++ b/src/jalview/gui/ColumnSelection.java @@ -0,0 +1,75 @@ +package jalview.gui; + +import java.util.*; + +/** + * NOTE: Columns are zero based. + */ +public class ColumnSelection { + Vector selected = new Vector(); + + public void addElement(int col) { + selected.addElement(new Integer(col)); + } + + public void clear() { + selected.removeAllElements(); + } + + public void removeElement(int col) { + Integer colInt = new Integer(col); + if (selected.contains(colInt)) { + selected.removeElement(colInt); + } else { + System.err.println("WARNING: Tried to remove Integer NOT in ColumnSelection"); + } + } + + public boolean contains(int col) { + return selected.contains(new Integer(col)); + } + + public int columnAt(int i) { + return ((Integer)selected.elementAt(i)).intValue(); + } + + public int size() { + return selected.size(); + } + + public int getMax() { + int max = -1; + + for (int i=0;i max) { + max = columnAt(i); + } + } + return max; + } + + public int getMin() { + int min = 1000000000; + + for (int i=0;i= start) { + selected.setElementAt(new Integer(temp-change),i); + } + } + } +} diff --git a/src/jalview/gui/CpGRenderer.java b/src/jalview/gui/CpGRenderer.java new file mode 100755 index 0000000..b5dc128 --- /dev/null +++ b/src/jalview/gui/CpGRenderer.java @@ -0,0 +1,87 @@ +package jalview.gui; +import jalview.datamodel.*; +import jalview.schemes.*; +import jalview.util.*; +import jalview.analysis.*; +import java.awt.*; +import java.awt.geom.*; +import java.util.*; + +public class CpGRenderer implements RendererI { + protected Color color = Color.black; + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i) { + Color c = cs.findColour(seq,seq.getSequence(i,i+1),i,null); + return c; + } + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector pid, int seqnum,AlignViewport av) { + + int i = start; + int length = seq.getLength(); + + Color currentColor = Color.white; + + g.setColor(Color.black); + + int window = 1000; + int max = window/5; + + int step = window/10; + + if (step > window) { + step = window; + } + + if (window < 2) { + window = 2; + step = 1; + } + + int cpgstart = start; + int cpgend = end; + + if (cpgstart <= window/2 ) { + cpgstart = window/2; + } + if (cpgend+window/2 >= length) { + cpgend = length-window/2; + } + + Hashtable vals = AAFrequency.findKmerCount(seq,cpgstart,cpgend,window,step,av.getKmers()); + + Enumeration en = vals.keys(); + + Vector valset = new Vector(); + + while (en.hasMoreElements()) { + valset.add((Integer)en.nextElement()); + } + Collections.sort(valset); + + g.setColor(Color.black); + + int j = 0; + + while (j < valset.size()) { + + Integer posInt = (Integer)valset.elementAt(j); + int count = ((Integer)vals.get(posInt)).intValue(); + int pos = posInt.intValue(); + + if (count > 40) { + g.setColor(Color.red); + } else { + g.setColor(Color.black); + } + + g.fillRect(x1 + (int)(width*(pos-start-width/2)), + y1+height - (int)(count*height/max), + (int)(step*width), + (int)(count*height/max)); + + j++; + } + } + +} diff --git a/src/jalview/gui/CutAndPasteTransfer.java b/src/jalview/gui/CutAndPasteTransfer.java new file mode 100755 index 0000000..67bce4a --- /dev/null +++ b/src/jalview/gui/CutAndPasteTransfer.java @@ -0,0 +1,55 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.gui; + +import jalview.jbgui.GCutAndPasteTransfer; +import java.awt.*; + +public class CutAndPasteTransfer extends GCutAndPasteTransfer +{ + public CutAndPasteTransfer(boolean forImport) + { + super(); + for (int i = 0; i < jalview.io.FormatProperties.getFormats().size(); i++) { + formatChoice.addItem((String)jalview.io.FormatProperties.getFormats().elementAt(i)); + } + + + if(forImport) + { + formatLabel.setVisible(false); + formatChoice.setVisible(false); + textarea.setBounds(new Rectangle(9, 6, 383, 284)); + } + } + + // this method is called once the user has selected an output format + public void formatForOutput() + { + textarea.setFont(new Font("Monospaced", Font.PLAIN, 12)); + setLayout(new BorderLayout()); + add(scrollPane, BorderLayout.CENTER); + remove(formatLabel); + remove(formatChoice); + } + + public String getFormat() + { + return formatChoice.getSelectedItem().toString(); + } + public String getText() + { + return textarea.getText(); + } + + public void setText(String text) + { + textarea.setText(text); + } +} diff --git a/src/jalview/gui/Desktop.java b/src/jalview/gui/Desktop.java new file mode 100755 index 0000000..f92f01c --- /dev/null +++ b/src/jalview/gui/Desktop.java @@ -0,0 +1,222 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + + +package jalview.gui; + +import jalview.gui.*; +import jalview.io.*; +import jalview.datamodel.*; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + +public class Desktop extends jalview.jbgui.GDesktop +{ + public static JDesktopPane desktop; + static int openFrameCount = 0; + static final int xOffset = 30, yOffset = 30; + + public Desktop() + { + try{ + java.net.URL url = getClass().getResource("/BartonGroupBanner.gif"); + if(url!=null) + { + Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url); + MediaTracker mt = new MediaTracker(this); + mt.addImage(image, 0); + mt.waitForID(0); + setIconImage(image); + } + + }catch(Exception ex){} + + setTitle("Jalview 2005"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setVisible(true); + desktop = new JDesktopPane(); + setContentPane(desktop); + desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); + int inset = 150; + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + setBounds(inset, inset, + screenSize.width - inset*2, + screenSize.height - inset*2); + } + + public static void addInternalFrame(final JInternalFrame frame, String title, int w, int h) + { + frame.setVisible(true); //necessary as of 1.3 + desktop.add(frame); + openFrameCount++; + try { + frame.setSelected(true); + } catch (java.beans.PropertyVetoException e) {} + frame.setTitle(title); + frame.setResizable(true); + frame.setSize(w,h); + frame.setClosable(true); + frame.setMaximizable(true); + frame.setIconifiable(true); + frame.setLocation(xOffset*openFrameCount, yOffset*openFrameCount); + frame.toFront(); + final JMenuItem menuItem = new JMenuItem(title); + frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() + { public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) + { + openFrameCount--; + windowMenu.remove(menuItem); + }; + }); + + menuItem.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + try{ frame.setSelected(true); frame.setIcon(false); } + catch(java.beans.PropertyVetoException ex){}; + } + }); + + windowMenu.add(menuItem); + } + + + + public void inputLocalFileMenuItem_actionPerformed(ActionEvent e) + { + JFileChooser chooser = new JFileChooser(jalview.bin.Cache.LAST_DIRECTORY); + chooser.setDialogTitle("Open local file"); + chooser.setToolTipText("Open"); + int value = chooser.showOpenDialog(this); + if(value == JFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.bin.Cache.LAST_DIRECTORY = choice; + String format = IdentifyFile.Identify(choice, "File"); + LoadFile(choice, "File", format); + } + } + + public void LoadFile(String file, String protocol, String format) + { + SequenceI [] sequences = null; + + + if (FormatProperties.contains(format)) + sequences = FormatAdapter.read(file, protocol, format); + + if (sequences != null) + { + AlignFrame af = new AlignFrame(new Alignment(sequences)); + addInternalFrame(af, file, 700, 500); + af.statusBar.setText("Successfully loaded file " + file); + } + else + JOptionPane.showMessageDialog(this, "Couldn't open file.\n" + + "Formats currently supported are\n" + + "Fasta, MSF, Clustal, BLC, PIR, MSP or PFAM" + ,"Error loading file", + JOptionPane.WARNING_MESSAGE); + + } + + public void inputURLMenuItem_actionPerformed(ActionEvent e) + { + String url = JOptionPane.showInputDialog(this,"Enter url of input file", + "Input alignment from URL", + JOptionPane.QUESTION_MESSAGE); + if (url == null) + return; + + String format = IdentifyFile.Identify(url, "URL"); + + System.out.println(format +" format"); + if (format.equals("URL NOT FOUND")) + { + JOptionPane.showMessageDialog(this,"Couldn't locate " + url, + "URL not found", + JOptionPane.WARNING_MESSAGE); + return; + } + + LoadFile(url, "URL", format); + } + + public void inputTextboxMenuItem_actionPerformed(ActionEvent e) + { + CutAndPasteTransfer cap = new CutAndPasteTransfer(true); + int accept = JOptionPane.showInternalOptionDialog(desktop, cap, "Cut & paste Alignment File", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + null, + new Object[]{"Accept", "Cancel", }, null); + + + if(accept == JOptionPane.YES_OPTION) + { + String format = IdentifyFile.Identify(cap.getText(), "Paste"); + SequenceI [] sequences = null; + + if (FormatProperties.contains( format )) + sequences = FormatAdapter.read(cap.getText(), "Paste", format); + + + if(sequences!=null) + { + AlignFrame af = new AlignFrame(new Alignment(sequences)); + addInternalFrame(af, "Cut & Paste input - "+format, 700, 500); + af.statusBar.setText("Successfully pasted alignment file"); + } + else + JOptionPane.showMessageDialog(this, "Couldn't read the pasted text.\n" + +"Formats currently supported are\n" + +"Fasta, MSF, Clustal, BLC, PIR, MSP or PFAM", + "Error parsing text", JOptionPane.WARNING_MESSAGE); + + + } + } + +/* +* Exit the program +*/ + public void quit_actionPerformed(ActionEvent e) + { + this.setVisible(false); + System.exit(0); + } + + + protected void colourIndexMenuItem_actionPerformed(ActionEvent e) + { + ColourKey colourKey = new ColourKey(null); + addInternalFrame(colourKey, "Colour scheme key", 400, 320); + } + + + public void aboutMenuItem_actionPerformed(ActionEvent e) + { + JOptionPane.showInternalMessageDialog(desktop, + "Jalview 1998-2005\n" + +"Sequence Alignment viewer & editor", + "About Jalview", + JOptionPane.INFORMATION_MESSAGE); + } + + public void documentationMenuItem_actionPerformed(ActionEvent e) + { + try{ + jalview.util.BrowserLauncher.openURL("http://jalview.org/documentation.html"); + }catch(Exception ex){} + } + + +} diff --git a/src/jalview/gui/DrawableSequence.java b/src/jalview/gui/DrawableSequence.java new file mode 100755 index 0000000..8b7015b --- /dev/null +++ b/src/jalview/gui/DrawableSequence.java @@ -0,0 +1,204 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; +import jalview.analysis.*; +import java.awt.*; + +public class DrawableSequence implements SequenceI { + protected boolean fastDraw = true; + + protected Color color = Color.black; + + protected SequenceI sequence; + + ColourSchemeI cs = new ZappoColourScheme(); + + public DrawableSequence(SequenceI s) { + this.sequence = s; + + _init(); + } + + public DrawableSequence(String name,String seq, int start, int end) { + sequence = new Sequence(name,seq,start,end); + + _init(); + } + + private void _init() { + + } + + public void setColourScheme(ColourSchemeI cs) { + this.cs = cs; + } + + public Color getResidueBoxColour(int i) { + Color c = cs.findColour(this,sequence.getSequence(i,i+1),i,null); + return c; + } + + public void drawSequence(Graphics g,int start, int end, int x1, int y1, int width, int height,boolean showScores, boolean displayBoxes, boolean displayText) { + + if (displayBoxes == true) { + drawBoxes(g,start,end,x1,y1,width, height); + } + if (displayText == true) { + drawText(g,start,end,x1,y1,width,height); + } + } + + public void drawBoxes(Graphics g,int start, int end, int x1, int y1, int width, int height) { + int i = start; + int length = getSequence().length(); + + Color currentColor = Color.white; + + int curStart = x1; + int curWidth = width; + + while (i <= end && i < length) { + Color c = getResidueBoxColour(i); + + if (c != currentColor || c != null) { + g.fillRect(x1+width*(curStart-start),y1,curWidth,height); + + currentColor = c; + g.setColor(c); + + curStart = i; + curWidth = width; + } else { + curWidth += width; + } + + i++; + } + g.fillRect(x1+width*(curStart-start),y1,curWidth,height); + } + + public void drawText(Graphics g, int start, int end, int x1, int y1, int width, int height) { + int pady = 2; + g.setColor(Color.black); +System.out.println("drawablesequence is drawing"); + // Need to find the sequence position here. + + if (fastDraw) { + String s; + if (end < getSequence().length()) { + s = getSequence().substring(start,end+1); + } else { + s = getSequence().substring(start); + } + System.out.println(s+" "+x1+" "+y1); + g.drawString(s,x1,y1+height-pady); + } else { + + for (int i=start; i <= end; i++) { + String s = ""; + + if (i < end && i < getSequence().length()) { + s = getSequence().substring(i,i+1); + } else { + s = getSequence().substring(i,i+1); + } + + + g.drawString(s,x1+width*(i-start),y1+height-pady); + } + + } + } + + + public int getPosition(int res) { + + return res; + } + + public int getResidue(int pos) { + + return pos; + } + + // SequenceI methods + + public void setName(String name) { + sequence.setName(name); + } + public String getName() { + return sequence.getName(); + } + public String getDisplayId() { + return sequence.getDisplayId(); + } + + public void setStart(int start) { + sequence.setStart(start); + } + public int getStart() { + return sequence.getStart(); + } + + public void setEnd(int end) { + sequence.setEnd(end); + } + public int getEnd() { + return sequence.getEnd(); + } + + public int getLength() { + return sequence.getLength(); + } + + public void setSequence(String seq) { + sequence.setSequence(seq); + } + public String getSequence() { + return sequence.getSequence(); + } + public String getSequence(int start,int end) { + return sequence.getSequence(start,end); + } + public char getCharAt(int i) { + return sequence.getCharAt(i); + } + + public void setDescription(String desc) { + sequence.setDescription(desc); + } + public String getDescription() { + return sequence.getDescription(); + } + + public int findIndex(int pos) { + return sequence.findIndex(pos); + } + public int findPosition(int i) { + return sequence.findPosition(i); + } + + + public void deleteCharAt(int i) { + sequence.deleteCharAt(i); + } + + public void insertCharAt(int i,char c) { + sequence.insertCharAt(i,c); + + } + + public void insertCharAt(int i,char c,boolean chop) { + sequence.insertCharAt(i,c,chop); + + } + public Color getColor() { + return this.color; + } + + public void setColor(Color c) { + this.color = c; + } + +} diff --git a/src/jalview/gui/FeatureRenderer.java b/src/jalview/gui/FeatureRenderer.java new file mode 100755 index 0000000..cd754c7 --- /dev/null +++ b/src/jalview/gui/FeatureRenderer.java @@ -0,0 +1,85 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; +import java.awt.*; +import java.util.*; + +public class FeatureRenderer implements RendererI { + + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i) { + Color c = cs.findColour(seq,seq.getSequence(i,i+1),i,null); + return c; + } + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector pid, int seqnum,AlignViewport av) { + + int i = start; + int length = seq.getLength(); + + Color currentColor = Color.black; + + + int prev = -1; + int fstart = 0; + char prevc = '-'; + + g.setColor(Color.magenta); + + while (i <= end && i < length) { + char c = seq.getCharAt(i); + if (c != '-') { + + if (prevc != c) { + + if (prevc == 'F') { + g.setColor(Color.green); + } else if (prevc == 'R') { + g.setColor(Color.cyan); + } else if (prevc == 'M') { + g.setColor(Color.magenta); + } else if (prevc == 'P') { + g.setColor(Color.yellow); + } + g.fillRect(x1+(int)(width*(i-fstart)),y1+height/4,(int)((prev-fstart+1)*width),height/2); + + prevc = c; + fstart = i; + } + } else if (prevc != '-') { + if (prevc == 'F') { + g.setColor(Color.green); + } else if (prevc == 'R') { + g.setColor(Color.cyan); + } else if (prevc == 'M') { + g.setColor(Color.magenta); + } else if (prevc == 'P') { + g.setColor(Color.yellow); + } + g.fillRect(x1+(int)(width*(fstart-start)),y1+height/4,(int)((i-fstart+1)*width),height/2); + + prevc = c; + } else { + fstart = -1; + } + i++; + } + + if (fstart != -1) { + if (prevc == 'F') { + g.setColor(Color.green); + } else if (prevc == 'R') { + g.setColor(Color.cyan); + } else if (prevc == 'M') { + g.setColor(Color.magenta); + } else if (prevc == 'P') { + g.setColor(Color.yellow); + } + + //g.fillRect(x1+(int)(width*(fstart-start)),y1+height/4,(int)((end-fstart+1)*width),height/2); + + } + } + +} diff --git a/src/jalview/gui/GraphRenderer.java b/src/jalview/gui/GraphRenderer.java new file mode 100755 index 0000000..e7d1757 --- /dev/null +++ b/src/jalview/gui/GraphRenderer.java @@ -0,0 +1,128 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; +import jalview.util.*; + +import java.awt.*; +import java.awt.geom.*; +import java.util.*; + +public class GraphRenderer implements RendererI { + protected Color color = Color.black; + protected Color maroon = new Color(200,0,50); + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i) { + Color c = cs.findColour(seq,seq.getSequence(i,i+1),i,null); + return c; + } + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector pid, int seqnum,AlignViewport av) { + + int i = start; + int length = seq.getLength(); + + Color currentColor = Color.white; + + g.setColor(Color.black); + + int prev = -1; + + while (i <= end && i < length) { + char c = seq.getCharAt(i); + + if (c != '-') { + Vector values = (Vector)pid.elementAt(i-start); + int val = ((Integer)values.elementAt(seqnum)).intValue(); + + int frac = (int)(100*val/(av.getPIDWindow()+1)); + +// if (frac > 95) { + // g.setColor(maroon); + // } else if (frac > 90) { +// g.setColor(Color.red); +// } else if (frac > 80) { +// g.setColor(Color.orange); +// } else if (frac > 70) { +// g.setColor(Color.pink); +// } else if (frac > 50) { +// g.setColor(Color.yellow); +// } else if (frac > 30) { +// g.setColor(Color.lightGray); +// } + + int baseline = av.getPIDBaseline(); + + frac -= baseline; + + if (frac < 0) { + frac = 0; + } + if (baseline == 100) { + baseline = 99; + } + + Graphics2D g2d = (Graphics2D)g; + + g2d.setColor(new Color(255*frac/(100-baseline),50*frac/(100-baseline),50*frac/(100-baseline))); + + //g.setColor(new Color(255*frac/(100-baseline),50*frac/(100-baseline),255-50*frac/(100-baseline))); + //g.fillRect(x1+(int)(width*(i-start)),y1+height - (int)(frac*height/(100-baseline)), + //width, (int)(frac*height/(100-baseline))); + + int[] xpoints = new int[4]; + int[] ypoints = new int[4]; + + if (prev == -1) { + prev = y1 + height - (int)(frac*height/(100-baseline)); + } + + // 1----2 + // | | + // 4----3 + + xpoints[0] = (x1+ (int)(width*(i-start))); + ypoints[0] = prev; + + xpoints[1] = (x1 + (int)(width*(i-start+1))); + ypoints[1] = y1 + height - (int)(frac*height/(100-baseline)); + + xpoints[3] = (x1 + (int)(width*(i-start)));; + ypoints[3] = y1 + height; + + xpoints[2] = (x1 + (int)(width*(i-start+1))); + ypoints[2] = y1 + height; + + Polygon poly = new Polygon(); + + poly.xpoints = xpoints; + poly.ypoints = ypoints; + poly.npoints = 4; + + g2d.fill(poly); + + if (width > 5) { + g.setColor(Color.black); + g.drawString(seq.getSequence().substring(i,i+1),x1+(int)(width*(i-start)),y1+height); + } else { + g.setColor(Color.black); + + if (prev != -1) { + + g.drawLine(x1+(int)(width*(i-start)-width/2), prev, + x1+(int)(width*(i-start+1)-width/2),y1+height - (int)(frac*height/(100-baseline))); + } else { + g.drawLine(x1+(int)(width*(i-start)), y1+height - (int)(frac*height/(100-baseline)), + x1+(int)(width*(i-start+1)),y1+height - (int)(frac*height/(100-baseline))); + } + + } + prev = ypoints[1]; + } else { + prev = -1; + } + i++; + } + } + +} diff --git a/src/jalview/gui/IdCanvas.java b/src/jalview/gui/IdCanvas.java new file mode 100755 index 0000000..03b85e4 --- /dev/null +++ b/src/jalview/gui/IdCanvas.java @@ -0,0 +1,231 @@ +package jalview.gui; + +import java.awt.*; +import javax.swing.*; +import jalview.datamodel.*; +import jalview.analysis.*; +public class IdCanvas extends JPanel +{ + protected Image img; + protected Graphics gg; + + protected int imgWidth; + protected int imgHeight; + + protected AlignViewport av; + + public boolean paintFlag = false; + protected boolean showScores = true; + + protected int maxIdLength = -1; + protected String maxIdStr = null; + + public IdCanvas(AlignViewport av) + { + setLayout(new BorderLayout()); + this.av = av; + PaintRefresher.Register(this); + } + + public void drawIdString(Graphics g,SequenceI ds,int i, int starty, int ypos) { + int charHeight = av.getCharHeight(); + + if (av.getSelection().contains(ds)) { + gg.setColor(Color.gray); + gg.fillRect(0,AlignmentUtil.getPixelHeight(starty,i,charHeight)+ ypos,getWidth(),charHeight); + gg.setColor(Color.white); + } else { + gg.setColor(ds.getColor()); + gg.fillRect(0,AlignmentUtil.getPixelHeight(starty,i,charHeight)+ ypos,getWidth(),charHeight); + gg.setColor(Color.black); + } + + String string = ds.getName() + "/" + ds.getStart() + "-" + ds.getEnd(); + + gg.drawString(string,0,AlignmentUtil.getPixelHeight(starty,i,charHeight) + ypos + charHeight/2); + + } + + public void paintComponent(Graphics g) { + AlignmentI da = av.getAlignment(); + int charWidth = (int)av.getCharWidth(); + int charHeight = av.getCharHeight(); + Font f = av.getFont(); + + if (img == null || + imgWidth != getWidth() || + imgHeight != getHeight() || + paintFlag == true) { + + imgWidth = getWidth(); + imgHeight = getHeight(); + + if (imgWidth <= 0 ) { + imgWidth = 700; + } + if (imgHeight <= 0 ) { + imgHeight = 500; + } + + img = createImage(imgWidth,imgHeight); + + gg = img.getGraphics(); + gg.setColor(Color.white); + gg.fillRect(0,0,imgWidth,imgHeight); + + gg.setFont(f); + + paintFlag = false; + + } + + + //Fill in the background + gg.setColor(Color.white); + gg.fillRect(0,0,imgWidth,imgHeight); + + Color currentColor = Color.white; + Color currentTextColor = Color.black; + + //Which ids are we printing + int starty = av.getStartSeq(); + int endy = av.getEndSeq(); + + + + if (av.getWrapAlignment()) { + starty = starty%av.getChunkHeight(); + + int ypos = 0; + int rowstart = starty; + + if (starty == 0) { + ypos = 2*charHeight; + } else if (starty == 1) { + starty = 0; + ypos = charHeight; + } + + endy = starty + da.getHeight(); + + if (endy > da.getHeight()) { + endy = da.getHeight(); + } + + for (int i = starty; i < endy; i++) { + SequenceI s = da.getSequenceAt(i); + drawIdString(gg,s,i,starty,ypos); + } + if (rowstart == 0) { + ypos = ypos + av.getChunkHeight(); + } else if (rowstart == 1) { + ypos = ypos + av.getChunkHeight(); + } else { + ypos = ypos + av.getChunkHeight() - rowstart*charHeight; + } + + starty = 0; + + int chunkwidth = av.getChunkWidth(); + int startx = (int)(av.getEndSeq()/chunkwidth)*chunkwidth; + int endx = startx + chunkwidth; + + + while (ypos <= getHeight() && endx < da.getWidth()) { + + for (int i = starty; i < endy; i++) { + SequenceI s = da.getSequenceAt(i); + drawIdString(gg,s,i,starty,ypos); + } + + ypos += av.getChunkHeight(); + startx += chunkwidth; + endx = startx + chunkwidth; + + if (endx > da.getWidth()) { + endx = da.getWidth(); + } + + starty = 0; + + if (endy > da.getHeight()) { + endy = da.getHeight(); + } + + } + } else { + + //Now draw the id strings + for (int i = starty; i < endy; i++) + { + + // Selected sequence colours + + if (av.getSelection().contains(da.getSequenceAt(i))) { + if (currentColor != Color.gray) { + currentColor = Color.gray; + currentTextColor = Color.black; + } + } else if (da.getSequenceAt(i).getColor() != null) + { + currentColor = Color.white; + /* Color newcol = da.getSequenceAt(i).getColor(); + if (newcol != currentColor) { + currentColor = newcol; + if (newcol == Color.black) { + currentTextColor = Color.white; + } else { + currentTextColor = Color.black; + } + }*/ + } + + gg.setColor(currentColor); + + if (currentColor != Color.white) { + gg.fillRect(0, + AlignmentUtil.getPixelHeight(starty,i,charHeight), + getWidth(), + charHeight); + } + + gg.setColor(currentTextColor); + + String string = da.getSequenceAt(i).getDisplayId(); + + gg.drawString(string,0,AlignmentUtil.getPixelHeight(starty,i,charHeight) + charHeight- (charHeight/5)); + } + } + + g.drawImage(img,0,0,this); + } + + + public Dimension getLabelWidth() + { + + FontMetrics fm = this.getGraphics().getFontMetrics(av.font); + AlignmentI al = av.getAlignment(); + + int i = 0; + int idWidth = 0; + + while (i < al.getHeight() && al.getSequenceAt(i) != null) + { + SequenceI s = al.getSequenceAt(i); + String str = s.getDisplayId(); + if (fm.stringWidth(str) > idWidth) + idWidth = fm.stringWidth(str); + i++; + } + + return new Dimension(idWidth + 10,getHeight()); + } + + public Dimension getPreferredSize() + { + return getLabelWidth(); + } + + +} diff --git a/src/jalview/gui/IdPanel.java b/src/jalview/gui/IdPanel.java new file mode 100755 index 0000000..26d4199 --- /dev/null +++ b/src/jalview/gui/IdPanel.java @@ -0,0 +1,126 @@ +package jalview.gui; + +import java.awt.*; +import java.awt.event.*; + +import jalview.datamodel.*; + +import javax.swing.*; + +public class IdPanel extends JPanel implements MouseListener, MouseMotionListener { + + protected IdCanvas idCanvas; + protected AlignViewport av; + protected AlignmentPanel alignPanel; + + protected int offy; + public int width; + public int lastid; + + + + boolean mouseDown; + boolean mouseUp; + + public IdPanel(AlignViewport av, AlignmentPanel parent) + { + this.av = av; + alignPanel = parent; + idCanvas = new IdCanvas(av); + setLayout(new BorderLayout()); + add(idCanvas, BorderLayout.CENTER); + addMouseListener(this); + addMouseMotionListener(this); + } + + public void mouseMoved(MouseEvent e) {} + + public void selectSeqs(int start, int end) { + if (end < start) { + int tmp = start; + start = end; + end = tmp; + } + + for (int i = start; i <= end; i++) { + SequenceI pickedSeq = av.getAlignment().getSequenceAt(i); + + if (av.getSelection().contains(pickedSeq)) { + av.getSelection().removeElement(pickedSeq); + } else { + av.getSelection().addElement(pickedSeq); + } + } + + repaint(); + + } + + public void mouseDragged(MouseEvent e) { + int y = e.getY(); + + int seq = av.getIndex(y); + + if (mouseDown == true) { + if (seq < lastid) { + selectSeqs(lastid-1,seq); + } else if (seq > lastid) { + selectSeqs(lastid+1,seq); + } + lastid = seq; + } + + return; + } + + public void mouseClicked(MouseEvent e) { } + public void mouseEntered(MouseEvent e) { } + public void mouseExited (MouseEvent e) { } + + public void mousePressed(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + + int seq = av.getIndex(y); + + mouseDown = true; + + if( javax.swing.SwingUtilities.isRightMouseButton(e)) + { + String id = av.getAlignment().getSequenceAt(seq).getName(); + String s = (String)JOptionPane.showInputDialog( + this, + "Edit sequence name", + "Edit sequence name", + JOptionPane.PLAIN_MESSAGE, + null, + null, + id); + + if(s!=null) + { + av.getAlignment().getSequenceAt(seq).setName(s); + alignPanel.RefreshPanels(); + } + + } + else + { + if (seq != -1) + selectSeqs(seq,seq); + + lastid = seq; + } + return; + } + + public void mouseReleased(MouseEvent e) { + lastid = -1; + + mouseDown = false; + mouseUp = true; + + PaintRefresher.Refresh(this); + + } +} diff --git a/src/jalview/gui/PCAPanel.java b/src/jalview/gui/PCAPanel.java new file mode 100755 index 0000000..97df517 --- /dev/null +++ b/src/jalview/gui/PCAPanel.java @@ -0,0 +1,112 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.analysis.PCA; +import jalview.jbgui.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; + + +public class PCAPanel extends GPCAPanel implements Runnable +{ + PCA pca; + int top; + RotatableCanvas rc; + AlignViewport av; + + public void run() + { + // do stuff + } + + public PCAPanel(AlignViewport av, SequenceI[] s) { + + this.av = av; + if(s==null) + { + s = new Sequence[av.getAlignment().getHeight()]; + for (int i = 0; i < av.getAlignment().getHeight(); i++) + s[i] = av.getAlignment().getSequenceAt(i); + } + +//////////////////////This part was done in PCATHread originally. Is it too slow??? + pca = new PCA(s); + pca.run(); + + // Now find the component coordinates + int ii=0; + while (ii < s.length && s[ii] != null) + { + ii++; + } + + double[][] comps = new double[ii][ii]; + + for (int i=0; i < ii; i++ ) + { + if (pca.getEigenvalue(i) > 1e-4) + { + comps[i] = pca.component(i); + } + } + + ////////////////// + + xCombobox.setSelectedIndex(0); + yCombobox.setSelectedIndex(1); + zCombobox.setSelectedIndex(2); + + top = pca.getM().rows-1; + + Vector points = new Vector(); + float[][] scores = pca.getComponents(top-1,top-2,top-3,100); + + for (int i =0; i < pca.getM().rows; i++ ) { + SequencePoint sp = new SequencePoint(s[i],scores[i]); + points.addElement(sp); + } + rc = new RotatableCanvas(av,points,pca.getM().rows); + + //rc.printPoints(); + + add(rc, BorderLayout.CENTER); + } + + + void doDimensionChange() + { + if(top==0) + return; + + int dim1 = top - xCombobox.getSelectedIndex(); + int dim2 = top - yCombobox.getSelectedIndex(); + int dim3 = top - zCombobox.getSelectedIndex(); + + float[][] scores = pca.getComponents(dim1,dim2,dim3,100); + for (int i=0; i < pca.getM().rows; i++) { + ((SequencePoint)rc.points.elementAt(i)).coord = scores[i]; + } + + rc.img = null; + rc.rotmat.setIdentity(); + rc.initAxes(); + rc.paint(rc.getGraphics()); + } + + protected void xCombobox_actionPerformed(ActionEvent e) + { + doDimensionChange(); + } + + protected void yCombobox_actionPerformed(ActionEvent e) + { + doDimensionChange(); + } + + protected void zCombobox_actionPerformed(ActionEvent e) + { + doDimensionChange(); + } + +} diff --git a/src/jalview/gui/PaintRefresher.java b/src/jalview/gui/PaintRefresher.java new file mode 100755 index 0000000..051721b --- /dev/null +++ b/src/jalview/gui/PaintRefresher.java @@ -0,0 +1,35 @@ +package jalview.gui; +import java.awt.*; +import java.util.*; + +public class PaintRefresher +{ + static Vector containers = new Vector(); + + public static void Register(Container c) + { + if(!containers.contains(c)) + containers.add(c); + else + containers.remove(c); + } + + public static void Refresh(Container c) + { + Container temp; + Enumeration e = containers.elements(); + while( e.hasMoreElements() ) + { + temp = (Container)e.nextElement(); + + if(!temp.isValid()) + containers.removeElement( temp ); + else if( temp == c ) + continue; + + temp.repaint(); + } + + } + +} diff --git a/src/jalview/gui/PairwiseAlignPanel.java b/src/jalview/gui/PairwiseAlignPanel.java new file mode 100755 index 0000000..c771693 --- /dev/null +++ b/src/jalview/gui/PairwiseAlignPanel.java @@ -0,0 +1,73 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.jbgui.GPairwiseAlignPanel; +import jalview.analysis.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.*; + + +public class PairwiseAlignPanel extends GPairwiseAlignPanel +{ + Vector sequences = new Vector(); + AlignViewport av; + + public PairwiseAlignPanel(AlignViewport av) + { + super(); + this.av = av; + float scores[][] = new float[av.getAlignment().getHeight()][av.getAlignment().getHeight()]; + double totscore = 0; + int count = av.getSelection().size(); + + int acount = 0; + for (int i = 1; i < count; i++) + { + for (int j = 0; j < i; j++) + { + acount++; + AlignSeq as = new AlignSeq(av.getSelection().sequenceAt(i),av.getSelection().sequenceAt(j),"pep"); + //tf.status.setText("Aligning " + as.getS1().getName() + " and " + as.getS2().getName() + " (" + acount + "/" + (count*(count-1)/2) + ")"); + + as.calcScoreMatrix(); + as.traceAlignment(); + as.printAlignment(); + scores[i][j] = (float)as.getMaxScore()/(float)as.getASeq1().length; + totscore = totscore + scores[i][j]; + + textarea.append(as.getOutput()); + sequences.add( as.getS1() ); + sequences.add( as.getS2() ); + + } + } + + if (count > 2) + { + for (int i = 0; i < count;i++) + for (int j = 0; j < i; j++) + jalview.util.Format.print(System.out,"%7.3f",scores[i][j]/totscore); + } + } + + + protected void viewInEditorButton_actionPerformed(ActionEvent e) + { + + Sequence [] seq = new Sequence[sequences.size()]; + + for (int i=0;i500) + newHeight=500; + + Desktop.addInternalFrame(af, "Pairwise Aligned Sequences", 700,newHeight); + + } + +} diff --git a/src/jalview/gui/RendererI.java b/src/jalview/gui/RendererI.java new file mode 100755 index 0000000..81c5612 --- /dev/null +++ b/src/jalview/gui/RendererI.java @@ -0,0 +1,14 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; +import java.awt.*; +import java.util.*; + +public interface RendererI { + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i); + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector pid, int seqnum,AlignViewport av); + +} diff --git a/src/jalview/gui/RotatableCanvas.java b/src/jalview/gui/RotatableCanvas.java new file mode 100755 index 0000000..90688d0 --- /dev/null +++ b/src/jalview/gui/RotatableCanvas.java @@ -0,0 +1,514 @@ +package jalview.gui; + +import jalview.math.*; +import jalview.datamodel.*; +import jalview.util.*; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.*; + + +public class RotatableCanvas extends JPanel implements MouseListener, + MouseMotionListener, + KeyListener + //RubberbandListener, + //SequenceSelectionListener +{ + RotatableMatrix idmat = new RotatableMatrix(3,3); + RotatableMatrix objmat = new RotatableMatrix(3,3); + RotatableMatrix rotmat = new RotatableMatrix(3,3); + + //RubberbandRectangle rubberband; + + boolean drawAxes = true; + + int omx = 0; + int mx = 0; + int omy = 0; + int my = 0; + + Image img; + Graphics ig; + + Dimension prefsize; + + float centre[] = new float[3]; + float width[] = new float[3]; + + float max[] = new float[3]; + float min[] = new float[3]; + + float maxwidth; + float scale; + + int npoint; + + Vector points; + float[][] orig; + float[][] axes; + + int startx; + int starty; + + int lastx; + int lasty; + + int rectx1; + int recty1; + int rectx2; + int recty2; + + float scalefactor = 1; + + AlignViewport av; +// Controller controller; + + + public RotatableCanvas(AlignViewport av, + Vector points, int npoint) { + this.points = points; + this.npoint = npoint; + this.av = av; + ToolTipManager.sharedInstance().registerComponent(this); + PaintRefresher.Register(this); +// + prefsize = getPreferredSize(); + orig = new float[npoint][3]; + + for (int i=0; i < npoint; i++) { + SequencePoint sp = (SequencePoint)points.elementAt(i); + for (int j=0; j < 3; j++) { + orig[i][j] = sp.coord[j]; + } + } + //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); + rotmat.addElement(i,j,0); + } else { + idmat.addElement(i,j,0); + objmat.addElement(i,j,0); + rotmat.addElement(i,j,0); + } + } + } + + axes = new float[3][3]; + initAxes(); + + findCentre(); + findWidth(); + + scale = findScale(); + + // System.out.println("Scale factor = " + scale); + + addMouseListener(this); + addKeyListener(this); + // if (getParent() != null) { + // getParent().addKeyListener(this); + //} + addMouseMotionListener(this); + + // Add rubberband + // rubberband = new RubberbandRectangle(this); + // rubberband.setActive(true); + // rubberband.addListener(this); + } + + /* public boolean handleSequenceSelectionEvent(SequenceSelectionEvent evt) { + redrawneeded = true; + repaint(); + return true; + } + + public void removeNotify() { + controller.removeListener(this); + super.removeNotify(); + }*/ + + public void initAxes() { + for (int i = 0; i < 3; i++) { + for (int j=0; j < 3; j++) { + if (i != j) { + axes[i][j] = 0; + } else { + axes[i][j] = 1; + } + } + } + } + + public void findWidth() { + max = new float[3]; + 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 i = 0; i < 3; i++) { + for (int j = 0; j < npoint; j++) { + SequencePoint sp = (SequencePoint)points.elementAt(j); + if (sp.coord[i] >= max[i]) { + max[i] = sp.coord[i]; + } + if (sp.coord[i] <= min[i]) { + min[i] = sp.coord[i]; + } + } + } + + // 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] = Math.abs(max[0] - min[0]); + width[1] = Math.abs(max[1] - min[1]); + width[2] = 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, width, 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*scalefactor/(2*maxwidth)); + } + + public void findCentre() { + //Find centre coordinate + findWidth(); + + centre[0] = (max[0] + min[0])/2; + centre[1] = (max[1] + min[1])/2; + centre[2] = (max[2] + min[2])/2; + + // System.out.println("Centre x " + centre[0]); + //System.out.println("Centre y " + centre[1]); + //System.out.println("Centre z " + centre[2]); + } + + public Dimension getPreferredSize() { + if (prefsize != null) { + return prefsize; + } else { + return new Dimension(400,400); + } + } + + public Dimension getMinimumSize() { + return getPreferredSize(); + } + + public void paintComponent(Graphics g) { + //Only create the image at the beginning - + if ((img == null) || (prefsize.width != getWidth()) || (prefsize.height != getHeight())) { + prefsize.width = getWidth(); + prefsize.height = getHeight(); + + scale = findScale(); + + // System.out.println("New scale = " + scale); + img = createImage(getWidth(),getHeight()); + ig = img.getGraphics(); + + } + + + drawBackground(ig,Color.black); + drawScene(ig); + if (drawAxes == true) + { + drawAxes(ig); + } + + + g.drawImage(img,0,0,this); + } + + public void drawAxes(Graphics g) { + + g.setColor(Color.yellow); + for (int i=0; i < 3 ; i++) { + g.drawLine(getWidth()/2,getHeight()/2, + (int)(axes[i][0]*scale*max[0] + getWidth()/2), + (int)(axes[i][1]*scale*max[1] + getHeight()/2)); + } + } + + public void drawBackground(Graphics g, Color col) { + g.setColor(col); + g.fillRect(0,0,prefsize.width,prefsize.height); + } + + + public void drawScene(Graphics g) { + boolean darker = false; + + int halfwidth = getWidth()/2; + int halfheight = getHeight()/2; + + for (int i = 0; i < npoint; i++) { + SequencePoint sp = (SequencePoint)points.elementAt(i); + int x = (int)((float)(sp.coord[0] - centre[0])*scale) + halfwidth; + int y = (int)((float)(sp.coord[1] - centre[1])*scale) + halfheight; + float z = sp.coord[1] - centre[2]; + if (sp.sequence instanceof DrawableSequence) { + if (((DrawableSequence)sp.sequence).color == Color.black) { + g.setColor(Color.white); + } else { + g.setColor(((DrawableSequence)sp.sequence).color); + } + } else { + g.setColor(Color.red); + } + if (av != null) { + if (av.getSelection().contains(((SequencePoint)points.elementAt(i)).sequence)) { + g.setColor(Color.gray); + } + } + if (z < 0) { + g.setColor(g.getColor().darker()); + } + + g.fillRect(x-3,y-3,6,6); + g.setColor(Color.red); + } +// //Now the rectangle +// if (rectx2 != -1 && recty2 != -1) { +// g.setColor(Color.white); +// +// g.drawRect(rectx1,recty1,rectx2-rectx1,recty2-recty1); +// } + } + + public Dimension minimumsize() { + return prefsize; + } + + public Dimension preferredsize() { + return prefsize; + } + + public void keyTyped(KeyEvent evt) { } + public void keyReleased(KeyEvent evt) { } + + public void keyPressed(KeyEvent evt) { + requestFocus(); + if (evt.getKeyCode() == KeyEvent.VK_UP) { + scalefactor = (float)(scalefactor * 1.1); + scale = findScale(); + } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) { + scalefactor = (float)(scalefactor * 0.9); + scale = findScale(); + } else if (evt.getKeyChar() == 's') { + System.out.println("Rectangle selection"); + if (rectx2 != -1 && recty2 != -1) { + rectSelect(rectx1,recty1,rectx2,recty2); + + } + } + repaint(); + } + + public void printPoints() { + for (int i=0; i < npoint; i++) { + SequencePoint sp = (SequencePoint)points.elementAt(i); + Format.print(System.out,"%5d ", i); + for (int j=0; j < 3;j++) { + Format.print(System.out,"%13.3f ",sp.coord[j]); + } + System.out.println(); + } + } + + public void mouseClicked(MouseEvent evt) { } + public void mouseEntered(MouseEvent evt) { } + public void mouseExited(MouseEvent evt) { } + public void mouseReleased(MouseEvent evt) { } + + public void mousePressed(MouseEvent evt) { + int x = evt.getX(); + int y = evt.getY(); + + mx = x; + my = y; + + omx = mx; + omy = my; + + startx = x; + starty = y; + + rectx1 = x; + recty1 = y; + + rectx2 = -1; + recty2 = -1; + + SequenceI found = findPoint(x,y); + + if (found != null) { + if (av != null) { + + if (av.getSelection().contains(found)) { + av.getSelection().removeElement(found); + } else { + av.getSelection().addElement(found); + } + PaintRefresher.Refresh(this); + } + } + repaint(); + } + + // private void fireSequenceSelectionEvent(Selection sel) { + // controller.handleSequenceSelectionEvent(new SequenceSelectionEvent(this,sel)); + //} + + public void mouseMoved(MouseEvent evt) + { + SequenceI found = findPoint(evt.getX(), evt.getY()); + if (found != null) + this.setToolTipText(found.getName()); + else + this.setToolTipText(null); + } + + public void mouseDragged(MouseEvent evt) { + mx = evt.getX(); + my = evt.getY(); + //Check if this is a rectangle drawing drag + if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { +// rectx2 = evt.getX(); +// recty2 = evt.getY(); + } else { + rotmat.setIdentity(); + + rotmat.rotate((float)(my-omy),'x'); + rotmat.rotate((float)(mx-omx),'y'); + + for (int i = 0; i < npoint; i++) { + SequencePoint sp = (SequencePoint)points.elementAt(i); + sp.coord[0] -= centre[0]; + sp.coord[1] -= centre[1]; + sp.coord[2] -= centre[2]; + + //Now apply the rotation matrix + sp.coord= rotmat.vectorMultiply(sp.coord); + + //Now translate back again + sp.coord[0] += centre[0]; + sp.coord[1] += centre[1]; + sp.coord[2] += centre[2]; + } + + for (int i=0; i < 3; i++) { + axes[i] = rotmat.vectorMultiply(axes[i]); + } + omx = mx; + omy = my; + + paint(this.getGraphics()); + } + + } + + public void rectSelect(int x1, int y1, int x2, int y2) { + boolean changedSel = false; + for (int i=0; i < npoint; i++) { + SequencePoint sp = (SequencePoint)points.elementAt(i); + int tmp1 = (int)((sp.coord[0] - centre[0])*scale + (float)getWidth()/2.0); + int tmp2 = (int)((sp.coord[1] - centre[1])*scale + (float)getHeight()/2.0); + + if (tmp1 > x1 && tmp1 < x2 && tmp2 > y1 && tmp2 < y2) { + if (av != null) { + if (!av.getSelection().contains(sp.sequence)) { + changedSel = true; + av.getSelection().addElement(sp.sequence); + } + } + } + } + // if (changedSel) { + // fireSequenceSelectionEvent(av.getSelection()); + // } + } + public SequenceI findPoint(int x, int y) { + + int halfwidth = getWidth()/2; + int halfheight = getHeight()/2; + + int found = -1; + + for (int i=0; i < npoint; i++) { + + SequencePoint sp = (SequencePoint)points.elementAt(i); + int px = (int)((float)(sp.coord[0] - centre[0])*scale) + halfwidth; + int py = (int)((float)(sp.coord[1] - centre[1])*scale) + halfheight; + + + if (Math.abs(px-x)<3 && Math.abs(py - y) < 3 ) { + found = i; + } + } + if (found != -1) { + return ((SequencePoint)points.elementAt(found)).sequence; + } else { + return null; + } + } +/* public boolean handleRubberbandEvent(RubberbandEvent evt) { + System.out.println("Rubberband handler called in RotatableCanvas with " + + evt.getBounds()); + + Rubberband rb = (Rubberband)evt.getSource(); + + // Clear the current selection (instance variable) + //if ((rb.getModifiers() & Event.SHIFT_MASK) == 0) { + // clearSelection(); + //} + + if (rb.getComponent() == this) { + Rectangle bounds = evt.getBounds(); + rectSelect(bounds.x,bounds.y,bounds.x+bounds.width,bounds.y+bounds.height); + } + + redrawneeded = true; + paint(this.getGraphics()); + + return true; + }*/ + +} diff --git a/src/jalview/gui/ScaleCanvas.java b/src/jalview/gui/ScaleCanvas.java new file mode 100755 index 0000000..090b272 --- /dev/null +++ b/src/jalview/gui/ScaleCanvas.java @@ -0,0 +1,130 @@ +package jalview.gui; + +import java.awt.*; +import javax.swing.*; + +public class ScaleCanvas extends JPanel { + + Image img; + Graphics gg; + + int imgWidth; + int imgHeight; + int xoffset; + + public static final int HEIGHT = 30; + + boolean paintFlag = false; + + protected AlignViewport av; + + public ScaleCanvas(AlignViewport av) { + this.av = av; + + } + public void paintComponent(Graphics g) { + + double charWidth = av.getCharWidth(); + int charHeight = av.getCharHeight(); + + if (img == null || + imgWidth != getWidth() || + imgHeight != getHeight() || + paintFlag == true) { + + imgWidth = getWidth(); + imgHeight = getHeight(); + img = createImage(imgWidth,imgHeight); + + gg = img.getGraphics(); + gg.setColor(Color.white); + gg.fillRect(0,0,imgWidth,imgHeight); + + + + paintFlag = false; + } + gg.setFont(av.getFont()); + + //Fill in the background + + gg.setColor(Color.white); + gg.fillRect(0,0,imgWidth,imgHeight); + + int tickSpace; + + int resWidth = av.getEndRes() - av.getStartRes() + 1; + + // We want roughly one tick every 50 pixels + + double rough = getWidth()/50.0; + + double roughtick = resWidth/rough; + + int digits = (int)(Math.log(roughtick)/Math.log(10)); + int num = (int)(roughtick/Math.pow(10,digits)); + + if (Math.abs(10-num) < 3) { + num = 10; + } else if (Math.abs(5-num) <= 2) { + num = 5; + } else { + num = 2; + } + //System.out.println("Dig " + digits + " " + rough + " " + roughtick + " " + getWidth() + " " + num); + + int space = (int)(num * Math.pow(10,digits)); + + //Set the text font + + gg.setColor(Color.black); + + int startx = av.getStartRes(); + int endx = av.getEndRes(); + int scalestartx = startx - startx%space + space; + + + //Fill the selected columns + ColumnSelection cs = av.getColumnSelection(); + int width = (int)charWidth; + if (width == 0) + width = 1; + + gg.setColor(new Color(220,0,0)); + for (int i=0; i1) + this.setToolTipText(characters); + else + this.setToolTipText(null); + } + + public void paintComponent(Graphics g) + { + setPreferredSize(new Dimension( this.getWidth(), 80)); + g.setColor(Color.white); + g.fillRect(0, 0, this.getWidth(), 80); + g.setColor(Color.blue); + g.setFont(av.getFont()); + + Vector freq = av.getConsensus(false); + + int value, charOffset; + String characters; + char character; + + + int i=0, iSize = av.getChunkWidth(); + if(iSize > freq.size()) + iSize=freq.size(); + + for (i = 0; i < iSize; i++) + { + g.setColor(Color.blue); + + Hashtable hash = (Hashtable) freq.elementAt(i+av.getStartRes()); + if(hash.containsKey("maxResidue")) + characters = hash.get("maxResidue").toString(); + else + characters="@"; + character = characters.charAt(0); + value = Integer.parseInt(hash.get("maxCount").toString()); + + if (characters.length() > 1) + character = '+'; + + charOffset = (int) (av.charWidth - + g.getFontMetrics().charWidth(character)) / 2; + g.drawString(character + "", charOffset + (int) (i * av.charWidth), + 60 + (int) av.charWidth); + + value = (int) ( (float) value / + Float.parseFloat(hash.get("size").toString()) * 55); + + if (character != ' ' && character != '.' && character != '-') + g.fillRect( (int) (i * av.charWidth), + 60 - value, + (int) av.charWidth, + value + ); + } + } + +} diff --git a/src/jalview/gui/Selection.java b/src/jalview/gui/Selection.java new file mode 100755 index 0000000..6f73f5d --- /dev/null +++ b/src/jalview/gui/Selection.java @@ -0,0 +1,60 @@ +package jalview.gui; + +import jalview.datamodel.*; + +import java.util.*; + +public class Selection { + Vector selected = new Vector(); + + public void addElement(DrawableSequence seq) { + addElement((SequenceI)seq); + } + public void addElement(SequenceI seq) { + selected.addElement(seq); + } + + public void removeElement(DrawableSequence seq) { + removeElement((SequenceI)seq); + } + + public void clear() { + selected.removeAllElements(); + } + + public void removeElement(SequenceI seq) { + if (selected.contains(seq)) { + selected.removeElement(seq); + } else { + System.err.println("WARNING: Tried to remove SequenceI NOT in Selection"); + } + } + + public boolean contains(DrawableSequence seq) { + return contains((SequenceI)seq); + } + public boolean contains(SequenceI seq) { + return selected.contains(seq); + } + + public SequenceI sequenceAt(int i) { + return (SequenceI)selected.elementAt(i); + } + + public int size() { + return selected.size(); + } + + public Vector asVector() { + return selected; + } + + public void selectAll(AlignmentI align) { + for (int i=0;i 0 ? getWidth() : 1); + imgHeight = (getHeight() > 0 ? getHeight() : 1); + + img = createImage(imgWidth,imgHeight); + gg = img.getGraphics(); + + // SMJS I added this in to update the AV when the size changes + // until I figure out how this should be done + setFont(av.getFont()); + + gg.setFont(av.getFont()); + + paintFlag = false; + + oldstartx = -1; + oldendx = -1; + oldstarty = -1; + oldendy = -1; + } + + int startx = av.getStartRes(); + int starty = av.getStartSeq(); + + int endx = av.getEndRes(); + int endy = av.getEndSeq(); + + double charWidth = av.getCharWidth(); + int charHeight = av.getCharHeight(); + + chunkWidth = (int)(getWidth()/charWidth); + chunkHeight = (da.getHeight() + 2)*charHeight; + + av.setChunkHeight(chunkHeight); + av.setChunkWidth(chunkWidth); + + int offy = av.getStartSeq(); + + if (oldendx == -1) { + fillBackground(gg,Color.WHITE,0,0,imgWidth,imgHeight); + + /* if (av.getWrapAlignment() == true) { + startx = (int)(offy/chunkWidth)*chunkWidth; + endx = startx + chunkWidth; + starty = offy%chunkHeight; + endy = starty + da.getHeight(); + + int ypos = 0; + int rowstart = starty; + + if (starty == 0) { + ypos = 2*charHeight; + } else if (starty == 1) { + starty = 0; + ypos = charHeight; + } + + if (endy > da.getHeight()) { + endy = da.getHeight(); + } + + if (endx > da.getWidth()) { + endx = da.getWidth(); + } + + if (rowstart < 2) { + drawScale(startx,endx,charWidth,charHeight,ypos); + } + + drawPanel(gg,startx,endx,starty,endy,startx,starty,ypos); + + if (rowstart == 0) { + ypos = ypos + chunkHeight; + } else if (rowstart == 1) { + ypos = ypos + chunkHeight; + } else { + ypos = ypos + chunkHeight - rowstart*charHeight; + } + + startx += chunkWidth; + endx = startx + chunkWidth; + starty = 0; + + if (endx > da.getWidth()) { + endx = da.getWidth(); + } + // Draw the rest of the panels + + while (ypos <= getHeight()) { + drawScale(startx,endx,charWidth,charHeight,ypos); + drawPanel(gg,startx,endx,0,da.getHeight(),startx,starty,ypos); + + ypos += chunkHeight; + startx += chunkWidth; + endx = startx + chunkWidth; + + if (endy > da.getHeight()) { + endy = da.getHeight(); + } + + if (endx > da.getWidth()) { + endx = da.getWidth(); + } + + } + } else*/ { + drawPanel(gg,startx,endx,starty,endy,startx,starty,0); + + oldstartx = startx; + oldendx = endx; + oldstarty = starty; + oldendy = endy; + + } + } + + else if (oldstartx < startx) + { + // This is dragging horizontal scrollbar to the right + + int delx = (int)((startx - oldstartx) * charWidth); + int delx2 = (int)((oldendx - startx + 1) * charWidth); + + gg.copyArea(delx,0,delx2,AlignmentUtil.getPixelHeight(starty,endy,charHeight),-delx,0); + + if (startx > oldendx) + drawPanel(gg,startx,endx,starty,endy,startx,starty,0); + else + drawPanel(gg,oldendx+1,endx,starty,endy,startx,starty,0); + + + oldstartx = startx; + oldendx = endx; + + } else if (oldstartx > startx) + { + // Horizontal scrollbar pulled to the left + + int delx = (int)((oldstartx - startx) * charWidth); + int delx2 = (int)((endx - oldstartx +1) * charWidth); + + gg.copyArea(0,0,delx2,AlignmentUtil.getPixelHeight(starty,endy,charHeight),delx,0); + + if (oldstartx > endx) { + drawPanel(gg,startx,endx,starty,endy,startx,starty,0); + } else { + drawPanel(gg,startx,oldstartx-1,starty,endy,startx,starty,0); + } + + oldstartx = startx; + oldendx = endx; + + } else if (oldstarty < starty) { + // Vertical scrollbar down + int dely = AlignmentUtil.getPixelHeight(oldstarty,starty,charHeight); + int dely2 = AlignmentUtil.getPixelHeight(starty,oldendy,charHeight); + + gg.copyArea(0,dely,(int)((endx-startx+1)*charWidth),dely2,0,-dely); + + if (starty > oldendy) { + drawPanel(gg,startx,endx,starty,endy,startx,starty,0); + } else { + drawPanel(gg,startx,endx,oldendy,endy,startx,starty,0); + } + + oldstarty = starty; + oldendy = endy; + + } else if (oldstarty > starty) { + + // Vertical scrollbar up + int dely = AlignmentUtil.getPixelHeight(endy,oldendy,charHeight); + int dely2 = AlignmentUtil.getPixelHeight(oldstarty,endy,charHeight); + + gg.copyArea(0,0,(int)((endx-startx+1)*charWidth),dely2,0,dely); + + if (oldstarty > endy) { + drawPanel(gg,startx,endx,starty,endy,startx,starty,0); + } else { + drawPanel(gg,startx,endx,starty,oldstarty,startx,starty,0); + } + + oldstarty = starty; + oldendy = endy; + } + + if ((oldendy -oldstarty) > (int)((getWidth() / av.getCharWidth()))) { + System.out.println("LIMITS ERROR LIMITS ERROR"); + System.out.println("Corrds " + (oldendy-oldstarty) + " " + (int)(getWidth()/av.getCharWidth()) + " " + getWidth() + " " + av.getCharWidth()); + } + + + g.drawImage(img,0,0,this); + + } + + + + + public void drawPanel(Graphics g,int x1,int x2, int y1, int y2,int startx, int starty,int offset) { + +/* + System.out.println("drawPanel called with g = " + g); + System.out.println(" x1 = " + x1); + System.out.println(" x2 = " + x2); + System.out.println(" y1 = " + y1); + System.out.println(" y2 = " + y2); + System.out.println(" startx = " + startx); + System.out.println(" starty = " + starty); +*/ + + g.setFont(av.getFont()); + double charWidth = av.getCharWidth(); + int charHeight = av.getCharHeight(); + + // Vector pid = av.calcNewConsensus(); + + RendererI sr = av.getRenderer(); + +/* Vector tmpseq = new Vector(); + + for (int i = 0; i < av.getAlignment().getHeight(); i++) { + if (!av.getSelection().contains(av.getAlignment().getSequenceAt(i))) { + tmpseq.addElement(av.getAlignment().getSequenceAt(i)); + } + } + + if (sr instanceof SequenceRenderer) { + pid = AAFrequency.calculate(tmpseq,x1,x2); + + } else if (sr instanceof GraphRenderer) { + pid = AAFrequency.calculatePID(av.getAlignment().getSequenceAt(0), + av.getAlignment().getSequences(), + av.getPIDWindow(),x1,x2); + + }*/ + + if (y2 > starty && y1 < av.getEndSeq()) { + + fillBackground(g, + Color.white, + (int)((x1-startx)*charWidth), + offset + AlignmentUtil.getPixelHeight(starty,y1,av.getCharHeight()), + (int)((x2-x1+1)*charWidth), + offset + AlignmentUtil.getPixelHeight(y1,y2,av.getCharHeight())); + } + + for (int i = y1 ; i < y2 ;i++) { + + RendererI r = sr; + + /* if (av.getSelection().contains(av.getAlignment().getSequenceAt(i))) { + r = fr; + System.out.println("use feature renderer"); + // } else if ( i == 0) { + // r = br; + } else if (av.getAlignment().getSequenceAt(i).getName().equals("CpG")) { + r = cgr; + System.out.println("cg renderer"); + }*/ + + r.drawSequence(g,cs,av.getAlignment().getSequenceAt(i), + x1, + x2, + (int)((x1-startx)*charWidth), + offset + AlignmentUtil.getPixelHeight(starty,i,av.getCharHeight()), + charWidth, + charHeight,showScores,av.getShowBoxes(),av.getShowText(),null,i,av); + + } + } + + + + public void fillBackground(Graphics g,Color c, int x1,int y1,int width,int height) { + g.setColor(c); + g.fillRect(x1,y1,width,height); + } + + public int getChunkWidth() { + return chunkWidth; + } + +} diff --git a/src/jalview/gui/SeqPanel.java b/src/jalview/gui/SeqPanel.java new file mode 100755 index 0000000..120a062 --- /dev/null +++ b/src/jalview/gui/SeqPanel.java @@ -0,0 +1,277 @@ +package jalview.gui; + +import java.awt.*; +import java.awt.event.*; +import jalview.datamodel.*; +import javax.swing.*; +import jalview.schemes.*; + + +public class SeqPanel extends JPanel +{ + + public AlignmentI align; + public SeqCanvas seqCanvas; + public AlignmentPanel parent; + + protected int startres; + protected int lastres; + protected int endres; + + protected int startseq; + protected int padseq; + + public boolean editFlag; + protected AlignViewport av; + + public SeqPanel(AlignViewport av, AlignmentPanel p) { + this.av = av; + this.align = av.getAlignment(); + + seqCanvas = new SeqCanvas(av); + setLayout(new BorderLayout()); + add(seqCanvas, BorderLayout.CENTER); + + parent = p; + + addMouseMotionListener( new MouseMotionAdapter() + { + public void mouseMoved(MouseEvent evt) + { doMouseMoved(evt); } + public void mouseDragged(MouseEvent evt) + { doMouseDragged(evt); } + }); + + addMouseListener( new MouseAdapter() + { + public void mouseReleased(MouseEvent evt) + { doMouseReleased(evt); } + public void mousePressed(MouseEvent evt) + { doMousePressed(evt); } + + }); + repaint(); + } + + + public void doMouseReleased(MouseEvent evt) { + + int x = evt.getX(); + int res = (int)(x/av.getCharWidth()) + av.getStartRes(); + + endres = res; + + // This is to detect edits - we're at the end of an edit if mouse is up + editFlag = false; + startseq = -1; + startres = -1; + lastres = -1; + + parent.RefreshPanels(); + repaint(); + + } + + public void doMousePressed(MouseEvent evt) { + int seq; + int res; + + int x = evt.getX(); + int y = evt.getY(); + + res = (int)(x/av.getCharWidth()) + av.getStartRes(); + seq = (y)/av.getCharHeight() + av.getStartSeq(); + + if (seq < align.getHeight() && res < align.getSequenceAt(seq).getLength()) + { + //char resstr = align.getSequenceAt(seq).getSequence().charAt(res); + // Find the residue's position in the sequence (res is the position + // in the alignment + + startseq = seq; + + if (startseq == (align.getHeight()-1)) { + padseq = 1; + } else { + padseq = 1; + } + + startres = res; + lastres = res; + + } else { + startseq = -1; + startres = -1; + lastres = -1; + } + + return; + } + + public void doMouseMoved(MouseEvent evt) + { + + int res = (int)(evt.getX()/av.getCharWidth()) + av.getStartRes(); + int seq = (evt.getY())/av.getCharHeight() + av.getStartSeq(); + if(seq>=av.getAlignment().getHeight()) + return; + + Object obj = ResidueProperties.aa2Triplet.get( av.getAlignment().getSequenceAt(seq).getCharAt(res)+"" ) ; + String aa = ""; + if(obj!=null) + aa = obj.toString(); + + StringBuffer text = new StringBuffer("Sequence ID: "+av.getAlignment().getSequenceAt(seq).getName()); + if(aa!="") + text.append(" Residue: "+aa+" ("+ av.getAlignment().getSequenceAt(seq).findPosition(res)+")"); + + parent.alignFrame.statusBar.setText(text.toString()); + + } + + public void doMouseDragged(MouseEvent evt) { + // If we're dragging we're editing + editFlag = true; + + int x = evt.getX(); + + int res = (int)(x/av.getCharWidth()) + av.getStartRes(); + if (res < 0) {res = 0;} + + if (res != lastres) { + if (startseq != -1) { + + // Group editing + if (av.getGroupEdit()) { + SequenceGroup sg = align.findGroup(startseq); + + if (res < align.getWidth() && res < lastres) { + boolean flag = false; + for (int i= 0 ; i < sg.getSize(); i++) { + SequenceI s = (SequenceI)sg.getSequenceAt(i); + for (int j=lastres-1; j >= res; j--) { + if (!flag) { + if (!s.getSequence().substring(j,j+1).equals(align.getGapCharacter()) && + !s.getSequence().substring(j,j+1).equals(" ")) { + res = j+1; + System.out.print("\07"); + System.out.flush(); + flag = true; + } + } + } + } + } + + for (int i= 0 ; i < sg.getSize(); i++) + { + SequenceI s = (SequenceI)sg.getSequenceAt(i); + boolean found = false; + int sno = -1; + for (int k = 0; k < align.getHeight(); k++) + { + if (align.getSequenceAt(k) == s) + { + found = true; + sno = k; + break; + } + } + if (found && sno != -1) { + if (res < align.getWidth() && res > lastres) + { + for (int j = lastres; j < res; j++) + insertChar(j,sno); + + int index = align.findIndex(s); + if (index != -1) + drawChars(index,index+1,lastres); + + + } else if (res < align.getWidth() && res < lastres) + { + for (int j = res; j < lastres; j++) + { + deleteChar(j,res,sno); + startres = res; + } + int index = align.findIndex(s); + if (index != -1) + drawChars(index,index+1,res); + + } + } + + } + lastres = res; + } else { + + + if (res < align.getWidth() && res > lastres) { + // dragging to the right + for (int j = lastres; j < res; j++) + { + insertChar(j,startseq); + } + drawChars(startseq,startseq+1,lastres); + + } else if (res < align.getWidth() && res < lastres) { + + // dragging to the left + for (int j = res; j < lastres; j++) { + deleteChar(j,res,startseq); + startres = res; + } + drawChars(startseq,startseq+1,res); + } + } + } + lastres = res; + } + + repaint(); + return; + } + + public void drawChars(int seqstart, int seqend, int start) { + seqCanvas.drawPanel(seqCanvas.gg, start,av.getEndRes(),seqstart,seqend,av.getStartRes(),av.getStartSeq(),0); + repaint(); + } + + public void insertChar(int j, int seq) + { + align.getSequenceAt(seq).insertCharAt(j, av.getGapCharacter().charAt(0)); + } + + public void deleteChar(int j, int res, int sno) + { + + if (align.getSequenceAt(sno).getSequence().substring(j,j+1).equals(".") || + align.getSequenceAt(sno).getSequence().substring(j,j+1).equals("-") || + align.getSequenceAt(sno).getSequence().substring(j,j+1).equals(" ") ) + { + align.getSequenceAt(sno).deleteCharAt(j); + } + + align.getWidth(); + repaint(); + } + + public void setColourScheme(ColourSchemeI cs) + { + seqCanvas.cs = cs; + seqCanvas.paintFlag = true; + repaint(); + } + + public ColourSchemeI getColourScheme() + { + return seqCanvas.cs; + } + + +} + + + + diff --git a/src/jalview/gui/SequenceRenderer.java b/src/jalview/gui/SequenceRenderer.java new file mode 100755 index 0000000..7df9149 --- /dev/null +++ b/src/jalview/gui/SequenceRenderer.java @@ -0,0 +1,130 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.schemes.*; + +import java.awt.*; +import java.util.*; + +public class SequenceRenderer implements RendererI +{ + FontMetrics fm; + AlignViewport av; + + public Color getResidueBoxColour(ColourSchemeI cs, SequenceI seq, int i) { + Color c = Color.WHITE; + + try{ + if (cs != null) + c = cs.findColour(seq, seq.getSequence(i, i + 1), i, null); + }catch(Exception ex) + { } + + return c; + } + + public void drawSequence(Graphics g,ColourSchemeI cs,SequenceI seq,int start, int end, int x1, int y1, double width, int height,boolean showScores, boolean displayBoxes, boolean displayText,Vector freq, int seqnum,AlignViewport av) { + + this.av = av; + + if (displayBoxes == true) { + drawBoxes(g,cs,seq,start,end,x1,y1,(int)width, height,freq); + } + if (displayText == true) { + fm = g.getFontMetrics(); + drawText(g,cs,seq,start,end,x1,y1,(int)width,height); + } + } + + public void drawBoxes(Graphics g,ColourSchemeI cs, SequenceI seq,int start, int end, int x1, int y1, int width, int height,Vector freq) { + int i = start; + int length = seq.getLength(); + + Color currentColor = Color.WHITE; + + int curStart = x1; + int curWidth = width; + + // int threshold = 80; + + while (i <= end && i < length) { + Color c = getResidueBoxColour(cs,seq,i); + + // Hashtable hash = (Hashtable)freq.elementAt(i-start); + // String s = (String)hash.get("maxResidue"); + // int count = ((Integer)hash.get("maxCount")).intValue(); + // int max = ((Integer)hash.get("size")).intValue(); + // int nongap = ((Integer)hash.get("nongap")).intValue(); + // float frac = (float)(count*1.0/(1.0*nongap)); + + //System.out.println("Frac/count/nongap " + frac + " " + count + " " + nongap); + /* if (!seq.getSequence().substring(i,i+1).equals(s) || + s.equals("-") || + s.equals(".") || + s.equals(" ")) + { + c = Color.white; + } else { + if (frac > 0.9) { + c = Color.red; + } else if (frac > 0.8) { + c = Color.orange; + } else if (frac > 0.7) { + c = Color.pink; + } else if (frac > 0.5) { + c = Color.yellow; + } else if (frac> 0.3) { + c = Color.lightGray; + } + }*/ + + if (c != currentColor || c != null) + { + g.fillRect(x1+width*(curStart-start),y1,curWidth,height); + + currentColor = c; + g.setColor(c); + + curStart = i; + curWidth = width; + } + else + curWidth += width; + + i++; + } + g.fillRect(x1+width*(curStart-start),y1,curWidth,height); + } + + public void drawText(Graphics g, ColourSchemeI cs, SequenceI seq,int start, int end, int x1, int y1, int width, int height) + { + int pady = height/5; + int charOffset=0; + g.setColor(Color.black); + boolean colourText = av.getColourText(); + Color c; + char s; + // Need to find the sequence position here. + for (int i = start; i <= end; i++) + { + if (i < end && i < seq.getLength()) + s = seq.getSequence().charAt(i); + else if(i 0) { + nodeLabel = new Format("%5.2f").form(node.dist); + } + if (showBootstrap) { + if (showDistances) { + nodeLabel = nodeLabel + " : "; + } + nodeLabel = nodeLabel + String.valueOf(node.getBootstrap()); + } + if (! nodeLabel.equals("")) { + g.drawString(nodeLabel,xstart,ypos - 10); + } + + // Colour selected leaves differently + String name = node.getName(); + FontMetrics fm = g.getFontMetrics(font); + int charWidth = fm.stringWidth(node.getName()) + 3; + int charHeight = fm.getHeight(); + + Rectangle rect = new Rectangle(xend+20,ypos-charHeight, + charWidth,charHeight); + + nameHash.put((SequenceI)node.element(),rect); + + if (selected.contains((SequenceI)node.element())) { + g.setColor(Color.gray); + + g.fillRect(xend + 10, ypos - charHeight + 3,charWidth,charHeight); + g.setColor(Color.white); + } + g.drawString(node.getName(),xend+10,ypos); + g.setColor(Color.black); + } else { + drawNode(g,(SequenceNode)node.left(), chunk,scale,width,offx,offy); + drawNode(g,(SequenceNode)node.right(),chunk,scale,width,offx,offy); + + float height = node.height; + float dist = node.dist; + + int xstart = (int)((height-dist)*scale) + offx; + int xend = (int)(height *scale) + offx; + int ypos = (int)(node.ycount *chunk) + offy; + + g.setColor(((SequenceNode)node).color.darker()); + + // Draw horizontal line + g.drawLine(xstart,ypos,xend,ypos); + g.fillRect(xend-2, ypos-2, 4,4); + + int ystart = (int)(((SequenceNode)node.left()) .ycount * chunk) + offy; + int yend = (int)(((SequenceNode)node.right()).ycount * chunk) + offy; + + Rectangle pos = new Rectangle(xend-2,ypos-2,5,5); + nodeHash.put(node,pos); + + g.drawLine((int)(height*scale) + offx, ystart, + (int)(height*scale) + offx, yend); + + if (showDistances && node.dist > 0) { + g.drawString(new Format("%5.2f").form(node.dist),xstart,ypos - 5); + } + + } + } + public Object findElement(int x, int y) { + Enumeration keys = nameHash.keys(); + + while (keys.hasMoreElements()) { + Object ob = keys.nextElement(); + Rectangle rect = (Rectangle)nameHash.get(ob); + + if (x >= rect.x && x <= (rect.x + rect.width) && + y >= rect.y && y <= (rect.y + rect.height)) { + return ob; + } + } + keys = nodeHash.keys(); + + while (keys.hasMoreElements()) { + Object ob = keys.nextElement(); + Rectangle rect = (Rectangle)nodeHash.get(ob); + + if (x >= rect.x && x <= (rect.x + rect.width) && + y >= rect.y && y <= (rect.y + rect.height)) { + return ob; + } + } + return null; + + } + + public void pickNodes(Rectangle pickBox, Selection sel) { + int width = getWidth(); + int height = getHeight(); + + SequenceNode top = tree.getTopNode(); + + float wscale = (float)(width*.8-offx*2)/tree.getMaxHeight() +; + if (top.count == 0) { + top.count = ((SequenceNode)top.left()).count + ((SequenceNode)top.right()).count ; + } + float chunk = (float)(height-offy*2)/top.count; + + pickNode(pickBox,sel,top,chunk,wscale,width,offx,offy); + } + + public void pickNode(Rectangle pickBox, Selection sel, SequenceNode node, float chunk, float scale, int width,int offx, int offy) { + if (node == null) { + return; + } + + if (node.left() == null && node.right() == null) { + float height = node.height; + float dist = node.dist; + + int xstart = (int)((height-dist)*scale) + offx; + int xend = (int)(height*scale) + offx; + + int ypos = (int)(node.ycount * chunk) + offy; + + if (pickBox.contains(new Point(xend,ypos))) { + if (node.element() instanceof SequenceI) { + SequenceI seq = (SequenceI)node.element(); + if (sel.contains(seq)) { + sel.removeElement(seq); + } else { + sel.addElement(seq); + } + } + } + } else { + pickNode(pickBox,sel,(SequenceNode)node.left(), chunk,scale,width,offx,offy); + pickNode(pickBox,sel,(SequenceNode)node.right(),chunk,scale,width,offx,offy); + } + } + + public void setColor(SequenceNode node, Color c) { + if (node == null) { + return; + } + + if (node.left() == null && node.right() == null) { + node.color = c; + + if (node.element() instanceof SequenceI) { + ((SequenceI)node.element()).setColor(c); + } + } else { + node.color = c; + setColor((SequenceNode)node.left(),c); + setColor((SequenceNode)node.right(),c); + } + } + + + public void paintComponent(Graphics g) { + + + font = new Font("Verdana",Font.PLAIN,fontSize); + g.setFont(font); + + FontMetrics fm = g.getFontMetrics(font); + + if(nameHash.size()==0) + repaint(); + + + if( scrollPane.getHeight() > fm.getHeight() * nameHash.size()+offy) + { + draw(g,scrollPane.getWidth(),scrollPane.getHeight()); + setPreferredSize(new Dimension(scrollPane.getWidth(), scrollPane.getHeight())); + } + else + { + setPreferredSize(new Dimension(getWidth(), fm.getHeight() * nameHash.size())); + draw( g,getWidth(), fm.getHeight() * nameHash.size()); + } + + + if (threshold != 0) + { + g.setColor(Color.red); + g.drawLine(threshold,0,threshold,getHeight()); + } + + scrollPane.revalidate(); + } + public int getFontSize() { + return fontSize; + } + public void setFontSize(int fontSize) { + this.fontSize = fontSize; + repaint(); + } + public void draw(Graphics g, int width, int height) { + g.setColor(Color.white); + g.fillRect(0,0,width,height); + + + labelLength = g.getFontMetrics(font).stringWidth(longestName)+ 20;//20 allows for scrollbar + + float wscale =(float)(width - labelLength -offx*2)/tree.getMaxHeight(); + + SequenceNode top = tree.getTopNode(); + + if (top.count == 0) { + top.count = ((SequenceNode)top.left()).count + ((SequenceNode)top.right()).count ; + } + float chunk = (float)(height-offy*2)/top.count ; + + drawNode(g,tree.getTopNode(),chunk,wscale,width,offx,offy); + } + + public void mouseReleased(MouseEvent e) { } + public void mouseEntered(MouseEvent e) { } + public void mouseExited(MouseEvent e) { } + public void mouseClicked(MouseEvent e) { + } + + public void mousePressed(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + + Object ob = findElement(x,y); + + if (ob instanceof SequenceI) + { + TreeSelectionChanged((Sequence)ob); + repaint(); + return; + + } else if (ob instanceof SequenceNode) { + SequenceNode tmpnode = (SequenceNode)ob; + tree.swapNodes(tmpnode); + tree.reCount(tree.getTopNode()); + tree.findHeight(tree.getTopNode()); + } else { + // Find threshold + + if (tree.getMaxHeight() != 0) { + float fthreshold = (float)(x - offx)/(float)(getWidth()-labelLength - 2*offx); + this.threshold = x; + tree.getGroups().removeAllElements(); + tree.groupNodes(tree.getTopNode(),fthreshold); + setColor(tree.getTopNode(),Color.black); + + for (int i=0; i < tree.getGroups().size(); i++) { + + int tmp = i%(7); + Color col = new Color((int)(Math.random()*255), + (int)(Math.random()*255), + (int)(Math.random()*255)); + + setColor((SequenceNode)tree.getGroups().elementAt(i),col.brighter()); + + // l is vector of Objects + Vector l = tree.findLeaves((SequenceNode)tree.getGroups().elementAt(i),new Vector()); + + } + } + } + + repaint(); + + } + + public void setShowDistances(boolean state) { + this.showDistances = state; + repaint(); + } + + public void setShowBootstrap(boolean state) { + this.showBootstrap = state; + repaint(); + } + +} + diff --git a/src/jalview/gui/TreePanel.java b/src/jalview/gui/TreePanel.java new file mode 100755 index 0000000..9e9e70b --- /dev/null +++ b/src/jalview/gui/TreePanel.java @@ -0,0 +1,274 @@ +package jalview.gui; + +import jalview.datamodel.*; +import jalview.analysis.*; +import jalview.jbgui.GTreePanel; +import jalview.io.*; +import java.awt.event.*; +import java.util.*; +import java.io.*; +import jalview.util.*; +import javax.swing.*; + + +public class TreePanel extends GTreePanel +{ + SequenceI[] seq; + String type; + String pwtype; + AlignViewport av; + int start; + int end; + TreeCanvas treeCanvas; + NJTree tree; + + FileProperties fp; + PostscriptProperties pp; + + PrintWriter bw; + PrintStream ps; + boolean makeString = false; + StringBuffer out; + + + + public TreePanel(AlignViewport av, Vector seqVector, String type, String pwtype, int s, int e) + { + super(); + + this.type = type; + this.pwtype = pwtype; + + start = s; + end = e; + + String longestName = ""; + seq = new Sequence [seqVector.size()]; + for (int i=0;i < seqVector.size();i++) + { + seq[i] = (Sequence) seqVector.elementAt(i); + if(seq[i].getName().length()>longestName.length()) + longestName = seq[i].getName(); + } + + tree = new NJTree(seq, type, pwtype, start, end); + av.setCurrentTree(tree); + + propertiesInit(); + + treeCanvas = new TreeCanvas(av, tree, scrollPane, longestName); + + tree.reCount(tree.getTopNode()); + tree.findHeight(tree.getTopNode()); + scrollPane.setViewportView(treeCanvas); + + } + + +public void drawPostscript(PostscriptProperties pp) { + try { + int width = 0; + int height = 0; + + printout("%!\n"); + + printout("/" + pp.font + " findfont\n"); + printout(pp.fsize + " scalefont setfont\n"); + + int offx = pp.xoffset; + int offy = pp.yoffset; + + if (pp.orientation == PostscriptProperties.PORTRAIT) { + width = PostscriptProperties.SHORTSIDE; + height = PostscriptProperties.LONGSIDE; + } else { + height = PostscriptProperties.SHORTSIDE; + width = PostscriptProperties.LONGSIDE; + printout(height + " 0 translate\n90 rotate\n"); + } + float wscale = (float)(width*.8-offx*2)/tree.getMaxHeight(); + SequenceNode top = tree.getTopNode(); + + if (top.count == 0) { + top.count = ((SequenceNode)top.left()).count + ((SequenceNode)top.right()).count ; + } + + float chunk = (float)(height-offy*2)/(((SequenceNode)top).count+1); + + drawPostscriptNode(top,chunk,wscale,width,offx,offy); + + printout("showpage\n"); + } catch (java.io.IOException e) { + System.out.println("Exception " + e); + } +} + +public void drawPostscriptNode(SequenceNode node, float chunk, float scale, int width, int offx, int offy) throws java.io.IOException { + if (node == null) { + return; + } + + if (node.left() == null && node.right() == null) { + // Drawing leaf node + + float height = node.height; + float dist = node.dist; + + int xstart = (int)((height-dist)*scale) + offx; + int xend = (int)(height*scale) + offx; + + int ypos = (int)(node.ycount * chunk) + offy; + + // g.setColor(Color.black); + printout("\n" + new Format("%5.3f").form((double)node.color.getRed()/255) + " " + + new Format("%5.3f").form((double)node.color.getGreen()/255) + " " + + new Format("%5.3f").form((double)node.color.getBlue()/255) + " setrgbcolor\n"); + + // Draw horizontal line + // g.drawLine(xstart,ypos,xend,ypos); + printout(xstart + " " + ypos + " moveto " + xend + " " + ypos + " lineto stroke \n"); + + if (treeCanvas.showDistances && node.dist > 0) { + // g.drawString(new Format("%5.2f").form(node.dist),xstart,ypos - 5); + printout("(" + new Format("%5.2f").form(node.dist) + ") " + xstart + " " + (ypos+5) + " moveto show\n"); + } + //g.drawString((String)node.element(),xend+20,ypos); + printout("(" + (((SequenceI)node.element()).getName()) + ") " + (xend+20) + " " + (ypos) + " moveto show\n"); + } else { + drawPostscriptNode((SequenceNode)node.left(),chunk,scale,width,offx,offy); + drawPostscriptNode((SequenceNode)node.right(),chunk,scale,width,offx,offy); + + + float height = node.height; + float dist = node.dist; + + int xstart = (int)((height-dist)*scale) + offx; + int xend = (int)(height*scale) + offx; + int ypos = (int)(node.ycount * chunk) + offy; + + printout("\n" + new Format("%5.3f").form((double)node.color.getRed()/255) + " " + + new Format("%5.3f").form((double)node.color.getGreen()/255) + " " + + new Format("%5.3f").form((double)node.color.getBlue()/255) + " setrgbcolor\n"); + // g.setColor(Color.black); + // bw.append("\nblack setrgbcolor\n"); + // Draw horizontal line + // g.drawLine(xstart,ypos,xend,ypos); + printout(xstart + " " + ypos + " moveto " + xend + " " + ypos + " lineto stroke\n"); + int ystart = (int)(((SequenceNode)node.left()).ycount * chunk) + offy; + int yend = (int)(((SequenceNode)node.right()).ycount * chunk) + offy; + + // g.drawLine((int)(height*scale) + offx, ystart, + // (int)(height*scale) + offx, yend); + printout + (((int)(height*scale) + offx) + " " + ystart + " moveto " + ((int)(height*scale) + offx) + " " + + yend + " lineto stroke\n"); + if (treeCanvas.showDistances && node.dist > 0) { + // g.drawString(new Format("%5.2f").form(node.dist),xstart,ypos - 5); + printout("(" +new Format("%5.2f").form(node.dist) + ") " + (xstart) + " " + (ypos+5) + " moveto show\n"); + } + } +} + +public void printout(String s) throws IOException { + if (bw != null) { + bw.write(s); + } + if (ps != null) { + ps.print(s); + } + if (makeString == true) { + out.append(s); + } +} + + +public PostscriptProperties getPostscriptProperties() { + return pp; +} + +public FileProperties getFileProperties() { + return fp; +} + +public void setPostscriptProperties(PostscriptProperties pp) { + this.pp = pp; +} + +public void setFileProperties(FileProperties fp) { + this.fp = fp; +} + +public String getText(String format) { + return null; +} + +public void getPostscript(PrintWriter bw) { + this.bw = bw; + drawPostscript(pp); + +} + +public void getPostscript(PrintStream bw) { + this.ps = bw; + drawPostscript(pp); + bw.flush(); +} + +public StringBuffer getPostscript() { + makeString = true; + out = new StringBuffer(); + drawPostscript(pp); + return out; +} + +public void propertiesInit() { + this.pp = new PostscriptProperties(); + this.fp = new FileProperties(); +} + + + public void saveButton_actionPerformed(ActionEvent e) + { + + try{ + JFileChooser chooser = new JFileChooser(jalview.bin.Cache.LAST_DIRECTORY); + chooser.setDialogTitle("Save Tree as postscript file"); + chooser.setToolTipText("Save"); + int value = chooser.showSaveDialog(this); + if (value == JFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.bin.Cache.LAST_DIRECTORY = choice; + + bw = new PrintWriter(new FileWriter(choice)); + getPostscript(bw); + bw.close(); + + } + + }catch(Exception ex){ex.printStackTrace();} + + } + + public void showDistanceCheckbox_actionPerformed(ActionEvent e) + { + treeCanvas.setShowDistances(showDistanceCheckbox.isSelected()); + } + + public void fontSizeCombobox_actionPerformed(ActionEvent e) + { + if( treeCanvas==null ) + return; + + int size = Integer.parseInt( fontSizeCombobox.getSelectedItem().toString() ); + treeCanvas.setFontSize( size ); + + scrollPane.setViewportView(treeCanvas); + } + + public void bootStrapCheckBox_actionPerformed(ActionEvent e) + { + treeCanvas.setShowBootstrap(bootStrapCheckBox.isSelected()); + } + +} diff --git a/src/jalview/gui/UserDefinedColours.java b/src/jalview/gui/UserDefinedColours.java new file mode 100755 index 0000000..0c181b0 --- /dev/null +++ b/src/jalview/gui/UserDefinedColours.java @@ -0,0 +1,165 @@ +package jalview.gui; + +import jalview.jbgui.GUserDefinedColours; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.event.*; +import jalview.schemes.*; +import java.io.*; +import java.util.*; + + +public class UserDefinedColours extends GUserDefinedColours implements ChangeListener +{ + + SeqPanel seqPanel; + ColourSchemeI colourScheme; + JButton selectedButton; + Vector oldColours = new Vector(); + JInternalFrame frame; + + public UserDefinedColours(JInternalFrame f, SeqPanel sp) + { + super(); + colorChooser.getSelectionModel().addChangeListener(this); + seqPanel = sp; + frame = f; + colourScheme = seqPanel.getColourScheme(); + // colourScheme. + + for(int i=0; i<20; i++) + makeButton(ResidueProperties.aa2Triplet.get( ResidueProperties.aa[i] )+"", ResidueProperties.aa[i]); + + makeButton("B","B"); + makeButton("Z","Z"); + makeButton("X","X"); + makeButton("'.','-',' '", "-"); + + } + + public void stateChanged(ChangeEvent evt) + { + if(selectedButton!=null) + selectedButton.setBackground( colorChooser.getColor() ); + } + + public void colourButtonPressed(MouseEvent e) + { + selectedButton = (JButton)e.getSource(); + colorChooser.setColor(selectedButton.getBackground()); + } + + void makeButton(String label, String aa) + { + final JButton button = new JButton(); + button.setBackground( colourScheme.findColour(null,aa,-1,null) ); + oldColours.addElement( colourScheme.findColour(null,aa,-1,null) ); + button.setText( label ); + button.setFont(new java.awt.Font("Verdana", 1, 10)); + button.addMouseListener(new java.awt.event.MouseAdapter() + { + public void mouseClicked(MouseEvent e) + { + colourButtonPressed(e); + } + }); + + buttonPanel.add(button); + } + + + protected void okButton_actionPerformed(ActionEvent e) + { + applyButton_actionPerformed(null); + try{ + frame.setClosed(true); + }catch(Exception ex){} + } + + protected void applyButton_actionPerformed(ActionEvent e) + { + UserColourScheme ucs = new UserColourScheme(); + Color [] newColours = new Color[24]; + for(int i=0; i<24; i++) + { + JButton button = (JButton)buttonPanel.getComponent(i); + newColours[i] = button.getBackground(); + } + + ucs.setThreshold(0); + ucs.setColourScheme( newColours ); + seqPanel.setColourScheme( ucs ); + } + + protected void loadbutton_actionPerformed(ActionEvent e) + { + JFileChooser chooser = new JFileChooser(jalview.bin.Cache.LAST_DIRECTORY); + chooser.setDialogTitle("Load colour scheme"); + chooser.setToolTipText("Load"); + int value = chooser.showOpenDialog(this); + if (value == JFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.bin.Cache.LAST_DIRECTORY = choice; + + try{ + BufferedReader in = new BufferedReader(new FileReader(choice)); + for(int i=0; i<24; i++) + { + JButton button = (JButton)buttonPanel.getComponent(i); + Color c = new Color(Integer.parseInt(in.readLine())); + button.setBackground(c); + } + + } + catch(Exception ex) + {} + } + + } + + protected void savebutton_actionPerformed(ActionEvent e) + { + JFileChooser chooser = new JFileChooser(jalview.bin.Cache.LAST_DIRECTORY); + chooser.setDialogTitle("Save colour scheme"); + chooser.setToolTipText("Save"); + int value = chooser.showSaveDialog(this); + if (value == JFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.bin.Cache.LAST_DIRECTORY = choice; + + try{ + PrintWriter out = new PrintWriter(new FileWriter(choice)); + for(int i=0; i<24; i++) + { + JButton button = (JButton)buttonPanel.getComponent(i); + out.println(button.getBackground().getRGB() + ""); + } + + out.close(); + } + catch(Exception ex) + {ex.printStackTrace();} + } + + } + + protected void cancelButton_actionPerformed(ActionEvent e) + { + UserColourScheme ucs = new UserColourScheme(); + Color [] newColours = new Color[24]; + for(int i=0; i<24; i++) + { + newColours[i] = (Color)oldColours.elementAt(i); + buttonPanel.getComponent(i).setBackground(newColours[i]); + } + + ucs.setColourScheme( newColours ); + seqPanel.setColourScheme( ucs ); + + } + + +} diff --git a/src/jalview/io/AlignFile.java b/src/jalview/io/AlignFile.java new file mode 100755 index 0000000..77002cf --- /dev/null +++ b/src/jalview/io/AlignFile.java @@ -0,0 +1,98 @@ +package jalview.io; + +import jalview.datamodel.*; + +import java.io.*; +import java.util.*; + +public abstract class AlignFile extends FileParse { + int noSeqs = 0; + int maxLength = 0; + + Vector seqs; + Vector headers; + + long start; + long end; + + public AlignFile() + {} + + public AlignFile(String inStr) { + initData(); +System.out.println("is this ever called??"); + try{ + parse(); + }catch(Exception ex){} + } + +/** + * Constructor which parses the data from a file of some specified type. + * @param inFile Filename to read from. + * @param type What type of file to read from (File, URL) + */ + public AlignFile(String inFile, String type) throws IOException { + super(inFile,type); + + initData(); + + parse(); + + } + +/** + * Return the seqs Vector + */ + public Vector getSeqs() { + return seqs; + } + +/** + * Return the Sequences in the seqs Vector as an array of Sequences + */ + public SequenceI [] getSeqsAsArray() { + SequenceI [] s = new SequenceI[seqs.size()]; + for (int i=0;i < seqs.size();i++) { + s[i] = (SequenceI)seqs.elementAt(i); + } + return s; + } + + +/** + * Initialise objects to store sequence data in. + */ + protected void initData() { + seqs = new Vector(); + headers = new Vector(); + } + + protected void setSeqs(SequenceI [] s) { + seqs = new Vector(); + for (int i=0; i -1) + { + idsFound=true; + break; + } + + if (line.indexOf(">") > -1) + { + + if(line.indexOf(" ")>-1 ) + { + //>54402046 0 1 137 137: immunog + ids.addElement(line.substring(1, line.indexOf(" "))); + + // remove p Value + line = line.substring(line.indexOf(" ") + 1); + line = line.trim(); + + line = line.substring(line.indexOf(" ") + 1); + line = line.trim(); + starts.addElement(line.substring(0, line.indexOf(" "))); + line = line.substring(line.indexOf(" ") + 1); + line = line.trim(); + ends.addElement(line.substring(0, line.indexOf(" "))); + } + else + { + ids.addElement( line.substring(line.indexOf(">") + 1, line.indexOf("/"))); + line = line.substring(line.indexOf("/") + 1); + starts.addElement(line.substring(0, line.indexOf("-"))); + ends.addElement(line.substring(line.indexOf("-")+1)); + } + } + }while(!idsFound); + + int starCol = line.indexOf("*"); + seqstrings = new StringBuffer[ids.size()]; + for(int i=0; i" + s[i].getName() + "/" + s[i].getStart() + "-" + s[i].getEnd() + "\n"); + if (s[i].getSequence().length() > max) { max = s[i].getSequence().length();} + i++; + } + + out.append("* iteration 1\n"); + for (int j = 0; j < max; j++) { + i=0; + while (i < s.length && s[i] != null) { + if(s[i].getSequence().length()>j ) + out.append(s[i].getSequence().substring(j,j+1)); + else + out.append("-"); + i++; + } + out.append("\n"); + } + out.append("*\n"); + return out.toString(); + + } +} diff --git a/src/jalview/io/ClustalFile.java b/src/jalview/io/ClustalFile.java new file mode 100755 index 0000000..98c500a --- /dev/null +++ b/src/jalview/io/ClustalFile.java @@ -0,0 +1,174 @@ +package jalview.io; + +import jalview.datamodel.*; +import jalview.util.*; + +import java.io.*; +import java.util.*; + +public class ClustalFile extends AlignFile { + + Vector ids; + + public ClustalFile() + {} + + public ClustalFile(String inStr) { + super(inStr); + } + + + public void initData() { + super.initData(); + ids = new Vector(); + } + + public ClustalFile(String inFile, String type) throws IOException { + super(inFile,type); + } + + public void parse() { + int i = 0; + boolean flag = false; + + Vector headers = new Vector(); + Hashtable seqhash = new Hashtable(); + + String line; + + try { + while ((line = nextLine()) != null) { + if (line.indexOf(" ") != 0) { + StringTokenizer str = new StringTokenizer(line," "); + String id = ""; + + if (str.hasMoreTokens()) { + id = str.nextToken(); + if (id.equals("CLUSTAL")) { + flag = true; + } else { + if (flag) { + StringBuffer tempseq; + if (seqhash.containsKey(id)) { + tempseq = (StringBuffer)seqhash.get(id); + } else { + tempseq = new StringBuffer(); + seqhash.put(id,tempseq); + } + + if (!(headers.contains(id))) { + headers.addElement(id); + } + + tempseq.append(str.nextToken()); + } + } + } + } + } + } catch (IOException e) { + System.out.println("Exception parsing clustal file " + e); + } + + if (flag) { + this.noSeqs = headers.size(); + + //Add sequences to the hash + for (i = 0; i < headers.size(); i++ ) { + int start = -1; + int end = -1; + + if ( seqhash.get(headers.elementAt(i)) != null) { + if (maxLength < seqhash.get(headers.elementAt(i)).toString().length() ) { + maxLength = seqhash.get(headers.elementAt(i)).toString().length(); + } + String head = headers.elementAt(i).toString(); + start = 1; + end = seqhash.get(headers.elementAt(i)).toString().length(); + + if (head.indexOf("/") > 0 ) { + StringTokenizer st = new StringTokenizer(head,"/"); + if (st.countTokens() == 2) { + + ids.addElement(st.nextToken()); + + String tmp = st.nextToken(); + st = new StringTokenizer(tmp,"-"); + if (st.countTokens() == 2) { + start = Integer.valueOf(st.nextToken()).intValue(); + end = Integer.valueOf(st.nextToken()).intValue(); + } + } else { + ids.addElement(headers.elementAt(i)); + } + } else { + ids.addElement(headers.elementAt(i)); + + } + Sequence newSeq = new Sequence(ids.elementAt(i).toString(), + seqhash.get(headers.elementAt(i).toString()).toString(),start,end); + + seqs.addElement(newSeq); + + } else { + System.out.println("Can't find sequence for " + headers.elementAt(i)); + } + } + } + + } + + public String print() { + return print(getSeqsAsArray()); + } + public static String print(SequenceI[] s) { + StringBuffer out = new StringBuffer("CLUSTAL\n\n"); + + int max = 0; + int maxid = 0; + + int i = 0; + + while (i < s.length && s[i] != null) { + String tmp = s[i].getName() + "/" + s[i].getStart() + "-" + s[i].getEnd(); + + if (s[i].getSequence().length() > max) { + max = s[i].getSequence().length(); + } + if (tmp.length() > maxid) { + maxid = tmp.length(); + } + i++; + } + + if (maxid < 15) { + maxid = 15; + } + maxid++; + int len = 60; + int nochunks = max / len + 1; + + for (i = 0; i < nochunks; i++) { + int j = 0; + while ( j < s.length && s[j] != null) { + out.append( new Format("%-" + maxid + "s").form(s[j].getName() + "/" + s[j].getStart() + "-" + s[j].getEnd()) + " "); + int start = i*len; + int end = start + len; + + if (end < s[j].getSequence().length() && start < s[j].getSequence().length() ) { + out.append(s[j].getSequence().substring(start,end) + "\n"); + } else { + if (start < s[j].getSequence().length()) { + out.append(s[j].getSequence().substring(start) + "\n"); + } + } + j++; + } + out.append("\n"); + + } + return out.toString(); + } + + +} diff --git a/src/jalview/io/FastaFile.java b/src/jalview/io/FastaFile.java new file mode 100755 index 0000000..28109d5 --- /dev/null +++ b/src/jalview/io/FastaFile.java @@ -0,0 +1,139 @@ +package jalview.io; + +import jalview.datamodel.*; +import jalview.analysis.*; + +import java.io.*; +import java.util.*; + +public class FastaFile extends AlignFile { + + public FastaFile() + {} + + public FastaFile(String inStr) { + super(inStr); + } + + public FastaFile(String inFile, String type) throws IOException { + super(inFile,type); + } + + public void parse() throws IOException + { + + String id = ""; + StringBuffer seq = new StringBuffer(); + int count = 0; + boolean flag = false; + + int sstart = 0; + int send = 0; + + String line; + + while ((line = nextLine()) != null) { + + if (line.length() > 0) { + + // Do we have an id line? + + if (line.substring(0,1).equals(">")) { + + if (count != 0) { + if (sstart != 0) { + seqs.addElement(new Sequence(id,seq.toString().toUpperCase(),sstart,send)); + } else { + seqs.addElement(new Sequence(id,seq.toString().toUpperCase(),1,seq.length())); + } + } + + count++; + + StringTokenizer str = new StringTokenizer(line," "); + + id = str.nextToken(); + id = id.substring(1); + + if (id.indexOf("/") > 0 ) { + + StringTokenizer st = new StringTokenizer(id,"/"); + if (st.countTokens() == 2) { + id = st.nextToken(); + String tmp = st.nextToken(); + + st = new StringTokenizer(tmp,"-"); + + if (st.countTokens() == 2) { + sstart = Integer.valueOf(st.nextToken()).intValue(); + send = Integer.valueOf(st.nextToken()).intValue(); + } + } + } + + seq = new StringBuffer(); + + } else { + seq = seq.append(line); + } + } + } + if (count > 0) { + + if(!isValidProteinSequence(seq.toString().toUpperCase())) + throw new IOException("Invalid protein sequence"); + + if (sstart != 0) { + seqs.addElement(new Sequence(id,seq.toString().toUpperCase(),sstart,send)); + } else { + seqs.addElement(new Sequence(id,seq.toString().toUpperCase(),1,seq.length())); + } + } + + } + + public static String print(SequenceI[] s) { + return print(s,72); + } + public static String print(SequenceI[] s, int len) { + return print(s,len,true); + } + public static String print(SequenceI[] s, int len,boolean gaps) { + StringBuffer out = new StringBuffer(); + int i = 0; + while (i < s.length && s[i] != null) { + String seq = ""; + if (gaps) { + seq = s[i].getSequence(); + } else { + seq = AlignSeq.extractGaps(s[i].getSequence(),"-"); + seq = AlignSeq.extractGaps(seq,"."); + seq = AlignSeq.extractGaps(seq," "); + } + + out.append(">" + s[i].getName() + "/" + s[i].getStart() + "-" + s[i].getEnd() + "\n"); + + int nochunks = seq.length() / len + 1; + + for (int j = 0; j < nochunks; j++) { + int start = j*len; + int end = start + len; + + if (end < seq.length()) { + out.append(seq.substring(start,end) + "\n"); + } else if (start < seq.length()) { + out.append(seq.substring(start) + "\n"); + } + } + i++; + } + return out.toString(); + } + + public String print() { + return print(getSeqsAsArray()); + } +} + + + diff --git a/src/jalview/io/FileParse.java b/src/jalview/io/FileParse.java new file mode 100755 index 0000000..5f2e856 --- /dev/null +++ b/src/jalview/io/FileParse.java @@ -0,0 +1,46 @@ +package jalview.io; + +import java.io.*; +import java.net.*; + +public class FileParse { + + public File inFile; + public int fileSize; + public int noLines; + + protected String type; + protected BufferedReader dataIn; + + public FileParse() {} + + public FileParse(String fileStr, String type) throws MalformedURLException, IOException + { + + this.type = type; + + if (type.equals("File")) { + this.inFile = new File(fileStr); + this.fileSize = (int)inFile.length(); + + dataIn = new BufferedReader(new FileReader( fileStr )); + + } else if (type.equals("URL")) { + URL url = new URL(fileStr); + this.fileSize = 0; + dataIn = new BufferedReader(new InputStreamReader( url.openStream() )); + } else if(type.equals("Paste")) + { + dataIn = new BufferedReader(new StringReader(fileStr)); + } + } + + public String nextLine() throws IOException { + String next = dataIn.readLine(); + if (next != null) { + noLines++; + } + return next; + } + +} diff --git a/src/jalview/io/FileProperties.java b/src/jalview/io/FileProperties.java new file mode 100755 index 0000000..9921d70 --- /dev/null +++ b/src/jalview/io/FileProperties.java @@ -0,0 +1,33 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +package jalview.io; + +import java.util.*; + +public class FileProperties { + public String directory = "./"; + public String extension = ".seq"; + + public FileProperties() {} + + public FileProperties(String directory, String extension) { + this.directory = directory; + this.extension = extension; + } +} diff --git a/src/jalview/io/FormatAdapter.java b/src/jalview/io/FormatAdapter.java new file mode 100755 index 0000000..d4179b6 --- /dev/null +++ b/src/jalview/io/FormatAdapter.java @@ -0,0 +1,46 @@ +package jalview.io; + +import jalview.datamodel.*; +import java.util.*; + +public class FormatAdapter { + + public static String get(String format,Vector seqs) { + + SequenceI [] s = new SequenceI[seqs.size()]; + + for (int i=0;i"); + out.println(""); + out.println(""); + out.println("
\n"); + out.println("\n"); + + + ////////////// + for (int i = 0; i < alignment.getHeight(); i++) + { + SequenceI seq = alignment.getSequenceAt(i); + out.println(""); + for (int res = 0; res < seq.getLength(); res++) + { + color = sr.getResidueBoxColour(cs, seq, res); + Integer.toHexString(color.getRed()); + + out.println(""); + } + + out.println(""); + } + ////////////// + out.println("
"+seq.getName()+"  
"+seq.getCharAt(res)+"
"); + out.println("
\n\n"); + + out.close(); + } + catch(Exception ex){} + } + } + + +} diff --git a/src/jalview/io/IdentifyFile.java b/src/jalview/io/IdentifyFile.java new file mode 100755 index 0000000..2baf323 --- /dev/null +++ b/src/jalview/io/IdentifyFile.java @@ -0,0 +1,85 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.io; + +import java.io.*; +import java.net.*; + +public class IdentifyFile +{ + public static String Identify(String file, String protocol) + { + String reply = "error"; + try{ + + BufferedReader reader = null; + + if(protocol.equals("File")) + reader = new BufferedReader(new FileReader(file)); + + else if (protocol.equals("URL")) + { + reply = "URL NOT FOUND"; + URL url = new URL(file); + reader = new BufferedReader(new InputStreamReader( url.openStream() ) ); + reply = "error"; + } + else if( protocol.equals("Paste")) + reader = new BufferedReader( new StringReader(file) ); + + + String data; + while( (data=reader.readLine())!=null) + { + data = data.toUpperCase(); + if(data.indexOf("#")==0 || data.length()<1) + continue; + + if(data.indexOf("PILEUP")>-1) + { + reply = "MSF"; + break; + } + else if(data.indexOf("CLUSTAL")>-1) + { + reply = "CLUSTAL"; + break; + } + else if(data.indexOf(">P1;")>-1 || data.indexOf(">DL;")>-1) + { + reply = "PIR"; + break; + } + else if(data.indexOf(">")==0) + { + // could be BLC file + data = reader.readLine(); + if(data.indexOf(">")==0) + reply = "BLC"; + else + reply = "FASTA"; + + break; + } + else + { + reply = "PFAM"; + break; + } + + } + reader.close(); + } + catch(Exception ex){ex.printStackTrace();} + + return reply; + } + + +} diff --git a/src/jalview/io/MSFfile.java b/src/jalview/io/MSFfile.java new file mode 100755 index 0000000..b9cad0a --- /dev/null +++ b/src/jalview/io/MSFfile.java @@ -0,0 +1,230 @@ +package jalview.io; + +import jalview.datamodel.*; +import jalview.util.*; + +import java.io.*; +import java.util.*; + +public class MSFfile extends AlignFile { + + public MSFfile() + {} + + public MSFfile(String inStr) { + super(inStr); + } + + public MSFfile(String inFile, String type) throws IOException { + super(inFile,type); + } + + public void parse() { + + int i = 0; + boolean seqFlag = false; + String key = new String(); + Vector headers = new Vector(); + Hashtable seqhash = new Hashtable(); + String line; + + try { + while ((line = nextLine()) != null) { + + StringTokenizer str = new StringTokenizer(line); + + while (str.hasMoreTokens()) { + + String inStr = str.nextToken(); + + //If line has header information add to the headers vector + if (inStr.indexOf("Name:") != -1) { + key = str.nextToken(); + headers.addElement(key); + } + + //if line has // set SeqFlag to 1 so we know sequences are coming + if (inStr.indexOf("//") != -1) { + seqFlag = true; + } + + //Process lines as sequence lines if seqFlag is set + if (( inStr.indexOf("//") == -1) && (seqFlag == true)) { + //seqeunce id is the first field + key = inStr; + StringBuffer tempseq; + + //Get sequence from hash if it exists + if (seqhash.containsKey(key)) { + tempseq = (StringBuffer)seqhash.get(key); + } else { + tempseq = new StringBuffer(); + seqhash.put(key,tempseq); + } + + //loop through the rest of the words + while (str.hasMoreTokens()) { + //append the word to the sequence + tempseq.append(str.nextToken()); + } + } + } + } + } catch (IOException e) { + System.out.println("Exception parsing MSFFile " + e); + } + + this.noSeqs = headers.size(); + + //Add sequences to the hash + for (i = 0; i < headers.size(); i++ ) { + + if ( seqhash.get(headers.elementAt(i)) != null) { + String head = headers.elementAt(i).toString(); + String seq = seqhash.get(head).toString(); + + int start = 1; + int end = seq.length(); + + if (maxLength < head.length() ) { + maxLength = head.length(); + } + + if (head.indexOf("/") > 0 ) { + + StringTokenizer st = new StringTokenizer(head,"/"); + + if (st.countTokens() == 2) { + + head = st.nextToken(); + String tmp = st.nextToken(); + st = new StringTokenizer(tmp,"-"); + if (st.countTokens() == 2) { + start = Integer.valueOf(st.nextToken()).intValue(); + end = Integer.valueOf(st.nextToken()).intValue(); + } + } + } + + Sequence newSeq = new Sequence(head,seq,start,end); + + seqs.addElement(newSeq); + + } else { + System.out.println("Can't find sequence for " + headers.elementAt(i)); + } + } + + } + + public static int checkSum(String seq) { + //String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.*~&@"; + int check = 0; + + String index = "--------------------------------------&---*---.-----------------@ABCDEFGHIJKLMNOPQRSTUVWXYZ------ABCDEFGHIJKLMNOPQRSTUVWXYZ----@"; + index += "--------------------------------------------------------------------------------------------------------------------------------"; + + for(int i = 0; i < seq.length(); i++) { + try { + if (i max) { + max = seq.length(); + } + if (name.length() > maxid) { + maxid = name.length(); + } + i++; + } + + if (maxid < 10) { + maxid = 10; + } + maxid++; + out.append( "\n\n//\n\n"); + + int len = 50; + + int nochunks = max / len + 1; + if (max%len == 0) { + nochunks--; + } + for (i = 0; i < nochunks; i++) { + int j = 0; + while (j < s.length && s[j] != null) { + String name = s[j].getName(); + out.append( new Format("%-" + maxid + "s").form(name + "/" + s[j].getStart() + "-" + s[j].getEnd()) + " "); + for (int k = 0; k < 5; k++) { + + int start = i*50 + k*10; + int end = start + 10; + + if (end < s[j].getSequence().length() && start < s[j].getSequence().length() ) { + out.append(s[j].getSequence().substring(start,end)); + if (k < 4) { + out.append(" "); + } else { + out.append("\n"); + } + } else { + if (start < s[j].getSequence().length()) { + out.append(s[j].getSequence().substring(start)); + out.append("\n"); + } else { + if (k == 0) { + out.append("\n"); + } + } + } + } + j++; + } + out.append("\n"); + + } + return out.toString(); + } + public String print() { + return print(getSeqsAsArray()); + } +} + + + + + + + diff --git a/src/jalview/io/OutputGenerator.java b/src/jalview/io/OutputGenerator.java new file mode 100755 index 0000000..c038e89 --- /dev/null +++ b/src/jalview/io/OutputGenerator.java @@ -0,0 +1,20 @@ +package jalview.io; + +import java.io.*; + +public interface OutputGenerator { + + public PostscriptProperties getPostscriptProperties(); + //public MailProperties getMailProperties(); + // public FileProperties getFileProperties(); + + public void setPostscriptProperties(PostscriptProperties pp); + // public void setFileProperties(FileProperties fp); + //public void setMailProperties(MailProperties mp); + + public String getText(String format); + public void getPostscript(PrintWriter bw); + public void getPostscript(PrintStream ps); + public StringBuffer getPostscript(); + +} diff --git a/src/jalview/io/PIRFile.java b/src/jalview/io/PIRFile.java new file mode 100755 index 0000000..be60a43 --- /dev/null +++ b/src/jalview/io/PIRFile.java @@ -0,0 +1,133 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +package jalview.io; + +import jalview.datamodel.*; +import jalview.analysis.*; + +import java.io.*; +import java.util.*; + +public class PIRFile extends AlignFile { + + Vector words = new Vector(); //Stores the words in a line after splitting + + public PIRFile() + {} + + public PIRFile(String inStr) { + super(inStr); + } + + public PIRFile(String inFile, String type) throws IOException { + super(inFile,type); + } + + public void parse() { + try{ + String id, start, end; + StringBuffer sequence; + String line = null; + while( (line = nextLine())!=null) + { + try{ + id = line.substring(line.indexOf(";") + 1, line.indexOf("/")); + line = line.substring(line.indexOf("/") + 1); + start = line.substring(0, line.indexOf("-")); + end = line.substring(line.indexOf("-") + 1); + }catch(Exception ex) + { id="No id"; start="0"; end="0"; } + + sequence = new StringBuffer(); + + line = nextLine(); // this is the title line + + boolean starFound = false; + do + { + line = nextLine(); + sequence.append( line ); + if(line.indexOf("*")>-1) + starFound = true; + + }while(!starFound); + + sequence.setLength( sequence.length()-1); + + Sequence newSeq = new Sequence(id, + sequence.toString(), + Integer.parseInt(start), + Integer.parseInt(end)); + seqs.addElement(newSeq); + } + + } + catch(Exception ex){ex.printStackTrace();} + } + + public String print() { + return print(getSeqsAsArray()); + } + public static String print(SequenceI[] s) { + return print(s,72,true); + } + public static String print(SequenceI[] s, int len) { + return print(s,len,true); + } + public static String print(SequenceI[] s, int len,boolean gaps) { + StringBuffer out = new StringBuffer(); + int i = 0; + + while (i < s.length && s[i] != null) { + String seq = ""; + if (gaps) { + seq = s[i].getSequence() + "*"; + } else { + seq = AlignSeq.extractGaps(s[i].getSequence(),"-"); + seq = AlignSeq.extractGaps(seq,"."); + seq = AlignSeq.extractGaps(seq," "); + seq = seq + "*"; + } + + out.append(">P1;" + s[i].getName() + "/" + s[i].getStart()+ "-" + s[i].getEnd() + "\n"); + out.append(" Dummy title\n"); + int nochunks = seq.length() / len + 1; + + for (int j = 0; j < nochunks; j++) { + int start = j*len; + int end = start + len; + + if (end < seq.length()) { + out.append(seq.substring(start,end) + "\n"); + } else if (start < seq.length()) { + out.append(seq.substring(start) + "\n"); + } + } + i++; + } + return out.toString(); + } + + public static void main(String[] args) { + String inStr = ">P1;LCAT_MOUSE_90.35\nMGLPGSPWQRVLLLLGLLLPPATPFWLLNVLFPPHTTPKAELSNHTRPVILVPGCLGNRLEAKLDKPDVVNW\nMCYRKTEDFFTIWLDFNLFLPLGVDCWIDNTRIVYNHSSGRVSNAPGVQIRVPGFGKTESVEYVDDNKLAGY\n\n>LCAT_PAPAN_95.78\nMGPPGSPWQWVPLLLGLLLPPAAPFWLLNVLFPPHTTPKAELSNHTRPVILVPGCLGNQLEAKLDKPDVVNW\nMCYRKTEDFFTIWLDLNMFLPLGVDCWIDNTRVVYNRSSGLVSNAPGVQIRVPGFGKTYSVEYLDSSKLAGY\nLHTLVQNLVNNGYVRDETVRAAPYDWRLEPGQQEEYYHKLAGLVEEMHAAYGKPVFLIGHSLGCLHLLYFLL\n"; + PIRFile fa = new PIRFile(inStr); + } +} + + + diff --git a/src/jalview/io/PfamFile.java b/src/jalview/io/PfamFile.java new file mode 100755 index 0000000..e17f831 --- /dev/null +++ b/src/jalview/io/PfamFile.java @@ -0,0 +1,173 @@ +package jalview.io; + +import jalview.datamodel.*; +import jalview.util.*; + +import java.io.*; +import java.util.*; + +public class PfamFile extends AlignFile { + + Vector ids; + + public PfamFile() + {} + + public PfamFile(String inStr) { + super(inStr); + } + + public void initData() { + super.initData(); + ids = new Vector(); + } + + public PfamFile(String inFile, String type) throws IOException { + super(inFile,type); + } + + public void parse() throws IOException{ + int i = 0; + String line; + + + Hashtable seqhash = new Hashtable(); + Vector headers = new Vector(); + + + while ((line = nextLine()) != null) + { + + if (line.indexOf(" ") != 0) + { + if (line.indexOf("#") != 0) + { + + StringTokenizer str = new StringTokenizer(line," "); + String id = ""; + + if (str.hasMoreTokens()) + { + id = str.nextToken(); + + StringBuffer tempseq; + + if (seqhash.containsKey(id)) + tempseq = (StringBuffer)seqhash.get(id); + else + { + tempseq = new StringBuffer(); + seqhash.put(id,tempseq); + } + + if (!(headers.contains(id))) + headers.addElement(id); + + + tempseq.append(str.nextToken()); + } + } + } + } + + this.noSeqs = headers.size(); + if(noSeqs<1) + throw new IOException("No sequences found (PFAM input)"); + + for (i = 0; i < headers.size(); i++ ) { + + if ( seqhash.get(headers.elementAt(i)) != null) { + if (maxLength < seqhash.get(headers.elementAt(i)).toString().length() ) + maxLength = seqhash.get(headers.elementAt(i)).toString().length(); + + String head = headers.elementAt(i).toString(); + int start = 1; + int end = seqhash.get(headers.elementAt(i)).toString().length(); + + if (head.indexOf("/") > 0 ) { + StringTokenizer st = new StringTokenizer(head,"/"); + if (st.countTokens() == 2) { + ids.addElement(st.nextToken()); + String tmp = st.nextToken(); + st = new StringTokenizer(tmp,"-"); + if (st.countTokens() == 2) { + start = Integer.valueOf(st.nextToken()).intValue(); + end = Integer.valueOf(st.nextToken()).intValue(); + } else + { + start = -1; + end = -1; + } + } else + ids.addElement(headers.elementAt(i)); + + } + else + ids.addElement(headers.elementAt(i)); + + + Sequence newSeq = null; + if (start != -1 && end != -1) + { + newSeq = new Sequence(ids.elementAt(i).toString(), + seqhash.get(headers.elementAt(i).toString()).toString(),start,end); + seqs.addElement(newSeq); + } + else + { + newSeq = new Sequence(ids.elementAt(i).toString(), + seqhash.get(headers.elementAt(i).toString()).toString(),1, + seqhash.get(headers.elementAt(i).toString()).toString().length()); + seqs.addElement(newSeq); + } + + if(!isValidProteinSequence(newSeq.getSequence())) + throw new IOException("Not a valid protein sequence - (PFAM input)"); + } + else + System.out.println("Can't find sequence for " + headers.elementAt(i)); + + } + + } + + public static String print(SequenceI[] s) { + StringBuffer out = new StringBuffer(""); + + int max = 0; + int maxid = 0; + + int i = 0; + + while (i < s.length && s[i] != null) { + String tmp = s[i].getName() + "/" + s[i].getStart()+ "-" + s[i].getEnd(); + + if (s[i].getSequence().length() > max) { + max = s[i].getSequence().length(); + } + if (tmp.length() > maxid) { + maxid = tmp.length(); + } + i++; + } + + if (maxid < 15) { + maxid = 15; + } + + int j = 0; + while ( j < s.length && s[j] != null) { + out.append( new Format("%-" + maxid + "s").form(s[j].getName() + "/" + s[j].getStart() + "-" + s[j].getEnd() ) + " "); + + out.append(s[j].getSequence() + "\n"); + j++; + } + out.append("\n"); + + return out.toString(); + } + + public String print() { + return print(getSeqsAsArray()); + } +} diff --git a/src/jalview/io/PostscriptProperties.java b/src/jalview/io/PostscriptProperties.java new file mode 100755 index 0000000..0aae0de --- /dev/null +++ b/src/jalview/io/PostscriptProperties.java @@ -0,0 +1,75 @@ +package jalview.io; + +import java.util.*; + +public class PostscriptProperties { + + public static final int PORTRAIT = 0; + public static final int LANDSCAPE = 1; + + public static int SHORTSIDE = 612; + public static int LONGSIDE = 792; + + static Vector fonts = new Vector(); + + static { + fonts.addElement("Helvetica"); + fonts.addElement("Times-Roman"); + fonts.addElement("Courier New"); + } + + static Vector fontsizes = new Vector(); + + static { + fontsizes.addElement("6"); + fontsizes.addElement("8"); + fontsizes.addElement("10"); + fontsizes.addElement("12"); + fontsizes.addElement("14"); + fontsizes.addElement("16"); + } + + public int orientation = PORTRAIT; + public int width = SHORTSIDE; + public int height = LONGSIDE; + + public int xoffset = 30; + public int yoffset = 30; + public int fsize = 8; + public String font = "Helvetica"; + + public PostscriptProperties() {} + + public PostscriptProperties(int or, int w, int h, int xoff, int yoff, int fsize, String font) { + + this.orientation = or; + this.width = w; + this.height = h; + this.xoffset = xoff; + this.yoffset = yoff; + this.fsize = fsize; + this.font = font; + } + + public int getOrientation() { + return orientation; + } + public int getWidth() { + return width; + } + public int getHeight() { + return height; + } + public int getXOffset() { + return xoffset; + } + public int getYOffset() { + return yoffset; + } + public int getFSize() { + return fsize; + } + public String getFont() { + return font; + } +} diff --git a/src/jalview/io/SequenceFeatureSourceI.java b/src/jalview/io/SequenceFeatureSourceI.java new file mode 100755 index 0000000..90c8bd3 --- /dev/null +++ b/src/jalview/io/SequenceFeatureSourceI.java @@ -0,0 +1,13 @@ +package jalview.io; + +import jalview.datamodel.*; +import java.util.*; + +public interface SequenceFeatureSourceI { + public Sequence getSequence(); + public String getSequenceString(); + public String getId(); + public Vector getFeatures(); + public Vector getPDBCode(); + +} diff --git a/src/jalview/jbgui/GAlignFrame.java b/src/jalview/jbgui/GAlignFrame.java new file mode 100755 index 0000000..20df46f --- /dev/null +++ b/src/jalview/jbgui/GAlignFrame.java @@ -0,0 +1,935 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.jbgui; + +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; +import javax.swing.event.*; + + +public class GAlignFrame extends JInternalFrame +{ + protected JMenuBar alignFrameMenuBar = new JMenuBar(); + protected JMenu fileMenu = new JMenu(); + protected JMenuItem saveAsPostscriptMenuItem = new JMenuItem(); + protected JMenuItem closeMenuItem = new JMenuItem(); + protected JMenu editMenu = new JMenu(); + protected JMenu fontMenu = new JMenu(); + protected JMenu viewMenu = new JMenu(); + protected JMenu colourMenu = new JMenu(); + protected JMenu calculateMenu = new JMenu(); + protected JMenu alignMenu = new JMenu(); + protected JMenuItem groupsMenuItem = new JMenuItem(); + protected JCheckBoxMenuItem groupEditingMenuItem = new JCheckBoxMenuItem(); + protected JMenuItem selectAllSequenceMenuItem = new JMenuItem(); + protected JMenuItem deselectAllSequenceMenuItem = new JMenuItem(); + protected JMenuItem invertSequenceMenuItem = new JMenuItem(); + protected JMenuItem deleteSelectedMenuItem = new JMenuItem(); + protected JMenuItem moveSelectedMenuItem = new JMenuItem(); + protected JMenuItem copySelectedMenuItem = new JMenuItem(); + protected JMenuItem deselectAllColumnsMenuItem = new JMenuItem(); + protected JMenuItem remove2LeftMenuItem = new JMenuItem(); + protected JMenuItem remove2RightMenuItem = new JMenuItem(); + protected JMenuItem removeGappedColumnMenuItem = new JMenuItem(); + protected JMenuItem removeAllGapsMenuItem = new JMenuItem(); + protected JMenuItem setGapCharMenuItem = new JMenuItem(); + protected JMenuItem fontNameMenuItem = new JMenuItem(); + protected JMenuItem fontSizeMenuItem = new JMenuItem(); + protected JMenuItem fontStyleMenuItem = new JMenuItem(); + protected JCheckBoxMenuItem viewBoxesMenuItem = new JCheckBoxMenuItem(); + protected JCheckBoxMenuItem viewTextMenuItem = new JCheckBoxMenuItem(); + protected JMenuItem sortPairwiseMenuItem = new JMenuItem(); + protected JMenuItem sortIDMenuItem = new JMenuItem(); + protected JMenuItem sortGroupMenuItem = new JMenuItem(); + protected JMenuItem sortTreeOrderMenuItem = new JMenuItem(); + protected JMenuItem removeRedundancyMenuItem = new JMenuItem(); + protected JMenuItem pairwiseAlignmentMenuItem = new JMenuItem(); + protected JMenuItem PCAMenuItem = new JMenuItem(); + protected JMenuItem averageDistanceTreeMenuItem = new JMenuItem(); + protected JMenuItem neighbourTreeMenuItem = new JMenuItem(); + protected JMenuItem clustalAlignMenuItem = new JMenuItem(); + BorderLayout borderLayout1 = new BorderLayout(); + public JLabel statusBar = new JLabel(); + protected JMenu saveAlignmentMenu = new JMenu(); + protected JMenu outputTextboxMenu = new JMenu(); + protected JRadioButtonMenuItem clustalColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem zappoColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem taylorColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem hydrophobicityColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem helixColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem strandColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem turnColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem buriedColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem conservationColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem abovePIDColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem userDefinedColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem PIDColour = new JRadioButtonMenuItem(); + protected JRadioButtonMenuItem BLOSUM62Colour = new JRadioButtonMenuItem(); + JMenuItem njTreeBlosumMenuItem = new JMenuItem(); + JMenuItem avDistanceTreeBlosumMenuItem = new JMenuItem(); + JMenuItem conservationColourIncMenuItem = new JMenuItem(); + protected JCheckBoxMenuItem consensusGraphMenuItem = new JCheckBoxMenuItem(); + protected JCheckBoxMenuItem colourTextMenuItem = new JCheckBoxMenuItem(); + JMenuItem htmlMenuItem = new JMenuItem(); + JMenuItem schemeKeyMenuItem = new JMenuItem(); + public GAlignFrame() + { + try + { + jbInit(); + setJMenuBar(alignFrameMenuBar); + + JMenuItem item; + // dynamically fill save as menu with available formats + for (int i = 0; i < jalview.io.FormatProperties.getFormats().size(); i++) { + item = new JMenuItem((String) jalview.io.FormatProperties.getFormats().elementAt(i)); + saveAlignmentMenu.add( item ); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + saveAs_actionPerformed(e); + } + }); + + item = new JMenuItem((String) jalview.io.FormatProperties.getFormats().elementAt(i)); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + outputText_actionPerformed(e); + } + }); + + outputTextboxMenu.add( item ); + } + + } + catch(Exception e) + { + e.printStackTrace(); + } + + ButtonGroup colours = new ButtonGroup(); + colours.add(clustalColour); + colours.add(zappoColour); + colours.add(taylorColour); + colours.add(hydrophobicityColour); + colours.add(helixColour); + colours.add(strandColour); + colours.add(turnColour); + colours.add(buriedColour); + colours.add(conservationColour); + colours.add(abovePIDColour); + colours.add(userDefinedColour); + colours.add(PIDColour); + colours.add(BLOSUM62Colour); + } + private void jbInit() throws Exception + { + fileMenu.setMnemonic('F'); + fileMenu.setText("File"); + saveAlignmentMenu.setMnemonic('L'); + saveAlignmentMenu.setText("Save alignment to local file"); + saveAsPostscriptMenuItem.setMnemonic('P'); + saveAsPostscriptMenuItem.setText("Save alignment as postscript"); + saveAsPostscriptMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + saveAsPostscriptMenuItem_actionPerformed(e); + } + }); + closeMenuItem.setMnemonic('C'); + closeMenuItem.setText("Close"); + closeMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + closeMenuItem_actionPerformed(e); + } + }); + editMenu.setText("Edit"); + fontMenu.setText("Font"); + viewMenu.setText("View"); + colourMenu.setText("Colour"); + calculateMenu.setText("Calculate"); + alignMenu.setText("Web Service"); + groupsMenuItem.setEnabled(false); + groupsMenuItem.setText("Groups"); + groupsMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + groupsMenuItem_actionPerformed(e); + } + }); + groupEditingMenuItem.setEnabled(false); + groupEditingMenuItem.setText("Group editing mode"); + groupEditingMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + groupEditingMenuItem_actionPerformed(e); + } + }); + selectAllSequenceMenuItem.setText("Select all sequences"); + selectAllSequenceMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + selectAllSequenceMenuItem_actionPerformed(e); + } + }); + deselectAllSequenceMenuItem.setText("Deselect all sequences"); + deselectAllSequenceMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + deselectAllSequenceMenuItem_actionPerformed(e); + } + }); + invertSequenceMenuItem.setText("Invert sequence selection"); + invertSequenceMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + invertSequenceMenuItem_actionPerformed(e); + } + }); + deleteSelectedMenuItem.setText("Delete selected sequences"); + deleteSelectedMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + deleteSelectedMenuItem_actionPerformed(e); + } + }); + moveSelectedMenuItem.setText("Move selected sequences to new alignment"); + moveSelectedMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + moveSelectedMenuItem_actionPerformed(e); + } + }); + copySelectedMenuItem.setText("Copy selected sequences to new alignment"); + copySelectedMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + copySelectedMenuItem_actionPerformed(e); + } + }); + deselectAllColumnsMenuItem.setText("Deselect all columns"); + deselectAllColumnsMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + deselectAllColumnsMenuItem_actionPerformed(e); + } + }); + remove2LeftMenuItem.setText("Remove sequence <- left of selected column"); + remove2LeftMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + remove2LeftMenuItem_actionPerformed(e); + } + }); + remove2RightMenuItem.setText("Remove sequence -> right of selected column"); + remove2RightMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + remove2RightMenuItem_actionPerformed(e); + } + }); + removeGappedColumnMenuItem.setText("Remove gapped columns"); + removeGappedColumnMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + removeGappedColumnMenuItem_actionPerformed(e); + } + }); + removeAllGapsMenuItem.setText("Remove all gaps"); + removeAllGapsMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + removeAllGapsMenuItem_actionPerformed(e); + } + }); + setGapCharMenuItem.setText("Set gap character to \"-\""); + setGapCharMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + setGapCharMenuItem_actionPerformed(e); + } + }); + fontNameMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + fontNameMenuItem_actionPerformed(e); + } + }); + fontSizeMenuItem.setText("10"); + fontSizeMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + fontSizeMenuItem_actionPerformed(e); + } + }); + fontStyleMenuItem.setText("Plain"); + fontStyleMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + fontStyleMenuItem_actionPerformed(e); + } + }); + viewBoxesMenuItem.setText("Boxes"); + viewBoxesMenuItem.setState(true); + viewBoxesMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + viewBoxesMenuItem_actionPerformed(e); + } + }); + viewTextMenuItem.setText("Text"); + viewTextMenuItem.setState(true); + viewTextMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + viewTextMenuItem_actionPerformed(e); + } + }); + sortPairwiseMenuItem.setText("Sort by pairwise identity"); + sortPairwiseMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortPairwiseMenuItem_actionPerformed(e); + } + }); + sortIDMenuItem.setText("Sort by ID"); + sortIDMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortIDMenuItem_actionPerformed(e); + } + }); + sortGroupMenuItem.setText("Sort by group"); + sortGroupMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortGroupMenuItem_actionPerformed(e); + } + }); + sortTreeOrderMenuItem.setText("Sort by tree order"); + sortTreeOrderMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortTreeOrderMenuItem_actionPerformed(e); + } + }); + removeRedundancyMenuItem.setText("Remove redundancy"); + removeRedundancyMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + removeRedundancyMenuItem_actionPerformed(e); + } + }); + pairwiseAlignmentMenuItem.setText("Pairwise alignments"); + pairwiseAlignmentMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + pairwiseAlignmentMenuItem_actionPerformed(e); + } + }); + PCAMenuItem.setText("Principal component analysis"); + PCAMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + PCAMenuItem_actionPerformed(e); + } + }); + averageDistanceTreeMenuItem.setText("Average distance tree using PID"); + averageDistanceTreeMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + averageDistanceTreeMenuItem_actionPerformed(e); + } + }); + neighbourTreeMenuItem.setText("Neighbour joining tree using PID"); + neighbourTreeMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + neighbourTreeMenuItem_actionPerformed(e); + } + }); + clustalAlignMenuItem.setText("Clustal alignment"); + clustalAlignMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + clustalAlignMenuItem_actionPerformed(e); + } + }); + this.getContentPane().setLayout(borderLayout1); + alignFrameMenuBar.setFont(new java.awt.Font("Verdana", 0, 11)); + statusBar.setBackground(Color.white); + statusBar.setFont(new java.awt.Font("Verdana", 0, 11)); + statusBar.setBorder(BorderFactory.createLineBorder(Color.black)); + statusBar.setText("Status bar"); + outputTextboxMenu.setMnemonic('T'); + outputTextboxMenu.setText("Output alignment via textbox"); + clustalColour.setSelected(false); + clustalColour.setText("Clustalx colours"); + clustalColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + clustalColour_actionPerformed(e); + } + }); + zappoColour.setSelected(true); + zappoColour.setText("Zappo colour scheme"); + zappoColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + zappoColour_actionPerformed(e); + } + }); + taylorColour.setText("Taylor colour scheme"); + taylorColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + taylorColour_actionPerformed(e); + } + }); + hydrophobicityColour.setText("By hydrophobicity"); + hydrophobicityColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + hydrophobicityColour_actionPerformed(e); + } + }); + helixColour.setText("Helix propensity"); + helixColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + helixColour_actionPerformed(e); + } + }); + strandColour.setText("Strand propensity"); + strandColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + strandColour_actionPerformed(e); + } + }); + turnColour.setText("Turn propensity"); + turnColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + turnColour_actionPerformed(e); + } + }); + buriedColour.setText("Buried index"); + buriedColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + buriedColour_actionPerformed(e); + } + }); + conservationColour.setEnabled(false); + conservationColour.setText("By conservation"); + conservationColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + conservationColour_actionPerformed(e); + } + }); + abovePIDColour.setEnabled(false); + abovePIDColour.setText("Above PID threshold only"); + abovePIDColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + abovePIDColour_actionPerformed(e); + } + }); + userDefinedColour.setText("User defined colours"); + userDefinedColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + userDefinedColour_actionPerformed(e); + } + }); + PIDColour.setEnabled(false); + PIDColour.setText("By PID"); + PIDColour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + PIDColour_actionPerformed(e); + } + }); + BLOSUM62Colour.setText("By BLOSUM62 score"); + BLOSUM62Colour.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + BLOSUM62Colour_actionPerformed(e); + } + }); + avDistanceTreeBlosumMenuItem.setText("Average distance tree using BLOSUM62"); + avDistanceTreeBlosumMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + avTreeBlosumMenuItem_actionPerformed(e); + } + }); + njTreeBlosumMenuItem.setText("Neighbour joining tree using BLOSUM62"); + njTreeBlosumMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + njTreeBlosumMenuItem_actionPerformed(e); + } + }); + conservationColourIncMenuItem.setEnabled(false); + conservationColourIncMenuItem.setText("Conservation Colour Increment"); + conservationColourIncMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + conservationColourIncMenuItem_actionPerformed(e); + } + }); + consensusGraphMenuItem.setActionCommand(""); + consensusGraphMenuItem.setText("Consensus graph"); + consensusGraphMenuItem.setState(true); + consensusGraphMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + consensusGraphMenuItem_actionPerformed(e); + } + }); + colourTextMenuItem.setText("Colour text"); + colourTextMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + colourTextMenuItem_actionPerformed(e); + } + }); + htmlMenuItem.setText("Output as HTML"); + htmlMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + htmlMenuItem_actionPerformed(e); + } + }); + schemeKeyMenuItem.setText("Colour Scheme Key"); + schemeKeyMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + schemeKeyMenuItem_actionPerformed(e); + } + }); + alignFrameMenuBar.add(fileMenu); + alignFrameMenuBar.add(editMenu); + alignFrameMenuBar.add(fontMenu); + alignFrameMenuBar.add(viewMenu); + alignFrameMenuBar.add(colourMenu); + alignFrameMenuBar.add(calculateMenu); + alignFrameMenuBar.add(alignMenu); + fileMenu.add(saveAlignmentMenu); + fileMenu.add(saveAsPostscriptMenuItem); + fileMenu.add(outputTextboxMenu); + fileMenu.add(htmlMenuItem); + fileMenu.addSeparator(); + fileMenu.add(closeMenuItem); + editMenu.add(groupsMenuItem); + editMenu.add(groupEditingMenuItem); + editMenu.addSeparator(); + editMenu.add(selectAllSequenceMenuItem); + editMenu.add(deselectAllSequenceMenuItem); + editMenu.add(invertSequenceMenuItem); + editMenu.addSeparator(); + editMenu.add(deleteSelectedMenuItem); + editMenu.add(moveSelectedMenuItem); + editMenu.add(copySelectedMenuItem); + editMenu.addSeparator(); + editMenu.add(deselectAllColumnsMenuItem); + editMenu.add(remove2LeftMenuItem); + editMenu.add(remove2RightMenuItem); + editMenu.addSeparator(); + editMenu.add(removeGappedColumnMenuItem); + editMenu.add(removeAllGapsMenuItem); + editMenu.add(setGapCharMenuItem); + fontMenu.add(fontNameMenuItem); + fontMenu.add(fontSizeMenuItem); + fontMenu.add(fontStyleMenuItem); + fontMenu.addSeparator(); + fontMenu.add(colourTextMenuItem); + viewMenu.add(viewBoxesMenuItem); + viewMenu.add(viewTextMenuItem); + viewMenu.add(consensusGraphMenuItem); + colourMenu.add(clustalColour); + colourMenu.add(zappoColour); + colourMenu.add(taylorColour); + colourMenu.add(hydrophobicityColour); + colourMenu.add(helixColour); + colourMenu.add(strandColour); + colourMenu.add(turnColour); + colourMenu.add(buriedColour); + colourMenu.add(userDefinedColour); + colourMenu.addSeparator(); + colourMenu.add(conservationColour); + colourMenu.add(conservationColourIncMenuItem); + colourMenu.addSeparator(); + colourMenu.add(abovePIDColour); + colourMenu.add(PIDColour); + colourMenu.add(BLOSUM62Colour); + colourMenu.addSeparator(); + colourMenu.add(schemeKeyMenuItem); + calculateMenu.add(sortPairwiseMenuItem); + calculateMenu.add(sortIDMenuItem); + calculateMenu.add(sortGroupMenuItem); + calculateMenu.add(sortTreeOrderMenuItem); + calculateMenu.add(removeRedundancyMenuItem); + calculateMenu.addSeparator(); + calculateMenu.add(pairwiseAlignmentMenuItem); + calculateMenu.add(PCAMenuItem); + calculateMenu.addSeparator(); + calculateMenu.add(averageDistanceTreeMenuItem); + calculateMenu.add(neighbourTreeMenuItem); + calculateMenu.add(avDistanceTreeBlosumMenuItem); + calculateMenu.add(njTreeBlosumMenuItem); + alignMenu.add(clustalAlignMenuItem); + this.getContentPane().add(statusBar, BorderLayout.SOUTH); + } + + protected void saveAs_actionPerformed(ActionEvent e) + { + + } + + protected void outputText_actionPerformed(ActionEvent e) + { + + } + + protected void htmlMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + protected void saveAsPostscriptMenuItem_actionPerformed(ActionEvent e) + { + + } + + + protected void closeMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void groupsMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void groupEditingMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void selectAllSequenceMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void invertSequenceMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void deleteSelectedMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void moveSelectedMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void copySelectedMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void deselectAllColumnsMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void remove2LeftMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void remove2RightMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void removeGappedColumnMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void removeAllGapsMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void setGapCharMenuItem_actionPerformed(ActionEvent e) + { + + } + + + protected void fontNameMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void fontSizeMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void fontStyleMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void viewBoxesMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void viewTextMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void colourTextMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + protected void consensusGraphMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + + + + protected void sortPairwiseMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void sortIDMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void sortGroupMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void sortTreeOrderMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void removeRedundancyMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void PCAMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void neighbourTreeMenuItem_actionPerformed(ActionEvent e) + { + + } + + + protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + protected void clustalAlignMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + + protected void clustalColour_actionPerformed(ActionEvent e) + { + + } + + protected void zappoColour_actionPerformed(ActionEvent e) + { + + } + + protected void taylorColour_actionPerformed(ActionEvent e) + { + + } + + + protected void hydrophobicityColour_actionPerformed(ActionEvent e) + { + + } + + protected void helixColour_actionPerformed(ActionEvent e) + { + + } + + protected void strandColour_actionPerformed(ActionEvent e) + { + + } + + protected void turnColour_actionPerformed(ActionEvent e) + { + + } + + protected void buriedColour_actionPerformed(ActionEvent e) + { + + } + + protected void conservationColour_actionPerformed(ActionEvent e) + { + + } + + protected void conservationColourIncMenuItem_actionPerformed(ActionEvent e) + { + + } + + + protected void abovePIDColour_actionPerformed(ActionEvent e) + { + + } + + + protected void userDefinedColour_actionPerformed(ActionEvent e) + { + + } + + protected void PIDColour_actionPerformed(ActionEvent e) + { + + } + + protected void BLOSUM62Colour_actionPerformed(ActionEvent e) + { + + } + + protected void schemeKeyMenuItem_actionPerformed(ActionEvent e) + { + + } + +} diff --git a/src/jalview/jbgui/GAlignmentPanel.java b/src/jalview/jbgui/GAlignmentPanel.java new file mode 100755 index 0000000..c361c1e --- /dev/null +++ b/src/jalview/jbgui/GAlignmentPanel.java @@ -0,0 +1,86 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.jbgui; + +import java.awt.*; +import javax.swing.*; + +public class GAlignmentPanel extends JPanel +{ + protected JPanel sequenceHolderPanel = new JPanel(); + protected JScrollBar vscroll = new JScrollBar(); + protected JScrollBar hscroll = new JScrollBar(); + protected JPanel seqPanelHolder = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + BorderLayout borderLayout3 = new BorderLayout(); + JPanel jPanel2 = new JPanel(); + BorderLayout borderLayout2 = new BorderLayout(); + protected JPanel scorePanelHolder = new JPanel(); + protected JPanel scalePanelHolder = new JPanel(); + protected JPanel idPanelHolder = new JPanel(); + BorderLayout borderLayout5 = new BorderLayout(); + JPanel jPanel3 = new JPanel(); + protected JPanel idSpaceFillerPanel = new JPanel(); + BorderLayout borderLayout4 = new BorderLayout(); + BorderLayout borderLayout6 = new BorderLayout(); + ButtonGroup buttonGroup1 = new ButtonGroup(); + BorderLayout borderLayout7 = new BorderLayout(); + + public GAlignmentPanel() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + private void jbInit() throws Exception + { + idPanelHolder.setBorder(null); + idPanelHolder.setPreferredSize(new Dimension(70, 10)); + this.setLayout(borderLayout7); + sequenceHolderPanel.setMaximumSize(new Dimension(2147483647, 2147483647)); + sequenceHolderPanel.setMinimumSize(new Dimension(150, 150)); + sequenceHolderPanel.setPreferredSize(new Dimension(150, 150)); + sequenceHolderPanel.setLayout(borderLayout3); + seqPanelHolder.setLayout(borderLayout1); + jPanel2.setBackground(new Color(212, 208, 230)); + jPanel2.setBorder(null); + jPanel2.setLayout(borderLayout2); + scalePanelHolder.setBackground(Color.white); + scalePanelHolder.setMinimumSize(new Dimension(10, 80)); + scalePanelHolder.setPreferredSize(new Dimension(10, 30)); + scalePanelHolder.setLayout(borderLayout6); + scorePanelHolder.setBackground(Color.white); + scorePanelHolder.setPreferredSize(new Dimension(10, 80)); + scorePanelHolder.setLayout(borderLayout4); + idPanelHolder.setLayout(borderLayout5); + jPanel3.setBackground(Color.white); + jPanel3.setPreferredSize(new Dimension(10, 30)); + idSpaceFillerPanel.setBackground(Color.white); + idSpaceFillerPanel.setPreferredSize(new Dimension(10, 80)); + hscroll.setOrientation(JScrollBar.HORIZONTAL); + vscroll.setEnabled(true); + sequenceHolderPanel.add(scorePanelHolder, BorderLayout.SOUTH); + sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH); + sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER); + this.add(jPanel2, BorderLayout.CENTER); + jPanel2.add(sequenceHolderPanel, BorderLayout.CENTER); + seqPanelHolder.add(vscroll, BorderLayout.EAST); + seqPanelHolder.add(hscroll, BorderLayout.SOUTH); + this.add(idPanelHolder, BorderLayout.WEST); + idPanelHolder.add(jPanel3, BorderLayout.NORTH); + idPanelHolder.add(idSpaceFillerPanel, BorderLayout.SOUTH); + } + + +} diff --git a/src/jalview/jbgui/GColourKey.java b/src/jalview/jbgui/GColourKey.java new file mode 100755 index 0000000..da4eb74 --- /dev/null +++ b/src/jalview/jbgui/GColourKey.java @@ -0,0 +1,201 @@ +package jalview.jbgui; + +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; + +public class GColourKey extends JInternalFrame +{ + JMenuBar jMenuBar1 = new JMenuBar(); + protected JMenu menu = new JMenu(); + JRadioButtonMenuItem clustalMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem zappoMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem taylorMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem hydroMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem helixMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem strandMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem turnMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem buriedMenuItem = new JRadioButtonMenuItem(); + JRadioButtonMenuItem blosumMenuItem = new JRadioButtonMenuItem(); + FlowLayout flowLayout1 = new FlowLayout(); + + public GColourKey() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + + this.setJMenuBar( jMenuBar1 ); + ButtonGroup colours = new ButtonGroup(); + colours.add(clustalMenuItem); + colours.add(zappoMenuItem); + colours.add(taylorMenuItem); + colours.add(hydroMenuItem); + colours.add(helixMenuItem); + colours.add(strandMenuItem); + colours.add(turnMenuItem); + colours.add(buriedMenuItem); + colours.add(blosumMenuItem); + + } + private void jbInit() throws Exception + { + menu.setBackground(new Color(212, 208, 255)); + menu.setActionCommand("Color Scheme"); + menu.setText("Zappo Colour Scheme"); + clustalMenuItem.setBackground(new Color(212, 208, 255)); + clustalMenuItem.setText("ClustalX "); + clustalMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + clustalMenuItem_actionPerformed(e); + } + }); + zappoMenuItem.setBackground(new Color(212, 208, 255)); + zappoMenuItem.setSelected(true); + zappoMenuItem.setText("Zappo"); + zappoMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + zappoMenuItem_actionPerformed(e); + } + }); + taylorMenuItem.setBackground(new Color(212, 208, 255)); + taylorMenuItem.setText("Taylor"); + taylorMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + taylorMenuItem_actionPerformed(e); + } + }); + hydroMenuItem.setBackground(new Color(212, 208, 255)); + hydroMenuItem.setText("Hydrophobicity"); + hydroMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + hydroMenuItem_actionPerformed(e); + } + }); + helixMenuItem.setBackground(new Color(212, 208, 255)); + helixMenuItem.setText("Helix Propensity"); + helixMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + helixMenuItem_actionPerformed(e); + } + }); + strandMenuItem.setBackground(new Color(212, 208, 255)); + strandMenuItem.setText("Strand Propensity"); + strandMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + strandMenuItem_actionPerformed(e); + } + }); + turnMenuItem.setBackground(new Color(212, 208, 255)); + turnMenuItem.setText("Turn Propensity"); + turnMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + turnMenuItem_actionPerformed(e); + } + }); + buriedMenuItem.setBackground(new Color(212, 208, 255)); + buriedMenuItem.setText("Buried Index"); + buriedMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + buriedMenuItem_actionPerformed(e); + } + }); + blosumMenuItem.setBackground(new Color(212, 208, 255)); + blosumMenuItem.setText("Blosum62"); + blosumMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + blosumMenuItem_actionPerformed(e); + } + }); + this.getContentPane().setLayout(flowLayout1); + this.getContentPane().setBackground(new Color(212, 208, 255)); + jMenuBar1.setBackground(new Color(212, 208, 255)); + jMenuBar1.add(menu); + menu.add(clustalMenuItem); + menu.add(zappoMenuItem); + menu.add(taylorMenuItem); + menu.add(hydroMenuItem); + menu.add(helixMenuItem); + menu.add(strandMenuItem); + menu.add(turnMenuItem); + menu.add(buriedMenuItem); + menu.add(blosumMenuItem); + + } + + protected void clustalMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void zappoMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void taylorMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void hydroMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void helixMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void strandMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void turnMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void buriedMenuItem_actionPerformed(ActionEvent e) + { + + } + + protected void blosumMenuItem_actionPerformed(ActionEvent e) + { + + } + + + + + + + + +} diff --git a/src/jalview/jbgui/GCutAndPasteTransfer.java b/src/jalview/jbgui/GCutAndPasteTransfer.java new file mode 100755 index 0000000..6922fd3 --- /dev/null +++ b/src/jalview/jbgui/GCutAndPasteTransfer.java @@ -0,0 +1,82 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.jbgui; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + +public class GCutAndPasteTransfer extends JPanel +{ + protected JTextArea textarea = new JTextArea(); + protected JComboBox formatChoice = new JComboBox(); + protected JLabel formatLabel = new JLabel(); + protected JScrollPane scrollPane = new JScrollPane(); + public GCutAndPasteTransfer() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + + } + private void jbInit() throws Exception + { + textarea.setFont(new java.awt.Font("Verdana", 0, 12)); + textarea.setBorder(BorderFactory.createLineBorder(Color.black)); + textarea.setText("Paste your alignment file here"); + textarea.addMouseListener(new java.awt.event.MouseAdapter() + { + public void mousePressed(MouseEvent e) + { + textarea_mousePressed(e); + } + }); + formatChoice.setFont(new java.awt.Font("Verdana", 0, 12)); + formatChoice.setBounds(new Rectangle(194, 269, 159, 22)); + formatChoice.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + formatChoice_actionPerformed(e); + } + }); + formatLabel.setFont(new java.awt.Font("Verdana", 0, 12)); + formatLabel.setHorizontalAlignment(SwingConstants.TRAILING); + formatLabel.setText("Alignment Format"); + formatLabel.setBounds(new Rectangle(76, 272, 110, 16)); + this.setLayout(null); + this.setPreferredSize(new Dimension(400, 300)); + scrollPane.setBounds(new Rectangle(5, 5, 389, 256)); + this.add(formatLabel, null); + this.add(formatChoice, null); + this.add(scrollPane, null); + scrollPane.getViewport().add(textarea, null); + + } + + + + protected void formatChoice_actionPerformed(ActionEvent e) + { + + } + + void textarea_mousePressed(MouseEvent e) + { + if(textarea.getText().equals("Paste your alignment file here")) + textarea.setText(""); + } + +} diff --git a/src/jalview/jbgui/GDesktop.java b/src/jalview/jbgui/GDesktop.java new file mode 100755 index 0000000..475153d --- /dev/null +++ b/src/jalview/jbgui/GDesktop.java @@ -0,0 +1,145 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.jbgui; + +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; + + +public class GDesktop extends JFrame +{ + JMenuBar DesktopMenubar = new JMenuBar(); + JMenu FileMenu = new JMenu(); + JMenu HelpMenu = new JMenu(); + JMenuItem inputLocalFileMenuItem = new JMenuItem(); + JMenuItem inputURLMenuItem = new JMenuItem(); + JMenuItem inputTextboxMenuItem = new JMenuItem(); + JMenuItem quit = new JMenuItem(); + JMenuItem aboutMenuItem = new JMenuItem(); + JMenuItem documentationMenuItem = new JMenuItem(); + JMenuItem colourIndexMenuItem = new JMenuItem(); + FlowLayout flowLayout1 = new FlowLayout(); + protected static JMenu windowMenu = new JMenu(); + public GDesktop() + { + try + { + jbInit(); + this.setJMenuBar(DesktopMenubar); + } + catch(Exception e) + { + e.printStackTrace(); + } + + } + private void jbInit() throws Exception + { + FileMenu.setMnemonic('F'); + FileMenu.setText("File"); + HelpMenu.setText("Help"); + inputLocalFileMenuItem.setMnemonic('L'); + inputLocalFileMenuItem.setText("Input Alignment From Local File"); + inputLocalFileMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + inputLocalFileMenuItem_actionPerformed(e); + } + }); + inputURLMenuItem.setMnemonic('U'); + inputURLMenuItem.setText("Input Alignment From URL"); + inputURLMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + inputURLMenuItem_actionPerformed(e); + } + }); + inputTextboxMenuItem.setMnemonic('T'); + inputTextboxMenuItem.setText("Input Alignment via Textbox"); + inputTextboxMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + inputTextboxMenuItem_actionPerformed(e); + } + }); + quit.setMnemonic('Q'); + quit.setText("Quit"); + quit.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + quit_actionPerformed(e); + } + }); + aboutMenuItem.setText("About"); + aboutMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + aboutMenuItem_actionPerformed(e); + } + }); + documentationMenuItem.setText("Documentation"); + documentationMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + documentationMenuItem_actionPerformed(e); + } + }); + colourIndexMenuItem.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + colourIndexMenuItem_actionPerformed(e); + } + }); + colourIndexMenuItem.setText("Colour Scheme Key"); + this.getContentPane().setLayout(flowLayout1); + windowMenu.setText("Window"); + DesktopMenubar.add(FileMenu); + DesktopMenubar.add(HelpMenu); + DesktopMenubar.add(windowMenu); + FileMenu.add(inputLocalFileMenuItem); + FileMenu.add(inputURLMenuItem); + FileMenu.add(inputTextboxMenuItem); + FileMenu.addSeparator(); + FileMenu.add(quit); + HelpMenu.add(colourIndexMenuItem); + HelpMenu.add(aboutMenuItem); + HelpMenu.add(documentationMenuItem); + } + + protected void inputLocalFileMenuItem_actionPerformed(ActionEvent e) + { } + + protected void inputURLMenuItem_actionPerformed(ActionEvent e) + { } + + protected void inputTextboxMenuItem_actionPerformed(ActionEvent e) + { } + + protected void quit_actionPerformed(ActionEvent e) + { } + + protected void aboutMenuItem_actionPerformed(ActionEvent e) + { } + + protected void documentationMenuItem_actionPerformed(ActionEvent e) + { } + + protected void colourIndexMenuItem_actionPerformed(ActionEvent e) + { + + } +} diff --git a/src/jalview/jbgui/GPCAPanel.java b/src/jalview/jbgui/GPCAPanel.java new file mode 100755 index 0000000..717c817 --- /dev/null +++ b/src/jalview/jbgui/GPCAPanel.java @@ -0,0 +1,97 @@ +package jalview.jbgui; + +import java.awt.*; +import javax.swing.*; +import java.awt.event.*; + +public class GPCAPanel extends JPanel +{ + JPanel jPanel2 = new JPanel(); + JLabel jLabel1 = new JLabel(); + JLabel jLabel2 = new JLabel(); + JLabel jLabel3 = new JLabel(); + protected JComboBox xCombobox = new JComboBox(); + protected JComboBox yCombobox = new JComboBox(); + protected JComboBox zCombobox = new JComboBox(); + FlowLayout flowLayout1 = new FlowLayout(); + BorderLayout borderLayout1 = new BorderLayout(); + + public GPCAPanel() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + + for(int i=1; i<8; i++) + { + xCombobox.addItem("dim "+i); + yCombobox.addItem("dim "+i); + zCombobox.addItem("dim "+i); + } + } + private void jbInit() throws Exception + { + this.setLayout(borderLayout1); + jPanel2.setLayout(flowLayout1); + jLabel1.setFont(new java.awt.Font("Verdana", 0, 12)); + jLabel1.setText("x="); + jLabel2.setFont(new java.awt.Font("Verdana", 0, 12)); + jLabel2.setText("y="); + jLabel3.setFont(new java.awt.Font("Verdana", 0, 12)); + jLabel3.setText("z="); + jPanel2.setBackground(Color.white); + jPanel2.setBorder(null); + zCombobox.setFont(new java.awt.Font("Verdana", 0, 12)); + zCombobox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + zCombobox_actionPerformed(e); + } + }); + yCombobox.setFont(new java.awt.Font("Verdana", 0, 12)); + yCombobox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + yCombobox_actionPerformed(e); + } + }); + xCombobox.setFont(new java.awt.Font("Verdana", 0, 12)); + xCombobox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + xCombobox_actionPerformed(e); + } + }); + this.add(jPanel2, BorderLayout.SOUTH); + jPanel2.add(jLabel1, null); + jPanel2.add(xCombobox, null); + jPanel2.add(jLabel2, null); + jPanel2.add(yCombobox, null); + jPanel2.add(jLabel3, null); + jPanel2.add(zCombobox, null); + } + + protected void xCombobox_actionPerformed(ActionEvent e) + { + + } + + protected void yCombobox_actionPerformed(ActionEvent e) + { + + } + + protected void zCombobox_actionPerformed(ActionEvent e) + { + + } + +} diff --git a/src/jalview/jbgui/GPairwiseAlignPanel.java b/src/jalview/jbgui/GPairwiseAlignPanel.java new file mode 100755 index 0000000..77c0d79 --- /dev/null +++ b/src/jalview/jbgui/GPairwiseAlignPanel.java @@ -0,0 +1,53 @@ +package jalview.jbgui; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + +public class GPairwiseAlignPanel extends JPanel +{ + protected JScrollPane scrollPane = new JScrollPane(); + protected JTextArea textarea = new JTextArea(); + protected JButton viewInEditorButton = new JButton(); + JPanel jPanel1 = new JPanel(); + BorderLayout borderLayout1 = new BorderLayout(); + + public GPairwiseAlignPanel() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + private void jbInit() throws Exception + { + this.setLayout(borderLayout1); + textarea.setFont(new java.awt.Font("Monospaced", 0, 12)); + textarea.setText(""); + textarea.setWrapStyleWord(false); + viewInEditorButton.setFont(new java.awt.Font("Verdana", 0, 12)); + viewInEditorButton.setText("View in alignment editor"); + viewInEditorButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + viewInEditorButton_actionPerformed(e); + } + }); + this.add(scrollPane, BorderLayout.CENTER); + scrollPane.getViewport().add(textarea, null); + this.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(viewInEditorButton, null); + } + + protected void viewInEditorButton_actionPerformed(ActionEvent e) + { + + } + +} diff --git a/src/jalview/jbgui/GTreePanel.java b/src/jalview/jbgui/GTreePanel.java new file mode 100755 index 0000000..43ee7c9 --- /dev/null +++ b/src/jalview/jbgui/GTreePanel.java @@ -0,0 +1,108 @@ +package jalview.jbgui; + +import java.awt.*; +import javax.swing.*; +import java.awt.event.*; + +public class GTreePanel extends JPanel +{ + BorderLayout borderLayout1 = new BorderLayout(); + JPanel jPanel1 = new JPanel(); + JLabel jLabel1 = new JLabel(); + protected JComboBox fontSizeCombobox = new JComboBox(); + protected JCheckBox showDistanceCheckbox = new JCheckBox(); + protected JButton saveButton = new JButton(); + protected JCheckBox bootStrapCheckBox = new JCheckBox(); + protected JScrollPane scrollPane = new JScrollPane(); + + public GTreePanel() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + + for(int i=2; i<26; i+=2) + fontSizeCombobox.addItem(i+""); + fontSizeCombobox.setSelectedItem("12"); + + } + private void jbInit() throws Exception + { + this.setLayout(borderLayout1); + jLabel1.setFont(new java.awt.Font("Verdana", 0, 12)); + jLabel1.setText("Font size"); + showDistanceCheckbox.setFont(new java.awt.Font("Verdana", 0, 12)); + showDistanceCheckbox.setText("Show distances"); + showDistanceCheckbox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + showDistanceCheckbox_actionPerformed(e); + } + }); + saveButton.setFont(new java.awt.Font("Verdana", 0, 12)); + saveButton.setToolTipText(""); + saveButton.setText("Save as postscript"); + saveButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + saveButton_actionPerformed(e); + } + }); + this.setBackground(Color.white); + this.setFont(new java.awt.Font("Verdana", 0, 12)); + this.setMinimumSize(new Dimension(530, 60)); + fontSizeCombobox.setFont(new java.awt.Font("Verdana", 0, 12)); + fontSizeCombobox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + fontSizeCombobox_actionPerformed(e); + } + }); + bootStrapCheckBox.setFont(new java.awt.Font("Verdana", 0, 12)); + bootStrapCheckBox.setText("Show bootstrap"); + bootStrapCheckBox.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bootStrapCheckBox_actionPerformed(e); + } + }); + scrollPane.setOpaque(false); + this.add(jPanel1, BorderLayout.SOUTH); + jPanel1.add(jLabel1, null); + jPanel1.add(fontSizeCombobox, null); + jPanel1.add(showDistanceCheckbox, null); + jPanel1.add(bootStrapCheckBox, null); + jPanel1.add(saveButton, null); + this.add(scrollPane, BorderLayout.CENTER); + } + + + public void saveButton_actionPerformed(ActionEvent e) + { + + } + + public void showDistanceCheckbox_actionPerformed(ActionEvent e) + { + + } + + public void fontSizeCombobox_actionPerformed(ActionEvent e) + { + + } + + public void bootStrapCheckBox_actionPerformed(ActionEvent e) + { + + } +} diff --git a/src/jalview/jbgui/GUserDefinedColours.java b/src/jalview/jbgui/GUserDefinedColours.java new file mode 100755 index 0000000..9086c39 --- /dev/null +++ b/src/jalview/jbgui/GUserDefinedColours.java @@ -0,0 +1,121 @@ +package jalview.jbgui; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + +public class GUserDefinedColours extends JPanel +{ + protected JColorChooser colorChooser = new JColorChooser(); + protected JPanel buttonPanel = new JPanel(); + protected GridLayout gridLayout = new GridLayout(); + JPanel jPanel2 = new JPanel(); + protected JButton okButton = new JButton(); + protected JButton applyButton = new JButton(); + protected JButton loadbutton = new JButton(); + protected JButton savebutton = new JButton(); + protected JButton cancelButton = new JButton(); + FlowLayout flowLayout1 = new FlowLayout(); + + public GUserDefinedColours() + { + try + { + jbInit(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + private void jbInit() throws Exception + { + this.setLayout(flowLayout1); + buttonPanel.setLayout(gridLayout); + gridLayout.setColumns(6); + gridLayout.setRows(4); + okButton.setFont(new java.awt.Font("Verdana", 0, 11)); + okButton.setText("OK"); + okButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + okButton_actionPerformed(e); + } + }); + applyButton.setFont(new java.awt.Font("Verdana", 0, 11)); + applyButton.setText("Apply"); + applyButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + applyButton_actionPerformed(e); + } + }); + loadbutton.setFont(new java.awt.Font("Verdana", 0, 11)); + loadbutton.setText("Load scheme"); + loadbutton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + loadbutton_actionPerformed(e); + } + }); + savebutton.setFont(new java.awt.Font("Verdana", 0, 11)); + savebutton.setText("Save scheme"); + savebutton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + savebutton_actionPerformed(e); + } + }); + cancelButton.setFont(new java.awt.Font("Verdana", 0, 11)); + cancelButton.setText("Cancel"); + cancelButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + cancelButton_actionPerformed(e); + } + }); + this.setBackground(new Color(212, 208, 223)); + jPanel2.setOpaque(false); + colorChooser.setOpaque(false); + this.add(colorChooser, null); + this.add(buttonPanel, null); + this.add(jPanel2, null); + jPanel2.add(okButton, null); + jPanel2.add(applyButton, null); + jPanel2.add(loadbutton, null); + jPanel2.add(savebutton, null); + jPanel2.add(cancelButton, null); + } + + + protected void okButton_actionPerformed(ActionEvent e) + { + + } + + protected void applyButton_actionPerformed(ActionEvent e) + { + + } + + protected void loadbutton_actionPerformed(ActionEvent e) + { + + } + + protected void savebutton_actionPerformed(ActionEvent e) + { + + } + + protected void cancelButton_actionPerformed(ActionEvent e) + { + + } +} diff --git a/src/jalview/math/Matrix.java b/src/jalview/math/Matrix.java new file mode 100755 index 0000000..d08fe22 --- /dev/null +++ b/src/jalview/math/Matrix.java @@ -0,0 +1,572 @@ +package jalview.math; + +import jalview.util.*; + +import java.io.*; + +public class Matrix { + + /** + * SMJSPUBLIC + */ + public double[][] value; + public int rows; + public int cols; + public double[] d; // Diagonal + public double[] e; // off diagonal + + public Matrix(double[][] value, int rows, int cols) { + this.rows = rows; + this.cols = cols; + this.value = value; + } + + public Matrix transpose() { + double[][] out = new double[cols][rows]; + + for (int i = 0; i < cols; i++) { + for (int j = 0; j < rows ; j++) { + out[i][j] = value[j][i]; + } + } + return new Matrix(out,cols,rows); + } + + public void print(PrintStream ps) { + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + Format.print(ps,"%8.2f",value[i][j]); + } + ps.println(); + } + } + + + public Matrix preMultiply(Matrix in) { + double[][] tmp = new double[in.rows][this.cols]; + + for (int i = 0; i < in.rows; i++) { + for (int j = 0; j < this.cols; j++ ) { + tmp[i][j] = 0.0; + + for (int k = 0; k < in.cols; k++) { + tmp[i][j] += in.value[i][k]*this.value[k][j]; + } + + } + } + + return new Matrix(tmp,in.rows,this.cols); + } + + public double[] vectorPostMultiply(double[] in) { + double[] out = new double[in.length]; + for (int i = 0; i < in.length; i++) { + out[i] = 0.0; + for (int k=0; k < in.length; k++) { + out[i] += value[i][k] * in[k]; + } + } + return out; + } + public Matrix postMultiply(Matrix in) { + + double[][] out = new double[this.rows][in.cols]; + for (int i = 0; i < this.rows; i++) { + for (int j = 0; j < in.cols; j++ ) { + + out[i][j] = 0.0; + + for (int k = 0; k < rows; k++) { + out[i][j] = out[i][j] + value[i][k]*in.value[k][j]; + } + + } + } + return new Matrix(out,this.cols,in.rows); + } + + public Matrix copy() { + double[][] newmat = new double[rows][cols]; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + newmat[i][j] = value[i][j]; + } + } + return new Matrix(newmat,rows,cols); + } + + public void tred() { + int n = rows; + int l; + int k; + int j; + int i; + + double scale; + double hh; + double h; + double g; + double f; + + this.d = new double[rows]; + this.e = new double[rows]; + + for (i=n; i >= 2;i--) { + l=i-1; + h = 0.0; + scale = 0.0; + + if (l > 1) { + for (k=1;k<=l;k++) { + scale += Math.abs(value[i-1][k-1]); + } + if (scale == 0.0) { + e[i-1] = value[i-1][l-1]; + } else { + for (k=1; k <= l; k++) { + value[i-1][k-1] /= scale; + h += value[i-1][k-1]*value[i-1][k-1]; + } + f = value[i-1][l-1]; + if (f>0) { + g = -1.0*Math.sqrt(h); + } else { + g = Math.sqrt(h); + } + e[i-1] = scale*g; + h -= f*g; + value[i-1][l-1] = f-g; + f=0.0; + for (j=1; j <= l; j++) { + value[j-1][i-1] = value[i-1][j-1]/h; + g=0.0; + for (k= 1; k <= j; k++) { + g += value[j-1][k-1]*value[i-1][k-1]; + } + for (k=j+1; k<=l;k++) { + g+= value[k-1][j-1]*value[i-1][k-1]; + } + e[j-1] = g/h; + f+=e[j-1]*value[i-1][j-1]; + } + hh=f/(h+h); + for (j=1;j<=l;j++) { + f=value[i-1][j-1]; + g = e[j-1] - hh*f; + e[j-1] = g; + for (k=1;k<=j;k++) { + value[j-1][k-1] -= (f*e[k-1]+g*value[i-1][k-1]); + } + } + } + } else { + e[i-1] = value[i-1][l-1]; + } + d[i-1] = h; + } + d[0] = 0.0; + e[0] = 0.0; + for (i=1;i<=n;i++) { + l=i-1; + if (d[i-1] != 0.0) { + for (j=1;j<=l;j++) { + g=0.0; + for (k=1;k<=l;k++) { + g+= value[i-1][k-1]*value[k-1][j-1]; + } + for (k=1;k<=l;k++) { + value[k-1][j-1] -= g*value[k-1][i-1]; + } + } + } + d[i-1] = value[i-1][i-1]; + value[i-1][i-1] = 1.0; + for (j=1;j<=l;j++) { + value[j-1][i-1] = 0.0; + value[i-1][j-1] = 0.0; + } + } + } + + public void tqli() { + int n = rows; + + int m; + int l; + int iter; + int i; + int k; + double s; + double r; + double p; + ; + double g; + double f; + double dd; + double c; + double b; + + for (i=2;i<=n;i++) { + e[i-2] = e[i-1]; + } + e[n-1] = 0.0; + for (l=1;l<=n;l++) { + iter=0; + do { + for (m=l;m<=(n-1);m++) { + dd=Math.abs(d[m-1]) + Math.abs(d[m]); + if (Math.abs(e[m-1]) + dd == dd) + break; + } + if (m != l) { + iter++; + if (iter == 30) { + System.out.print("Too many iterations in tqli"); + System.exit(0); + } else { + // System.out.println("Iteration " + iter); + } + g=(d[l]-d[l-1])/(2.0*e[l-1]); + r = Math.sqrt((g*g) + 1.0); + g=d[m-1]-d[l-1]+e[l-1]/(g + sign(r,g)); + c = 1.0; + s = c; + p=0.0; + for (i=m-1;i>=l;i--) { + f = s*e[i-1]; + b = c*e[i-1]; + if (Math.abs(f) >= Math.abs(g)) { + c=g/f; + r = Math.sqrt((c*c)+1.0); + e[i] = f*r; + s = 1.0/r; + c *= s; + } else { + s=f/g; + r = Math.sqrt((s*s)+1.0); + e[i] = g*r; + c = 1.0/r; + s *= c; + } + g=d[i] -p; + r=(d[i-1]-g)*s + 2.0*c*b; + p=s*r; + d[i] = g + p; + g = c * r - b; + for (k=1; k <= n; k++) { + f=value[k-1][i]; + value[k-1][i] = s*value[k-1][i-1] + c*f; + value[k-1][i-1] = c*value[k-1][i-1] - s*f; + } + } + d[l-1] = d[l-1] - p; + e[l-1] = g; + e[m-1] = 0.0; + } + } while ( m != l); + } + } + public void tred2() { + int n = rows; + int l; + int k; + int j; + int i; + + double scale; + double hh; + double h; + double g; + double f; + + this.d = new double[rows]; + this.e = new double[rows]; + + for (i=n-1; i >= 1;i--) { + l=i-1; + h = 0.0; + scale = 0.0; + + if (l > 0) { + for (k=0;k0) { + g = -1.0*Math.sqrt(h); + } else { + g = Math.sqrt(h); + } + e[i] = scale*g; + h -= f*g; + value[i][l] = f-g; + f=0.0; + for (j=0; j < l; j++) { + value[j][i] = value[i][j]/h; + g=0.0; + for (k= 0; k < j; k++) { + g += value[j][k]*value[i][k]; + } + for (k=j; k=l;i--) { + f = s*e[i-1]; + b = c*e[i-1]; + if (Math.abs(f) >= Math.abs(g)) { + c=g/f; + r = Math.sqrt((c*c)+1.0); + e[i] = f*r; + s = 1.0/r; + c *= s; + } else { + s=f/g; + r = Math.sqrt((s*s)+1.0); + e[i] = g*r; + c = 1.0/r; + s *= c; + } + g=d[i] -p; + r=(d[i-1]-g)*s + 2.0*c*b; + p=s*r; + d[i] = g + p; + g = c * r - b; + for (k=1; k <= n; k++) { + f=value[k-1][i]; + value[k-1][i] = s*value[k-1][i-1] + c*f; + value[k-1][i-1] = c*value[k-1][i-1] - s*f; + } + } + d[l-1] = d[l-1] - p; + e[l-1] = g; + e[m-1] = 0.0; + } + } while ( m != l); + } + } + + public double sign(double a, double b) { + if (b < 0) { + return -Math.abs(a); + } else { + return Math.abs(a); + } + } + + public double[] getColumn(int n) { + double[] out = new double[rows]; + for (int i=0;i 0) + return new Color(204, 204, 255); + else + return Color.white; + + } + else + return Color.white; + + } + + public boolean canThreshold() + { + return false; + } + +} diff --git a/src/jalview/schemes/BuriedColourScheme.java b/src/jalview/schemes/BuriedColourScheme.java new file mode 100755 index 0000000..66a9ce5 --- /dev/null +++ b/src/jalview/schemes/BuriedColourScheme.java @@ -0,0 +1,15 @@ +package jalview.schemes; + +import java.util.*; +import java.awt.*; + +public class BuriedColourScheme extends ScoreColourScheme { + + public BuriedColourScheme() { + super(ResidueProperties.buried,ResidueProperties.buriedmin,ResidueProperties.buriedmax); + } + + public Color makeColour(float c) { + return new Color(0,(float)(1.0-c),c); + } +} diff --git a/src/jalview/schemes/ClustalxColourScheme.java b/src/jalview/schemes/ClustalxColourScheme.java new file mode 100755 index 0000000..0479e5c --- /dev/null +++ b/src/jalview/schemes/ClustalxColourScheme.java @@ -0,0 +1,247 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +/* +package jalview.schemes; +import java.util.*; +import java.awt.*; + +public class ClustalxColourScheme implements ColourSchemeI +{ + Hashtable[] cons; + int[][] cons2; + ConsensusColour[] colours; + ConsensusColour[] ResidueColour; + int size; + Consensus[] conses = new Consensus[32]; + public static Hashtable colhash = new Hashtable(); + + { + colhash.put("RED",new Color((float)0.9,(float)0.2,(float)0.1)); + colhash.put("BLUE",new Color((float)0.5,(float)0.7,(float)0.9)); + colhash.put("GREEN",new Color((float)0.1,(float)0.8,(float)0.1)); + colhash.put("ORANGE",new Color((float)0.9,(float)0.6,(float)0.3)); + colhash.put("CYAN",new Color((float)0.1,(float)0.7,(float)0.7)); + colhash.put("PINK",new Color((float)0.9,(float)0.5,(float)0.5)); + colhash.put("MAGENTA",new Color((float)0.8,(float)0.3,(float)0.8)); + colhash.put("YELLOW",new Color((float)0.8,(float)0.8,(float)0.0)); + + } + Vector colourTable = new Vector(); + public ClustalxColourScheme() { + this.cons2 = null; + this.size = 0; + makeColours(); + } + public ClustalxColourScheme(int[][] cons2, int size) { + this.cons2 = cons2; + this.size = size; + makeColours(); + } + public void makeColours() { + conses[0] = new Consensus("WLVIMAFCYHP",60); + conses[1] = new Consensus("WLVIMAFCYHP",80); + conses[2] = new Consensus("ED",50); + conses[3] = new Consensus("KR",60); + conses[4] = new Consensus("G",50); + conses[5] = new Consensus("N",50); + conses[6] = new Consensus("QE",50); + conses[7] = new Consensus("P",50); + conses[8] = new Consensus("TS",50); + + conses[26] = new Consensus("A",85); + conses[27] = new Consensus("C",85); + conses[10] = new Consensus("E",85); + conses[11] = new Consensus("F",85); + conses[12] = new Consensus("G",85); + conses[13] = new Consensus("H",85); + conses[14] = new Consensus("I",85); + conses[15] = new Consensus("L",85); + conses[16] = new Consensus("M",85); + conses[17] = new Consensus("N",85); + conses[18] = new Consensus("P",85); + conses[19] = new Consensus("Q",85); + conses[20] = new Consensus("R",85); + conses[21] = new Consensus("S",85); + conses[22] = new Consensus("T",85); + conses[23] = new Consensus("V",85); + conses[24] = new Consensus("W",85); + conses[25] = new Consensus("Y",85); + conses[28] = new Consensus("K",85); + conses[29] = new Consensus("D",85); + + conses[30] = new Consensus("G",0); + conses[31] = new Consensus("P",0); + + // We now construct the colours + colours = new ConsensusColour[11]; + + + Consensus[] tmp8 = new Consensus[1]; + tmp8[0] = conses[30];//G + colours[7] =new ConsensusColour((Color)colhash.get("ORANGE"),tmp8); + + Consensus[] tmp9 = new Consensus[1]; + tmp9[0] = conses[31];//P + colours[8] =new ConsensusColour((Color)colhash.get("YELLOW"),tmp9); + + Consensus[] tmp10 = new Consensus[1]; + tmp10[0] = conses[27];//C + colours[9] =new ConsensusColour((Color)colhash.get("PINK"),tmp8); + + Consensus[] tmp1 = new Consensus[14]; + tmp1[0] = conses[0]; //% + tmp1[1] = conses[1]; //# + tmp1[2] = conses[26]; //A + tmp1[3] = conses[27]; //C + tmp1[4] = conses[11]; //F + tmp1[5] = conses[13]; //H + tmp1[6] = conses[14]; //I + tmp1[7] = conses[15]; //L + tmp1[8] = conses[16]; //M + tmp1[9] = conses[23]; //V + tmp1[10] = conses[24]; //W + tmp1[11] = conses[25]; //Y + tmp1[12] = conses[18]; //P + tmp1[13] = conses[19]; //p + colours[0] = new ConsensusColour((Color)colhash.get("BLUE"),tmp1); + + colours[10] = new ConsensusColour((Color)colhash.get("CYAN"),tmp1); + + Consensus[] tmp2 = new Consensus[5]; + tmp2[0] = conses[8]; //t + tmp2[1] = conses[21]; //S + tmp2[2] = conses[22]; //T + tmp2[3] = conses[0]; //% + tmp2[4] = conses[1]; //# + colours[1] = new ConsensusColour((Color)colhash.get("GREEN"),tmp2); + + Consensus[] tmp3 = new Consensus[3]; + + tmp3[0] = conses[17]; //N + tmp3[1] = conses[29]; //D + tmp3[2] = conses[5]; //n + colours[2] = new ConsensusColour((Color)colhash.get("GREEN"),tmp3); + + Consensus[] tmp4 = new Consensus[6]; + tmp4[0] = conses[6]; // q = QE + tmp4[1] = conses[19]; //Q + tmp4[2] = conses[22]; //E + tmp4[3] = conses[3]; //+ + tmp4[4] = conses[28]; //K + tmp4[5] = conses[20]; //R + colours[3] = new ConsensusColour((Color)colhash.get("GREEN"),tmp4); + Consensus[] tmp5 = new Consensus[4]; + tmp5[0] = conses[3]; //+ + tmp5[1] = conses[28]; //K + tmp5[2] = conses[20]; //R + tmp5[3] = conses[19]; //Q + colours[4] = new ConsensusColour((Color)colhash.get("RED"),tmp5); + Consensus[] tmp6 = new Consensus[5]; + tmp6[0] = conses[3]; //- + tmp6[1] = conses[29]; //D + tmp6[2] = conses[10]; //E + tmp6[3] = conses[6]; //q + tmp6[4] = conses[19]; //Q + colours[5] = new ConsensusColour((Color)colhash.get("MAGENTA"),tmp6); + + Consensus[] tmp7 = new Consensus[5]; + tmp7[0] = conses[3]; //- + tmp7[1] = conses[29]; //D + tmp7[2] = conses[10]; //E + tmp7[3] = conses[17]; //N + tmp7[4] = conses[2]; //DE + colours[6] = new ConsensusColour((Color)colhash.get("MAGENTA"),tmp7); + + // Now attach the ConsensusColours to the residue letters + ResidueColour = new ConsensusColour[20]; + ResidueColour[0] = colours[0]; // A + ResidueColour[1] = colours[4]; // R + ResidueColour[2] = colours[2]; // N + ResidueColour[3] = colours[6]; // D + ResidueColour[4] = colours[0]; // C + ResidueColour[5] = colours[3]; // Q + ResidueColour[6] = colours[5]; // E + ResidueColour[7] = colours[7]; // G + ResidueColour[8] = colours[10]; // H + ResidueColour[9] = colours[0]; // I + ResidueColour[10] = colours[0]; // L + ResidueColour[11] = colours[4]; // K + ResidueColour[12] = colours[0]; // M + ResidueColour[13] = colours[0]; // F + ResidueColour[14] = colours[8]; // P + ResidueColour[15] = colours[1]; // S + ResidueColour[16] = colours[1]; // T + ResidueColour[17] = colours[0]; // W + ResidueColour[18] = colours[10]; // Y + ResidueColour[19] = colours[0]; // V + } + + public Color findColour(DrawableSequence seq, String s, int j) { + // System.out.println("Finding colour for " + s + " " + j); + int i = seq.num[j]; + Color c = Color.white; + for (int k=0; k < ResidueColour[i].conses.length ; k++) { + if (ResidueColour[i].conses[k].isConserved(cons2,j,seq.num[j],size)) { + c = ResidueColour[i].c; + } + } + if (i ==4) { + if (conses[27].isConserved(cons2,j,seq.num[j],size)) { + c = (Color)colhash.get("PINK"); + } + } + return c; + } + + public void setColours(DrawableSequence seq, int j) { + Color c = Color.white; + + String s = seq.getSequence().substring(j,j+1); + try { + c = findColour(seq,s,j); + seq.setResidueBoxColour(j,c); + } catch (Exception e) { + seq.setResidueBoxColour(j,Color.white); + } + } + + public void setColours(DrawableSequence s) { + for (int j = 0; j < s.sequence.length(); j++) { + setColours(s,j); + } + } + + public void setColours(SequenceGroup sg) { + for (int j = 0; j < sg.sequences.size(); j++) { + + DrawableSequence s = (DrawableSequence)sg.sequences.elementAt(j); + for (int i = 0; i < s.getSequence().length();i++) { + setColours(s,i); + } + } + } + + +} + +*/ + + + + + diff --git a/src/jalview/schemes/ColourProperties.java b/src/jalview/schemes/ColourProperties.java new file mode 100755 index 0000000..ff2c6bc --- /dev/null +++ b/src/jalview/schemes/ColourProperties.java @@ -0,0 +1,120 @@ +package jalview.schemes; + +import java.util.*; + +public class ColourProperties { + + public static final int ZAPPO = 0; + public static final int TAYLOR = 1; + public static final int PID = 2; + public static final int BLOSUM62 = 3; + public static final int SECONDARY = 4; + public static final int USER = 5; + public static final int HYDROPHOBIC = 6; + public static final int CONSERVATION = 7; + public static final int HELIX = 8; + public static final int STRAND = 9; + public static final int TURN = 10; + public static final int BURIED = 11; + public static final int FEATURES = 12; + public static final int CLUSTALX = 13; + + static ColourSchemePropertyVector colourSchemes = new ColourSchemePropertyVector(); + + static { + String prefix = getDefaultClassPrefix(); + + // MC 27/03/02 These should be read in from a file + + colourSchemes.add(new ColourSchemeProperty("Zappo", + prefix + "ZappoColourScheme", + "Zappo colours")); + + colourSchemes.add(new ColourSchemeProperty("Taylor", + prefix + "TaylorColourScheme", + "Taylor colours")); + + colourSchemes.add(new ColourSchemeProperty("PID", + prefix + "PIDColourScheme", + "By PID")); + + colourSchemes.add(new ColourSchemeProperty("BLOSUM62", + prefix + "Blosum62ColourScheme", + "By BLOSUM62 Score")); + + colourSchemes.add(new ColourSchemeProperty("Secondary structure", + prefix + "SecondaryColourScheme", + "By Secondary Structure")); + + colourSchemes.add(new ColourSchemeProperty("User defined", + prefix + "ZappoColourScheme", + "User defined colours")); + + colourSchemes.add(new ColourSchemeProperty("Hydrophobic", + prefix + "HydrophobicColourScheme", + "By Hydrophobicity")); + + colourSchemes.add(new ColourSchemeProperty("Conservation", + prefix + "ZappoColourScheme", + null)); + + colourSchemes.add(new ColourSchemeProperty("Helix", + prefix + "HelixColourScheme", + "Helix propensity")); + + colourSchemes.add(new ColourSchemeProperty("Strand", + prefix + "StrandColourScheme", + "Strand propensity")); + + colourSchemes.add(new ColourSchemeProperty("Turn", + prefix + "TurnColourScheme", + "Turn propensity")); + + colourSchemes.add(new ColourSchemeProperty("Buried", + prefix + "BuriedColourScheme", + "Buried index")); + + // colourSchemes.add(new ColourSchemeProperty("Features", + // prefix + "FeatureColourScheme", + // null)); + + colourSchemes.add(new ColourSchemeProperty("Clustalx", + prefix + "ClustalXColourScheme", + "ClustalX colours")); + } + + static int indexOf(String scheme) { + if (colourSchemes.contains(scheme)) { + return colourSchemes.indexOf(scheme); + } else { + return -1; + } + } + + static int indexOfClass(ColourSchemeI scheme) { + return colourSchemes.indexOfClass(scheme); + } + + public static String getClassName(int index) { + return colourSchemes.getClassName(index); + } + + public static String getMenuString(int index) { + return colourSchemes.getMenuString(index); + } + + static boolean contains(String scheme) { + return colourSchemes.contains(scheme); + } + + public static Vector getColourSchemeNames() { + return colourSchemes.getColourSchemeNames(); + } + + protected static String getDefaultClassPrefix() { + return "jalview.schemes."; + } +} + + + diff --git a/src/jalview/schemes/ColourSchemeFactory.java b/src/jalview/schemes/ColourSchemeFactory.java new file mode 100755 index 0000000..7cc59b9 --- /dev/null +++ b/src/jalview/schemes/ColourSchemeFactory.java @@ -0,0 +1,29 @@ +package jalview.schemes; + +import java.lang.reflect.*; +import java.util.*; + +public class ColourSchemeFactory { + + public static ColourSchemeI get(int index) { + try { + System.out.println("Getting " + index); + String name = ColourProperties.getClassName(index); + System.out.println("Name " + name); + Class c = Class.forName(name); + + return (ColourSchemeI)c.newInstance(); + } catch (Exception e) { + System.err.println(e); + return null; + } + } + + public static ColourSchemeI get(String scheme) { + return get(ColourProperties.indexOf(scheme)); + } + + public static int get(ColourSchemeI cs) { + return ColourProperties.indexOfClass(cs); + } +} diff --git a/src/jalview/schemes/ColourSchemeI.java b/src/jalview/schemes/ColourSchemeI.java new file mode 100755 index 0000000..0c66da3 --- /dev/null +++ b/src/jalview/schemes/ColourSchemeI.java @@ -0,0 +1,18 @@ +package jalview.schemes; + +import jalview.datamodel.*; +import jalview.jbgui.*; +import java.awt.*; +import java.util.*; + +public interface ColourSchemeI +{ + public Color findColour(String aa); + public Vector getColours(SequenceI s, Vector aa); + public Color getColour (SequenceI s, int pos, Vector aa); + public Vector getColours(SequenceGroup sg, Vector aa); + public Color findColour(SequenceI seq, String s,int j, Vector aa); + + public boolean canThreshold(); + public boolean isUserDefinable(); +} diff --git a/src/jalview/schemes/ColourSchemeProperty.java b/src/jalview/schemes/ColourSchemeProperty.java new file mode 100755 index 0000000..518f7ab --- /dev/null +++ b/src/jalview/schemes/ColourSchemeProperty.java @@ -0,0 +1,28 @@ +package jalview.schemes; + +public class ColourSchemeProperty { + String description; + String className; + String menuString = null; + + public ColourSchemeProperty(String description, String className, String menuString) { + this.description = new String(description); + this.className = new String(className); + if (menuString != null) { + this.menuString = new String(menuString); + } + } + + public String getClassName() { + return className; + } + public String getDescription() { + return description; + } + public String getMenuString() { + return menuString; + } + public boolean isMenuItem() { + return (menuString != null); + } +} diff --git a/src/jalview/schemes/ColourSchemePropertyVector.java b/src/jalview/schemes/ColourSchemePropertyVector.java new file mode 100755 index 0000000..0fb028b --- /dev/null +++ b/src/jalview/schemes/ColourSchemePropertyVector.java @@ -0,0 +1,46 @@ +package jalview.schemes; + +import java.util.*; + +public class ColourSchemePropertyVector { + Vector schemeProps = new Vector(); + Vector schemeDescs = new Vector(); + + public void add(ColourSchemeProperty prop) { + schemeProps.addElement(prop); + schemeDescs.addElement(prop.getDescription()); + } + public Vector getColourSchemeNames() { + return schemeDescs; + } + public String getClassName(int ind) { + return get(ind).getClassName(); + } + public String getMenuString(int ind) { + return get(ind).getMenuString(); + } + public String getSchemeName(int ind) { + return get(ind).getDescription(); + } + public boolean contains(String description) { + return schemeDescs.contains(description); + } + public int indexOf(String description) { + return schemeDescs.indexOf(description); + } + public ColourSchemeProperty get(int index) { + return (ColourSchemeProperty)schemeProps.elementAt(index); + } + + public int indexOfClass(ColourSchemeI cs) { + if (cs != null) { + String className = cs.getClass().getName(); + for (int i=0; i thresholds[i]) { + c = pidColours[i]; + break; + } + } + } else { + c = Color.white; + } + } + return c; + } +} diff --git a/src/jalview/schemes/ResidueColourScheme.java b/src/jalview/schemes/ResidueColourScheme.java new file mode 100755 index 0000000..f90f475 --- /dev/null +++ b/src/jalview/schemes/ResidueColourScheme.java @@ -0,0 +1,113 @@ +package jalview.schemes; + +import jalview.datamodel.*; +import jalview.jbgui.*; + +import java.util.*; +import java.awt.*; + +public class ResidueColourScheme implements ColourSchemeI { + Color [] colors; + int threshold = 90; + + public ResidueColourScheme(Color[] colors, int threshold) { + this.colors = colors; + this.threshold = threshold; + } + + public ResidueColourScheme() { + } + + public Color findColour(String aa) + { + return colors[((Integer)(ResidueProperties.aaHash.get(aa))).intValue()]; + } + + public Color findColour(SequenceI seq,String s, int j, Vector aa) { + try { + return colors[((Integer)(ResidueProperties.aaHash.get(s))).intValue()]; + } catch (Exception e) { + return Color.white; + } + } + + // aa should maybe be a class + public Color getColour(SequenceI seq, int j,Vector aa) { + + Color c = Color.white; + String s = seq.getSequence(j,j+1); + + if (threshold > 0 && aa != null) + { + if (aboveThreshold(aa,seq,j,threshold)) + c = findColour(seq,s,j,aa); + } + else + c = findColour(seq,s,j,aa); + + + return c; + } + public int getThreshold() { + return threshold; + } + + public void setThreshold(int ct) { + threshold = ct; + } + + public Vector getColours(SequenceI s, Vector aa) { + Vector colours = new Vector(); + + for (int j = 0; j < s.getLength(); j++) + colours.addElement(getColour(s,j,aa)); + + return colours; + } + + public Vector getColours(SequenceGroup sg, Vector aa) { + Vector colours = new Vector(); + + for (int j = 0; j < sg.getSize(); j++) { + SequenceI s = sg.getSequenceAt(j); + + for (int i = 0; i < s.getLength();i++) { + colours.addElement(getColour(s,i,aa)); + } + } + return colours; + } + + public boolean aboveThreshold(Vector aa,SequenceI seq, int j, int threshold) { + String s = seq.getSequence(j,j+1); + Hashtable hash = (Hashtable)aa.elementAt(j); + + if (j < aa.size()) { + String maxRes = (String)hash.get("maxResidue"); + + double sc = 0; + + if (((Integer)hash.get("maxCount")).intValue() != -1 && hash.contains(s)) { + int maxCount = ((Integer)hash.get("maxCount")).intValue(); + int resCount = ((Integer)hash.get(s)).intValue(); + + sc = resCount * 100.0 / resCount; + + // This should be isGap somewhere + if ( !s.equals("-") && !s.equals(".") && !s.equals(" ")) { + if (sc >= (double)threshold) { + return true; + } + } + } + } + return false; + } + + public boolean canThreshold() { + return true; + } + public boolean isUserDefinable() { + return false; + } +} diff --git a/src/jalview/schemes/ResidueProperties.java b/src/jalview/schemes/ResidueProperties.java new file mode 100755 index 0000000..aa0297e --- /dev/null +++ b/src/jalview/schemes/ResidueProperties.java @@ -0,0 +1,995 @@ + +/* Copyright (C) 1998 Michele Clamp +* +* 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +package jalview.schemes; + +import java.awt.Color; +import java.util.*; +import jalview.jbgui.*; +import jalview.datamodel.*; + +public class ResidueProperties { + + //Stores residue codes/names and colours and other things + public static Hashtable aaHash = new Hashtable(); // stores the number value of the aa + public static Hashtable aa3Hash = new Hashtable(); + public static Hashtable aa2Triplet = new Hashtable(); + + static { + aaHash.put("A", new Integer(0)); + aaHash.put("R", new Integer(1)); + aaHash.put("N", new Integer(2)); + aaHash.put("D", new Integer(3)); + aaHash.put("C", new Integer(4)); + aaHash.put("Q", new Integer(5)); + aaHash.put("E", new Integer(6)); + aaHash.put("G", new Integer(7)); + aaHash.put("H", new Integer(8)); + aaHash.put("I", new Integer(9)); + aaHash.put("L", new Integer(10)); + aaHash.put("K", new Integer(11)); + aaHash.put("M", new Integer(12)); + aaHash.put("F", new Integer(13)); + aaHash.put("P", new Integer(14)); + aaHash.put("S", new Integer(15)); + aaHash.put("T", new Integer(16)); + aaHash.put("W", new Integer(17)); + aaHash.put("Y", new Integer(18)); + aaHash.put("V", new Integer(19)); + aaHash.put("B", new Integer(20)); + aaHash.put("Z", new Integer(21)); + aaHash.put("X", new Integer(22)); + aaHash.put("-", new Integer(23)); + aaHash.put("*", new Integer(23)); + aaHash.put(".", new Integer(23)); + aaHash.put(" ", new Integer(23)); + } + + // These numbers should correspond to the indices in the Color hashes + public static Hashtable aaSpecialsHash = new Hashtable(); + static { + aaSpecialsHash.put("-", new Integer(23)); + aaSpecialsHash.put("*", new Integer(24)); + aaSpecialsHash.put(".", new Integer(25)); + aaSpecialsHash.put(" ", new Integer(26)); + } + + static { + aa3Hash.put("ALA", new Integer(0)); + aa3Hash.put("ARG", new Integer(1)); + aa3Hash.put("ASN", new Integer(2)); + aa3Hash.put("ASP", new Integer(3)); //D + aa3Hash.put("CYS", new Integer(4)); + aa3Hash.put("GLN", new Integer(5)); //Q + aa3Hash.put("GLU", new Integer(6)); // E + aa3Hash.put("GLY", new Integer(7)); + aa3Hash.put("HIS", new Integer(8)); + aa3Hash.put("ILE", new Integer(9)); + aa3Hash.put("LEU", new Integer(10)); + aa3Hash.put("LYS", new Integer(11)); + aa3Hash.put("MET", new Integer(12)); + aa3Hash.put("PHE", new Integer(13)); + aa3Hash.put("PRO", new Integer(14)); + aa3Hash.put("SER", new Integer(15)); + aa3Hash.put("THR", new Integer(16)); + aa3Hash.put("TRP", new Integer(17)); + aa3Hash.put("TYR", new Integer(18)); + aa3Hash.put("VAL", new Integer(19)); + aa3Hash.put("B", new Integer(20)); + aa3Hash.put("Z", new Integer(21)); + aa3Hash.put("X", new Integer(22)); + aa3Hash.put("-", new Integer(23)); + aa3Hash.put("*", new Integer(23)); + aa3Hash.put(".", new Integer(23)); + aa3Hash.put(" ", new Integer(23)); + } + + static{ + aa2Triplet.put("A", "ALA"); + aa2Triplet.put("R", "ARG"); + aa2Triplet.put("N", "ASN"); + aa2Triplet.put("D", "ASP"); + aa2Triplet.put("C", "CYS"); + aa2Triplet.put("Q", "GLN"); + aa2Triplet.put("E", "GLU"); + aa2Triplet.put("G", "GLY"); + aa2Triplet.put("H", "HIS"); + aa2Triplet.put("I", "ILE"); + aa2Triplet.put("L", "LEU"); + aa2Triplet.put("K", "LYS"); + aa2Triplet.put("M", "MET"); + aa2Triplet.put("F", "PHE"); + aa2Triplet.put("P", "PRO"); + aa2Triplet.put("S", "SER"); + aa2Triplet.put("T", "THR"); + aa2Triplet.put("W", "TRP"); + aa2Triplet.put("Y", "TYR"); + aa2Triplet.put("V", "VAL"); + } + + public static String aa[] = { + "A","R","N","D","C","Q","E","G","H","I","L","K","M","F","P","S","T","W","Y","V","B","Z","X","_","*","."," " + }; + public static Color midBlue = new Color(100,100,255); + public static Vector scaleColours = new Vector(); + static { + scaleColours.addElement(new Color(114,0,147)); + scaleColours.addElement(new Color(156,0,98)); + scaleColours.addElement(new Color(190,0,0)); + scaleColours.addElement(Color.red); + scaleColours.addElement(new Color(255,125,0)); + scaleColours.addElement(Color.orange); + scaleColours.addElement(new Color(255,194,85)); + scaleColours.addElement(Color.yellow); + scaleColours.addElement(new Color(255,255,181)); + scaleColours.addElement(Color.white); + } + + public static Color[] taylor = { + new Color(204,255,0), // A Greenish-yellowy-yellow + new Color(0,0,255), // R Blueish-bluey-blue + new Color(204,0,255), // N Blueish-reddy-blue + new Color(255,0,0), // D Reddish-reddy-red + new Color(255,255,0), // C Yellowish-yellowy-yellow + new Color(255,0,204), // Q Reddish-bluey-red + new Color(255,0,102), // E Blueish-reddy-red + new Color(255,153,0), // G Yellowy-reddy-yellow + new Color(0,102,255), // H Greenish-bluey-blue + new Color(102,255,0), // I Greenish-yellowy-green + new Color(51,255,0), // L Yellowish-greeny-green + new Color(102,0,255), // K Reddish-bluey-blue + new Color(0,255,0), // M Greenish-greeny-green + new Color(0,255,102), // F Blueish-greeny-green + new Color(255,204,0), // P Reddish-yellowy-yellow + new Color(255,51,0), // S Yellowish-reddy-red + new Color(255,102,0), // T Reddish-yellowy-red + new Color(0,204,255), // W Blueish-greeny-green + new Color(0,255,204), // Y Greenish-bluey-green + new Color(153,255,0), // V Yellowish-greeny-yellow + Color.white, // B + Color.white, // Z + Color.white, // X + Color.white, // - + Color.white, // * + Color.white // . + }; + + public static Color[] color = { + Color.pink, // A + midBlue, // R + Color.green, // N + Color.red, // D + Color.yellow, // C + Color.green, // Q + Color.red, // E + Color.magenta, // G + Color.red, // H + Color.pink, // I + Color.pink, // L + midBlue, // K + Color.pink, // M + Color.orange, // F + Color.magenta, // P + Color.green, // S + Color.green, // T + Color.orange, // W + Color.orange, // Y + Color.pink, // V + Color.white, // B + Color.white, // Z + Color.white, // X + Color.white, // - + Color.white, // * + Color.white, // . + Color.white // ' ' + }; + + // Dunno where I got these numbers from + public static double[] hyd2 = { + 0.62, //A + 0.29, //R + -0.90, //N + -0.74, //D + 1.19, //C + 0.48, //Q + -0.40, //E + 1.38, //G + -1.50, //H + 1.06, //I + 0.64, //L + -0.78, //K + 0.12, //M + -0.85, //F + -2.53, //P + -0.18, //S + -0.05, //T + 1.08, //W + 0.81, //Y + 0.0, //V + 0.26, //B + 0.0, //Z + 0.0 //X + }; + public static double[] helix = { + 1.42, + 0.98, + 0.67, + 1.01, + 0.70, + 1.11, + 1.51, + 0.57, + 1.00, + 1.08, + 1.21, + 1.16, + 1.45, + 1.13, + 0.57, + 0.77, + 0.83, + 1.08, + 0.69, + 1.06, + 0.84, + 1.31, + 1.00, + 0.0 + }; + public static double helixmin = 0.57; + public static double helixmax = 1.51; + + public static double[] strand = { + 0.83,0.93,0.89,0.54,1.19,1.10,0.37, + 0.75,0.87,1.60,1.30,0.74,1.05,1.38,0.55, + 0.75,1.19,1.37,1.47,1.70,0.72,0.74,1.0,0.0}; + + public static double strandmin = 0.37; + public static double strandmax = 1.7; + + public static double[] turn = { + 0.66,0.95,1.56,1.46,1.19,0.98,0.74, + 1.56,0.95,0.47,0.59,1.01,0.60,0.60,1.52, + 1.43,0.96,0.96,1.14,0.50,1.51,0.86,1.00,0,0}; + + public static double turnmin = 0.47; + public static double turnmax = 1.56; + + public static double[] buried = { + 1.7, + 0.1, + 0.4, + 0.4, + 4.6, + 0.3, + 0.3, + 1.8, + 0.8, + 3.1, + 2.4, + 0.05, + 1.9, + 2.2, + 0.6, + 0.8,0.7,1.6,0.5,2.9,0.4,0.3, + 1.358, + 0.00 + }; + + public static double buriedmin = 0.05; + public static double buriedmax = 4.6; + + // This is hydropathy index + // Kyte, J., and Doolittle, R.F., J. Mol. Biol. + // 1157, 105-132, 1982 + + public static double hyd[] = { + 1.8, + -4.5, + -3.5, + -3.5, + 2.5, + -3.5, + -3.5, + -0.4, + -3.2, + 4.5, + 3.8, + -3.9, + 1.9, + 2.8, + -1.6, + -0.8, + -0.7, + -0.9, + -1.3, + 4.2, + -3.5, + -3.5, + -0.49, + 0.0 + }; + + public static final double hydmax = 4.5; + public static final double hydmin = -3.9; + + public static double getHydmax() { + return hydmax; + } + public static double getHydmin() { + return hydmin; + } + public static double[] getHyd() { + return hyd; + } + //public static final double hydmax = 1.38; + //public static final double hydmin = -2.53; + + static final int[][] BLOSUM62 = { + //A R N D C Q E G H I L K M F P S T W Y V B Z X - + { 4 ,-1, -2 ,-2 , 0 ,-1 ,-1 , 0 ,-2 ,-1 ,-1 ,-1 ,-1 ,-2 ,-1 , 1 , 0 ,-3 ,-2 , 0 ,-2, -1 , 0 ,-4}, + {-1 , 5 , 0 ,-2 ,-3 , 1 , 0 ,-2 , 0 ,-3 ,-2 , 2 ,-1 ,-3 ,-2 ,-1 ,-1 ,-3 ,-2 ,-3 ,-1 , 0 ,-1 ,-4 }, + {-2 , 0 , 6 , 1 ,-3 , 0 , 0 , 0 , 1 ,-3 ,-3 , 0 ,-2 ,-3 ,-2 , 1 , 0 ,-4 ,-2 ,-3 , 3 , 0 ,-1 ,-4 }, + {-2 ,-2 , 1 , 6 ,-3 , 0 , 2 ,-1 ,-1 ,-3 ,-4 ,-1 ,-3 ,-3 ,-1 , 0 ,-1 ,-4 ,-3 ,-3 , 4 , 1 ,-1 ,-4 }, + { 0 , 3 ,-3 ,-3 , 9 ,-3 ,-4 ,-3 ,-3 ,-1 ,-1 ,-3 ,-1 ,-2 ,-3 ,-1 ,-1 ,-2 ,-2 ,-1 ,-3 ,-3 ,-2 ,-4 }, + {-1 , 1 , 0 , 0 ,-3 , 5 , 2 ,-2 , 0 ,-3 ,-2 , 1 , 0 ,-3 ,-1 , 0 ,-1 ,-2 ,-1 ,-2 , 0 , 3 ,-1 ,-4 }, + {-1 , 0 , 0 , 2 ,-4 , 2 , 5 ,-2 , 0 ,-3 ,-3 , 1 ,-2 ,-3 ,-1 , 0 ,-1 ,-3 ,-2 ,-2 , 1 , 4 ,-1 ,-4 }, + { 0 ,-2 , 0 ,-1 ,-3 ,-2 ,-2 , 6 ,-2 ,-4 ,-4 ,-2 ,-3 ,-3 ,-2 , 0 ,-2 ,-2 ,-3 ,-3 ,-1 ,-2 ,-1 ,-4 }, + {-2 , 0 , 1 ,-1 ,-3 , 0 , 0 ,-2 , 8 ,-3 ,-3 ,-1 ,-2 ,-1 ,-2 ,-1 ,-2 ,-2 , 2 ,-3 , 0 , 0 ,-1 ,-4 }, + {-1 ,-3 ,-3 ,-3 ,-1 ,-3 ,-3 ,-4 ,-3 , 4 , 2 ,-3 , 1 , 0 ,-3 ,-2 ,-1 ,-3 ,-1 , 3 ,-3 ,-3 ,-1 ,-4 }, + {-1 ,-2 ,-3 ,-4 ,-1 ,-2 ,-3 ,-4 ,-3 , 2 , 4 ,-2 , 2 , 0 ,-3 ,-2 ,-1 ,-2 ,-1 , 1 ,-4 ,-3 ,-1 ,-4 }, + {-1 , 2 , 0 ,-1 ,-3 , 1 , 1 ,-2 ,-1 ,-3 ,-2 , 5 ,-1 ,-3 ,-1 , 0 ,-1 ,-3 ,-2 ,-2 , 0 , 1 ,-1 ,-4 }, + {-1 ,-1 ,-2 ,-3 ,-1 , 0 ,-2 ,-3 ,-2 , 1 , 2 ,-1 , 5 , 0 ,-2 ,-1 ,-1 ,-1 ,-1 , 1 ,-3 ,-1 ,-1 ,-4 }, + {-2 ,-3 ,-3 ,-3 ,-2 ,-3 ,-3 ,-3 ,-1 , 0 , 0 ,-3 , 0 , 6 ,-4 ,-2 ,-2 , 1 , 3 ,-1 ,-3 ,-3 ,-1 ,-4 }, + {-1 ,-2 ,-2 ,-1 ,-3 ,-1 ,-1 ,-2 ,-2 ,-3 ,-3 ,-1 ,-2 ,-4 , 7 ,-1 ,-1 ,-4 ,-3 ,-2 ,-2 ,-1 ,-2 ,-4 }, + { 1 ,-1 , 1 , 0 ,-1 , 0 , 0 , 0 ,-1 ,-2 ,-2 , 0 ,-1 ,-2 ,-1 , 4 , 1 ,-3 ,-2 ,-2 , 0 , 0 , 0 ,-4 }, + { 0 ,-1 , 0 ,-1 ,-1 ,-1 ,-1 ,-2 ,-2 ,-1 ,-1 ,-1 ,-1 ,-2 ,-1 , 1 , 5 ,-2 ,-2 , 0 ,-1 ,-1 , 0 ,-4 }, + {-3 ,-3 ,-4 ,-4 ,-2 ,-2 ,-3 ,-2 ,-2 ,-3 ,-2 ,-3 ,-1 , 1 ,-4 ,-3 ,-2 ,11 , 2 ,-3 ,-4 ,-3 ,-2 ,-4 }, + {-2 ,-2 ,-2 ,-3 ,-2 ,-1 ,-2 ,-3 , 2 ,-1 ,-1 ,-2 ,-1 , 3 ,-3 ,-2 ,-2 , 2 , 7 ,-1 ,-3 ,-2 ,-1 ,-4 }, + { 0 ,-3 ,-3 ,-3 ,-1 ,-2 ,-2 ,-3 ,-3 , 3 , 1 ,-2 , 1 ,-1 ,-2 ,-2 , 0 ,-3 ,-1 , 4 ,-3 ,-2 ,-1 ,-4 }, + {-2 ,-1 , 3 , 4 ,-3 , 0 , 1 ,-1 , 0 ,-3 ,-4 , 0 ,-3 ,-3 ,-2 , 0 ,-1 ,-4 ,-3 ,-3 , 4 , 1 ,-1 ,-4 }, + {-1 , 0 , 0 , 1 ,-3 , 3 , 4 ,-2 , 0 ,-3 ,-3 , 1 ,-1 ,-3 ,-1 , 0 ,-1 ,-3 ,-2 ,-2 , 1 , 4 ,-1 ,-4 }, + { 0 ,-1 ,-1 ,-1 ,-2 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-2 , 0 , 0 ,-2 ,-1 ,-1 ,-1 ,-1 ,-1 ,-4 }, + {-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 ,-4 , 1 }, + }; + static final int[][] PAM250 = { + { 2,-2 ,0 ,0,-2 ,0 ,0 ,1,-1,-1,-2,-1,-1,-3 ,1 ,1 ,1,-6,-3 ,0 ,0 ,0 ,0,-8}, + { -2 ,6 ,0,-1,-4 ,1,-1,-3 ,2,-2,-3 ,3 ,0,-4 ,0 ,0,-1 ,2,-4,-2,-1 ,0,-1,-8}, + { 0 ,0 ,2 ,2,-4 ,1 ,1 ,0 ,2,-2,-3 ,1,-2,-3 ,0 ,1 ,0,-4,-2,-2 ,2 ,1 ,0,-8}, + { 0,-1 ,2 ,4,-5 ,2 ,3 ,1 ,1,-2,-4 ,0,-3,-6,-1 ,0 ,0,-7,-4,-2 ,3 ,3,-1,-8}, + { -2,-4,-4,-5,12,-5,-5,-3,-3,-2,-6,-5,-5,-4,-3 ,0,-2,-8 ,0,-2,-4,-5,-3,-8}, + { 0 ,1 ,1 ,2,-5 ,4 ,2,-1 ,3,-2,-2 ,1,-1,-5 ,0,-1,-1,-5,-4,-2 ,1 ,3,-1,-8}, + { 0,-1 ,1 ,3,-5 ,2 ,4 ,0 ,1,-2,-3 ,0,-2,-5,-1 ,0 ,0,-7,-4,-2 ,3 ,3,-1,-8}, + { 1,-3 ,0 ,1,-3,-1 ,0 ,5,-2,-3,-4,-2,-3,-5 ,0 ,1 ,0,-7,-5,-1 ,0 ,0,-1,-8}, + { -1 ,2 ,2 ,1,-3 ,3 ,1,-2 ,6,-2,-2 ,0,-2,-2 ,0,-1,-1,-3 ,0,-2 ,1 ,2,-1,-8}, + { -1,-2,-2,-2,-2,-2,-2,-3,-2 ,5 ,2,-2 ,2 ,1,-2,-1 ,0,-5,-1 ,4,-2,-2,-1,-8}, + { -2,-3,-3,-4,-6,-2,-3,-4,-2 ,2 ,6,-3 ,4 ,2,-3,-3,-2,-2,-1 ,2,-3,-3,-1,-8}, + { -1 ,3 ,1 ,0,-5 ,1 ,0,-2 ,0,-2,-3 ,5 ,0,-5,-1 ,0 ,0,-3,-4,-2 ,1 ,0,-1,-8}, + { -1 ,0,-2,-3,-5,-1,-2,-3,-2 ,2 ,4 ,0 ,6 ,0,-2,-2,-1,-4,-2 ,2,-2,-2,-1,-8}, + { -3,-4,-3,-6,-4,-5,-5,-5,-2 ,1 ,2,-5 ,0 ,9,-5,-3,-3 ,0 ,7,-1,-4,-5,-2,-8}, + { 1 ,0 ,0,-1,-3 ,0,-1 ,0 ,0,-2,-3,-1,-2,-5 ,6 ,1 ,0,-6,-5,-1,-1 ,0,-1,-8}, + { 1 ,0 ,1 ,0 ,0,-1 ,0 ,1,-1,-1,-3 ,0,-2,-3 ,1 ,2 ,1,-2,-3,-1 ,0 ,0 ,0,-8}, + { 1,-1 ,0 ,0,-2,-1 ,0 ,0,-1 ,0,-2 ,0,-1,-3 ,0 ,1 ,3,-5,-3 ,0 ,0,-1 ,0,-8}, + { -6 ,2,-4,-7,-8,-5,-7,-7,-3,-5,-2,-3,-4 ,0,-6,-2,-5,17 ,0,-6,-5,-6,-4,-8}, + { -3,-4,-2,-4 ,0,-4,-4,-5 ,0,-1,-1,-4,-2 ,7,-5,-3,-3 ,0,10,-2,-3,-4,-2,-8}, + { 0,-2,-2,-2,-2,-2,-2,-1,-2 ,4 ,2,-2 ,2,-1,-1,-1 ,0,-6,-2 ,4,-2,-2,-1,-8}, + { 0,-1 ,2 ,3,-4 ,1 ,3 ,0 ,1,-2,-3 ,1,-2,-4,-1 ,0 ,0,-5,-3,-2 ,3 ,2,-1,-8}, + { 0 ,0 ,1 ,3,-5 ,3 ,3 ,0 ,2,-2,-3 ,0,-2,-5 ,0 ,0,-1,-6,-4,-2 ,2 ,3,-1,-8}, + { 0,-1 ,0,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-2,-1 ,0 ,0,-4,-2,-1,-1,-1,-1,-8}, + { -8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8 ,1}, + }; + + public static Hashtable ssHash = new Hashtable(); // stores the number value of the aa + + static { + ssHash.put("H", Color.magenta); + ssHash.put("E", Color.yellow); + ssHash.put("-", Color.white); + ssHash.put(".", Color.white); + ssHash.put("S", Color.cyan); + ssHash.put("T", Color.blue); + ssHash.put("G", Color.pink); + ssHash.put("I", Color.pink); + ssHash.put("B", Color.yellow); + } + static final int[][] DNA = { + // C T A G - + { 5,-4,-4,-4, 1},// C + {-4, 5,-4,-4, 1},// T + {-4,-4, 5,-4, 1},// A + {-4,-4,-4, 5, 1},// G + { 1, 1, 1, 1, 1},// - + }; + public static Hashtable getAAHash() { + return aaHash; + } + public static Hashtable getAA3Hash() { + return aa3Hash; + } + public static int[][] getDNA() { + return ResidueProperties.DNA; + } + public static int[][] getBLOSUM62() { + return ResidueProperties.BLOSUM62; + } + public static int getPAM250(String A1, String A2) { + Integer pog1 = (Integer)aaHash.get(A1); + Integer pog2 = (Integer)aaHash.get(A2); + int pog = ResidueProperties.PAM250[pog1.intValue()][pog2.intValue()]; + return pog ; + } + public static int getBLOSUM62(String A1, String A2) { + int pog = 0; + try { + Integer pog1 = (Integer)aaHash.get(A1); + Integer pog2 = (Integer)aaHash.get(A2); + pog = ResidueProperties.BLOSUM62[pog1.intValue()][pog2.intValue()]; + } catch (Exception e) { + //System.out.println("Unknown residue in " + A1 + " " + A2); + } + return pog ; + } + + public static Color[] pidColours = { + midBlue, + new Color(153,153,255), + // Color.lightGray, + new Color(204,204,255), + }; + public static float[] pidThresholds = { + 80, + 60, + 40, + } ; + private ResidueProperties() {} + + public static Hashtable codonHash = new Hashtable(); + + public static Vector Lys = new Vector(); + public static Vector Asn = new Vector(); + public static Vector Gln = new Vector(); + public static Vector His = new Vector(); + public static Vector Glu = new Vector(); + public static Vector Asp = new Vector(); + public static Vector Tyr = new Vector(); + public static Vector Thr = new Vector(); + public static Vector Pro = new Vector(); + public static Vector Ala = new Vector(); + public static Vector Ser = new Vector(); + public static Vector Arg = new Vector(); + public static Vector Gly = new Vector(); + public static Vector Trp = new Vector(); + public static Vector Cys = new Vector(); + public static Vector Ile = new Vector(); + public static Vector Met = new Vector(); + public static Vector Leu = new Vector(); + public static Vector Val = new Vector(); + public static Vector Phe = new Vector(); + public static Vector STOP = new Vector(); + + static { + codonHash.put("K",Lys); + codonHash.put("N",Asn); + codonHash.put("Q",Gln); + codonHash.put("H",His); + codonHash.put("E",Glu); + codonHash.put("D",Asp); + codonHash.put("Y",Tyr); + codonHash.put("T",Thr); + codonHash.put("P",Pro); + codonHash.put("A",Ala); + codonHash.put("S",Ser); + codonHash.put("R",Arg); + codonHash.put("G",Gly); + codonHash.put("W",Trp); + codonHash.put("C",Cys); + codonHash.put("I",Ile); + codonHash.put("M",Met); + codonHash.put("L",Leu); + codonHash.put("V",Val); + codonHash.put("F",Phe); + codonHash.put("STOP",STOP); + } + + public static Vector getCodons(String res) { + if (codonHash.containsKey(res)) + return (Vector)codonHash.get(res); + return null; + } + + public static String codonTranslate(String codon) { + Enumeration e = codonHash.keys(); + while (e.hasMoreElements()) { + String key = (String)e.nextElement(); + Vector tmp = (Vector)codonHash.get(key); + if (tmp.contains(codon)) { + return key; + } + } + return null; + } + public static Hashtable codonHash2 = new Hashtable(); + static { + codonHash2.put("AAA","K"); + codonHash2.put("AAG","K"); + codonHash2.put("AAC","N"); + codonHash2.put("AAT","N"); + + codonHash2.put("CAA","E"); + codonHash2.put("CAG","E"); + codonHash2.put("CAC","H"); + codonHash2.put("CAT","H"); + + codonHash2.put("GAA","Q"); + codonHash2.put("GAG","Q"); + codonHash2.put("GAC","D"); + codonHash2.put("GAT","D"); + + codonHash2.put("TAC","Y"); + codonHash2.put("TAT","Y"); + + codonHash2.put("ACA","T"); + codonHash2.put("AAG","T"); + codonHash2.put("ACC","T"); + codonHash2.put("ACT","T"); + + codonHash2.put("CCA","P"); + codonHash2.put("CCG","P"); + codonHash2.put("CCC","P"); + codonHash2.put("CCT","P"); + + codonHash2.put("GCA","A"); + codonHash2.put("GCG","A"); + codonHash2.put("GCC","A"); + codonHash2.put("GCT","A"); + + codonHash2.put("TCA","S"); + codonHash2.put("TCG","S"); + codonHash2.put("TCC","S"); + codonHash2.put("TCT","S"); + codonHash2.put("AGC","S"); + codonHash2.put("AGT","S"); + + codonHash2.put("AGA","R"); + codonHash2.put("AGG","R"); + codonHash2.put("CGA","R"); + codonHash2.put("CGG","R"); + codonHash2.put("CGC","R"); + codonHash2.put("CGT","R"); + + codonHash2.put("GGA","G"); + codonHash2.put("GGG","G"); + codonHash2.put("GGC","G"); + codonHash2.put("GGT","G"); + + codonHash2.put("TGA","*"); + codonHash2.put("TAA","*"); + codonHash2.put("TAG","*"); + + codonHash2.put("TGG","W"); + + codonHash2.put("TGC","C"); + codonHash2.put("TGT","C"); + + codonHash2.put("ATA","I"); + codonHash2.put("ATC","I"); + codonHash2.put("ATT","I"); + + codonHash2.put("ATG","M"); + + codonHash2.put("CTA","L"); + codonHash2.put("CTG","L"); + codonHash2.put("CTC","L"); + codonHash2.put("CTT","L"); + codonHash2.put("TTA","L"); + codonHash2.put("TTG","L"); + + codonHash2.put("GTA","V"); + codonHash2.put("GTG","V"); + codonHash2.put("GTC","V"); + codonHash2.put("GTT","V"); + + codonHash2.put("TTC","F"); + codonHash2.put("TTT","F"); + + } + + static { + Lys.addElement("AAA"); + Lys.addElement("AAG"); + Asn.addElement("AAC"); + Asn.addElement("AAT"); + + Gln.addElement("CAA"); + Gln.addElement("CAG"); + His.addElement("CAC"); + His.addElement("CAT"); + + Glu.addElement("GAA"); + Glu.addElement("GAG"); + Asp.addElement("GAC"); + Asp.addElement("GAT"); + + Tyr.addElement("TAC"); + Tyr.addElement("TAT"); + + Thr.addElement("ACA"); + Thr.addElement("ACG"); + Thr.addElement("ACC"); + Thr.addElement("ACT"); + + Pro.addElement("CCA"); + Pro.addElement("CCG"); + Pro.addElement("CCC"); + Pro.addElement("CCT"); + + Ala.addElement("GCA"); + Ala.addElement("GCG"); + Ala.addElement("GCC"); + Ala.addElement("GCT"); + + Ser.addElement("TCA"); + Ser.addElement("TCG"); + Ser.addElement("TCC"); + Ser.addElement("TCT"); + Ser.addElement("AGC"); + Ser.addElement("AGT"); + + Arg.addElement("AGA"); + Arg.addElement("AGG"); + Arg.addElement("CGA"); + Arg.addElement("CGG"); + Arg.addElement("CGC"); + Arg.addElement("CGT"); + + Gly.addElement("GGA"); + Gly.addElement("GGG"); + Gly.addElement("GGC"); + Gly.addElement("GGT"); + + STOP.addElement("TGA"); + STOP.addElement("TAA"); + STOP.addElement("TAG"); + + Trp.addElement("TGG"); + + Cys.addElement("TGC"); + Cys.addElement("TGT"); + + Ile.addElement("ATA"); + Ile.addElement("ATC"); + Ile.addElement("ATT"); + + Met.addElement("ATG"); + + Leu.addElement("CTA"); + Leu.addElement("CTG"); + Leu.addElement("CTC"); + Leu.addElement("CTT"); + Leu.addElement("TTA"); + Leu.addElement("TTG"); + + Val.addElement("GTA"); + Val.addElement("GTG"); + Val.addElement("GTC"); + Val.addElement("GTT"); + + Phe.addElement("TTC"); + Phe.addElement("TTT"); + } + + public static Color[][] groupColors = { + {Color.red,Color.red.brighter(),Color.red.brighter().brighter()}, + {Color.orange,Color.orange.brighter(),Color.orange.brighter().brighter()}, + {Color.green,Color.green.brighter(),Color.green.brighter().brighter()}, + {Color.blue,Color.blue.brighter(),Color.blue.brighter().brighter()}, + {Color.magenta,Color.magenta.brighter(),Color.magenta.brighter().brighter()}, + {Color.cyan,Color.cyan.brighter(),Color.cyan.brighter().brighter()}, + {Color.pink,Color.pink.brighter(),Color.pink.brighter().brighter()}, + + }; + + + + //Stores residue codes/names and colours and other things + public static Hashtable propHash = new Hashtable(); + public static Hashtable hydrophobic = new Hashtable(); + public static Hashtable polar = new Hashtable(); + public static Hashtable small = new Hashtable(); + public static Hashtable positive = new Hashtable(); + public static Hashtable negative = new Hashtable(); + public static Hashtable charged = new Hashtable(); + public static Hashtable aromatic = new Hashtable(); + public static Hashtable aliphatic = new Hashtable(); + public static Hashtable tiny = new Hashtable(); + public static Hashtable proline = new Hashtable(); + + static { + hydrophobic.put("I",new Integer(1)); + hydrophobic.put("L",new Integer(1)); + hydrophobic.put("V",new Integer(1)); + hydrophobic.put("C",new Integer(1)); + hydrophobic.put("A",new Integer(1)); + hydrophobic.put("G",new Integer(1)); + hydrophobic.put("M",new Integer(1)); + hydrophobic.put("F",new Integer(1)); + hydrophobic.put("Y",new Integer(1)); + hydrophobic.put("W",new Integer(1)); + hydrophobic.put("H",new Integer(1)); + hydrophobic.put("K",new Integer(1)); + hydrophobic.put("X",new Integer(1)); + hydrophobic.put("-",new Integer(1)); + hydrophobic.put("*",new Integer(1)); + hydrophobic.put("R",new Integer(0)); + hydrophobic.put("E",new Integer(0)); + hydrophobic.put("Q",new Integer(0)); + hydrophobic.put("D",new Integer(0)); + hydrophobic.put("N",new Integer(0)); + hydrophobic.put("S",new Integer(0)); + hydrophobic.put("T",new Integer(0)); + hydrophobic.put("P",new Integer(0)); + } + static { + polar.put("Y",new Integer(1)); + polar.put("W",new Integer(1)); + polar.put("H",new Integer(1)); + polar.put("K",new Integer(1)); + polar.put("R",new Integer(1)); + polar.put("E",new Integer(1)); + polar.put("Q",new Integer(1)); + polar.put("D",new Integer(1)); + polar.put("N",new Integer(1)); + polar.put("S",new Integer(1)); + polar.put("T",new Integer(1)); + polar.put("X",new Integer(1)); + polar.put("-",new Integer(1)); + polar.put("*",new Integer(1)); + polar.put("I",new Integer(0)); + polar.put("L",new Integer(0)); + polar.put("V",new Integer(0)); + polar.put("C",new Integer(0)); + polar.put("A",new Integer(0)); + polar.put("G",new Integer(0)); + polar.put("M",new Integer(0)); + polar.put("F",new Integer(0)); + polar.put("P",new Integer(0)); + + } + static { + small.put("I",new Integer(0)); + small.put("L",new Integer(0)); + small.put("V",new Integer(1)); + small.put("C",new Integer(1)); + small.put("A",new Integer(1)); + small.put("G",new Integer(1)); + small.put("M",new Integer(0)); + small.put("F",new Integer(0)); + small.put("Y",new Integer(0)); + small.put("W",new Integer(0)); + small.put("H",new Integer(0)); + small.put("K",new Integer(0)); + small.put("R",new Integer(0)); + small.put("E",new Integer(0)); + small.put("Q",new Integer(0)); + small.put("D",new Integer(1)); + small.put("N",new Integer(1)); + small.put("S",new Integer(1)); + small.put("T",new Integer(1)); + small.put("P",new Integer(1)); + small.put("-",new Integer(1)); + small.put("*",new Integer(1)); + } + static { + positive.put("I",new Integer(0)); + positive.put("L",new Integer(0)); + positive.put("V",new Integer(0)); + positive.put("C",new Integer(0)); + positive.put("A",new Integer(0)); + positive.put("G",new Integer(0)); + positive.put("M",new Integer(0)); + positive.put("F",new Integer(0)); + positive.put("Y",new Integer(0)); + positive.put("W",new Integer(0)); + positive.put("H",new Integer(1)); + positive.put("K",new Integer(1)); + positive.put("R",new Integer(1)); + positive.put("E",new Integer(0)); + positive.put("Q",new Integer(0)); + positive.put("D",new Integer(0)); + positive.put("N",new Integer(0)); + positive.put("S",new Integer(0)); + positive.put("T",new Integer(0)); + positive.put("P",new Integer(0)); + positive.put("-",new Integer(1)); + positive.put("*",new Integer(1)); + } + static { + negative.put("I",new Integer(0)); + negative.put("L",new Integer(0)); + negative.put("V",new Integer(0)); + negative.put("C",new Integer(0)); + negative.put("A",new Integer(0)); + negative.put("G",new Integer(0)); + negative.put("M",new Integer(0)); + negative.put("F",new Integer(0)); + negative.put("Y",new Integer(0)); + negative.put("W",new Integer(0)); + negative.put("H",new Integer(0)); + negative.put("K",new Integer(0)); + negative.put("R",new Integer(0)); + negative.put("E",new Integer(1)); + negative.put("Q",new Integer(0)); + negative.put("D",new Integer(1)); + negative.put("N",new Integer(0)); + negative.put("S",new Integer(0)); + negative.put("T",new Integer(0)); + negative.put("P",new Integer(0)); + negative.put("-",new Integer(1)); + negative.put("*",new Integer(1)); + } + static { + charged.put("I",new Integer(0)); + charged.put("L",new Integer(0)); + charged.put("V",new Integer(0)); + charged.put("C",new Integer(0)); + charged.put("A",new Integer(0)); + charged.put("G",new Integer(0)); + charged.put("M",new Integer(0)); + charged.put("F",new Integer(0)); + charged.put("Y",new Integer(0)); + charged.put("W",new Integer(0)); + charged.put("H",new Integer(1)); + charged.put("K",new Integer(1)); + charged.put("R",new Integer(1)); + charged.put("E",new Integer(1)); + charged.put("Q",new Integer(0)); + charged.put("D",new Integer(1)); + charged.put("N",new Integer(1)); + charged.put("S",new Integer(0)); + charged.put("T",new Integer(0)); + charged.put("P",new Integer(0)); + charged.put("-",new Integer(1)); + charged.put("*",new Integer(1)); + } + static { + aromatic.put("I",new Integer(0)); + aromatic.put("L",new Integer(0)); + aromatic.put("V",new Integer(0)); + aromatic.put("C",new Integer(0)); + aromatic.put("A",new Integer(0)); + aromatic.put("G",new Integer(0)); + aromatic.put("M",new Integer(0)); + aromatic.put("F",new Integer(1)); + aromatic.put("Y",new Integer(1)); + aromatic.put("W",new Integer(1)); + aromatic.put("H",new Integer(1)); + aromatic.put("K",new Integer(0)); + aromatic.put("R",new Integer(0)); + aromatic.put("E",new Integer(0)); + aromatic.put("Q",new Integer(0)); + aromatic.put("D",new Integer(0)); + aromatic.put("N",new Integer(0)); + aromatic.put("S",new Integer(0)); + aromatic.put("T",new Integer(0)); + aromatic.put("P",new Integer(0)); + aromatic.put("-",new Integer(1)); + aromatic.put("*",new Integer(1)); + } + static { + aliphatic.put("I",new Integer(1)); + aliphatic.put("L",new Integer(1)); + aliphatic.put("V",new Integer(1)); + aliphatic.put("C",new Integer(0)); + aliphatic.put("A",new Integer(0)); + aliphatic.put("G",new Integer(0)); + aliphatic.put("M",new Integer(0)); + aliphatic.put("F",new Integer(0)); + aliphatic.put("Y",new Integer(0)); + aliphatic.put("W",new Integer(0)); + aliphatic.put("H",new Integer(0)); + aliphatic.put("K",new Integer(0)); + aliphatic.put("R",new Integer(0)); + aliphatic.put("E",new Integer(0)); + aliphatic.put("Q",new Integer(0)); + aliphatic.put("D",new Integer(0)); + aliphatic.put("N",new Integer(0)); + aliphatic.put("S",new Integer(0)); + aliphatic.put("T",new Integer(0)); + aliphatic.put("P",new Integer(0)); + aliphatic.put("-",new Integer(1)); + aliphatic.put("*",new Integer(1)); + } + + static { + tiny.put("I",new Integer(0)); + tiny.put("L",new Integer(0)); + tiny.put("V",new Integer(0)); + tiny.put("C",new Integer(0)); + tiny.put("A",new Integer(1)); + tiny.put("G",new Integer(1)); + tiny.put("M",new Integer(0)); + tiny.put("F",new Integer(0)); + tiny.put("Y",new Integer(0)); + tiny.put("W",new Integer(0)); + tiny.put("H",new Integer(0)); + tiny.put("K",new Integer(0)); + tiny.put("R",new Integer(0)); + tiny.put("E",new Integer(0)); + tiny.put("Q",new Integer(0)); + tiny.put("D",new Integer(0)); + tiny.put("N",new Integer(0)); + tiny.put("S",new Integer(1)); + tiny.put("T",new Integer(0)); + tiny.put("P",new Integer(0)); + tiny.put("-",new Integer(1)); + tiny.put("*",new Integer(1)); + } + + static { + proline.put("I",new Integer(0)); + proline.put("L",new Integer(0)); + proline.put("V",new Integer(0)); + proline.put("C",new Integer(0)); + proline.put("A",new Integer(0)); + proline.put("G",new Integer(0)); + proline.put("M",new Integer(0)); + proline.put("F",new Integer(0)); + proline.put("Y",new Integer(0)); + proline.put("W",new Integer(0)); + proline.put("H",new Integer(0)); + proline.put("K",new Integer(0)); + proline.put("R",new Integer(0)); + proline.put("E",new Integer(0)); + proline.put("Q",new Integer(0)); + proline.put("D",new Integer(0)); + proline.put("N",new Integer(0)); + proline.put("S",new Integer(0)); + proline.put("T",new Integer(0)); + proline.put("P",new Integer(1)); + proline.put("-",new Integer(1)); + proline.put("*",new Integer(1)); + } + + + static { + propHash.put("hydrophobic",hydrophobic); + propHash.put("small",small); + propHash.put("positive",positive); + propHash.put("negative",negative); + propHash.put("charged",charged); + propHash.put("aromatic",aromatic); + propHash.put("aliphatic",aliphatic); + propHash.put("tiny",tiny); + propHash.put("proline",proline); + propHash.put("polar",polar); + } + + public static Hashtable chainColours = new Hashtable(); + static { + chainColours.put("A",Color.red); + chainColours.put("B",Color.orange); + chainColours.put("C",Color.yellow); + chainColours.put("D",Color.green); + chainColours.put("E",Color.cyan); + chainColours.put("F",Color.blue); + chainColours.put("G",Color.magenta); + chainColours.put("H",Color.pink); + } + public static Hashtable getChainColours() { + return chainColours; + } +} diff --git a/src/jalview/schemes/ScoreColourScheme.java b/src/jalview/schemes/ScoreColourScheme.java new file mode 100755 index 0000000..e8d7156 --- /dev/null +++ b/src/jalview/schemes/ScoreColourScheme.java @@ -0,0 +1,63 @@ +package jalview.schemes; + +import jalview.datamodel.*; +import jalview.jbgui.*; + +import java.util.*; +import java.awt.*; + +public class ScoreColourScheme extends ResidueColourScheme { + public double min; + public double max; + public double[] scores; + + public ScoreColourScheme( double[] scores, + double min, + double max) { + + super(); + + this.scores = scores; + this.min = min; + this.max = max; + } + + public Color getColour(SequenceI seq, int j, Vector aa) { + Color c = Color.white; + String s = seq.getSequence(j,j+1); + + if (threshold > 0) + { + if (aboveThreshold(aa,seq,j,threshold)) + c = findColour(seq,s,j,aa); + } + else if ( !s.equals("-") && !s.equals(".") && !s.equals(" ") ) + c = findColour(seq,s,j,aa); + // else + // c = Color.white; + + return c; + } + + public Color findColour(SequenceI seq,String s,int j,Vector aa) + { + + float red = (float)(scores[((Integer)ResidueProperties.aaHash.get(s)).intValue()] + - (float)min)/(float)(max - min); + if (red > (float)1.0) + red = (float)1.0; + + if (red < (float)0.0) + red = (float)0.0; + + if(s.equals(" ")|| s.equals(".") || s.equals("-")) + return Color.white; + + // This isn';t great - pool of colours in here? + return makeColour(red); + } + public Color makeColour(float c) { + return new Color(c,(float)0.0,(float)1.0-c); + } +} + diff --git a/src/jalview/schemes/SecondaryColourScheme.java b/src/jalview/schemes/SecondaryColourScheme.java new file mode 100755 index 0000000..ddf205c --- /dev/null +++ b/src/jalview/schemes/SecondaryColourScheme.java @@ -0,0 +1,28 @@ +package jalview.schemes; + +import jalview.gui.DrawableSequence; + +import java.util.*; +import java.awt.*; + + +public class SecondaryColourScheme extends ResidueColourScheme { + + public Color getColor(DrawableSequence seq, int j, Vector aa) { + Color c = Color.white; + + String s = seq.getSequence().substring(j,j+1); + + if (ResidueProperties.ssHash.containsKey(s)) { + c = (Color)ResidueProperties.ssHash.get(s); + } else { + c = Color.white; + } + return c; + } +} + + + + + diff --git a/src/jalview/schemes/StrandColourScheme.java b/src/jalview/schemes/StrandColourScheme.java new file mode 100755 index 0000000..9ffed08 --- /dev/null +++ b/src/jalview/schemes/StrandColourScheme.java @@ -0,0 +1,36 @@ + +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +package jalview.schemes; + +import java.util.*; +import java.awt.*; + +public class StrandColourScheme extends ScoreColourScheme { + + + public StrandColourScheme() { + super(ResidueProperties.strand,ResidueProperties.strandmin,ResidueProperties.strandmax); + } + + public Color makeColour(float c) { + return new Color(c,c,(float)1.0-c); + } +} + diff --git a/src/jalview/schemes/TaylorColourScheme.java b/src/jalview/schemes/TaylorColourScheme.java new file mode 100755 index 0000000..b13a312 --- /dev/null +++ b/src/jalview/schemes/TaylorColourScheme.java @@ -0,0 +1,15 @@ +package jalview.schemes; + +import jalview.jbgui.*; +import jalview.datamodel.*; + +import java.util.*; +import java.awt.*; + +public class TaylorColourScheme extends ResidueColourScheme { + + public TaylorColourScheme() { + super(ResidueProperties.taylor,0); + } + +} diff --git a/src/jalview/schemes/TurnColourScheme.java b/src/jalview/schemes/TurnColourScheme.java new file mode 100755 index 0000000..b251c76 --- /dev/null +++ b/src/jalview/schemes/TurnColourScheme.java @@ -0,0 +1,35 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +package jalview.schemes; + + +import java.util.*; +import java.awt.*; + +public class TurnColourScheme extends ScoreColourScheme { + + public TurnColourScheme() { + super(ResidueProperties.turn,ResidueProperties.turnmin,ResidueProperties.turnmax); + } + + public Color makeColour(float c) { + return new Color(c,1-c,1-c); + } +} + diff --git a/src/jalview/schemes/UserColourScheme.java b/src/jalview/schemes/UserColourScheme.java new file mode 100755 index 0000000..24e35bb --- /dev/null +++ b/src/jalview/schemes/UserColourScheme.java @@ -0,0 +1,30 @@ +/* Jalview - a java multiple alignment editor + * Copyright (C) 1998 Michele Clamp + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +package jalview.schemes; + +import java.util.*; +import java.awt.*; + +public class UserColourScheme extends ResidueColourScheme +{ + public void setColourScheme(Color [] newColors) + { + colors = newColors; + } +} diff --git a/src/jalview/schemes/ZappoColourScheme.java b/src/jalview/schemes/ZappoColourScheme.java new file mode 100755 index 0000000..b72ff02 --- /dev/null +++ b/src/jalview/schemes/ZappoColourScheme.java @@ -0,0 +1,19 @@ +package jalview.schemes; + +import jalview.jbgui.*; +import jalview.datamodel.*; + +import java.util.*; +import java.awt.*; + +public class ZappoColourScheme extends ResidueColourScheme { + + public ZappoColourScheme() { + super(ResidueProperties.color,0); + } + + public boolean isUserDefinable() { + return true; + } + +} diff --git a/src/jalview/util/BrowserLauncher.java b/src/jalview/util/BrowserLauncher.java new file mode 100755 index 0000000..b169dc4 --- /dev/null +++ b/src/jalview/util/BrowserLauncher.java @@ -0,0 +1,591 @@ +/******************** + * 2004 Jalview Reengineered + * Barton Group + * Dundee University + * + * AM Waterhouse + *******************/ + +package jalview.util; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * BrowserLauncher is a class that provides one static method, openURL, which opens the default + * web browser for the current user of the system to the given URL. It may support other + * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously + * tested and is not guaranteed to work. + *

+ * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms + * that are not part of the standard JDK. What we're trying to do, though, is to take something + * that's frequently desirable but inherently platform-specific -- opening a default browser -- + * and allow programmers (you, for example) to do so without worrying about dropping into native + * code or doing anything else similarly evil. + *

+ * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without + * modification or a need for additional libraries. All classes that are required on certain + * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not + * found, will not cause this to do anything other than returning an error when opening the + * browser. + *

+ * There are certain system requirements for this class, as it's running through Runtime.exec(), + * which is Java's way of making a native system call. Currently, this requires that a Macintosh + * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that + * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder + * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and + * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems + * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops + * back from the inherently platform-sensitive concept of a default browser and simply attempts + * to launch Netscape via a shell command. + *

+ * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be + * redistributed or modified in any form without restrictions as long as the portion of this + * comment from this paragraph through the end of the comment is not removed. The author + * requests that he be notified of any application, applet, or other binary that makes use of + * this code, but that's more out of curiosity than anything and is not required. This software + * includes no warranty. The author is not repsonsible for any loss of data or functionality + * or any adverse or unexpected effects of using this software. + *

+ * Credits: + *
Steven Spencer, JavaWorld magazine (Java Tip 66) + *
Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, + * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk + * + * @author Eric Albert (ejalbert@cs.stanford.edu) + * @version 1.4b1 (Released June 20, 2001) + */ +public class BrowserLauncher { + + /** + * The Java virtual machine that we are running on. Actually, in most cases we only care + * about the operating system, but some operating systems require us to switch on the VM. */ + private static int jvm; + + /** The browser for the system */ + private static Object browser; + + /** + * Caches whether any classes, methods, and fields that are not part of the JDK and need to + * be dynamically loaded at runtime loaded successfully. + *

+ * Note that if this is false, openURL() will always return an + * IOException. + */ + private static boolean loadedWithoutErrors; + + /** The com.apple.mrj.MRJFileUtils class */ + private static Class mrjFileUtilsClass; + + /** The com.apple.mrj.MRJOSType class */ + private static Class mrjOSTypeClass; + + /** The com.apple.MacOS.AEDesc class */ + private static Class aeDescClass; + + /** The (int) method of com.apple.MacOS.AETarget */ + private static Constructor aeTargetConstructor; + + /** The (int, int, int) method of com.apple.MacOS.AppleEvent */ + private static Constructor appleEventConstructor; + + /** The (String) method of com.apple.MacOS.AEDesc */ + private static Constructor aeDescConstructor; + + /** The findFolder method of com.apple.mrj.MRJFileUtils */ + private static Method findFolder; + + /** The getFileCreator method of com.apple.mrj.MRJFileUtils */ + private static Method getFileCreator; + + /** The getFileType method of com.apple.mrj.MRJFileUtils */ + private static Method getFileType; + + /** The openURL method of com.apple.mrj.MRJFileUtils */ + private static Method openURL; + + /** The makeOSType method of com.apple.MacOS.OSUtils */ + private static Method makeOSType; + + /** The putParameter method of com.apple.MacOS.AppleEvent */ + private static Method putParameter; + + /** The sendNoReply method of com.apple.MacOS.AppleEvent */ + private static Method sendNoReply; + + /** Actually an MRJOSType pointing to the System Folder on a Macintosh */ + private static Object kSystemFolderType; + + /** The keyDirectObject AppleEvent parameter type */ + private static Integer keyDirectObject; + + /** The kAutoGenerateReturnID AppleEvent code */ + private static Integer kAutoGenerateReturnID; + + /** The kAnyTransactionID AppleEvent code */ + private static Integer kAnyTransactionID; + + /** The linkage object required for JDirect 3 on Mac OS X. */ + private static Object linkage; + + /** The framework to reference on Mac OS X */ + private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox"; + + /** JVM constant for MRJ 2.0 */ + private static final int MRJ_2_0 = 0; + + /** JVM constant for MRJ 2.1 or later */ + private static final int MRJ_2_1 = 1; + + /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */ + private static final int MRJ_3_0 = 3; + + /** JVM constant for MRJ 3.1 */ + private static final int MRJ_3_1 = 4; + + /** JVM constant for any Windows NT JVM */ + private static final int WINDOWS_NT = 5; + + /** JVM constant for any Windows 9x JVM */ + private static final int WINDOWS_9x = 6; + + /** JVM constant for any other platform */ + private static final int OTHER = -1; + + /** + * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English + * systems from working properly. + */ + private static final String FINDER_TYPE = "FNDR"; + + /** + * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the + * application. + */ + private static final String FINDER_CREATOR = "MACS"; + + /** The name for the AppleEvent type corresponding to a GetURL event. */ + private static final String GURL_EVENT = "GURL"; + + /** + * The first parameter that needs to be passed into Runtime.exec() to open the default web + * browser on Windows. + */ + private static final String FIRST_WINDOWS_PARAMETER = "/c"; + + /** The second parameter for Runtime.exec() on Windows. */ + private static final String SECOND_WINDOWS_PARAMETER = "start"; + + /** + * The third parameter for Runtime.exec() on Windows. This is a "title" + * parameter that the command line expects. Setting this parameter allows + * URLs containing spaces to work. + */ + private static final String THIRD_WINDOWS_PARAMETER = "\"\""; + + /** + * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape + * on many command-line systems. + */ + private static final String NETSCAPE_REMOTE_PARAMETER = "-remote"; + private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL("; + private static final String NETSCAPE_OPEN_PARAMETER_END = ")"; + + /** + * The message from any exception thrown throughout the initialization process. + */ + private static String errorMessage; + + /** + * An initialization block that determines the operating system and loads the necessary + * runtime data. + */ + static { + loadedWithoutErrors = true; + String osName = System.getProperty("os.name"); + if (osName.startsWith("Mac OS")) { + String mrjVersion = System.getProperty("mrj.version"); + String majorMRJVersion = mrjVersion.substring(0, 3); + try { + double version = Double.valueOf(majorMRJVersion).doubleValue(); + if (version == 2) { + jvm = MRJ_2_0; + } else if (version >= 2.1 && version < 3) { + // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually + // works via Runtime.exec() and 2.2 supports that but has an openURL() method + // as well that we currently ignore. + jvm = MRJ_2_1; + } else if (version == 3.0) { + jvm = MRJ_3_0; + } else if (version >= 3.1) { + // Assume that all 3.1 and later versions of MRJ work the same. + jvm = MRJ_3_1; + } else { + loadedWithoutErrors = false; + errorMessage = "Unsupported MRJ version: " + version; + } + } catch (NumberFormatException nfe) { + loadedWithoutErrors = false; + errorMessage = "Invalid MRJ version: " + mrjVersion; + } + } else if (osName.startsWith("Windows")) { + if (osName.indexOf("9") != -1) { + jvm = WINDOWS_9x; + } else { + jvm = WINDOWS_NT; + } + } else { + jvm = OTHER; + } + + if (loadedWithoutErrors) { // if we haven't hit any errors yet + loadedWithoutErrors = loadClasses(); + } + } + + /** + * This class should be never be instantiated; this just ensures so. + */ + private BrowserLauncher() { } + + /** + * Called by a static initializer to load any classes, fields, and methods required at runtime + * to locate the user's web browser. + * @return true if all intialization succeeded + * false if any portion of the initialization failed + */ + private static boolean loadClasses() { + switch (jvm) { + case MRJ_2_0: + try { + Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget"); + Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils"); + Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent"); + Class aeClass = Class.forName("com.apple.MacOS.ae"); + aeDescClass = Class.forName("com.apple.MacOS.AEDesc"); + + aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class }); + appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class }); + aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class }); + + makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class }); + putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass }); + sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { }); + + Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject"); + keyDirectObject = (Integer) keyDirectObjectField.get(null); + Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID"); + kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null); + Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID"); + kAnyTransactionID = (Integer) anyTransactionIDField.get(null); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (NoSuchFieldException nsfe) { + errorMessage = nsfe.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_2_1: + try { + mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); + mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType"); + Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType"); + kSystemFolderType = systemFolderField.get(null); + findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass }); + getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class }); + getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchFieldException nsfe) { + errorMessage = nsfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (SecurityException se) { + errorMessage = se.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_3_0: + try { + Class linker = Class.forName("com.apple.mrj.jdirect.Linker"); + Constructor constructor = linker.getConstructor(new Class[]{ Class.class }); + linkage = constructor.newInstance(new Object[] { BrowserLauncher.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (InvocationTargetException ite) { + errorMessage = ite.getMessage(); + return false; + } catch (InstantiationException ie) { + errorMessage = ie.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_3_1: + try { + mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); + openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } + break; + default: + break; + } + return true; + } + + /** + * Attempts to locate the default web browser on the local system. Caches results so it + * only locates the browser once for each use of this class per JVM instance. + * @return The browser for the system. Note that this may not be what you would consider + * to be a standard web browser; instead, it's the application that gets called to + * open the default web browser. In some cases, this will be a non-String object + * that provides the means of calling the default browser. + */ + private static Object locateBrowser() { + if (browser != null) { + return browser; + } + switch (jvm) { + case MRJ_2_0: + try { + Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR }); + Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode }); + Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT }); + Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID }); + // Don't set browser = appleEvent because then the next time we call + // locateBrowser(), we'll get the same AppleEvent, to which we'll already have + // added the relevant parameter. Instead, regenerate the AppleEvent every time. + // There's probably a way to do this better; if any has any ideas, please let + // me know. + return appleEvent; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InstantiationException ie) { + browser = null; + errorMessage = ie.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getMessage(); + return browser; + } + case MRJ_2_1: + File systemFolder; + try { + systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType }); + } catch (IllegalArgumentException iare) { + browser = null; + errorMessage = iare.getMessage(); + return browser; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); + return browser; + } + String[] systemFolderFiles = systemFolder.list(); + // Avoid a FilenameFilter because that can't be stopped mid-list + for(int i = 0; i < systemFolderFiles.length; i++) { + try { + File file = new File(systemFolder, systemFolderFiles[i]); + if (!file.isFile()) { + continue; + } + // We're looking for a file with a creator code of 'MACS' and + // a type of 'FNDR'. Only requiring the type results in non-Finder + // applications being picked up on certain Mac OS 9 systems, + // especially German ones, and sending a GURL event to those + // applications results in a logout under Multiple Users. + Object fileType = getFileType.invoke(null, new Object[] { file }); + if (FINDER_TYPE.equals(fileType.toString())) { + Object fileCreator = getFileCreator.invoke(null, new Object[] { file }); + if (FINDER_CREATOR.equals(fileCreator.toString())) { + browser = file.toString(); // Actually the Finder, but that's OK + return browser; + } + } + } catch (IllegalArgumentException iare) { + browser = browser; + errorMessage = iare.getMessage(); + return null; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); + return browser; + } + } + browser = null; + break; + case MRJ_3_0: + case MRJ_3_1: + browser = ""; // Return something non-null + break; + case WINDOWS_NT: + browser = "cmd.exe"; + break; + case WINDOWS_9x: + browser = "command.com"; + break; + case OTHER: + default: + browser = "netscape"; + break; + } + return browser; + } + + /** + * Attempts to open the default web browser to the given URL. + * @param url The URL to open + * @throws IOException If the web browser could not be located or does not run + */ + public static void openURL(String url) throws IOException { + if (!loadedWithoutErrors) { + throw new IOException("Exception in finding browser: " + errorMessage); + } + Object browser = locateBrowser(); + if (browser == null) { + throw new IOException("Unable to locate browser: " + errorMessage); + } + + switch (jvm) { + case MRJ_2_0: + Object aeDesc = null; + try { + aeDesc = aeDescConstructor.newInstance(new Object[] { url }); + putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc }); + sendNoReply.invoke(browser, new Object[] { }); + } catch (InvocationTargetException ite) { + throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage()); + } catch (IllegalAccessException iae) { + throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage()); + } catch (InstantiationException ie) { + throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage()); + } finally { + aeDesc = null; // Encourage it to get disposed if it was created + browser = null; // Ditto + } + break; + case MRJ_2_1: + Runtime.getRuntime().exec(new String[] { (String) browser, url } ); + break; + case MRJ_3_0: + int[] instance = new int[1]; + int result = ICStart(instance, 0); + if (result == 0) { + int[] selectionStart = new int[] { 0 }; + byte[] urlBytes = url.getBytes(); + int[] selectionEnd = new int[] { urlBytes.length }; + result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, + urlBytes.length, selectionStart, + selectionEnd); + if (result == 0) { + // Ignore the return value; the URL was launched successfully + // regardless of what happens here. + ICStop(instance); + } else { + throw new IOException("Unable to launch URL: " + result); + } + } else { + throw new IOException("Unable to create an Internet Config instance: " + result); + } + break; + case MRJ_3_1: + try { + openURL.invoke(null, new Object[] { url }); + } catch (InvocationTargetException ite) { + throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage()); + } catch (IllegalAccessException iae) { + throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage()); + } + break; + case WINDOWS_NT: + case WINDOWS_9x: + // Add quotes around the URL to allow ampersands and other special + // characters to work. + Process process = Runtime.getRuntime().exec(new String[] { (String) browser, + FIRST_WINDOWS_PARAMETER, + SECOND_WINDOWS_PARAMETER, + THIRD_WINDOWS_PARAMETER, + '"' + url + '"' }); + // This avoids a memory leak on some versions of Java on Windows. + // That's hinted at in . + try { + process.waitFor(); + process.exitValue(); + } catch (InterruptedException ie) { + throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); + } + break; + case OTHER: + // Assume that we're on Unix and that Netscape is installed + + // First, attempt to open the URL in a currently running session of Netscape + process = Runtime.getRuntime().exec(new String[] { (String) browser, + NETSCAPE_REMOTE_PARAMETER, + NETSCAPE_OPEN_PARAMETER_START + + url + + NETSCAPE_OPEN_PARAMETER_END }); + try { + int exitCode = process.waitFor(); + if (exitCode != 0) { // if Netscape was not open + Runtime.getRuntime().exec(new String[] { (String) browser, url }); + } + } catch (InterruptedException ie) { + throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); + } + break; + default: + // This should never occur, but if it does, we'll try the simplest thing possible + Runtime.getRuntime().exec(new String[] { (String) browser, url }); + break; + } + } + + /** + * Methods required for Mac OS X. The presence of native methods does not cause + * any problems on other platforms. + */ + private native static int ICStart(int[] instance, int signature); + private native static int ICStop(int[] instance); + private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len, + int[] selectionStart, int[] selectionEnd); +} diff --git a/src/jalview/util/Comparison.java b/src/jalview/util/Comparison.java new file mode 100755 index 0000000..72fb1d1 --- /dev/null +++ b/src/jalview/util/Comparison.java @@ -0,0 +1,114 @@ +package jalview.util; + +import jalview.datamodel.*; + +public class Comparison { + + public static float compare(SequenceI ii, SequenceI jj) + { + return Comparison.compare(ii,jj,0,ii.getLength()-1); + } + public static float compare(SequenceI ii, SequenceI jj, int start, int end) { + + String si = ii.getSequence(); + String sj = jj.getSequence(); + + int ilen = end-start+1; + int jlen = end-start+1; + + if ( si.substring(start + ilen).equals("-") || + si.substring(start + ilen).equals(".") || + si.substring(start + ilen).equals(" ")) { + + ilen--; + + while (si.substring(start + ilen,start + ilen+1).equals("-") || + si.substring(start + ilen,start + ilen+1).equals(".") || + si.substring(start + ilen,start + ilen+1).equals(" ")) { + ilen--; + } + } + + if ( sj.substring(start + jlen).equals("-") || + sj.substring(start + jlen).equals(".") || + sj.substring(start + jlen).equals(" ")) { + jlen--; + + while (sj.substring(start + jlen,start + jlen+1).equals("-") || + sj.substring(start + jlen,start + jlen+1).equals(".") || + sj.substring(start + jlen,start + jlen+1).equals(" ")) { + jlen--; + } + } + + int count = 0; + int match = 0; + float pid = -1; + + if (ilen > jlen) { + + for (int j = 0; j < jlen; j++) { + if (si.substring(start + j,start + j+1).equals(sj.substring(start + j,start + j+1))) { + match++; + } + count++; + } + pid = (float)match/(float)ilen * 100; + } else { + for (int j = 0; j < jlen; j++) { + if (si.substring(start + j,start + j+1).equals(sj.substring(start + j,start + j+1))) { + match++; + } + count++; + } + pid = (float)match/(float)jlen * 100; + } + + return pid; + } + + /** */ + public static float PID(Sequence s1 , Sequence s2) { + int res = 0; + int len; + + if (s1.getSequence().length() > s2.getSequence().length()) { + len = s1.getSequence().length(); + } else { + len = s2.getSequence().length(); + } + + int bad = 0; + + for (int i = 0; i < len; i++) { + String str1 = ""; + String str2 = ""; + + if (i < s1.getSequence().length()) { + str1 = s1.getSequence().substring(i,i+1); + } else { + str1 = "."; + } + + if (i < s2.getSequence().length()) { + str2 = s2.getSequence().substring(i,i+1); + } else { + str2 = "."; + } + + if (!(str1.equals(".") || + str1.equals("-") || + str1.equals(" ")) && + !(str2.equals(".") || + str2.equals("-") || + str2.equals(" "))) { + + if (!str1.equals(str2)) { + bad++; + } + } + } + + return (float)100*(len-bad)/len; + } +} diff --git a/src/jalview/util/ErrorLog.java b/src/jalview/util/ErrorLog.java new file mode 100755 index 0000000..dd95b06 --- /dev/null +++ b/src/jalview/util/ErrorLog.java @@ -0,0 +1,18 @@ +package jalview.util; + +import java.io.*; + +public class ErrorLog { + static PrintStream errStream = System.err; + static PrintStream teeFile = null; + + private ErrorLog() {} + + public static void println(String str) { + errStream.println("Error Logger: " + str); + } + + public static void main(String [] argv) { + ErrorLog.println("ERROR"); + } +} diff --git a/src/jalview/util/Format.java b/src/jalview/util/Format.java new file mode 100755 index 0000000..4acf29e --- /dev/null +++ b/src/jalview/util/Format.java @@ -0,0 +1,612 @@ +/* + * Cay S. Horstmann & Gary Cornell, Core Java + * Published By Sun Microsystems Press/Prentice-Hall + * Copyright (C) 1997 Sun Microsystems Inc. + * All Rights Reserved. + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for NON-COMMERCIAL purposes + * and without fee is hereby granted provided that this + * copyright notice appears in all copies. + * + * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR + * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS + * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED + * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING + * THIS SOFTWARE OR ITS DERIVATIVES. + */ + +/** + * A class for formatting numbers that follows printf conventions. + * Also implements C-like atoi and atof functions + * @version 1.03 25 Oct 1997 + * @author Cay Horstmann + */ + +package jalview.util; + +import java.io.*; + +public class Format { /** + * Formats the number following printf conventions. + * Main limitation: Can only handle one format parameter at a time + * Use multiple Format objects to format more than one number + * @param s the format string following printf conventions + * The string has a prefix, a format code and a suffix. The prefix and suffix + * become part of the formatted output. The format code directs the + * formatting of the (single) parameter to be formatted. The code has the + * following structure + *

    + *
  • a % (required) + *
  • a modifier (optional) + *
    + *
    +
    forces display of + for positive numbers + *
    0
    show leading zeroes + *
    -
    align left in the field + *
    space
    prepend a space in front of positive numbers + *
    #
    use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format. + *
    + *
  • an integer denoting field width (optional) + *
  • a period followed by an integer denoting precision (optional) + *
  • a format descriptor (required) + *
    + *
    f
    floating point number in fixed format + *
    e, E
    floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e. + *
    g, G
    floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e. + *
    d, i
    integer in decimal + *
    x
    integer in hexadecimal + *
    o
    integer in octal + *
    s
    string + *
    c
    character + *
    + *
+ * @exception IllegalArgumentException if bad format + */ + + public Format(String s) { + width = 0; + precision = -1; + pre = ""; + post = ""; + leading_zeroes = false; + show_plus = false; + alternate = false; + show_space = false; + left_align = false; + fmt = ' '; + + int state = 0; + int length = s.length(); + int parse_state = 0; + // 0 = prefix, 1 = flags, 2 = width, 3 = precision, + // 4 = format, 5 = end + int i = 0; + + while (parse_state == 0) { + if (i >= length) + parse_state = 5; + else if (s.charAt(i) == '%') { + if (i < length - 1) { + if (s.charAt(i + 1) == '%') { + pre = pre + '%'; + i++; + } else + parse_state = 1; + } else + throw new java.lang.IllegalArgumentException(); + } else + pre = pre + s.charAt(i); + i++; + } + while (parse_state == 1) { + if (i >= length) + parse_state = 5; + else if (s.charAt(i) == ' ') + show_space = true; + else if (s.charAt(i) == '-') + left_align = true; + else if (s.charAt(i) == '+') + show_plus = true; + else if (s.charAt(i) == '0') + leading_zeroes = true; + else if (s.charAt(i) == '#') + alternate = true; + else { + parse_state = 2; + i--; + } + i++; + } + while (parse_state == 2) { + if (i >= length) + parse_state = 5; + else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') { + width = width * 10 + s.charAt(i) - '0'; + i++; + } else if (s.charAt(i) == '.') { + parse_state = 3; + precision = 0; + i++; + } else + parse_state = 4; + } + while (parse_state == 3) { + if (i >= length) + parse_state = 5; + else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') { + precision = precision * 10 + s.charAt(i) - '0'; + i++; + } else + parse_state = 4; + } + if (parse_state == 4) { + if (i >= length) + parse_state = 5; + else + fmt = s.charAt(i); + i++; + } + if (i < length) + post = s.substring(i, length); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the double to print + */ + + public static void print(java.io.PrintStream s, String fmt, double x) { + s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the long to print + */ + public static void print(java.io.PrintStream s, String fmt, long x) { + s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the character to + */ + + public static void print(java.io.PrintStream s, String fmt, char x) { + s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream, fmt the format string + * @param x a string that represents the digits to print + */ + + public static void print(java.io.PrintStream s, String fmt, String x) { + s.print(new Format(fmt).form(x)); + } + + /** + * Converts a string of digits (decimal, octal or hex) to an integer + * @param s a string + * @return the numeric value of the prefix of s representing a base 10 integer + */ + + public static int atoi(String s) { + return (int)atol(s); + } + + /** + * Converts a string of digits (decimal, octal or hex) to a long integer + * @param s a string + * @return the numeric value of the prefix of s representing a base 10 integer + */ + + public static long atol(String s) { + int i = 0; + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) + i++; + if (i < s.length() && s.charAt(i) == '0') { + if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X')) + return parseLong(s.substring(i + 2), 16); + else + return parseLong(s, 8); + } else + return parseLong(s, 10); + } + + private static long parseLong(String s, int base) { + int i = 0; + int sign = 1; + long r = 0; + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) + i++; + if (i < s.length() && s.charAt(i) == '-') { + sign = -1; + i++; + } else if (i < s.length() && s.charAt(i) == '+') { + i++; + } + while (i < s.length()) { + char ch = s.charAt(i); + if ('0' <= ch && ch < '0' + base) + r = r * base + ch - '0'; + else if ('A' <= ch && ch < 'A' + base - 10) + r = r * base + ch - 'A' + 10 ; + else if ('a' <= ch && ch < 'a' + base - 10) + r = r * base + ch - 'a' + 10 ; + else + return r * sign; + i++; + } + return r * sign; + } + + /** + * Converts a string of digits to an double + * @param s a string + */ + + public static double atof(String s) { + int i = 0; + int sign = 1; + double r = 0; // integer part + double f = 0; // fractional part + double p = 1; // exponent of fractional part + int state = 0; // 0 = int part, 1 = frac part + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) + i++; + if (i < s.length() && s.charAt(i) == '-') { + sign = -1; + i++; + } else if (i < s.length() && s.charAt(i) == '+') { + i++; + } + while (i < s.length()) { + char ch = s.charAt(i); + if ('0' <= ch && ch <= '9') { + if (state == 0) + r = r * 10 + ch - '0'; + else if (state == 1) { + p = p / 10; + r = r + p * (ch - '0'); + } + } else if (ch == '.') { + if (state == 0) + state = 1; + else + return sign * r; + } else if (ch == 'e' || ch == 'E') { + long e = (int)parseLong(s.substring(i + 1), 10); + return sign * r * Math.pow(10, e); + } else + return sign * r; + i++; + } + return sign * r; + } + + /** + * Formats a double into a string (like sprintf in C) + * @param x the number to format + * @return the formatted string + * @exception IllegalArgumentException if bad argument + */ + + public String form(double x) { + String r; + if (precision < 0) + precision = 6; + int s = 1; + if (x < 0) { + x = -x; + s = -1; + } + if (fmt == 'f') + r = fixed_format(x); + else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G') + r = exp_format(x); + else + throw new java.lang.IllegalArgumentException(); + + return pad(sign(s, r)); + } + + /** + * Formats a long integer into a string (like sprintf in C) + * @param x the number to format + * @return the formatted string + */ + + public String form(long x) { + String r; + int s = 0; + if (fmt == 'd' || fmt == 'i') { + if (x < 0) { + r = ("" + x).substring(1); + s = -1; + } else { + r = "" + x; + s = 1; + } + } else if (fmt == 'o') + r = convert(x, 3, 7, "01234567"); + else if (fmt == 'x') + r = convert(x, 4, 15, "0123456789abcdef"); + else if (fmt == 'X') + r = convert(x, 4, 15, "0123456789ABCDEF"); + else + throw new java.lang.IllegalArgumentException(); + + return pad(sign(s, r)); + } + + /** + * Formats a character into a string (like sprintf in C) + * @param x the value to format + * @return the formatted string + */ + + public String form(char c) { + if (fmt != 'c') + throw new java.lang.IllegalArgumentException(); + + String r = "" + c; + return pad(r); + } + + /** + * Formats a string into a larger string (like sprintf in C) + * @param x the value to format + * @return the formatted string + */ + + public String form(String s) { + if (fmt != 's') + throw new java.lang.IllegalArgumentException(); + if (precision >= 0) + s = s.substring(0, precision); + return pad(s); + } + + + /** + * a test stub for the format class + */ + + public static void main(String[] a) { + double x = 1.23456789012; + double y = 123; + double z = 1.2345e30; + double w = 1.02; + double u = 1.234e-5; + int d = 0xCAFE; + Format.print(System.out, "x = |%f|\n", x); + Format.print(System.out, "u = |%20f|\n", u); + Format.print(System.out, "x = |% .5f|\n", x); + Format.print(System.out, "w = |%20.5f|\n", w); + Format.print(System.out, "x = |%020.5f|\n", x); + Format.print(System.out, "x = |%+20.5f|\n", x); + Format.print(System.out, "x = |%+020.5f|\n", x); + Format.print(System.out, "x = |% 020.5f|\n", x); + Format.print(System.out, "y = |%#+20.5f|\n", y); + Format.print(System.out, "y = |%-+20.5f|\n", y); + Format.print(System.out, "z = |%20.5f|\n", z); + + Format.print(System.out, "x = |%e|\n", x); + Format.print(System.out, "u = |%20e|\n", u); + Format.print(System.out, "x = |% .5e|\n", x); + Format.print(System.out, "w = |%20.5e|\n", w); + Format.print(System.out, "x = |%020.5e|\n", x); + Format.print(System.out, "x = |%+20.5e|\n", x); + Format.print(System.out, "x = |%+020.5e|\n", x); + Format.print(System.out, "x = |% 020.5e|\n", x); + Format.print(System.out, "y = |%#+20.5e|\n", y); + Format.print(System.out, "y = |%-+20.5e|\n", y); + + Format.print(System.out, "x = |%g|\n", x); + Format.print(System.out, "z = |%g|\n", z); + Format.print(System.out, "w = |%g|\n", w); + Format.print(System.out, "u = |%g|\n", u); + Format.print(System.out, "y = |%.2g|\n", y); + Format.print(System.out, "y = |%#.2g|\n", y); + + Format.print(System.out, "d = |%d|\n", d); + Format.print(System.out, "d = |%20d|\n", d); + Format.print(System.out, "d = |%020d|\n", d); + Format.print(System.out, "d = |%+20d|\n", d); + Format.print(System.out, "d = |% 020d|\n", d); + Format.print(System.out, "d = |%-20d|\n", d); + Format.print(System.out, "d = |%20.8d|\n", d); + Format.print(System.out, "d = |%x|\n", d); + Format.print(System.out, "d = |%20X|\n", d); + Format.print(System.out, "d = |%#20x|\n", d); + Format.print(System.out, "d = |%020X|\n", d); + Format.print(System.out, "d = |%20.8x|\n", d); + Format.print(System.out, "d = |%o|\n", d); + Format.print(System.out, "d = |%020o|\n", d); + Format.print(System.out, "d = |%#20o|\n", d); + Format.print(System.out, "d = |%#020o|\n", d); + Format.print(System.out, "d = |%20.12o|\n", d); + + Format.print(System.out, "s = |%-20s|\n", "Hello"); + Format.print(System.out, "s = |%-20c|\n", '!'); + + // regression test to confirm fix of reported bugs + + Format.print(System.out, "|%i|\n", Long.MIN_VALUE); + + Format.print(System.out, "|%6.2e|\n", 0.0); + Format.print(System.out, "|%6.2g|\n", 0.0); + + Format.print(System.out, "|%6.2f|\n", 9.99); + Format.print(System.out, "|%6.2f|\n", 9.999); + + Format.print(System.out, "|%6.0f|\n", 9.999); + } + + private static String repeat(char c, int n) { + if (n <= 0) + return ""; + StringBuffer s = new StringBuffer(n); + for (int i = 0; i < n; i++) + s.append(c); + return s.toString(); + } + + private static String convert(long x, int n, int m, String d) { + if (x == 0) + return "0"; + String r = ""; + while (x != 0) { + r = d.charAt((int)(x & m)) + r; + x = x >>> n; + } + return r; + } + + private String pad(String r) { + String p = repeat(' ', width - r.length()); + if (left_align) + return pre + r + p + post; + else + return pre + p + r + post; + } + + private String sign(int s, String r) { + String p = ""; + if (s < 0) + p = "-"; + else if (s > 0) { + if (show_plus) + p = "+"; + else if (show_space) + p = " "; + } else { + if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') + p = "0"; + else if (fmt == 'x' && alternate) + p = "0x"; + else if (fmt == 'X' && alternate) + p = "0X"; + } + int w = 0; + if (leading_zeroes) + w = width; + else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') + && precision > 0) + w = precision; + + return p + repeat('0', w - p.length() - r.length()) + r; + } + + private String fixed_format(double d) { + boolean removeTrailing + = (fmt == 'G' || fmt == 'g') && !alternate; + // remove trailing zeroes and decimal point + + if (d > 0x7FFFFFFFFFFFFFFFL) + return exp_format(d); + if (precision == 0) + return (long)(d + 0.5) + (removeTrailing ? "" : "."); + + long whole = (long)d; + double fr = d - whole; // fractional part + if (fr >= 1 || fr < 0) + return exp_format(d); + + double factor = 1; + String leading_zeroes = ""; + for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) { + factor *= 10; + leading_zeroes = leading_zeroes + "0"; + } + long l = (long) (factor * fr + 0.5); + if (l >= factor) { + l = 0; + whole++; + } // CSH 10-25-97 + + String z = leading_zeroes + l; + z = "." + z.substring(z.length() - precision, z.length()); + + if (removeTrailing) { + int t = z.length() - 1; + while (t >= 0 && z.charAt(t) == '0') + t--; + if (t >= 0 && z.charAt(t) == '.') + t--; + z = z.substring(0, t + 1); + } + + return whole + z; + } + + private String exp_format(double d) { + String f = ""; + int e = 0; + double dd = d; + double factor = 1; + if (d != 0) { + while (dd > 10) { + e++; + factor /= 10; + dd = dd / 10; + } + while (dd < 1) { + e--; + factor *= 10; + dd = dd * 10; + } + } + if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) + return fixed_format(d); + + d = d * factor; + f = f + fixed_format(d); + + if (fmt == 'e' || fmt == 'g') + f = f + "e"; + else + f = f + "E"; + + String p = "000"; + if (e >= 0) { + f = f + "+"; + p = p + e; + } else { + f = f + "-"; + p = p + (-e); + } + + return f + p.substring(p.length() - 3, p.length()); + } + + private int width; + private int precision; + private String pre; + private String post; + private boolean leading_zeroes; + private boolean show_plus; + private boolean alternate; + private boolean show_space; + private boolean left_align; + private char fmt; // one of cdeEfgGiosxXos +} + + + + + diff --git a/src/jalview/util/Format.save b/src/jalview/util/Format.save new file mode 100755 index 0000000..5783670 --- /dev/null +++ b/src/jalview/util/Format.save @@ -0,0 +1,563 @@ +/* + * Cay S. Horstmann & Gary Cornell, Core Java + * Published By Sun Microsystems Press/Prentice-Hall + * Copyright (C) 1997 Sun Microsystems Inc. + * All Rights Reserved. + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for NON-COMMERCIAL purposes + * and without fee is hereby granted provided that this + * copyright notice appears in all copies. + * + * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR + * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS + * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED + * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING + * THIS SOFTWARE OR ITS DERIVATIVES. + */ + +/** + * A class for formatting numbers that follows printf conventions. + * Also implements C-like atoi and atof functions + * @version 1.03 25 Oct 1997 + * @author Cay Horstmann + */ + +package jalview.util; + +import java.io.*; + +public class Format + +{ /** + * Formats the number following printf conventions. + * Main limitation: Can only handle one format parameter at a time + * Use multiple Format objects to format more than one number + * @param s the format string following printf conventions + * The string has a prefix, a format code and a suffix. The prefix and suffix + * become part of the formatted output. The format code directs the + * formatting of the (single) parameter to be formatted. The code has the + * following structure + *
    + *
  • a % (required) + *
  • a modifier (optional) + *
    + *
    +
    forces display of + for positive numbers + *
    0
    show leading zeroes + *
    -
    align left in the field + *
    space
    prepend a space in front of positive numbers + *
    #
    use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format. + *
    + *
  • an integer denoting field width (optional) + *
  • a period followed by an integer denoting precision (optional) + *
  • a format descriptor (required) + *
    + *
    f
    floating point number in fixed format + *
    e, E
    floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e. + *
    g, G
    floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e. + *
    d, i
    integer in decimal + *
    x
    integer in hexadecimal + *
    o
    integer in octal + *
    s
    string + *
    c
    character + *
    + *
+ * @exception IllegalArgumentException if bad format + */ + + public Format(String s) + { width = 0; + precision = -1; + pre = ""; + post = ""; + leading_zeroes = false; + show_plus = false; + alternate = false; + show_space = false; + left_align = false; + fmt = ' '; + + int state = 0; + int length = s.length(); + int parse_state = 0; + // 0 = prefix, 1 = flags, 2 = width, 3 = precision, + // 4 = format, 5 = end + int i = 0; + + while (parse_state == 0) + { if (i >= length) parse_state = 5; + else if (s.charAt(i) == '%') + { if (i < length - 1) + { if (s.charAt(i + 1) == '%') + { pre = pre + '%'; + i++; + } + else + parse_state = 1; + } + else throw new java.lang.IllegalArgumentException(); + } + else + pre = pre + s.charAt(i); + i++; + } + while (parse_state == 1) + { if (i >= length) parse_state = 5; + else if (s.charAt(i) == ' ') show_space = true; + else if (s.charAt(i) == '-') left_align = true; + else if (s.charAt(i) == '+') show_plus = true; + else if (s.charAt(i) == '0') leading_zeroes = true; + else if (s.charAt(i) == '#') alternate = true; + else { parse_state = 2; i--; } + i++; + } + while (parse_state == 2) + { if (i >= length) parse_state = 5; + else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') + { width = width * 10 + s.charAt(i) - '0'; + i++; + } + else if (s.charAt(i) == '.') + { parse_state = 3; + precision = 0; + i++; + } + else + parse_state = 4; + } + while (parse_state == 3) + { if (i >= length) parse_state = 5; + else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') + { precision = precision * 10 + s.charAt(i) - '0'; + i++; + } + else + parse_state = 4; + } + if (parse_state == 4) + { if (i >= length) parse_state = 5; + else fmt = s.charAt(i); + i++; + } + if (i < length) + post = s.substring(i, length); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the double to print + */ + + public static void print(java.io.PrintStream s, String fmt, double x) + { s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the long to print + */ + public static void print(java.io.PrintStream s, String fmt, long x) + { s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream + * @param fmt the format string + * @param x the character to + */ + + public static void print(java.io.PrintStream s, String fmt, char x) + { s.print(new Format(fmt).form(x)); + } + + /** + * prints a formatted number following printf conventions + * @param s a PrintStream, fmt the format string + * @param x a string that represents the digits to print + */ + + public static void print(java.io.PrintStream s, String fmt, String x) + { s.print(new Format(fmt).form(x)); + } + + /** + * Converts a string of digits (decimal, octal or hex) to an integer + * @param s a string + * @return the numeric value of the prefix of s representing a base 10 integer + */ + + public static int atoi(String s) + { return (int)atol(s); + } + + /** + * Converts a string of digits (decimal, octal or hex) to a long integer + * @param s a string + * @return the numeric value of the prefix of s representing a base 10 integer + */ + + public static long atol(String s) + { int i = 0; + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; + if (i < s.length() && s.charAt(i) == '0') + { if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X')) + return parseLong(s.substring(i + 2), 16); + else return parseLong(s, 8); + } + else return parseLong(s, 10); + } + + private static long parseLong(String s, int base) + { int i = 0; + int sign = 1; + long r = 0; + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; + if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; } + else if (i < s.length() && s.charAt(i) == '+') { i++; } + while (i < s.length()) + { char ch = s.charAt(i); + if ('0' <= ch && ch < '0' + base) + r = r * base + ch - '0'; + else if ('A' <= ch && ch < 'A' + base - 10) + r = r * base + ch - 'A' + 10 ; + else if ('a' <= ch && ch < 'a' + base - 10) + r = r * base + ch - 'a' + 10 ; + else + return r * sign; + i++; + } + return r * sign; + } + + /** + * Converts a string of digits to an double + * @param s a string + */ + + public static double atof(String s) + { int i = 0; + int sign = 1; + double r = 0; // integer part + double f = 0; // fractional part + double p = 1; // exponent of fractional part + int state = 0; // 0 = int part, 1 = frac part + + while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; + if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; } + else if (i < s.length() && s.charAt(i) == '+') { i++; } + while (i < s.length()) + { char ch = s.charAt(i); + if ('0' <= ch && ch <= '9') + { if (state == 0) + r = r * 10 + ch - '0'; + else if (state == 1) + { p = p / 10; + r = r + p * (ch - '0'); + } + } + else if (ch == '.') + { if (state == 0) state = 1; + else return sign * r; + } + else if (ch == 'e' || ch == 'E') + { long e = (int)parseLong(s.substring(i + 1), 10); + return sign * r * Math.pow(10, e); + } + else return sign * r; + i++; + } + return sign * r; + } + + /** + * Formats a double into a string (like sprintf in C) + * @param x the number to format + * @return the formatted string + * @exception IllegalArgumentException if bad argument + */ + + public String form(double x) + { String r; + if (precision < 0) precision = 6; + int s = 1; + if (x < 0) { x = -x; s = -1; } + if (fmt == 'f') + r = fixed_format(x); + else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G') + r = exp_format(x); + else throw new java.lang.IllegalArgumentException(); + + return pad(sign(s, r)); + } + + /** + * Formats a long integer into a string (like sprintf in C) + * @param x the number to format + * @return the formatted string + */ + + public String form(long x) + { String r; + int s = 0; + if (fmt == 'd' || fmt == 'i') + { if (x < 0) + { r = ("" + x).substring(1); + s = -1; + } + else + { r = "" + x; + s = 1; + } + } + else if (fmt == 'o') + r = convert(x, 3, 7, "01234567"); + else if (fmt == 'x') + r = convert(x, 4, 15, "0123456789abcdef"); + else if (fmt == 'X') + r = convert(x, 4, 15, "0123456789ABCDEF"); + else throw new java.lang.IllegalArgumentException(); + + return pad(sign(s, r)); + } + + /** + * Formats a character into a string (like sprintf in C) + * @param x the value to format + * @return the formatted string + */ + + public String form(char c) + { if (fmt != 'c') + throw new java.lang.IllegalArgumentException(); + + String r = "" + c; + return pad(r); + } + + /** + * Formats a string into a larger string (like sprintf in C) + * @param x the value to format + * @return the formatted string + */ + + public String form(String s) + { if (fmt != 's') + throw new java.lang.IllegalArgumentException(); + if (precision >= 0) s = s.substring(0, precision); + return pad(s); + } + + + /** + * a test stub for the format class + */ + + public static void main(String[] a) + { double x = 1.23456789012; + double y = 123; + double z = 1.2345e30; + double w = 1.02; + double u = 1.234e-5; + int d = 0xCAFE; + Format.print(System.out, "x = |%f|\n", x); + Format.print(System.out, "u = |%20f|\n", u); + Format.print(System.out, "x = |% .5f|\n", x); + Format.print(System.out, "w = |%20.5f|\n", w); + Format.print(System.out, "x = |%020.5f|\n", x); + Format.print(System.out, "x = |%+20.5f|\n", x); + Format.print(System.out, "x = |%+020.5f|\n", x); + Format.print(System.out, "x = |% 020.5f|\n", x); + Format.print(System.out, "y = |%#+20.5f|\n", y); + Format.print(System.out, "y = |%-+20.5f|\n", y); + Format.print(System.out, "z = |%20.5f|\n", z); + + Format.print(System.out, "x = |%e|\n", x); + Format.print(System.out, "u = |%20e|\n", u); + Format.print(System.out, "x = |% .5e|\n", x); + Format.print(System.out, "w = |%20.5e|\n", w); + Format.print(System.out, "x = |%020.5e|\n", x); + Format.print(System.out, "x = |%+20.5e|\n", x); + Format.print(System.out, "x = |%+020.5e|\n", x); + Format.print(System.out, "x = |% 020.5e|\n", x); + Format.print(System.out, "y = |%#+20.5e|\n", y); + Format.print(System.out, "y = |%-+20.5e|\n", y); + + Format.print(System.out, "x = |%g|\n", x); + Format.print(System.out, "z = |%g|\n", z); + Format.print(System.out, "w = |%g|\n", w); + Format.print(System.out, "u = |%g|\n", u); + Format.print(System.out, "y = |%.2g|\n", y); + Format.print(System.out, "y = |%#.2g|\n", y); + + Format.print(System.out, "d = |%d|\n", d); + Format.print(System.out, "d = |%20d|\n", d); + Format.print(System.out, "d = |%020d|\n", d); + Format.print(System.out, "d = |%+20d|\n", d); + Format.print(System.out, "d = |% 020d|\n", d); + Format.print(System.out, "d = |%-20d|\n", d); + Format.print(System.out, "d = |%20.8d|\n", d); + Format.print(System.out, "d = |%x|\n", d); + Format.print(System.out, "d = |%20X|\n", d); + Format.print(System.out, "d = |%#20x|\n", d); + Format.print(System.out, "d = |%020X|\n", d); + Format.print(System.out, "d = |%20.8x|\n", d); + Format.print(System.out, "d = |%o|\n", d); + Format.print(System.out, "d = |%020o|\n", d); + Format.print(System.out, "d = |%#20o|\n", d); + Format.print(System.out, "d = |%#020o|\n", d); + Format.print(System.out, "d = |%20.12o|\n", d); + + Format.print(System.out, "s = |%-20s|\n", "Hello"); + Format.print(System.out, "s = |%-20c|\n", '!'); + + // regression test to confirm fix of reported bugs + + Format.print(System.out, "|%i|\n", Long.MIN_VALUE); + + Format.print(System.out, "|%6.2e|\n", 0.0); + Format.print(System.out, "|%6.2g|\n", 0.0); + + Format.print(System.out, "|%6.2f|\n", 9.99); + Format.print(System.out, "|%6.2f|\n", 9.999); + + Format.print(System.out, "|%6.0f|\n", 9.999); + } + + private static String repeat(char c, int n) + { if (n <= 0) return ""; + StringBuffer s = new StringBuffer(n); + for (int i = 0; i < n; i++) s.append(c); + return s.toString(); + } + + private static String convert(long x, int n, int m, String d) + { if (x == 0) return "0"; + String r = ""; + while (x != 0) + { r = d.charAt((int)(x & m)) + r; + x = x >>> n; + } + return r; + } + + private String pad(String r) + { String p = repeat(' ', width - r.length()); + if (left_align) return pre + r + p + post; + else return pre + p + r + post; + } + + private String sign(int s, String r) + { String p = ""; + if (s < 0) p = "-"; + else if (s > 0) + { if (show_plus) p = "+"; + else if (show_space) p = " "; + } + else + { if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0"; + else if (fmt == 'x' && alternate) p = "0x"; + else if (fmt == 'X' && alternate) p = "0X"; + } + int w = 0; + if (leading_zeroes) + w = width; + else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') + && precision > 0) w = precision; + + return p + repeat('0', w - p.length() - r.length()) + r; + } + + private String fixed_format(double d) + { boolean removeTrailing + = (fmt == 'G' || fmt == 'g') && !alternate; + // remove trailing zeroes and decimal point + + if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d); + if (precision == 0) + return (long)(d + 0.5) + (removeTrailing ? "" : "."); + + long whole = (long)d; + double fr = d - whole; // fractional part + if (fr >= 1 || fr < 0) return exp_format(d); + + double factor = 1; + String leading_zeroes = ""; + for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) + { factor *= 10; + leading_zeroes = leading_zeroes + "0"; + } + long l = (long) (factor * fr + 0.5); + if (l >= factor) { l = 0; whole++; } // CSH 10-25-97 + + String z = leading_zeroes + l; + z = "." + z.substring(z.length() - precision, z.length()); + + if (removeTrailing) + { int t = z.length() - 1; + while (t >= 0 && z.charAt(t) == '0') t--; + if (t >= 0 && z.charAt(t) == '.') t--; + z = z.substring(0, t + 1); + } + + return whole + z; + } + + private String exp_format(double d) + { String f = ""; + int e = 0; + double dd = d; + double factor = 1; + if (d != 0) + { while (dd > 10) { e++; factor /= 10; dd = dd / 10; } + while (dd < 1) { e--; factor *= 10; dd = dd * 10; } + } + if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) + return fixed_format(d); + + d = d * factor; + f = f + fixed_format(d); + + if (fmt == 'e' || fmt == 'g') + f = f + "e"; + else + f = f + "E"; + + String p = "000"; + if (e >= 0) + { f = f + "+"; + p = p + e; + } + else + { f = f + "-"; + p = p + (-e); + } + + return f + p.substring(p.length() - 3, p.length()); + } + + private int width; + private int precision; + private String pre; + private String post; + private boolean leading_zeroes; + private boolean show_plus; + private boolean alternate; + private boolean show_space; + private boolean left_align; + private char fmt; // one of cdeEfgGiosxXos +} + + + + + diff --git a/src/jalview/util/ListenList.java b/src/jalview/util/ListenList.java new file mode 100755 index 0000000..cc0fc5a --- /dev/null +++ b/src/jalview/util/ListenList.java @@ -0,0 +1,28 @@ +package jalview.util; + +import java.util.*; + +public class ListenList { + protected Vector listeners; + public ListenList() { + listeners = new Vector(); + } + + public void addListener(EventListener l) { + if (l == null) { + return; + } + if (!listeners.contains(l)) { + listeners.addElement(l); + } + } + + public void removeListener(EventListener l) { + if (l == null) { + return; + } + if (listeners.contains(l)) { + listeners.removeElement(l); + } + } +} diff --git a/src/jalview/util/QuickSort.java b/src/jalview/util/QuickSort.java new file mode 100755 index 0000000..f81056a --- /dev/null +++ b/src/jalview/util/QuickSort.java @@ -0,0 +1,91 @@ +package jalview.util; + + +public class QuickSort { + + public static void sort(float[] arr,Object[] s) { + sort(arr,0,arr.length-1,s); + } + + public static void sort(String[] arr,Object[] s) { + stringSort(arr,0,arr.length-1,s); + } + + public static void stringSort(String[] arr,int p, int r,Object[] s) { + int q; + + if (p < r) { + q = stringPartition(arr,p,r,s); + stringSort(arr,p,q,s); + stringSort(arr,q+1,r,s); + } + } + + public static void sort(float[] arr,int p, int r,Object[] s) { + int q; + + if (p < r) { + q = partition(arr,p,r,s); + sort(arr,p,q,s); + sort(arr,q+1,r,s); + } + } + + private static int partition(float[] arr, int p, int r,Object[] s) { + float x = arr[p]; + int i = p-1; + int j = r+1; + + while(true) { + do { + j = j-1; + } while (arr[j] > x); + + do { + i = i+1; + } while (arr[i] < x); + + if ( i < j) { + float tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + + Object tmp2 = s[i]; + s[i] = s[j]; + s[j] = tmp2; + } else { + return j; + } + } + } + private static int stringPartition(String[] arr, int p, int r,Object[] s) { + String x = arr[p]; + int i = p-1; + int j = r+1; + + while(true) { + do { + j = j-1; + } while (arr[j].compareTo(x) < 0); + + do { + i = i+1; + } while (arr[i].compareTo(x) > 0); + + if ( i < j) { + String tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + + Object tmp2 = s[i]; + s[i] = s[j]; + s[j] = tmp2; + } else { + return j; + } + } + } +} + + + diff --git a/src/jalview/util/WindowUtil.java b/src/jalview/util/WindowUtil.java new file mode 100755 index 0000000..3f44167 --- /dev/null +++ b/src/jalview/util/WindowUtil.java @@ -0,0 +1,45 @@ +package jalview.util; + +import java.awt.*; +import java.lang.reflect.*; + +public class WindowUtil { + + public static Window getWindowAncestor(Component c) { + for(Container p = c.getParent(); p != null; p = p.getParent()) { + if (p instanceof Window) { + return (Window)p; + } + } + return null; + } + + public static void removeComponents(Container cont) { + Component[] components = cont.getComponents(); + Component comp; + + for (int i = 0; i < components.length; i++) { + comp = components[i]; + if (comp != null) { + cont.remove(comp); + if (comp instanceof Container) + removeComponents((Container) comp); + } + } + } + public static void invalidateComponents(Container cont) { + Component[] components = cont.getComponents(); + Component comp; + + cont.invalidate(); + for (int i = 0; i < components.length; i++) { + comp = components[i]; + if (comp != null) { + if (comp instanceof Container) + invalidateComponents((Container) comp); + else + comp.invalidate(); + } + } + } +}