rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
public void setAttribute(String name, Object value) { super.setAttribute( name, value.toString() ); | public void setAttribute(String name, Object value) { if ( value == null ) { super.setAttribute( name, "" ); } else { super.setAttribute( name, value.toString() ); } | public void setAttribute(String name, Object value) { super.setAttribute( name, value.toString() ); } |
context.getVariable("usedDefaultNamespace").equals("tru")); | context.getVariable("usedDefaultNamespace").equals("true")); | public void testParserCache2() throws Exception { // no default namespace setUp("nsFilterTest.jelly"); Script script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have no var when default namspace is not set", context.getVariable("usedDefaultNamespace") == null); // now we have a default namespace, so we // should see a variable, despite the XMLParser cache jelly.setDefaultNamespaceURI("jelly:core"); script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have var when default namspace is set", context.getVariable("usedDefaultNamespace").equals("tru")); } |
void prepareHapsInput(File infile) throws IOException, HaploViewException{ | public Vector prepareHapsInput(File infile) throws IOException, HaploViewException, PedFileException { | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
String currentLine; | isHaps = true; | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
byte[] genos = new byte[0]; String ped, indiv; | Vector hapsFileStrings = new Vector(); BufferedReader reader = new BufferedReader(new FileReader(infile)); | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; if (currentLine.length() == 0){ | String line; while((line = reader.readLine())!=null){ if (line.length() == 0){ | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
even = !even; StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); | if (line.startsWith("#")){ continue; | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
|
return result; | void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; } |
|
invokeBody(output); | JellyContext newContext = new JellyContext( context ); getBody().run(newContext, output); | public void doTag(final XMLOutput output) throws Exception { String name = getName(); if ( name == null ) { name = toString(); } // #### we need to redirect the output to a TestListener // or something? TestCase testCase = new TestCase(name) { protected void runTest() throws Throwable { invokeBody(output); } }; // lets find the test suite TestSuite suite = getSuite(); if ( suite == null ) { throw new JellyException( "Could not find a TestSuite to add this test to. This tag should be inside a <test:suite> tag" ); } suite.addTest(testCase); } |
invokeBody(output); | JellyContext newContext = new JellyContext( context ); getBody().run(newContext, output); | protected void runTest() throws Throwable { invokeBody(output); } |
rootFolder.addPhotoCollectionChangeListener( this ); | public void setRoot( PhotoFolder root ) { rootFolder = root; log.warn( "New root " + root.getName() + " - subfolderCount: " + getChildCount( root ) ); } |
|
textData = new HaploData(0); | textData = new HaploData(); | private void processFile(String fileName, int fileType, String infoFileName){ try { int outputType; long maxDistance; HaploData textData; File OutputFile; File inputFile; if(!arg_quiet && fileName != null){ System.out.println("Using data file " + fileName); } inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; outputType = this.arg_output; textData = new HaploData(0); Vector result = null; if(fileType == HAPS){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == PED) { //read in ped file /* if(this.arg_ignoreMarkers.size()>0) { for(int i=0;i<this.arg_ignoreMarkers.size();i++){ int index = Integer.parseInt((String)this.arg_ignoreMarkers.get(i)); if(index>0 && index<markerResultArray.length){ markerResultArray[index] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (index)); } } } }*/ result = textData.linkageToChrom(inputFile, 3, arg_skipCheck); }else{ //read in hapmapfile result = textData.linkageToChrom(inputFile,4,arg_skipCheck); } File infoFile; if(infoFileName.equals("")) { infoFile = null; }else{ infoFile = new File(infoFileName); } if (result != null){ textData.prepareMarkerInput(infoFile,maxDistance,textData.getPedFile().getHMInfo()); }else{ textData.prepareMarkerInput(infoFile,maxDistance,null); } if(!arg_quiet && infoFile != null){ System.out.println("Using marker file " + infoFile.getName()); } if(this.arg_showCheck && result != null) { CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(null); } if(this.arg_check && result != null){ CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(new File (fileName + ".CHECK")); } Vector cust = new Vector(); if(outputType != -1){ textData.generateDPrimeTable(); Haplotype[][] haplos; switch(outputType){ case BLOX_GABRIEL: OutputFile = new File(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = new File(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = new File(fileName + ".SPINEblocks"); break; case BLOX_CUSTOM: OutputFile = new File(fileName + ".CUSTblocks"); //read in the blocks file File blocksFile = new File(arg_blockfile); cust = textData.readBlocks(blocksFile); break; default: OutputFile = new File(fileName + ".GABRIELblocks"); break; } //this handles output type ALL int start = 0; int stop = Chromosome.getSize(); if(outputType == BLOX_ALL) { OutputFile = new File(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); }else{ textData.guessBlocks(outputType, cust); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } } if(this.arg_dprime) { OutputFile = new File(fileName + ".DPRIME"); if (textData.dpTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getSize()); } } if (this.arg_png || this.arg_smallpng){ OutputFile = new File(fileName + ".LD.PNG"); if (textData.dpTable == null){ textData.generateDPrimeTable(); textData.guessBlocks(BLOX_CUSTOM, new Vector()); } if (this.arg_trackName != null){ textData.readAnalysisTrack(new File(arg_trackName)); } DPrimeDisplay dpd = new DPrimeDisplay(textData); BufferedImage i = dpd.export(0,Chromosome.getSize(),this.arg_smallpng); try{ Jimi.putImage("image/png", i, OutputFile.getName()); }catch(JimiException je){ System.out.println(je.getMessage()); } } //if(fileType){ //TDT.calcTrioTDT(textData.chromosomes); //TODO: Deal with this. why do we calc TDT? and make sure not to do it except when appropriate //} } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } } |
new TextMethods().saveDprimeToText(theData.getFilteredTable(theData.dPrimeTable), fc.getSelectedFile(), infoKnown, new Vector()); | theData.saveDprimeToText(theData.getFilteredTable(theData.dPrimeTable), fc.getSelectedFile(), infoKnown, new Vector()); | void saveDprimeToText(){ fc.setSelectedFile(null); try{ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { new TextMethods().saveDprimeToText(theData.getFilteredTable(theData.dPrimeTable), fc.getSelectedFile(), infoKnown, new Vector()); } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } |
ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; | public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; } |
|
try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); | if (hasNext()) { actual++; amount--; mHasNext = false; | public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; } |
fc = new JFileChooser(System.getProperty("user.dir")); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); viewMenuItems[i].setEnabled(false); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); clearBlocksItem = new JMenuItem(CLEAR_BLOCKS); setAccelerator(clearBlocksItem, 'C', false); clearBlocksItem.addActionListener(this); clearBlocksItem.setEnabled(false); analysisMenu.add(clearBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); addComponentListener(new ResizeListener()); } |
|
double max() default Double.MAX_VALUE; | double max() default Double.POSITIVE_INFINITY; | double max() default Double.MAX_VALUE; |
double min() default Double.MIN_VALUE; | double min() default Double.NEGATIVE_INFINITY; | double min() default Double.MIN_VALUE; |
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { | public static void initODMG( String user, String passwd, PVDatabase dbDesc ) throws PhotovaultException { | public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); } |
} | } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } | public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); } |
} catch ( Throwable t ) { | } catch ( Exception t ) { | public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); } |
log.error( "Error closing database" ); } | log.error( "Error closing database" ); } throw new PhotovaultException( "Unknown error while starting database:\n" + t.getMessage(), t ); | public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); } |
return ( success ); | public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); } |
|
return endDate; | return endDate != null ? (java.util.Date) endDate.clone() : null; | public java.util.Date getEndDate() { return endDate; } |
return startDate; | return startDate != null ? (java.util.Date)startDate.clone() : null; | public java.util.Date getStartDate() { return startDate; } |
endDate = date; | endDate = (date != null) ? (java.util.Date) date.clone() : null; | public void setEndDate( java.util.Date date ) { endDate = date; modified(); } |
startDate = date; | startDate = (date != null) ? (java.util.Date)date.clone() : null; | public void setStartDate( java.util.Date date ) { startDate = date; modified(); } |
Dimension size = dPrimeDisplay.getSize(); | dPrimeDisplay.computePreferredSize(); | public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } } |
Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } | ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); | public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } } |
dPrimeDisplay.computePreferredSize(); | void readAnalysisFile(File inFile){ try{ theData.readAnalysisTrack(inFile); }catch (HaploViewException hve){ JOptionPane.showMessageDialog(this, hve.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (IOException ioe){ JOptionPane.showMessageDialog(this, ioe.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } if (dPrimeDisplay != null && tabs.getSelectedIndex() == VIEW_D_NUM){ dPrimeDisplay.repaint(); } } |
|
if (dPrimeDisplay != null){ dPrimeDisplay.computePreferredSize(); } | void readMarkers(File inputFile, String[][] hminfo){ try { theData.prepareMarkerInput(inputFile, maxCompDist, hminfo); if (theData.infoKnown){ analysisItem.setEnabled(true); }else{ analysisItem.setEnabled(false); } if (checkPanel != null){ //this is triggered when loading markers after already loading genotypes //it is dumb and sucks, but at least it works. bah. checkPanel = new CheckDataPanel(theData, true); Container checkTab = (Container)tabs.getComponentAt(VIEW_CHECK_NUM); checkTab.removeAll(); JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); checkTab.add(metaCheckPanel); repaint(); } if (tdtPanel != null){ tdtPanel.refreshNames(); } }catch (HaploViewException e){ JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (PedFileException pfe){ } } |
|
if(fullProbMap == null || superdata == null || realAffectedStatus == null) { | if(fullProbMap == null || superdata == null || realAffectedStatus == null || realKidAffectedStatus == null) { | public void doAssociationTests(Vector affStatus, Vector permuteInd, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.add(new Boolean(false)); } } Vector caseCounts = new Vector(); Vector controlCounts = new Vector(); if (Options.getAssocTest() == ASSOC_CC){ MapWrap totalCase = new MapWrap(0); MapWrap totalControl = new MapWrap(0); for (int i = numFilteredTrios*2; i < superdata.length; i++){ MapWrap tempCase = new MapWrap(0); MapWrap tempControl = new MapWrap(0); double tempnorm=0; for (int n=0; n<superdata[i].nsuper; n++) { Long long1 = new Long(superdata[i].superposs[n].h1); Long long2 = new Long(superdata[i].superposs[n].h2); if (((Integer)affStatus.elementAt(i)).intValue() == 1){ tempControl.put(long1,tempControl.get(long1) + superdata[i].superposs[n].p); tempControl.put(long2,tempControl.get(long2) + superdata[i].superposs[n].p); }else if (((Integer)affStatus.elementAt(i)).intValue() == 2){ tempCase.put(long1,tempCase.get(long1) + superdata[i].superposs[n].p); tempCase.put(long2,tempCase.get(long2) + superdata[i].superposs[n].p); } tempnorm += superdata[i].superposs[n].p; } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempCase.get(curHap) > 0.0000 || tempControl.get(curHap) > 0.0000) { totalCase.put(curHap,totalCase.get(curHap) + (tempCase.get(curHap)/tempnorm)); totalControl.put(curHap,totalControl.get(curHap) + (tempControl.get(curHap)/tempnorm)); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { caseCounts.add(new Double(totalCase.get(sortedKeySet.get(j)))); controlCounts.add(new Double(totalControl.get(sortedKeySet.get(j)))); } } } Vector obsT = new Vector(); Vector obsU = new Vector(); if(Options.getAssocTest() == ASSOC_TRIO) { double product; MapWrap totalT = new MapWrap(0); MapWrap totalU = new MapWrap(0); discordantCounts = new Vector(); HashMap totalDiscordantCounts = new HashMap(); for (int i=0; i<numFilteredTrios*2; i+=2) { MapWrap tempT = new MapWrap(0); MapWrap tempU = new MapWrap(0); HashMap tempDiscordantCounts = new HashMap(); double tempnorm = 0; if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ boolean discordantParentPhenos = false; if(((Integer)affStatus.elementAt(i)).intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { discordantParentPhenos = true; } for (int n=0; n<superdata[i].nsuper; n++) { for (int m=0; m<superdata[i+1].nsuper; m++) { if(kidConsistentCache[i/2][n][m]) { product=superdata[i].superposs[n].p*superdata[i+1].superposs[m].p; Long h1 = new Long(superdata[i].superposs[n].h1); Long h2 = new Long(superdata[i].superposs[n].h2); Long h3 = new Long(superdata[i+1].superposs[m].h1); Long h4 = new Long(superdata[i+1].superposs[m].h2); if(((Boolean)permuteInd.get(i)).booleanValue()) { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempU.put(h1, tempU.get(h1) + product); tempT.put(h2, tempT.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempU.put(h3, tempU.get(h3) + product); tempT.put(h4, tempT.get(h4) + product); } } else { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempT.put(h1, tempT.get(h1) + product); tempU.put(h2, tempU.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempT.put(h3, tempT.get(h3) + product); tempU.put(h4, tempU.get(h4) + product); } } // normalize by all possibilities, even double hom tempnorm+=product; if(discordantParentPhenos) { Long aff1,aff2,unaff1,unaff2; if(((Integer)affStatus.elementAt(i)).intValue() == 2) { aff1 = h1; aff2 = h2; unaff1 = h3; unaff2 = h4; }else { unaff1 = h1; unaff2 = h2; aff1 = h3; aff2 = h4; } DiscordantTally dt = getTally(aff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); if(!aff2.equals(aff1)) { dt = getTally(aff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff1.equals(aff1) && !unaff1.equals(aff2)) { dt = getTally(unaff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff2.equals(aff1) && !unaff2.equals(aff2) && !unaff2.equals(unaff1)) { dt = getTally(unaff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } } } } } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempT.get(curHap) > 0.0000 || tempU.get(curHap) > 0.0000) { totalT.put(curHap, totalT.get(curHap) + tempT.get(curHap)/tempnorm); totalU.put(curHap, totalU.get(curHap) + tempU.get(curHap)/tempnorm); } } itr = tempDiscordantCounts.keySet().iterator(); while(itr.hasNext()) { Long key = (Long)itr.next(); DiscordantTally dt = (DiscordantTally) tempDiscordantCounts.get(key); dt.normalize(tempnorm); DiscordantTally totalDT = getTally(key,totalDiscordantCounts); totalDT.combine(dt); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { obsT.add(new Double(totalT.get(sortedKeySet.get(j)))); obsU.add(new Double(totalU.get(sortedKeySet.get(j)))); if(Options.getTdtType() == TDT_PAREN) { if(totalDiscordantCounts.containsKey(sortedKeySet.get(j))) { discordantCounts.add(((DiscordantTally)totalDiscordantCounts.get(sortedKeySet.get(j))).getCounts()); }else { discordantCounts.add(new double[9]); } } } } } if (Options.getAssocTest() == ASSOC_TRIO){ this.obsT = obsT; this.obsU = obsU; } else if (Options.getAssocTest() == ASSOC_CC){ this.caseCounts = caseCounts; this.controlCounts = controlCounts; } } |
if (kidAffStatus == null){ kidAffStatus = realKidAffectedStatus; } | public void doAssociationTests(Vector affStatus, Vector permuteInd, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.add(new Boolean(false)); } } Vector caseCounts = new Vector(); Vector controlCounts = new Vector(); if (Options.getAssocTest() == ASSOC_CC){ MapWrap totalCase = new MapWrap(0); MapWrap totalControl = new MapWrap(0); for (int i = numFilteredTrios*2; i < superdata.length; i++){ MapWrap tempCase = new MapWrap(0); MapWrap tempControl = new MapWrap(0); double tempnorm=0; for (int n=0; n<superdata[i].nsuper; n++) { Long long1 = new Long(superdata[i].superposs[n].h1); Long long2 = new Long(superdata[i].superposs[n].h2); if (((Integer)affStatus.elementAt(i)).intValue() == 1){ tempControl.put(long1,tempControl.get(long1) + superdata[i].superposs[n].p); tempControl.put(long2,tempControl.get(long2) + superdata[i].superposs[n].p); }else if (((Integer)affStatus.elementAt(i)).intValue() == 2){ tempCase.put(long1,tempCase.get(long1) + superdata[i].superposs[n].p); tempCase.put(long2,tempCase.get(long2) + superdata[i].superposs[n].p); } tempnorm += superdata[i].superposs[n].p; } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempCase.get(curHap) > 0.0000 || tempControl.get(curHap) > 0.0000) { totalCase.put(curHap,totalCase.get(curHap) + (tempCase.get(curHap)/tempnorm)); totalControl.put(curHap,totalControl.get(curHap) + (tempControl.get(curHap)/tempnorm)); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { caseCounts.add(new Double(totalCase.get(sortedKeySet.get(j)))); controlCounts.add(new Double(totalControl.get(sortedKeySet.get(j)))); } } } Vector obsT = new Vector(); Vector obsU = new Vector(); if(Options.getAssocTest() == ASSOC_TRIO) { double product; MapWrap totalT = new MapWrap(0); MapWrap totalU = new MapWrap(0); discordantCounts = new Vector(); HashMap totalDiscordantCounts = new HashMap(); for (int i=0; i<numFilteredTrios*2; i+=2) { MapWrap tempT = new MapWrap(0); MapWrap tempU = new MapWrap(0); HashMap tempDiscordantCounts = new HashMap(); double tempnorm = 0; if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ boolean discordantParentPhenos = false; if(((Integer)affStatus.elementAt(i)).intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { discordantParentPhenos = true; } for (int n=0; n<superdata[i].nsuper; n++) { for (int m=0; m<superdata[i+1].nsuper; m++) { if(kidConsistentCache[i/2][n][m]) { product=superdata[i].superposs[n].p*superdata[i+1].superposs[m].p; Long h1 = new Long(superdata[i].superposs[n].h1); Long h2 = new Long(superdata[i].superposs[n].h2); Long h3 = new Long(superdata[i+1].superposs[m].h1); Long h4 = new Long(superdata[i+1].superposs[m].h2); if(((Boolean)permuteInd.get(i)).booleanValue()) { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempU.put(h1, tempU.get(h1) + product); tempT.put(h2, tempT.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempU.put(h3, tempU.get(h3) + product); tempT.put(h4, tempT.get(h4) + product); } } else { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempT.put(h1, tempT.get(h1) + product); tempU.put(h2, tempU.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempT.put(h3, tempT.get(h3) + product); tempU.put(h4, tempU.get(h4) + product); } } // normalize by all possibilities, even double hom tempnorm+=product; if(discordantParentPhenos) { Long aff1,aff2,unaff1,unaff2; if(((Integer)affStatus.elementAt(i)).intValue() == 2) { aff1 = h1; aff2 = h2; unaff1 = h3; unaff2 = h4; }else { unaff1 = h1; unaff2 = h2; aff1 = h3; aff2 = h4; } DiscordantTally dt = getTally(aff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); if(!aff2.equals(aff1)) { dt = getTally(aff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff1.equals(aff1) && !unaff1.equals(aff2)) { dt = getTally(unaff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff2.equals(aff1) && !unaff2.equals(aff2) && !unaff2.equals(unaff1)) { dt = getTally(unaff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } } } } } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempT.get(curHap) > 0.0000 || tempU.get(curHap) > 0.0000) { totalT.put(curHap, totalT.get(curHap) + tempT.get(curHap)/tempnorm); totalU.put(curHap, totalU.get(curHap) + tempU.get(curHap)/tempnorm); } } itr = tempDiscordantCounts.keySet().iterator(); while(itr.hasNext()) { Long key = (Long)itr.next(); DiscordantTally dt = (DiscordantTally) tempDiscordantCounts.get(key); dt.normalize(tempnorm); DiscordantTally totalDT = getTally(key,totalDiscordantCounts); totalDT.combine(dt); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { obsT.add(new Double(totalT.get(sortedKeySet.get(j)))); obsU.add(new Double(totalU.get(sortedKeySet.get(j)))); if(Options.getTdtType() == TDT_PAREN) { if(totalDiscordantCounts.containsKey(sortedKeySet.get(j))) { discordantCounts.add(((DiscordantTally)totalDiscordantCounts.get(sortedKeySet.get(j))).getCounts()); }else { discordantCounts.add(new double[9]); } } } } } if (Options.getAssocTest() == ASSOC_TRIO){ this.obsT = obsT; this.obsU = obsU; } else if (Options.getAssocTest() == ASSOC_CC){ this.caseCounts = caseCounts; this.controlCounts = controlCounts; } } |
|
realKidAffectedStatus = kidAffStatus; | private void full_em_breakup( byte[][] input_haplos, int[] block_size, Vector affStatus, Vector kidAffStatus, boolean[] haploid) throws HaploViewException{ int num_poss, iter; double total = 0; int block, start_locus, end_locus, biggest_block_size; int num_indivs = 0; int num_blocks = block_size.length; int num_haplos = input_haplos.length; int num_loci = input_haplos[0].length; Recovery tempRec; if (num_loci > MAXLOCI){ throw new HaploViewException("Too many loci in a single block (> "+MAXLOCI+" non-redundant)"); } //figure out the size of the biggest block biggest_block_size=block_size[0]; for (int i=1; i<num_blocks; i++) { if (block_size[i] > biggest_block_size) biggest_block_size=block_size[i]; } num_poss = two_n[biggest_block_size]; data = new OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) data[i]= new OBS(); superdata = new SUPER_OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) superdata[i]= new SUPER_OBS(num_blocks); double[][] hprob = new double[num_blocks][num_poss]; int[][] hlist = new int[num_blocks][num_poss]; int[] num_hlist = new int[num_blocks]; int[] hint = new int[num_poss]; MapWrap probMap = new MapWrap(PSEUDOCOUNT); /* for trio option */ if (Options.getAssocTest() == ASSOC_TRIO) { ambighet = new int[(num_haplos/4)][num_loci]; store_dhet_status(num_haplos,num_loci,input_haplos); } end_locus=-1; //now we loop through the blocks for (block=0; block<num_blocks; block++) { start_locus=end_locus+1; end_locus=start_locus+block_size[block]-1; num_poss=two_n[block_size[block]]; //read_observations initializes the values in data[] (array of OBS) num_indivs=read_observations(num_haplos,num_loci,input_haplos,start_locus,end_locus); total=(double)num_poss; total *= PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (data[i].nposs==1) { tempRec = (Recovery)data[i].poss.elementAt(0); probMap.put(new Long(tempRec.h1), probMap.get(new Long(tempRec.h1)) + 1.0); if (!haploid[i]){ probMap.put(new Long(tempRec.h2), probMap.get(new Long(tempRec.h2)) + 1.0); total+=2.0; }else{ total+=1.0; } } } probMap.normalize(total); // EM LOOP: assign ambiguous data based on p, then re-estimate p iter=0; while (iter<20) { // compute probabilities of each possible observation for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); if(haploid[i]){ if (tempRec.h1 == tempRec.h2){ //for haploids we only consider reconstructions where both chroms are equal, //since those are the only truly possible ones (i.e. heterozygous reconstructions //are mistakes) tempRec.p = (float)(probMap.get(new Long(tempRec.h1))); }else{ tempRec.p = 0; } }else { tempRec.p = (float)(probMap.get(new Long(tempRec.h1))*probMap.get(new Long(tempRec.h2))); } total+=tempRec.p; } // normalize for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); tempRec.p /= total; } } // re-estimate prob probMap = new MapWrap(1e-10); total=num_poss*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); probMap.put(new Long(tempRec.h1),probMap.get(new Long(tempRec.h1)) + tempRec.p); if (!haploid[i]){ probMap.put(new Long(tempRec.h2),probMap.get(new Long(tempRec.h2)) + tempRec.p); total+=(2.0*(tempRec.p)); }else{ total += tempRec.p; } } } probMap.normalize(total); iter++; } int m=0; for(long j=0;j<num_poss; j++){ hint[(int)j]=-1; if (probMap.get(new Long(j)) > .001) { // printf("haplo %s p = %.4lf\n",haplo_str(j,block_size[block]),prob[j]); hlist[block][m]=(int)j; hprob[block][m]=probMap.get(new Long(j)); hint[(int)j]=m; m++; } } num_hlist[block]=m; // store current block results in super obs structure store_block_haplos(hlist, hprob, hint, block, num_indivs); } /* for each block */ double poss_full=1; for (block=0; block<num_blocks; block++) { poss_full *= num_hlist[block]; } /* LIGATE and finish this mess :) */ fullProbMap = new MapWrap(PSEUDOCOUNT); create_super_haplos(num_indivs,num_blocks,num_hlist); /* run standard EM on supercombos */ /* start prob array with probabilities from full observations */ total = poss_full * PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (superdata[i].nsuper==1) { Long h1 = new Long(superdata[i].superposs[0].h1); Long h2 = new Long(superdata[i].superposs[0].h2); fullProbMap.put(h1,fullProbMap.get(h1) +1.0); if (!haploid[i]){ fullProbMap.put(h2,fullProbMap.get(h2) +1.0); total+=2.0; }else{ total+=1.0; } } } fullProbMap.normalize(total); /* EM LOOP: assign ambiguous data based on p, then re-estimate p */ iter=0; while (iter<20) { /* compute probabilities of each possible observation */ for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<superdata[i].nsuper; k++) { if(haploid[i]){ if (superdata[i].superposs[k].h1 == superdata[i].superposs[k].h2){ //only consider reconstructions of haploid chromosomes where h1 == h2 //since heterozygous reconstructions aren't possible for haploids superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))); }else{ superdata[i].superposs[k].p = 0; } }else{ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))* fullProbMap.get(new Long(superdata[i].superposs[k].h2))); } total+=superdata[i].superposs[k].p; } /* normalize */ for (int k=0; k<superdata[i].nsuper; k++) { superdata[i].superposs[k].p /= total; } } /* re-estimate prob */ fullProbMap = new MapWrap(1e-10); total=poss_full*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<superdata[i].nsuper; k++) { fullProbMap.put(new Long(superdata[i].superposs[k].h1),fullProbMap.get(new Long(superdata[i].superposs[k].h1)) + superdata[i].superposs[k].p); if(!haploid[i]){ fullProbMap.put(new Long(superdata[i].superposs[k].h2),fullProbMap.get(new Long(superdata[i].superposs[k].h2)) + superdata[i].superposs[k].p); total+=(2.0*superdata[i].superposs[k].p); }else{ total += superdata[i].superposs[k].p; } } } fullProbMap.normalize(total); iter++; } /* we're done - the indices of superprob now have to be decoded to reveal the actual haplotypes they represent */ if(Options.getAssocTest() == ASSOC_TRIO) { kidConsistentCache = new boolean[numFilteredTrios][][]; for(int i=0;i<numFilteredTrios*2;i+=2) { if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ kidConsistentCache[i/2] = new boolean[superdata[i].nsuper][]; for (int n=0; n<superdata[i].nsuper; n++) { kidConsistentCache[i/2][n] = new boolean[superdata[i+1].nsuper]; for (int m=0; m<superdata[i+1].nsuper; m++) { kidConsistentCache[i/2][n][m] = kid_consistent(superdata[i].superposs[n].h1, superdata[i+1].superposs[m].h1,num_blocks, block_size,hlist,num_hlist,i/2,num_loci); } } } } } realAffectedStatus = affStatus; doAssociationTests(affStatus, null, kidAffStatus); Vector haplos_present = new Vector(); Vector haplo_freq= new Vector(); ArrayList keys = new ArrayList(fullProbMap.theMap.keySet()); Collections.sort(keys); Iterator kitr = keys.iterator(); while(kitr.hasNext()) { Object key = kitr.next(); long keyLong = ((Long)key).longValue(); if(fullProbMap.get(key) > .001) { haplos_present.addElement(decode_haplo_str(keyLong,num_blocks,block_size,hlist,num_hlist)); haplo_freq.addElement(new Double(fullProbMap.get(key))); } } double[] freqs = new double[haplo_freq.size()]; for(int j=0;j<haplo_freq.size();j++) { freqs[j] = ((Double)haplo_freq.elementAt(j)).doubleValue(); } this.haplotypes = (int[][])haplos_present.toArray(new int[0][0]); this.frequencies = freqs; /* if (dump_phased_haplos) { if ((fpdump=fopen("emphased.haps","w"))!=NULL) { for (i=0; i<num_indivs; i++) { best=0; for (k=0; k<superdata[i].nsuper; k++) { if (superdata[i].superposs[k].p > superdata[i].superposs[best].p) { best=k; } } h1 = superdata[i].superposs[best].h1; h2 = superdata[i].superposs[best].h2; fprintf(fpdump,"%s\n",decode_haplo_str(h1,num_blocks,block_size,hlist,num_hlist)); fprintf(fpdump,"%s\n",decode_haplo_str(h2,num_blocks,block_size,hlist,num_hlist)); } fclose(fpdump); } } */ //return 0; } |
|
getBody().run(context, output); | invokeBody( output); | public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } output.startElement(namespace, localName, name, attributes); getBody().run(context, output); output.endElement(namespace, localName, name); } |
dbField.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { if ( itemEvent.getStateChange() == ItemEvent.SELECTED ) { Object item = itemEvent.getItem(); String dbName = item.toString(); PhotovaultSettings settings = PhotovaultSettings.getSettings(); PVDatabase db = settings.getDatabase( dbName ); if ( db != null ) { setCredentialsEnabled( db.getInstanceType() == PVDatabase.TYPE_SERVER ); } } } }); dbField.setSelectedIndex( -1 ); dbField.setSelectedIndex( 0 ); | protected void createUI() { GridBagConstraints labelConstraints = new GridBagConstraints(); labelConstraints.insets = new Insets( 2, 20, 2, 2 ); labelConstraints.anchor = GridBagConstraints.EAST; labelConstraints.gridwidth = GridBagConstraints.RELATIVE; //next-to-last labelConstraints.fill = GridBagConstraints.NONE; //reset to default labelConstraints.weightx = 0.0; //reset to default GridBagConstraints fieldConstraints = new GridBagConstraints(); fieldConstraints.insets = new Insets( 2, 2, 2, 20 ); fieldConstraints.anchor = GridBagConstraints.WEST; fieldConstraints.gridwidth = GridBagConstraints.REMAINDER; //end row fieldConstraints.weightx = 1.0; JPanel loginPane = new JPanel(); GridBagLayout gb = new GridBagLayout(); loginPane.setLayout( gb ); JLabel idLabel = new JLabel( "Username" ); labelConstraints.insets = new Insets( 20, 20, 4, 4 ); gb.setConstraints( idLabel, labelConstraints ); loginPane.add( idLabel ); idField = new JTextField( 15 ); fieldConstraints.insets = new Insets( 20, 4, 4, 20 ); gb.setConstraints( idField, fieldConstraints ); loginPane.add( idField ); JLabel passLabel = new JLabel( "Password" ); labelConstraints.insets = new Insets( 4, 20, 4, 4 ); gb.setConstraints( passLabel, labelConstraints ); loginPane.add( passLabel ); passField = new JPasswordField( 15 ); fieldConstraints.insets = new Insets( 4, 4, 4, 20 ); gb.setConstraints( passField, fieldConstraints ); loginPane.add( passField ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); Collection databases = settings.getDatabases(); Vector dbNames = new Vector(); Iterator iter = databases.iterator(); while ( iter.hasNext() ) { PVDatabase db = (PVDatabase) iter.next(); dbNames.add( db.getName() ); } Object[] dbs = dbNames.toArray(); JLabel dbLabel = new JLabel( "Database" ); gb.setConstraints( dbLabel, labelConstraints ); loginPane.add( dbLabel ); dbField = new JComboBox( dbs ); gb.setConstraints( dbField, fieldConstraints ); loginPane.add( dbField ); getContentPane().add( loginPane, BorderLayout.NORTH ); JButton newDbBtn = new JButton( "New database..." ); newDbBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_NEWDB; setVisible( false ); } }); JButton okBtn = new JButton( "OK" ); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_APPROVE; setVisible( false ); } } ); JButton cancelBtn = new JButton( "Cancel" ); cancelBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_CANCEL; setVisible( false ); } } ); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add( newDbBtn ); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelBtn); getContentPane().add( buttonPane, BorderLayout.SOUTH ); getRootPane().setDefaultButton( okBtn ); pack(); // setResizable( false ); // Center the dialog on screen int w = getSize().width; int h = getSize().height; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screenSize.width-w)/2; int y = (screenSize.height-h)/2; setLocation( x, y ); } |
|
returnReason = RETURN_REASON_APPROVE; setVisible( false ); } | returnReason = RETURN_REASON_NEWDB; setVisible( false ); } | public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_APPROVE; setVisible( false ); } |
returnReason = RETURN_REASON_CANCEL; | returnReason = RETURN_REASON_APPROVE; | public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_CANCEL; setVisible( false ); } |
popup = new JPopupMenu(); JMenuItem propsItem = new JMenuItem( "Properties" ); propsItem.addActionListener( this ); propsItem.setActionCommand( FOLDER_PROPS_CMD ); JMenuItem renameItem = new JMenuItem( "Rename" ); renameItem.addActionListener( this ); renameItem.setActionCommand( FOLDER_RENAME_CMD ); JMenuItem newFolderItem = new JMenuItem( "New folder..." ); newFolderItem.addActionListener( this ); newFolderItem.setActionCommand( FOLDER_NEW_CMD ); popup.add( newFolderItem ); popup.add( renameItem ); popup.add( propsItem ); MouseListener popupListener = new PopupListener(); tree.addMouseListener( popupListener ); | private void createUI() { setLayout( new BorderLayout() ); tree = new JTree( model ); scrollPane = new JScrollPane( tree ); scrollPane.setPreferredSize( new Dimension( 200, 500 ) ); add( scrollPane, BorderLayout.CENTER ); } |
|
do{ | if(args.length == 1){ password = args[0].toCharArray(); user = userManager.verifyUsernamePassword( AuthConstants.USER_ADMIN, password); if(user == null){ invalidAttempts ++; } } while(user == null){ | public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; do{ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } }while(user == null); /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); } |
}while(user == null); | } | public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; do{ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } }while(user == null); /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); } |
rs = null; | static void addColumnsToTable(SQLTable addTo, String catalog, String schema, String tableName) throws SQLException, DuplicateColumnException, ArchitectException { Connection con = addTo.getParentDatabase().getConnection(); ResultSet rs = null; try { DatabaseMetaData dbmd = con.getMetaData(); logger.debug("SQLColumn.addColumnsToTable: catalog="+catalog+"; schema="+schema+"; tableName="+tableName); rs = dbmd.getColumns(catalog, schema, tableName, "%"); while (rs.next()) { logger.debug("addColumnsToTable SQLColumn constructor invocation."); SQLColumn col = new SQLColumn(addTo, rs.getString(4), // col name rs.getInt(5), // data type (from java.sql.Types) rs.getString(6), // native type name rs.getInt(7), // column size (precision) rs.getInt(9), // decimal size (scale) rs.getInt(11), // nullable rs.getString(12), // remarks rs.getString(13), // default value null, // primaryKeySeq false // isAutoIncrement ); // work around oracle 8i bug: when table names are long and similar, // getColumns() sometimes returns columns from multiple tables! String dbTableName = rs.getString(3); if (dbTableName != null) { if (!dbTableName.equalsIgnoreCase(tableName)) { logger.warn("Got column "+col.getName()+" from "+dbTableName +" in metadata for "+tableName+"; not adding this column."); continue; } } else { logger.warn("Table name not specified in metadata. Continuing anyway..."); } logger.debug("Adding column "+col.getColumnName()); if (addTo.getColumnByName(col.getColumnName(), false) != null) { throw new DuplicateColumnException(addTo, col.getColumnName()); } // do any database specific transformations required for this column if(TypeMap.getInstance().applyRules(col)) { logger.debug("Applied mapppings to column: " + col); } addTo.columnsFolder.children.add(col); // don't use addTo.columnsFolder.addColumn() (avoids multiple SQLObjectEvents) // XXX: need to find out if column is auto-increment } rs.close(); rs = dbmd.getPrimaryKeys(catalog, schema, tableName); while (rs.next()) { SQLColumn col = addTo.getColumnByName(rs.getString(4), false); col.primaryKeySeq = new Integer(rs.getInt(5)); addTo.setPrimaryKeyName(rs.getString(6)); } rs.close(); rs = null; } finally { if (rs != null) rs.close(); } } |
|
getVisibleRect().height/2 + infoHeight; | getVisibleRect().height/2; | public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2 + infoHeight; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } } |
if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; | if (bigClickY > chartSize.height - getVisibleRect().height){ bigClickY = chartSize.height - getVisibleRect().height; | public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2 + infoHeight; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } } |
final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; | final int WM_BD_GAP = 4; final int WM_BD_HEIGHT = 3; | public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); | double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); | public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
(int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, | (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, | public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; | double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; | public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
String phaseChoice = info[5]; | String phaseChoice; if (info[5].equals("I+II")){ phaseChoice = "II"; }else{ phaseChoice = info[5]; } | public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } } |
BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); | GZIPInputStream g = new GZIPInputStream(hmpCon.getInputStream()); BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(g)); | public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } } |
throw new IOException("Could not connect to HapMap database."); | throw new IOException("Could not connect to HapMap database: \n" + io.getMessage()); | public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } } |
tempVect.add(new Double(currentResult.getObsHet())); tempVect.add(new Double(currentResult.getPredHet())); | tempVect.add(new Double(45)); tempVect.add(new Double(45)); | public CheckDataPanel(File file) throws IOException{ //okay, for now we're going to assume the ped file has no header Vector pedFileStrings = new Vector(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine())!=null){ pedFileStrings.add(line); } pedfile = new PedFile(); pedfile.parse(pedFileStrings); //Vector result = data.check(); Vector result = pedfile.check(); int numResults = result.size(); Vector tableColumnNames = new Vector(); tableColumnNames.add("Name"); tableColumnNames.add("ObsHET"); tableColumnNames.add("PredHET"); tableColumnNames.add("HWpval"); tableColumnNames.add("%Geno"); tableColumnNames.add("FamTrio"); tableColumnNames.add("MendErr"); tableColumnNames.add("Rating"); Vector tableData = new Vector(); int[] ratingArray = new int[numResults]; for (int i = 0; i < numResults; i++){ Vector tempVect = new Vector(); MarkerResult currentResult = (MarkerResult)result.get(i); tempVect.add(currentResult.getName()); tempVect.add(new Double(currentResult.getObsHet())); tempVect.add(new Double(currentResult.getPredHet())); tempVect.add(new Double(currentResult.getHWpvalue())); tempVect.add(new Double(currentResult.getGenoPercent())); tempVect.add(new Integer(currentResult.getFamTrioNum())); tempVect.add(new Integer(currentResult.getMendErrNum())); if (currentResult.getRating() > 0){ tempVect.add(new Boolean(true)); }else{ tempVect.add(new Boolean(false)); } //this value is never displayed, just kept for bookkeeping ratingArray[i] = currentResult.getRating(); tableData.add(tempVect.clone()); } final CheckDataTableModel tableModel = new CheckDataTableModel(tableColumnNames, tableData, ratingArray); tableModel.addTableModelListener(this); table = new JTable(tableModel); final CheckDataCellRenderer renderer = new CheckDataCellRenderer(); try{ table.setDefaultRenderer(Class.forName("java.lang.Double"), renderer); table.setDefaultRenderer(Class.forName("java.lang.Integer"), renderer); }catch (Exception e){ } table.getColumnModel().getColumn(0).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); } |
StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1)); | StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); | public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1)); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } } |
try { ApplicationConfigManager.addApplication(config); } catch (ApplicationConfigManager.DuplicateApplicationNameException e) { throw new ServiceException(ErrorCodes.APPLICATION_NAME_ALREADY_EXISTS, e.getAppName()); } data.setApplicationId(appId); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Added application "+ "\""+config.getName()+"\""); return data; | return addAppBasicDetails(context, data, config); | public ApplicationConfigData addApplication(ServiceContext context, ApplicationConfigData data){ AccessController.checkAccess(context, ACLConstants.ACL_ADD_APPLICATIONS); /* do the operation */ String appId = ApplicationConfig.getNextApplicationId(); Integer port = data.getPort(); ApplicationConfig config = ApplicationConfigFactory.create(appId, data.getName(), data.getType(), data.getHost(), port, data.getURL(), data.getUsername(), data.getPassword(), data.getParamValues()); try { ApplicationConfigManager.addApplication(config); } catch (ApplicationConfigManager.DuplicateApplicationNameException e) { throw new ServiceException(ErrorCodes.APPLICATION_NAME_ALREADY_EXISTS, e.getAppName()); } data.setApplicationId(appId); /* log the operation */ UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Added application "+ "\""+config.getName()+"\""); return data; } |
dashboardConfigs.add(config); saveConfig(); | public static void addDashboard(DashboardConfig config){ assert config != null; dashboardConfigs.add(config); saveConfig(); } |
|
for(Iterator it=dashboardConfigs.iterator(); it.hasNext();){ DashboardConfig config = (DashboardConfig)it.next(); if(config.getDashboardId().equals(dashboardId)){ return config; } } | public static DashboardConfig getDashboard(String dashboardId){ for(Iterator it=dashboardConfigs.iterator(); it.hasNext();){ DashboardConfig config = (DashboardConfig)it.next(); if(config.getDashboardId().equals(dashboardId)){ return config; } } return null; } |
|
assert config != null: "application config is null"; synchronized(writeLock){ int index = dashboardConfigs.indexOf(config); assert index != -1; dashboardConfigs.remove(index); dashboardConfigs.add(index, config); saveConfig(); } | public static void updateDashboard(DashboardConfig config){ assert config != null: "application config is null"; synchronized(writeLock){ int index = dashboardConfigs.indexOf(config); assert index != -1; dashboardConfigs.remove(index); dashboardConfigs.add(index, config); saveConfig(); } } |
|
DBCS_OkAction okAction = new DBCS_OkAction(dbcsPanel, true); | public void showDbcsDialog() { final DBCSPanel dbcsPanel = new DBCSPanel(); dbcsPanel.setDbcs(db.getDataSource()); DBCS_OkAction okAction = new DBCS_OkAction(dbcsPanel, true); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dbcsPanel.discardChanges(); } }; JDialog d = ArchitectPanelBuilder.createArchitectPanelDialog( dbcsPanel, ArchitectFrame.getMainInstance(), "Target Database Connection", ArchitectPanelBuilder.OK_BUTTON_LABEL, okAction, cancelAction); okAction.setConnectionDialog(d); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); dbcsDialog = d; dbcsDialog.setVisible(true); } |
|
} | log.error("Caught exception while closing statement: " + e, e); } | public void doTag(XMLOutput output) throws Exception { try { conn = getConnection(); } catch (SQLException e) { throw new JellyException(sql + ": " + e.getMessage(), e); } /* * Use the SQL statement specified by the sql attribute, if any, * otherwise use the body as the statement. */ String sqlStatement = null; if (sql != null) { sqlStatement = sql; } else { sqlStatement = getBodyText(); } if (sqlStatement == null || sqlStatement.trim().length() == 0) { throw new JellyException(Resources.getMessage("SQL_NO_STATEMENT")); } Statement statement = null; int result = 0; try { if ( hasParameters() ) { PreparedStatement ps = conn.prepareStatement(sqlStatement); statement = ps; setParameters(ps); result = ps.executeUpdate(); } else { statement = conn.createStatement(); result = statement.executeUpdate(sqlStatement); } if (var != null) { context.setVariable(var, new Integer(result)); } } catch (SQLException e) { throw new JellyException(sqlStatement + ": " + e.getMessage(), e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } // Not much we can do } if (conn != null && !isPartOfTransaction) { try { conn.close(); } catch (SQLException e) { // Not much we can do } } clearParameters(); } } |
log.error("Caught exception while closing connection: " + e, e); | public void doTag(XMLOutput output) throws Exception { try { conn = getConnection(); } catch (SQLException e) { throw new JellyException(sql + ": " + e.getMessage(), e); } /* * Use the SQL statement specified by the sql attribute, if any, * otherwise use the body as the statement. */ String sqlStatement = null; if (sql != null) { sqlStatement = sql; } else { sqlStatement = getBodyText(); } if (sqlStatement == null || sqlStatement.trim().length() == 0) { throw new JellyException(Resources.getMessage("SQL_NO_STATEMENT")); } Statement statement = null; int result = 0; try { if ( hasParameters() ) { PreparedStatement ps = conn.prepareStatement(sqlStatement); statement = ps; setParameters(ps); result = ps.executeUpdate(); } else { statement = conn.createStatement(); result = statement.executeUpdate(sqlStatement); } if (var != null) { context.setVariable(var, new Integer(result)); } } catch (SQLException e) { throw new JellyException(sqlStatement + ": " + e.getMessage(), e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } // Not much we can do } if (conn != null && !isPartOfTransaction) { try { conn.close(); } catch (SQLException e) { // Not much we can do } } clearParameters(); } } |
|
if ( log.isDebugEnabled() ) { log.debug( "Receiving message on destination: " + destination ); } | public void doTag(XMLOutput output) throws Exception { // evaluate body as it may contain a <destination> tag invokeBody(output); Destination destination = getDestination(); if ( destination == null ) { throw new JellyException( "No destination specified. Either specify a 'destination' attribute or use a nested <jms:destination> tag" ); } Message message = null; if ( timeout > 0 ) { message = getConnection().receive( destination, timeout ); } else if ( timeout == 0 ) { message = getConnection().receiveNoWait( destination ); } else { message = getConnection().receive( destination ); } onMessage( message ); } |
|
try { final String objectNameString = request.getParameter(RequestParams.OBJECT_NAME); if(objectNameString != null){ return new ObjectName(objectNameString); }else{ return null; } } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } | return getObjectName(request); | public ObjectName getObjectName() { try { final String objectNameString = request.getParameter(RequestParams.OBJECT_NAME); if(objectNameString != null){ return new ObjectName(objectNameString); }else{ return null; } } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } } |
Utils.copyProperties(appConfigData, appForm); | CoreUtils.copyProperties(appConfigData, appForm); | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationForm appForm = (ApplicationForm)actionForm; /* create ApplicationConfigData from this form */ ApplicationConfigData appConfigData = new ApplicationConfigData(); Utils.copyProperties(appConfigData, appForm); ConfigurationService service = ServiceFactory.getConfigurationService(); service.addApplication(Utils.getServiceContext(context), appConfigData); return mapping.findForward(Forwards.SUCCESS); } |
initialHaplotypeDisplayThreshold = Options.getHaplotypeDisplayThreshold(); Vector colNames = new Vector(); colNames.add("Haplotype"); colNames.add("Freq."); if (Options.getAssocTest() == ASSOC_TRIO){ colNames.add("T:U"); }else{ colNames.add("Case, Control Ratios"); } colNames.add("Chi Squared"); colNames.add("p value"); HaplotypeAssociationNode root = new HaplotypeAssociationNode("Haplotype Associations"); String[] alleleCodes = new String[5]; alleleCodes[0] = "X"; alleleCodes[1] = "A"; alleleCodes[2] = "C"; alleleCodes[3] = "G"; alleleCodes[4] = "T"; for(int i=0;i< haps.length;i++){ Haplotype[] curBlock = haps[i]; HaplotypeAssociationNode han = new HaplotypeAssociationNode("Block " + (i+1)); double chisq; for(int j=0;j< curBlock.length; j++) { if (curBlock[j].getPercentage()*100 >= Options.getHaplotypeDisplayThreshold()){ int[] genotypes = curBlock[j].getGeno(); StringBuffer curHap = new StringBuffer(genotypes.length); for(int k=0;k<genotypes.length;k++) { curHap.append(alleleCodes[genotypes[k]]); } double[][] counts; if(Options.getAssocTest() == ASSOC_TRIO) { counts = new double[1][2]; counts[0][0] = curBlock[j].getTransCount(); counts[0][1] = curBlock[j].getUntransCount(); } else { counts = new double[2][2]; counts[0][0] = curBlock[j].getCaseFreq(); counts[1][0] = curBlock[j].getControlFreq(); double caseSum=0; double controlSum=0; for (int k=0; k < curBlock.length; k++){ if (j!=k){ caseSum += curBlock[k].getCaseFreq(); controlSum += curBlock[k].getControlFreq(); } } counts[0][1] = caseSum; counts[1][1] = controlSum; } chisq = getChiSq(counts); han.add(new HaplotypeAssociationNode(curHap.toString(),curBlock[j].getPercentage(),counts,chisq,getPValue(chisq))); } } root.add(han); } JTreeTable jtt = new JTreeTable(new HaplotypeAssociationModel(colNames, root)); jtt.getColumnModel().getColumn(0).setPreferredWidth(200); jtt.getColumnModel().getColumn(1).setPreferredWidth(50); jtt.getColumnModel().getColumn(2).setPreferredWidth(100); jtt.getColumnModel().getColumn(3).setPreferredWidth(100); jtt.getColumnModel().getColumn(4).setPreferredWidth(100); jtt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Font monoFont = new Font("Monospaced",Font.PLAIN,12); jtt.setFont(monoFont); JTree theTree = jtt.getTree(); theTree.setFont(monoFont); DefaultTreeCellRenderer r = new DefaultTreeCellRenderer(); r.setLeafIcon(null); r.setOpenIcon(null); r.setClosedIcon(null); theTree.setCellRenderer(r); jtt.setPreferredScrollableViewportSize(new Dimension(550,jtt.getPreferredScrollableViewportSize().height)); JScrollPane treeScroller = new JScrollPane(jtt); add(treeScroller); | makeTable(haps); | public HaploAssocPanel(Haplotype[][] haps){ initialHaplotypeDisplayThreshold = Options.getHaplotypeDisplayThreshold(); Vector colNames = new Vector(); colNames.add("Haplotype"); colNames.add("Freq."); if (Options.getAssocTest() == ASSOC_TRIO){ colNames.add("T:U"); }else{ colNames.add("Case, Control Ratios"); } colNames.add("Chi Squared"); colNames.add("p value"); HaplotypeAssociationNode root = new HaplotypeAssociationNode("Haplotype Associations"); String[] alleleCodes = new String[5]; alleleCodes[0] = "X"; alleleCodes[1] = "A"; alleleCodes[2] = "C"; alleleCodes[3] = "G"; alleleCodes[4] = "T"; for(int i=0;i< haps.length;i++){ Haplotype[] curBlock = haps[i]; HaplotypeAssociationNode han = new HaplotypeAssociationNode("Block " + (i+1)); double chisq; for(int j=0;j< curBlock.length; j++) { if (curBlock[j].getPercentage()*100 >= Options.getHaplotypeDisplayThreshold()){ int[] genotypes = curBlock[j].getGeno(); StringBuffer curHap = new StringBuffer(genotypes.length); for(int k=0;k<genotypes.length;k++) { curHap.append(alleleCodes[genotypes[k]]); } double[][] counts; if(Options.getAssocTest() == ASSOC_TRIO) { counts = new double[1][2]; counts[0][0] = curBlock[j].getTransCount(); counts[0][1] = curBlock[j].getUntransCount(); } else { counts = new double[2][2]; counts[0][0] = curBlock[j].getCaseFreq(); counts[1][0] = curBlock[j].getControlFreq(); double caseSum=0; double controlSum=0; for (int k=0; k < curBlock.length; k++){ if (j!=k){ caseSum += curBlock[k].getCaseFreq(); controlSum += curBlock[k].getControlFreq(); } } counts[0][1] = caseSum; counts[1][1] = controlSum; } chisq = getChiSq(counts); han.add(new HaplotypeAssociationNode(curHap.toString(),curBlock[j].getPercentage(),counts,chisq,getPValue(chisq))); } } root.add(han); } JTreeTable jtt = new JTreeTable(new HaplotypeAssociationModel(colNames, root)); jtt.getColumnModel().getColumn(0).setPreferredWidth(200); jtt.getColumnModel().getColumn(1).setPreferredWidth(50); jtt.getColumnModel().getColumn(2).setPreferredWidth(100); jtt.getColumnModel().getColumn(3).setPreferredWidth(100); jtt.getColumnModel().getColumn(4).setPreferredWidth(100); jtt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Font monoFont = new Font("Monospaced",Font.PLAIN,12); jtt.setFont(monoFont); JTree theTree = jtt.getTree(); theTree.setFont(monoFont); DefaultTreeCellRenderer r = new DefaultTreeCellRenderer(); r.setLeafIcon(null); r.setOpenIcon(null); r.setClosedIcon(null); theTree.setCellRenderer(r); jtt.setPreferredScrollableViewportSize(new Dimension(550,jtt.getPreferredScrollableViewportSize().height)); JScrollPane treeScroller = new JScrollPane(jtt); add(treeScroller); } |
if (stop >= Chromosome.getUnfilteredSize()){ stop = Chromosome.getUnfilteredSize()-1; | if (stop > Chromosome.getUnfilteredSize()){ stop = Chromosome.getUnfilteredSize(); | public BufferedImage export(int start, int stop, boolean compress) throws HaploViewException { forExport = true; exportStart = -1; if (start < 0){ start = 0; } while (true){ //if the marker we want has been filtered walk up until we find a valid one exportStart = Chromosome.filterIndex[start]; if (exportStart == -1){ start++; if (start >= Chromosome.getUnfilteredSize()){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } exportStop = -1; if (stop >= Chromosome.getUnfilteredSize()){ stop = Chromosome.getUnfilteredSize()-1; } while (true){ //if the marker we want has been filtered walk down until we find a valid one exportStop = Chromosome.filterIndex[stop-1]; if (exportStop == -1){ stop--; if (stop < 0){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } this.computePreferredSize(); int startBS = boxSize; int startBR = boxRadius; boolean startPD = printDPrimeValues; boolean startMN = printMarkerNames; int startZL = zoomLevel; if (compress){ zoomLevel = 2; printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } this.computePreferredSize(); } Dimension pref = getPreferredSize(); if(pref.width > 10000 || pref.height > 10000) { throw new HaploViewException("Image too large. Try saving as compressed PNG."); } BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; zoomLevel = startZL; printMarkerNames = startMN; printDPrimeValues = startPD; forExport = false; this.computePreferredSize(); return i; } |
ty += ttp.getHeight(); | ty += ttp.getHeight()+unrelatedSourcesGap; | private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight(); } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; } |
ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); | else { sy += unrelatedSourcesGap; } sy = Math.max(ty, sy); | private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight(); } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; } |
revalidate(); | revalidate(); repaint(); | public void fitToRect( double width, double height ) { // System.err.println( "Fitting to " + width + ", " + height ); fitSize = true; maxWidth = width; maxHeight = height; // Revalidate the geometry & image size xformImage = null; revalidate(); } |
changeToolTip(pp.getSelectedItems()); | setupAction(pp.getSelectedItems()); | public void itemDeselected(SelectionEvent e) { changeToolTip(pp.getSelectedItems()); } |
changeToolTip(pp.getSelectedItems()); | setupAction(pp.getSelectedItems()); | public void itemSelected(SelectionEvent e) { changeToolTip(pp.getSelectedItems()); } |
repaint(); | public void colorDPrime(int scheme){ currentScheme = scheme; DPrimeTable dPrime = theData.dpTable; noImage = true; if (scheme == STD_SCHEME){ // set coloring based on LOD and D' for (int i = 0; i < Chromosome.getSize()-1; i++){ for (int j = i+1; j < dPrime.getLength(i)+i; j++){ PairwiseLinkage thisPair = dPrime.getLDStats(i,j); if (thisPair == null){ continue; } double d = thisPair.getDPrime(); double l = thisPair.getLOD(); Color boxColor = null; if (l > 2) { if (d < 0.5) { //high LOD, low D' boxColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red double blgr = (255-32)*2*(1-d); boxColor = new Color(255, (int) blgr, (int) blgr); //boxColor = new Color(224, (int) blgr, (int) blgr); } } else if (d > 0.99) { //high D', low LOD blueish color boxColor = new Color(192, 192, 240); } else { //no LD boxColor = Color.white; } thisPair.setColor(boxColor); } } }else if (scheme == SFS_SCHEME){ for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ PairwiseLinkage thisPair = dPrime.getLDStats(x,y); if (thisPair == null){ continue; } //get the right bits double lowCI = thisPair.getConfidenceLow(); double highCI = thisPair.getConfidenceHigh(); //color in squares if (lowCI >= FindBlocks.cutLowCI && highCI >= FindBlocks.cutHighCI) { thisPair.setColor(Color.darkGray); //strong LD }else if (highCI >= FindBlocks.recHighCI) { thisPair.setColor(Color.lightGray); //uninformative } else { thisPair.setColor(Color.white); //recomb } } } }else if (scheme == GAM_SCHEME){ for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ PairwiseLinkage thisPair = dPrime.getLDStats(x,y); if (thisPair == null) { continue; } double[] freqs = thisPair.getFreqs(); int numGam = 0; for (int i = 0; i < freqs.length; i++){ //add a little bump for EM probs which should be zero but are really like 10^-10 if (freqs[i] > FindBlocks.fourGameteCutoff + 1E-8) numGam++; } //color in squares if(numGam > 3){ thisPair.setColor(Color.white); }else{ thisPair.setColor(Color.darkGray); } } } }else if (scheme == WMF_SCHEME){ // set coloring based on LOD and D', but without (arbitrary) cutoffs to introduce // "color damage" (Tufte) // first get the maximum LOD score so we can scale relative to that. double max_l = 0.0; for (int i = 0; i < Chromosome.getSize(); i++){ for (int j = i+1; j < i + dPrime.getLength(i); j++){ PairwiseLinkage thisPair = dPrime.getLDStats(i,j); if (thisPair == null){ continue; } if (thisPair.getLOD() > max_l) max_l = thisPair.getLOD(); } } // cap the max LOD score if (max_l > 5.0) max_l = 5.0; for (int i = 0; i < Chromosome.getSize(); i++){ for (int j = i+1; j < i + dPrime.getLength(i); j++){ PairwiseLinkage thisPair = dPrime.getLDStats(i,j); if (thisPair == null){ continue; } double d = thisPair.getDPrime(); double l = thisPair.getLOD(); Color boxColor = null; double lod_scale = l / max_l; // if greater than the cap, call it the cap if (lod_scale > 1.0) lod_scale = 1.0; // there can be negative LOD scores, apparently if (lod_scale < 0.0) lod_scale = 0.0; // also, scale the D' so anything under .2 is white. d = (1.0 / 0.8) * (d - 0.2); if (d < 0.0) d = 0.0; // if there is low(er) D' but big LOD score, this should be in a gray scale // scaled to the D' value if (lod_scale > d) { lod_scale = d; } int r, g, b; // r = (int)(200.0 * d + 55.0 * lod_scale); // g = (int)(255.0 * d - 255.0 * lod_scale); // b = (int)(255.0 * d - 255.0 * lod_scale); double ap, cp, dp, ep, jp, kp; ap = 0.0; cp = -255.0; dp = -55.0; ep = -200.0; jp = 255.0; kp = 255.0; r = (int)(ap * d + cp * lod_scale + jp); g = b = (int)(dp * d + ep * lod_scale + kp); if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; boxColor = new Color(r, g, b); thisPair.setColor(boxColor); } } }else if (scheme == RSQ_SCHEME){ // set coloring based on R-squared values for (int i = 0; i < Chromosome.getSize(); i++){ for (int j = i+1; j < i + dPrime.getLength(i); j++){ PairwiseLinkage thisPair = dPrime.getLDStats(i,j); if (thisPair == null){ continue; } double rsq = thisPair.getRSquared(); Color boxColor = null; int r, g, b; r = g = b = (int)(255.0 * (1.0 - rsq)); boxColor = new Color(r, g, b); thisPair.setColor(boxColor); } } } } |
|
project.init(); | project.getBaseDir(); | public static Project createProject() { Project project = new Project(); BuildLogger logger = new NoBannerLogger(); logger.setMessageOutputLevel( org.apache.tools.ant.Project.MSG_INFO ); logger.setOutputPrintStream( System.out ); logger.setErrorPrintStream( System.err); project.addBuildListener( logger ); project.init(); return project; } |
TaskTag tag = new TaskTag( project, taskName ); | AntTag tag = new AntTag( project, taskName ); | public TagScript createRuntimeTaskTagScript(String taskName, Attributes attributes) throws Exception { TaskTag tag = new TaskTag( project, taskName ); return TagScript.newInstance( tag ); } |
suite.addTestSuite(TestBasicRelationshipUI.class); suite.addTestSuite(TestPlayPenComponent.class); | public static Test suite() { TestSuite suite = new TestSuite("Test for Architect's Swing GUI"); //$JUnit-BEGIN$ suite.addTestSuite(TestSwingUIProject.class); suite.addTestSuite(TestArchitectFrame.class); suite.addTestSuite(TestAutoLayoutAction.class); suite.addTestSuite(TestPlayPen.class); suite.addTestSuite(TestUndoManager.class); suite.addTestSuite(TestColumnEditPanel.class); suite.addTestSuite(TestSQLObjectUndoableEventAdapter.class); suite.addTestSuite(TestFruchtermanReingoldForceLayout.class); suite.addTestSuite(TestCompareDMPanel.class); suite.addTestSuite(TestTablePane.class); suite.addTestSuite(TestDeleteSelectedAction.class); suite.addTestSuite(TestRelationship.class); suite.addTestSuite(TestTableEditPane.class); //$JUnit-END$ return suite; } |
|
if (candidate == TEXT && a.toString().startsWith(TEXT_2)) { found = true; break; } | protected void validateIndexEntry(TestDef test, Class syntheticClass) { assertEquals(test.mClassName, syntheticClass.getName()); Map<String, String[]> expectedMethods = new HashMap<String, String[]>(); if (null != test.mMethods) { for (MethodDef m : test.mMethods) { expectedMethods.put(m.mName, m.mAnnotations); } } Class iface = syntheticClass.getInterfaces()[0]; assertEquals(test.mTestMoniker, Storable.class, iface); boolean missed = false; int storableIfaceMethodCount = 0; int methodCount = 0; for (Method m : syntheticClass.getMethods()) { if (s_storableInterfaceMethods.contains(m.getName())) { storableIfaceMethodCount++; } else { Set expectedAnnotations = null; if (expectedMethods.containsKey(m.getName())) { expectedAnnotations = new HashSet(); String[] expectedAnnotationArray = expectedMethods.get(m.getName()); if (null != expectedAnnotationArray) { for (String a : expectedAnnotationArray) { expectedAnnotations.add(a); } } } else { System.out.println("missed method " + methodCount + "\nMethodDef(\"" + m.getName() + "\", null),"); missed = true; } if (expectedAnnotations != null) { assertEquals(test.mTestMoniker + ": " + m.getName(), expectedAnnotations.size(), m.getDeclaredAnnotations().length); } else { assertEquals(test.mTestMoniker + ": " + m.getName(), 0, m.getDeclaredAnnotations().length); } for (Annotation a : m.getDeclaredAnnotations()) { if (missed) { System.out.println(" " + a); } if (expectedAnnotations != null) { if (!expectedAnnotations.contains(a.toString())) { boolean found = false; for (Object candidate : expectedAnnotations.toArray()) { if (a.toString().startsWith((String) candidate)) { found = true; break; } } assertTrue(test.mTestMoniker + ':' + m.getName() + " -- unexpected annotation " + a, found); } // else we're ok } ; } } methodCount++; } assertEquals(test.mTestMoniker, s_storableInterfaceMethods.size(), storableIfaceMethodCount); assertFalse(test.mTestMoniker, missed); } |
|
File file = new File(fileName); available = file.exists(); | try { InputStream is = url.openStream(); available = (is != null); is.close(); } catch (IOException ioe) { available = false; } | public void doTag(final XMLOutput output) throws Exception { boolean available = false; if (file != null) { available = file.exists(); } else if (uri != null) { URL url = context.getResource(uri); String fileName = url.getFile(); File file = new File(fileName); available = file.exists(); } if (available) { invokeBody(output); } } |
public void addColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException; | public void addColumn(SQLColumn c); | public void addColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException; |
public abstract void addPrimaryKey(SQLTable t, String primaryKeyName) throws ArchitectException; | public abstract void addPrimaryKey(SQLTable t) throws ArchitectException; | public abstract void addPrimaryKey(SQLTable t, String primaryKeyName) throws ArchitectException; |
public void addRelationship(SQLRelationship r) throws ArchitectDiffException; | public void addRelationship(SQLRelationship r); | public void addRelationship(SQLRelationship r) throws ArchitectDiffException; |
public void dropColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException; | public void dropColumn(SQLColumn c); | public void dropColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException; |
public abstract void dropPrimaryKey(SQLTable t, String primaryKeyName); | public abstract void dropPrimaryKey(SQLTable t); | public abstract void dropPrimaryKey(SQLTable t, String primaryKeyName); |
public abstract List generateDDLStatements(SQLDatabase source) | public abstract List<DDLStatement> generateDDLStatements(SQLDatabase source) | public abstract List generateDDLStatements(SQLDatabase source) throws SQLException, ArchitectException; |
public abstract String makeDropForeignKeySQL(String fkCatalog, String fkSchema, String fkTable, String fkName); | public abstract String makeDropForeignKeySQL(String fkTable, String fkName); | public abstract String makeDropForeignKeySQL(String fkCatalog, String fkSchema, String fkTable, String fkName); |
public abstract String makeDropTableSQL(String catalog, String schema, String table); | public abstract String makeDropTableSQL(String table); | public abstract String makeDropTableSQL(String catalog, String schema, String table); |
public void modifyColumn(SQLColumn c) throws ArchitectDiffException ; | public void modifyColumn(SQLColumn c); | public void modifyColumn(SQLColumn c) throws ArchitectDiffException ; |
user.getStatus() != null ? user.getStatus() : "A"); | user.getStatus() != null ? user.getStatus() : User.STATUS_ACTIVE); | private void saveUser(){ try { Document doc = new Document(); Element rootElement = new Element(AuthConstants.JM_USERS); for(Iterator it=users.values().iterator(); it.hasNext();){ User user = (User)it.next(); /* create a user element */ Element userElement = new Element(AuthConstants.USER); userElement.setAttribute(AuthConstants.NAME, user.getUsername()); userElement.setAttribute(AuthConstants.PASSWORD, user.getPassword()); userElement.setAttribute(AuthConstants.STATUS, user.getStatus() != null ? user.getStatus() : "A"); userElement.setAttribute(AuthConstants.LOCK_COUNT, String.valueOf(user.getStatus() != null ? user.getLockCount() : 0)); /* add roles */ for(Iterator iterator = user.getRoles().iterator(); iterator.hasNext();){ Role role = (Role)iterator.next(); Element roleElement = new Element(AuthConstants.ROLE); roleElement.setText(role.getName()); userElement.addContent(roleElement); } rootElement.addContent(userElement); } doc.setRootElement(rootElement); /* write to the disc */ XMLOutputter writer = new XMLOutputter(); writer.output(doc, new FileOutputStream(AuthConstants.USER_CONFIG_FILE_NAME)); } catch (Exception e) { throw new RuntimeException(e); } } |
"A".equals(user.getStatus()) ? user : null; | User.STATUS_ACTIVE.equals(user.getStatus()) ? user : null; | public User verifyUsernamePassword(String username, char[] password){ User user = (User)users.get(username); if(user != null){ final String hashedPassword = Crypto.hash(password); user = hashedPassword.equals(user.getPassword()) && "A".equals(user.getStatus()) ? user : null; } return user; } |
superKey.put(property, new Tally(property)); | if (!superKey.containsKey(property)) { superKey.put(property, new Tally(property)); } | private Result buildResult(Filter<S> filter, OrderingList<S> ordering) throws SupportException, RepositoryException { List<IndexedQueryAnalyzer<S>.Result> subResults; if (filter == null) { subResults = Collections.singletonList(mIndexAnalyzer.analyze(filter, ordering)); } else { subResults = splitIntoSubResults(filter, ordering); } if (subResults.size() <= 1) { // Total ordering not required. return new Result(subResults); } // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < ordering.size(); pos++) { OrderedProperty<S> op = ordering.get(pos); if (op.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(op.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, op)); } ordering = ordering.replace(pos, op.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> op : ordering) { ChainedProperty<S> property = op.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults, ordering); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Keep looping until total ordering achieved. while (true) { // For each ordering score, iterate over the entire unused ordering // properties and select the next free property. If property is in // the super key increment a tally associated with property // direction. Choose the property with the best tally and augment // the orderings with it and create new sub-results. Remove the // property from the super key and the key set. If any key is now // fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); OrderingList<S> unused = score.getUnusedOrdering(); if (unused.size() > 0) { for (OrderedProperty<S> prop : unused) { ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } OrderingList<S> free = score.getFreeOrdering(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. ordering = ordering.concat(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults, ordering); } |
Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(propCount); | Set<ChainedProperty<S>> props = new LinkedHashSet<ChainedProperty<S>>(propCount); | private List<Set<ChainedProperty<S>>> getKeys() throws SupportException, RepositoryException { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } // Also fold in all unique indexes, just in case they weren't reported // as actual keys. Collection<StorableIndex<S>> indexes = mRepoAccess.storageAccessFor(getStorableType()).getAllIndexes(); for (StorableIndex<S> index : indexes) { if (!index.isUnique()) { continue; } int propCount = index.getPropertyCount(); Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(propCount); for (int i=0; i<propCount; i++) { props.add(index.getOrderedProperty(i).getChainedProperty()); } keys.add(props); } return keys; } |
Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(orderedProps.size()); | Set<ChainedProperty<S>> props = new LinkedHashSet<ChainedProperty<S>>(orderedProps.size()); | private Set<ChainedProperty<S>> stripOrdering(Set<? extends OrderedProperty<S>> orderedProps) { Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(orderedProps.size()); for (OrderedProperty<S> ordering : orderedProps) { props.add(ordering.getChainedProperty()); } return props; } |
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.CONNECTION_FAILED)); | return mapping.findForward(Forwards.CONNECTION_FAILED); | public ActionForward execute(Exception exception, ExceptionConfig exConfig, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionErrors errors = new ActionErrors(); ActionForward forward; if(exception instanceof ServiceException){ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.WEB_UI_ERROR_KEY, exception.getMessage())); }else if(exception instanceof ConnectionFailedException){ //TODO: We need not handle this condition once all the code throwing this exception gets moved to service layer. // TODO: this is not right. We have a special page for such exceptions -rk errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.CONNECTION_FAILED)); }else{ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.UNKNOWN_ERROR)); } request.setAttribute(Globals.ERROR_KEY, errors); forward = mapping.getInputForward(); forward = forward != null && forward.getPath() != null ? forward : mapping.findForward(Forwards.FAILURE); forward = forward != null ? forward : new ActionForward(Forwards.FAILURE); return forward; } |
System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); | logger.debug("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); | public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; } |
System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); | logger.debug("representation class = "+cls); logger.debug("mime type = "+flavors[i].getMimeType()); logger.debug("type = "+flavors[i].getPrimaryType()); logger.debug("subtype = "+flavors[i].getSubType()); logger.debug("class = "+flavors[i].getParameter("class")); logger.debug("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); logger.debug("isInputStream = "+flavors[i].isRepresentationClassInputStream()); logger.debug("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); logger.debug("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); | public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; } |
System.out.println("YES"); | logger.debug("YES"); | public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; } |
System.out.println("NO!"); | logger.debug("NO!"); | public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; } |
System.out.println("PlayPenDropTarget.dragOver()"); | public void dragOver(DropTargetDragEvent dtde) { System.out.println("PlayPenDropTarget.dragOver()"); dtde.acceptDrag(DnDConstants.ACTION_COPY); } |
|
JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); | PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); | public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } } |
System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); | logger.debug("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); | public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } } |
SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); | c.addTable((SQLTable) someData, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dtde.getLocation()); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.addTable(sourceTable, dtde.getLocation()); } } | public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.