From a835c726735aadf64aabbbde972bdab61c538017 Mon Sep 17 00:00:00 2001 From: Peter Midford Date: Wed, 5 Oct 2016 09:30:51 -0400 Subject: [PATCH] Java 5 updates - mostly to use generics, but also remove some deprecated stuff --- src/mesquite/pdap/Alog10TransformChar/Alog10TransformChar.java | 2 +- src/mesquite/pdap/DivideChars/DivideChars.java | 2 +- src/mesquite/pdap/ExpTransformChar/ExpTransformChar.java | 2 +- src/mesquite/pdap/InterpretPDI/InterpretPDI.java | 2 +- .../NodeValueNodeHeightCorrelation.java | 7 ------- src/mesquite/pdap/PDAPReRootingSet/PDAPReRootingSet.java | 2 -- .../pdap/RaiseStatesToPowerChar/RaiseStatesToPowerChar.java | 2 +- src/mesquite/pdap/ScatterDiagnostics/ScatterDiagnostics.java | 2 +- src/mesquite/pdap/ScatterOriDiagnostics/ScatterOriDiagnostics.java | 2 +- src/mesquite/pdap/ScatterRegDiagnostics/ScatterRegDiagnostics.java | 2 +- .../pdap/ScatterResXDiagnostics/ScatterResXDiagnostics.java | 2 +- src/mesquite/pdap/ScatterRootCIPI/ScatterRootCIPI.java | 2 +- src/mesquite/pdap/ScatterRootRegCIPI/ScatterRootRegCIPI.java | 2 +- src/mesquite/pdap/lib/PDAPRootRegStatPak.java | 5 +++-- 14 files changed, 14 insertions(+), 22 deletions(-) diff --git a/src/mesquite/pdap/Alog10TransformChar/Alog10TransformChar.java b/src/mesquite/pdap/Alog10TransformChar/Alog10TransformChar.java index 07fa741..df68ba4 100644 --- a/src/mesquite/pdap/Alog10TransformChar/Alog10TransformChar.java +++ b/src/mesquite/pdap/Alog10TransformChar/Alog10TransformChar.java @@ -1 +1 @@ -/* PDAP:PDTREE package for Mesquite copyright 2001-2010 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.Alog10TransformChar; import mesquite.lib.*; import mesquite.lib.characters.*; import mesquite.cont.lib.*; import mesquite.lib.table.*; /** ======================================================================== */ public class Alog10TransformChar extends ContDataAlterer { static final double log10 = Math.log(10.0); static final double maxExp = Math.log(Double.MAX_VALUE)/log10; /*.................................................................................................................*/ public boolean startJob(String arguments, Object condition, boolean hiredByName) { return true; } /** Called to alter data in those cells selected in table*/ public boolean alterData(CharacterData data, MesquiteTable table, UndoReference undoReference){ boolean valid=true; boolean did=false; if (!(data instanceof ContinuousData)) return false; UndoInstructions undoInstructions = null; ContinuousData cData = (ContinuousData)data; if (table==null && data !=null){ // first check for (int i=0; i= cData.getNumChars()) return false; divisorColumn--; // because these columns are zero-based. if (table==null && data !=null){ // first check for (int i=0; i= cData.getNumChars()) return false; divisorColumn--; // because these columns are zero-based. if (table==null && data !=null){ // first check for (int i=0; i 0); //return false; } /*.................................................................................................................*/ public boolean canImport() { return true; } //TODO check this code for ASCII character encoding dependency private String processName(String name){ if (name == null) return ""; if (MOTHER_OF_ROOT_NAME.equals(name)) return name; int result = 0; if (name.length()>=1){ char c = name.charAt(0); if (c>='0' && c<='9') result += 0; else if (c>='a' && c<='z') result += 1; else if (c>='A' && c<='Z') result += 2; } if (name.length()>=2){ char c = name.charAt(1); if (c>='0' && c<='9') result += 0; else if (c>='a' && c<='z') result += 3; else if (c>='A' && c<='Z') result += 6; } if (result<8) //result is a case encoding if result is 8, name is two caps, no code appended return name + indexString.charAt(result); else return name; } // Generate a two character internal node name. Unlike PDNEXUS, we don't maintain a counter // since the node already has a unique index in the tree. Otherwise it has the same (912) // node limitation. //TODO check for ASCII character coding dependency private String genName(int nodeIndex) { final int n1 = nodeIndex / 36; final int n2 = nodeIndex % 36; char ch1; char ch2; genBuffer.setLength(0); if (n1 <= 25) ch1= (char)(65+n1); else ch1= (char)(71+n1); if (n2 <= 9) ch2 = (char)(48+n2); else ch2 = (char)(55+n2); genBuffer.append(ch1); genBuffer.append(ch2); return genBuffer.toString(); } // This converts zlbs to polytomies private void cleanupZLBs(MesquiteTree tree, int nd){ if (tree.nodeIsInternal(nd)){ for (int daughter = tree.firstDaughterOfNode(nd); tree.nodeExists(daughter); daughter = tree.nextSisterOfNode(daughter)) cleanupZLBs(tree, daughter); if (tree.getRoot() != nd){ if (tree.getBranchLength(nd) == 0){ tree.collapseBranch(nd, false); } } } } /*.................................................................................................................*/ public void readFile(MesquiteProject mf, MesquiteFile file, String arguments) { if (mf == null){ alert("InterpretPDI got a null project argument", "InterpretPDI null project", "InterpretPDI null project" ); return; } if (file == null){ alert("InterpretPDI got a null file argument", "InterpretPDI file project", "InterpretPDI null file"); return; } incrementMenuResetSuppression(); if (file == null) return; ProgressIndicator progIndicator = new ProgressIndicator(mf,"Importing File "+ file.getName(),file.existingLength()); progIndicator.start(); file.linkProgressIndicator(progIndicator); if (file.openReading()) { boolean abort = false; TaxaManager taxaTask = (TaxaManager)findElementManager(Taxa.class); CharactersManager charTask = (CharactersManager)findElementManager(CharacterData.class); // The number of taxa is on the first line of the file String line = file.readLine(); parser.setString(line); String token = parser.getNextToken(); final int numTaxa = MesquiteInteger.fromString(token); if (!MesquiteInteger.isCombinable(numTaxa) || numTaxa == 0) abort = true; TreeVector trees = null; MesquiteTree tree =null; CharacterData data = null; final Taxa taxa = taxaTask.makeNewTaxa(getProject().getTaxas().getUniqueName("Taxa from PDIfile"), numTaxa, false); if (taxa !=null){ // This doesn't work... //for (int i = 0; i=0) //found taxon label tree.setTaxonNumber(i, whichTaxon, false); } } } tree.setAsDefined(true); } if (!taxaOK(taxa)) { alert("The PDI file could not be read successfully. It may have been misformatted."); abort = true; } // Need to convert PDAP ZLB's into Mesquite polytomies // Discussion with TG on 7 August 2009 decided to remove this because it causes inconsistent // results in diagnostic screens (not 9, 9A) when PDAPDiagnosticScreen converts these back // into ZLBs. Maybe we should add a switch (default off) or a separate command if people // want this functionality. // Further discussion (2 October 2009) we will leave this in and add warning to the results on screens // 1-6. Note that if you want to actually check the calculations for a polytomy, you can read a PDI file, // do the calcuations in Mesquite, then save a new copy of the PDI file, which will use the same resolution of // polytomies into ZLB's as Mesquite uses internally. This new PDI should produce identical results in DOS PDTREE. cleanupZLBs(tree,tree.getRoot()); // ->polytomies finishImport(progIndicator, file, abort); MesquiteModule treeWindowCoord = getFileCoordinator().findEmployeeWithName("#BasicTreeWindowCoord"); if (treeWindowCoord!=null){ CommandRecord rec = MesquiteThread.getCurrentCommandRecord(); MesquiteThread.setCurrentCommandRecord(CommandRecord.scriptingRecord); String commands = "makeTreeWindow " + getProject().getTaxaReference(taxa) + " #BasicTreeWindowMaker; tell It; "; commands += "setTreeSource #StoredTrees; tell It; setTaxa " + getProject().getTaxaReference(taxa) + " ; setTreeBlock 1; endTell; "; commands += "getTreeDrawCoordinator #BasicTreeDrawCoordinator; tell It; suppress; setTreeDrawer #SquareTree; "; commands += "tell It; setEdgeWidth 4; getEmployee #NodeLocsStandard; tell It; branchLengthsToggle on; "; commands += " endTell; endTell; desuppress; endTell;"; commands += "getTreeWindow; tell It; setSize 500 400; setLocation 150 70; showWindow; newWindowAssistant #PDAPDiagnosticChart; tell It; setCharacterSource #StoredCharacters; "; commands += "getWindow; tell It; setSize 600 400; setLocation 300 150; endTell; showWindow; endTell; endTell;"; commands += "endTell; "; MesquiteInteger pos = new MesquiteInteger(0); Puppeteer p = new Puppeteer(this); p.execute(treeWindowCoord, commands, pos, null, false); MesquiteThread.setCurrentCommandRecord(rec); MesquiteThread.setCurrentCommandRecord(rec); } } //TODO why is this here - does something require activity in the log at this point? logln(""); // ,0,0); decrementMenuResetSuppression(); } // InterpretPDI.readFile() private boolean taxaOK(Taxa taxa){ if (taxa == null || taxa.getNumTaxa() == 0) return false; for (int i=0; i 0); //return false; } /*.................................................................................................................*/ public boolean canImport() { return true; } //TODO check this code for ASCII character encoding dependency private String processName(String name){ if (name == null) return ""; if (MOTHER_OF_ROOT_NAME.equals(name)) return name; int result = 0; if (name.length()>=1){ char c = name.charAt(0); if (c>='0' && c<='9') result += 0; else if (c>='a' && c<='z') result += 1; else if (c>='A' && c<='Z') result += 2; } if (name.length()>=2){ char c = name.charAt(1); if (c>='0' && c<='9') result += 0; else if (c>='a' && c<='z') result += 3; else if (c>='A' && c<='Z') result += 6; } if (result<8) //result is a case encoding if result is 8, name is two caps, no code appended return name + indexString.charAt(result); else return name; } // Generate a two character internal node name. Unlike PDNEXUS, we don't maintain a counter // since the node already has a unique index in the tree. Otherwise it has the same (912) // node limitation. //TODO check for ASCII character coding dependency private String genName(int nodeIndex) { final int n1 = nodeIndex / 36; final int n2 = nodeIndex % 36; char ch1; char ch2; genBuffer.setLength(0); if (n1 <= 25) ch1= (char)(65+n1); else ch1= (char)(71+n1); if (n2 <= 9) ch2 = (char)(48+n2); else ch2 = (char)(55+n2); genBuffer.append(ch1); genBuffer.append(ch2); return genBuffer.toString(); } // This converts zlbs to polytomies private void cleanupZLBs(MesquiteTree tree, int nd){ if (tree.nodeIsInternal(nd)){ for (int daughter = tree.firstDaughterOfNode(nd); tree.nodeExists(daughter); daughter = tree.nextSisterOfNode(daughter)) cleanupZLBs(tree, daughter); if (tree.getRoot() != nd){ if (tree.getBranchLength(nd) == 0){ tree.collapseBranch(nd, false); } } } } /*.................................................................................................................*/ public void readFile(MesquiteProject mf, MesquiteFile file, String arguments) { if (mf == null){ alert("InterpretPDI got a null project argument", "InterpretPDI null project", "InterpretPDI null project" ); return; } if (file == null){ alert("InterpretPDI got a null file argument", "InterpretPDI file project", "InterpretPDI null file"); return; } incrementMenuResetSuppression(); ProgressIndicator progIndicator = new ProgressIndicator(mf,"Importing File "+ file.getName(),file.existingLength()); progIndicator.start(); file.linkProgressIndicator(progIndicator); if (file.openReading()) { boolean abort = false; TaxaManager taxaTask = (TaxaManager)findElementManager(Taxa.class); CharactersManager charTask = (CharactersManager)findElementManager(CharacterData.class); // The number of taxa is on the first line of the file String line = file.readLine(); parser.setString(line); String token = parser.getNextToken(); final int numTaxa = MesquiteInteger.fromString(token); if (!MesquiteInteger.isCombinable(numTaxa) || numTaxa == 0) abort = true; TreeVector trees = null; MesquiteTree tree =null; CharacterData data = null; final Taxa taxa = taxaTask.makeNewTaxa(getProject().getTaxas().getUniqueName("Taxa from PDIfile"), numTaxa, false); if (taxa !=null){ // This doesn't work... //for (int i = 0; i=0) //found taxon label tree.setTaxonNumber(i, whichTaxon, false); } } } tree.setAsDefined(true); } if (!taxaOK(taxa)) { alert("The PDI file could not be read successfully. It may have been misformatted."); abort = true; } // Need to convert PDAP ZLB's into Mesquite polytomies // Discussion with TG on 7 August 2009 decided to remove this because it causes inconsistent // results in diagnostic screens (not 9, 9A) when PDAPDiagnosticScreen converts these back // into ZLBs. Maybe we should add a switch (default off) or a separate command if people // want this functionality. // Further discussion (2 October 2009) we will leave this in and add warning to the results on screens // 1-6. Note that if you want to actually check the calculations for a polytomy, you can read a PDI file, // do the calcuations in Mesquite, then save a new copy of the PDI file, which will use the same resolution of // polytomies into ZLB's as Mesquite uses internally. This new PDI should produce identical results in DOS PDTREE. cleanupZLBs(tree,tree.getRoot()); // ->polytomies finishImport(progIndicator, file, abort); MesquiteModule treeWindowCoord = getFileCoordinator().findEmployeeWithName("#BasicTreeWindowCoord"); if (treeWindowCoord!=null){ CommandRecord rec = MesquiteThread.getCurrentCommandRecord(); MesquiteThread.setCurrentCommandRecord(CommandRecord.scriptingRecord); String commands = "makeTreeWindow " + getProject().getTaxaReference(taxa) + " #BasicTreeWindowMaker; tell It; "; commands += "setTreeSource #StoredTrees; tell It; setTaxa " + getProject().getTaxaReference(taxa) + " ; setTreeBlock 1; endTell; "; commands += "getTreeDrawCoordinator #BasicTreeDrawCoordinator; tell It; suppress; setTreeDrawer #SquareTree; "; commands += "tell It; setEdgeWidth 4; getEmployee #NodeLocsStandard; tell It; branchLengthsToggle on; "; commands += " endTell; endTell; desuppress; endTell;"; commands += "getTreeWindow; tell It; setSize 500 400; setLocation 150 70; showWindow; newWindowAssistant #PDAPDiagnosticChart; tell It; setCharacterSource #StoredCharacters; "; commands += "getWindow; tell It; setSize 600 400; setLocation 300 150; endTell; showWindow; endTell; endTell;"; commands += "endTell; "; MesquiteInteger pos = new MesquiteInteger(0); Puppeteer p = new Puppeteer(this); p.execute(treeWindowCoord, commands, pos, null, false); MesquiteThread.setCurrentCommandRecord(rec); MesquiteThread.setCurrentCommandRecord(rec); } } //TODO why is this here - does something require activity in the log at this point? logln(""); // ,0,0); decrementMenuResetSuppression(); } // InterpretPDI.readFile() private boolean taxaOK(Taxa taxa){ if (taxa == null || taxa.getNumTaxa() == 0) return false; for (int i=0; i nameUsed = new HashSet(); /*..............................................................*/ /** * This protects the two character names of non-conflicting and first found conficting * tips. */ private void namePass1(Tree tree, int node){ if (tree.nodeIsInternal(node)){ for (int daughter = tree.firstDaughterOfNode(node); tree.nodeExists(daughter); daughter = tree.nextSisterOfNode(daughter)) namePass1(tree,daughter); } else { final String rawName = tree.getNodeLabel(node); if (rawName != null){ final String shortName = unProcessName(rawName); if (!nameUsed.contains(shortName)){ nameUsed.add(shortName); nameArray[node] = shortName; } } } } /** * This fills in names for conflicting tips and internal nodes. * @param tree the Tree to save * @param node int specifying the node in the tree that needs a name */ private void namePass2(Tree tree, int node){ if (tree.nodeIsInternal(node)){ for (int daughter = tree.firstDaughterOfNode(node); tree.nodeExists(daughter); daughter = tree.nextSisterOfNode(daughter)) namePass2(tree,daughter); } if (nameArray[node] == null){ // name not already assigned int idx = node; String newName = genName(idx); while(nameUsed.contains(newName)) newName = genName(idx++); nameUsed.add(newName); nameArray[node]=newName; } } /** * This walks through the tree and assigns each node, internal and external * a two-character identifier for the duration of this file. Doing this once * avoids collisions */ private void setNames(Tree tree, int root){ if (nameUsed == null) nameUsed = new HashSet(); else nameUsed.clear(); if (nameArray == null || nameArray.length != tree.getNumNodeSpaces()) nameArray = new String[tree.getNumNodeSpaces()]; for (int i= 0;i maxExp)) return false; else return true; else return true; //if not combinable, transformCell ignores it, so should checkCell } private void transformCell(ContinuousData data, int ic, int it, double power){ int item = 0; //TODO: other items final double state = data.getState(ic,it, item); if (MesquiteDouble.isCombinable(state)) { data.setState(ic,it, item, Math.exp(power*Math.log(state))); } } /*.................................................................................................................*/ public String getName() { return "Raise to Power"; } /*.................................................................................................................*/ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*................................................................................................................*/ public boolean isSubstantive(){ return true; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison"; } /*.................................................................................................................*/ /** returns an explanation of what the module does.*/ public String getExplanation() { return "Alters continuous data by raising values to a power." ; } } \ No newline at end of file +/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.RaiseStatesToPowerChar; /*~~ */ import mesquite.lib.*; import mesquite.lib.characters.*; import mesquite.cont.lib.*; import mesquite.lib.table.*; /** ======================================================================== */ public class RaiseStatesToPowerChar extends ContDataAlterer { static final double maxExp = Math.log(Double.MAX_VALUE); private double savedPower = 1.0; /*.................................................................................................................*/ public boolean startJob(String arguments, Object condition, boolean hiredByName) { return true; } /** Called to alter data in those cells selected in table*/ public boolean alterData(CharacterData data, MesquiteTable table, UndoReference undoReference){ boolean did=false; boolean valid=true; if (!(data instanceof ContinuousData)) return false; final double power = MesquiteDouble.queryDouble(containerOfModule(), "Raise to Power", "Raise values in matrix to power:", savedPower); if (MesquiteDouble.isCombinable(power)) savedPower = power; else return false; ContinuousData cData = (ContinuousData)data; if (table==null && data !=null){ // first check for (int i=0; i maxExp)) return false; else return true; else return true; //if not combinable, transformCell ignores it, so should checkCell } private void transformCell(ContinuousData data, int ic, int it, double power){ int item = 0; //TODO: other items final double state = data.getState(ic,it, item); if (MesquiteDouble.isCombinable(state)) { data.setState(ic,it, item, Math.exp(power*Math.log(state))); } } /*.................................................................................................................*/ public String getName() { return "Raise to Power"; } /*.................................................................................................................*/ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*................................................................................................................*/ public boolean isSubstantive(){ return true; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison"; } /*.................................................................................................................*/ /** returns an explanation of what the module does.*/ public String getExplanation() { return "Alters continuous data by raising values to a power." ; } } \ No newline at end of file diff --git a/src/mesquite/pdap/ScatterDiagnostics/ScatterDiagnostics.java b/src/mesquite/pdap/ScatterDiagnostics/ScatterDiagnostics.java index a3426c9..613d9cf 100755 --- a/src/mesquite/pdap/ScatterDiagnostics/ScatterDiagnostics.java +++ b/src/mesquite/pdap/ScatterDiagnostics/ScatterDiagnostics.java @@ -1 +1 @@ -/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterDiagnostics; import java.awt.*; import java.util.*; import mesquite.lib.*; import mesquite.lib.duties.*; /** * This module may be obsolete * @author peter * */ public class ScatterDiagnostics extends ScattergramAssistantA { final ArrayList extras = new ArrayList(); public boolean startJob(String arguments, Object condition, boolean hiredByName) { return true; } public ChartExtra createExtra(MesquiteChart chart){ ChartExtra s = new ScatterDiagnosticsExtra(this, chart); extras.add(s); return s; } public void endJob(){ for (int i=0; i0) meanX = sum/count; NumberArray yValues = chart.getYArray(); count = 0; sum = 0; for (int i = 0; i< yValues.getNumParts(); i++){ if (yValues.isCombinable(i)){ count++; sum += yValues.getDouble(i); } } if (count>0) meanY = sum/count; } return false; } /**draw on the chart*/ public void drawOnChart(Graphics g){ Charter c = chart.getCharter(); g.drawLine(c.xToPixel(0,chart), c.yToPixel(0,chart),c.xToPixel(10,chart), c.yToPixel(10,chart)); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ return "Mean value on X: "+ MesquiteDouble.toString(meanX) + "\n" + "Mean value on Y: " + MesquiteDouble.toString(meanY) ; } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file +/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterDiagnostics; import java.awt.*; import java.util.List; import java.util.ArrayList; import mesquite.lib.*; import mesquite.lib.duties.*; /** * This module may be obsolete * @author peter * */ public class ScatterDiagnostics extends ScattergramAssistantA { final List extras = new ArrayList(); public boolean startJob(String arguments, Object condition, boolean hiredByName) { return true; } public ChartExtra createExtra(MesquiteChart chart){ ChartExtra s = new ScatterDiagnosticsExtra(this, chart); extras.add(s); return s; } public void endJob(){ for (int i=0; i0) meanX = sum/count; NumberArray yValues = chart.getYArray(); count = 0; sum = 0; for (int i = 0; i< yValues.getNumParts(); i++){ if (yValues.isCombinable(i)){ count++; sum += yValues.getDouble(i); } } if (count>0) meanY = sum/count; } return false; } /**draw on the chart*/ public void drawOnChart(Graphics g){ Charter c = chart.getCharter(); g.drawLine(c.xToPixel(0,chart), c.yToPixel(0,chart),c.xToPixel(10,chart), c.yToPixel(10,chart)); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ return "Mean value on X: "+ MesquiteDouble.toString(meanX) + "\n" + "Mean value on Y: " + MesquiteDouble.toString(meanY) ; } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file diff --git a/src/mesquite/pdap/ScatterOriDiagnostics/ScatterOriDiagnostics.java b/src/mesquite/pdap/ScatterOriDiagnostics/ScatterOriDiagnostics.java index e00c8c7..edcfae3 100755 --- a/src/mesquite/pdap/ScatterOriDiagnostics/ScatterOriDiagnostics.java +++ b/src/mesquite/pdap/ScatterOriDiagnostics/ScatterOriDiagnostics.java @@ -1 +1 @@ -/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterOriDiagnostics; /*~~ */ import java.awt.*; import java.util.*; import mesquite.cont.lib.ContinuousDistribution; import mesquite.lib.*; import mesquite.pdap.lib.*; public class ScatterOriDiagnostics extends ScatterRegisterableAsst { public void getEmployeeNeeds(){ //This gets called on startup to harvest information; override this and inside, call registerEmployeeNeed EmployeeNeed e = registerEmployeeNeed(PDAP2CTStatPakSource.class, getName() + " needs a method to calculate correlations.", "The method to calculate correlations is selected initially"); EmployeeNeed e1 = registerEmployeeNeed(PDAPFileReporter.class, getName() + " needs a method to write FIC reports.", "The method to write FIC reports is selected initially"); } // Text to display explaining FIC columns static final private String FIC_COLUMN_DESCRIPTION = "FIC files contain the following columns:\n\n" + " 1. Name of Contrast as Node - Node (e.g., 'Tm - Ta')\n" + " 2. Name of Node at Base of Contrast\n" + " 3. Unstandardized Contrast for Trait 1\n" + " 4. Unstandardized Contrast for Trait 2\n" + " 5. Standard Deviation of Contrast\n" + " = square root of sum of corrected branch lengths\n" + " 6. Nodal Value for Trait 1\n" + " 7. Nodal Value for Trait 2\n" + " 8. Uncorrected Height of Base Node from Root of Tree\n" + " 9. Corrected Height of Base Node from Root of Tree\n" + " (as used in screens 5, 6, 7, 8, and 11)\n" + "10. Average Uncorrected Height of Daughter Nodes\n" + "11. Average Corrected Height of Daughter Nodes\n" + "12. Name of First Daughter Branch (Descendant-Ancestor)\n" + "13. Corrected Length of First Daughter Branch\n" + "14. Name of Second Daughter Branch (Descendant-Ancestor)\n" + "15. Corrected Length of Second Daughter Branch\n"; // String constants for module commands static final private String TOGGLESHOWLINES_CMD = "toggleShowLines"; static final private String WRITEFIC_CMD = "writeFIC"; static final private String TOGGLEFICINPANE_CMD = "toggleFICinPane"; static final private String GETCORRCOEFF_CMD = "getCorrelationCoefficient"; static final private String GETPVALUE_CMD = "getPValue"; static final private String SHOWFIC_CMD = "showFIC"; static final private String SETDFREDUCTION_CMD = "setDFReduction"; static final private String SETVERBOSEQUERYMODE_CMD = "setVerboseQueryMode"; static final private String SETIGNOREROOTTRITOMIES_CMD = "setIgnoreRootTritomies"; private final MesquiteInteger zeroPos = new MesquiteInteger(0); private ArrayList extras; private PDAP2CTStatPakSource sps; private MesquiteBoolean showLines; private PDAPFileReporter FICReportTask; private PDAPTreeWinAsstC chartModule; private MesquiteBoolean paneHasFICData; private MesquiteBoolean spaceConvertFICNames; protected PDAP2CTStatPak myStats = null; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new ArrayList(); showLines = new MesquiteBoolean(true); paneHasFICData = new MesquiteBoolean(false); spaceConvertFICNames = new MesquiteBoolean(true); addCheckMenuItem(null, "Show Regression Lines", makeCommand(TOGGLESHOWLINES_CMD, (Commandable)this), showLines); addMenuItem(null, "Generate File of Independent Contrasts (FIC)", makeCommand(WRITEFIC_CMD, (Commandable)this)); addCheckMenuItem(null, "Show data from File of Independent Contrasts in text pane", makeCommand(TOGGLEFICINPANE_CMD,(Commandable)this),paneHasFICData); addMenuItem(null,"Show columns in File of Independent Contrasts (FIC)",makeCommand(SHOWFIC_CMD,(Commandable)this)); addMenuItem(null, "Root Calculation Query Mode...", makeCommand(SETVERBOSEQUERYMODE_CMD, (Commandable)this)); addMenuItem(null, "Set Polytomy DF Reduction...", makeCommand(SETDFREDUCTION_CMD, (Commandable)this)); addMenuItem("Ignore Root Tritomies...", makeCommand(SETIGNOREROOTTRITOMIES_CMD, (Commandable)this)); sps = (PDAP2CTStatPakSource)hireNamedEmployee(PDAP2CTStatPakSource.class, "#SPOriDiagnostics"); if (sps == null) return sorry(getName() + " couldn't start because no source of correlations obtained."); FICReportTask = (PDAPFileReporter)hireNamedEmployee(PDAPFileReporter.class, "#FICReport"); if (FICReportTask == null) return sorry(getName() + " couldn't start because no FIC reporter module obtained."); return true; } /*.................................................................................................................*/ public String getLegendText(){ String s = ""; if (myStats != null){ String b = myStats.getLegendText(); if (!StringUtil.blank(b)) s += b + "\n"; } s += "Regression lines through origin: \n" + " Black is ordinary least squares (OLS) \n" + " Green is major axis (MA) \n" + " Red is reduced major axis \n"; return s; } public boolean suppliesWritableResults(){ return (sps.getStatPak() != null); } public Object getResultsHeading() { return getName(); } /*-----------------------------------------*/ /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { if (myStats == null) myStats = sps.getStatPak(); return myStats.getWritableResults(); } /*-----------------------------------------*/ public Snapshot getSnapshot(MesquiteFile file) { Snapshot temp = new Snapshot(); temp.addLine("toggleShowLines " + showLines.toOffOnString()); return temp; } /*.................................................................................................................*/ /** * Dispatches a script command * @param String commandName * @param String argments * @param CommandChecker checker */ public Object doCommand(String commandName, String arguments, CommandChecker checker) { final Class thisClass = this.getClass(); if (checker.compare(thisClass, "Sets whether or not the regression line is shown", "[on = show; off]", commandName, TOGGLESHOWLINES_CMD)) { showLines.toggleValue(parser.getFirstToken(arguments)); parametersChanged(); } else if (checker.compare(thisClass, "Generate File of Independent Contrasts (FIC)",null,commandName,WRITEFIC_CMD)) { if (chartModule!=null) { MesquiteFile FICfile = new MesquiteFile(); FICReportTask.writeReport(FICfile,chartModule.getObserved1(),chartModule.getObserved2(),chartModule.getTree(),arguments); } } else if (checker.compare(thisClass,"Sets whether or not data from File of Independent Contrasts is shown in the text pane","[on = show; off]",commandName,TOGGLEFICINPANE_CMD)) { paneHasFICData.toggleValue(parser.getFirstToken(arguments)); if (paneHasFICData.getValue()){ spaceConvertFICNames.setValue(AlertDialog.query(chartModule.containerOfModule(),"Convert Spaces?", "Convert Spaces in node names to underscores (_); useful if pasting into Excel","Convert","Leave Unchanged")); } parametersChanged(); } else if (checker.compare(thisClass, "Gets correl coef", null, commandName, GETCORRCOEFF_CMD)) { if (extras.size() == 1){ SODExtra extra = (SODExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else if (checker.compare(thisClass, "Gets p value", null, commandName, GETPVALUE_CMD)) { if (extras.size() == 1){ SODExtra extra = (SODExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else if (checker.compare(thisClass, "Show columns in File of Independent Contrasts (FIC)",null,commandName,SHOWFIC_CMD)) { AlertDialog.notice(null,"FIC Columns",FIC_COLUMN_DESCRIPTION); } else if (checker.compare(thisClass,"Sets the number of DF's reduced because of polytomies","[number of dof]", commandName, SETDFREDUCTION_CMD)) { if (myStats == null){ MesquiteMessage.warnProgrammer("ScatterOriDiagnostics statPak should not be null"); return null; } int dfReduction = MesquiteInteger.fromFirstToken(arguments, zeroPos); if (!MesquiteInteger.isCombinable(dfReduction)) chartModule.queryDFReduce(myStats, true); else chartModule.setDFReduction(dfReduction); chartModule.setDFQueryDone(true); myStats.setDFReduction(chartModule.getDFReduction()); parametersChanged(); } else if (checker.compare(thisClass,"Sets the query mode to verbose or not", "[on/off]",commandName, SETVERBOSEQUERYMODE_CMD)) { if (StringUtil.blank(arguments)) chartModule.queryVerboseQueryMode(); else chartModule.toggleVerboseQueryMode(parser.getFirstToken(arguments)); } else if (checker.compare(thisClass,"Sets whether to ignore a tritomy at the root ", "[boolean]",commandName, SETIGNOREROOTTRITOMIES_CMD)){ if (StringUtil.blank(arguments)) //not a menu command.. chartModule.queryIgnoreRootTritomies(); else{ String s = parser.getFirstToken(arguments); chartModule.setIgnoreRootTritomies("true".equalsIgnoreCase(s)); } myStats.setIgnoreRootTritomies(chartModule.getIgnoreRootTritomies()); } else return super.doCommand(commandName, arguments, checker); return null; } /*-----------------------------------------*/ public boolean canHireMoreThanOnce () { return false; } /*-----------------------------------------*/ public void setChartModule(PDAPTreeWinAsstC module){ chartModule = module; } public PDAPTreeWinAsstC getChartModule(){ return chartModule; } /** * * gets observed from the chart module; count internal nodes, ZLBs; ask about df reduce */ protected void updateStats(){ if (chartModule != null){ Tree tree = chartModule.getTree(); int root = tree.getRoot(); if (myStats == null){ myStats = sps.getStatPak(); myStats.setDFReduction(0); } //pass the tree 'context' into the statPak so it can properly handle missing data myStats.setTree(tree); myStats.setObserved1((ContinuousDistribution)chartModule.getObserved1()); myStats.setObserved2((ContinuousDistribution)chartModule.getObserved2()); myStats.countInternalNodes(tree, root); // count the internal nodes, // to set number myStats.setIgnoreRootTritomies(chartModule.getIgnoreRootTritomies()); int zlb = ((NoPolyTree)tree).countZLBs(myStats.getIgnoreRootTritomies()); // Zero-Length-Branches are what PDAP calls "polytomies"; count to if (!MesquiteThread.isScripting()){ if (!chartModule.getDFQueryDone() && ((zlb > 0) || chartModule.getVerboseQueryMode())){ chartModule.queryDFReduce(myStats, true); myStats.setDFReduction(chartModule.getDFReduction()); chartModule.setDFQueryDone(true); } } else myStats.setDFReduction(chartModule.getDFReduction()); } } /** * * @return contains summary text for diagnostics chart */ protected String getTextSummary(){ if (myStats!=null) { if (paneHasFICData.getValue()) { FICReportTask.pushConvertSpaces(spaceConvertFICNames.getValue()); String tmp = FICReportTask.reportToString(chartModule.getObserved1(), chartModule.getObserved2(), chartModule.getTree(), "\n", " " ); FICReportTask.popConvertSpaces(); return tmp + "\n\n" + myStats.flst(); } else return myStats.flst(); } else return ""; } /** * This draws the colored line segments for the three different regression models that will * be dumped below. Unlike ScatterRegDiagnostics, these should all go through the origin, so * this method starts the lines at the origin, rather than min[x], which should be positive, * (or rarely zero in real data sets) since contrasts are positivized. * @param g * @param chart */ protected void getDrawing(Graphics g, MesquiteChart chart){ if (myStats==null || !showLines.getValue()) return; final double ls = myStats.getLeastSquaresSlope(); if (!MesquiteDouble.isCombinable(ls)) return; final double min0 = myStats.getMin(0); final double max0 = myStats.getMax(0); final double rma = myStats.getReducedMajorAxis(); final double ma = myStats.getMajorAxis(); final Charter c = chart.getCharter(); final int startX = c.xToPixel(0,chart); final int startYOLS = c.yToPixel(ls*min0,chart); final int endX = c.xToPixel(max0,chart); final int endYOLS = c.yToPixel(ls*max0,chart); final int startYRMA = c.yToPixel(rma*min0,chart); final int endYRMA = c.yToPixel(rma*max0,chart); final int startYMA = c.yToPixel(ma*min0,chart); final int endYMA = c.yToPixel(ma*max0,chart); final int extraLineWidth = 1; g.setColor(Color.red); g.drawLine(startX, startYRMA,endX,endYRMA); // conditional handles drawing thicker lines if (Math.abs(endYRMA-startYRMA)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYRMA,endX+extraLineWidth,endYRMA); else g.drawLine(startX,startYRMA+extraLineWidth,endX,endYRMA+extraLineWidth); g.setColor(Color.green); g.drawLine(startX,startYMA,endX,endYMA); // conditional handles drawing thicker lines if (Math.abs(endYMA-startYMA)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYMA,endX+extraLineWidth,endYMA); else g.drawLine(startX,startYMA+extraLineWidth,endX,endYMA+extraLineWidth); // Draw the OLS line last so if it and the MA line are "almost" the same, the OLS line "wins." g.setColor(Color.black); g.drawLine(startX, startYOLS,endX,endYOLS); if (Math.abs(endYOLS-startYOLS)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); } /** * Factory method for creating and initializing ChartExtras * @parm chart * @return a new ChartExtra initialized with chart */ public ChartExtra createExtra(MesquiteChart chart){ ChartExtra s = new SODExtra(this, chart); extras.add(s); return s; } /** */ public void endJob(){ if (extras!=null){ for (int i=0; i extras; private PDAP2CTStatPakSource sps; private MesquiteBoolean showLines; private PDAPFileReporter FICReportTask; private PDAPTreeWinAsstC chartModule; private MesquiteBoolean paneHasFICData; private MesquiteBoolean spaceConvertFICNames; protected PDAP2CTStatPak myStats = null; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new ArrayList(); showLines = new MesquiteBoolean(true); paneHasFICData = new MesquiteBoolean(false); spaceConvertFICNames = new MesquiteBoolean(true); addCheckMenuItem(null, "Show Regression Lines", makeCommand(TOGGLESHOWLINES_CMD, (Commandable)this), showLines); addMenuItem(null, "Generate File of Independent Contrasts (FIC)", makeCommand(WRITEFIC_CMD, (Commandable)this)); addCheckMenuItem(null, "Show data from File of Independent Contrasts in text pane", makeCommand(TOGGLEFICINPANE_CMD,(Commandable)this),paneHasFICData); addMenuItem(null,"Show columns in File of Independent Contrasts (FIC)",makeCommand(SHOWFIC_CMD,(Commandable)this)); addMenuItem(null, "Root Calculation Query Mode...", makeCommand(SETVERBOSEQUERYMODE_CMD, (Commandable)this)); addMenuItem(null, "Set Polytomy DF Reduction...", makeCommand(SETDFREDUCTION_CMD, (Commandable)this)); addMenuItem("Ignore Root Tritomies...", makeCommand(SETIGNOREROOTTRITOMIES_CMD, (Commandable)this)); sps = (PDAP2CTStatPakSource)hireNamedEmployee(PDAP2CTStatPakSource.class, "#SPOriDiagnostics"); if (sps == null) return sorry(getName() + " couldn't start because no source of correlations obtained."); FICReportTask = (PDAPFileReporter)hireNamedEmployee(PDAPFileReporter.class, "#FICReport"); if (FICReportTask == null) return sorry(getName() + " couldn't start because no FIC reporter module obtained."); return true; } /*.................................................................................................................*/ public String getLegendText(){ String s = ""; if (myStats != null){ String b = myStats.getLegendText(); if (!StringUtil.blank(b)) s += b + "\n"; } s += "Regression lines through origin: \n" + " Black is ordinary least squares (OLS) \n" + " Green is major axis (MA) \n" + " Red is reduced major axis \n"; return s; } public boolean suppliesWritableResults(){ return (sps.getStatPak() != null); } public Object getResultsHeading() { return getName(); } /*-----------------------------------------*/ /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { if (myStats == null) myStats = sps.getStatPak(); return myStats.getWritableResults(); } /*-----------------------------------------*/ public Snapshot getSnapshot(MesquiteFile file) { Snapshot temp = new Snapshot(); temp.addLine("toggleShowLines " + showLines.toOffOnString()); return temp; } /*.................................................................................................................*/ /** * Dispatches a script command * @param String commandName * @param String argments * @param CommandChecker checker */ public Object doCommand(String commandName, String arguments, CommandChecker checker) { final Class thisClass = this.getClass(); if (checker.compare(thisClass, "Sets whether or not the regression line is shown", "[on = show; off]", commandName, TOGGLESHOWLINES_CMD)) { showLines.toggleValue(parser.getFirstToken(arguments)); parametersChanged(); } else if (checker.compare(thisClass, "Generate File of Independent Contrasts (FIC)",null,commandName,WRITEFIC_CMD)) { if (chartModule!=null) { MesquiteFile FICfile = new MesquiteFile(); FICReportTask.writeReport(FICfile,chartModule.getObserved1(),chartModule.getObserved2(),chartModule.getTree(),arguments); } } else if (checker.compare(thisClass,"Sets whether or not data from File of Independent Contrasts is shown in the text pane","[on = show; off]",commandName,TOGGLEFICINPANE_CMD)) { paneHasFICData.toggleValue(parser.getFirstToken(arguments)); if (paneHasFICData.getValue()){ spaceConvertFICNames.setValue(AlertDialog.query(chartModule.containerOfModule(),"Convert Spaces?", "Convert Spaces in node names to underscores (_); useful if pasting into Excel","Convert","Leave Unchanged")); } parametersChanged(); } else if (checker.compare(thisClass, "Gets correl coef", null, commandName, GETCORRCOEFF_CMD)) { if (extras.size() == 1){ SODExtra extra = (SODExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else if (checker.compare(thisClass, "Gets p value", null, commandName, GETPVALUE_CMD)) { if (extras.size() == 1){ SODExtra extra = (SODExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else if (checker.compare(thisClass, "Show columns in File of Independent Contrasts (FIC)",null,commandName,SHOWFIC_CMD)) { AlertDialog.notice(null,"FIC Columns",FIC_COLUMN_DESCRIPTION); } else if (checker.compare(thisClass,"Sets the number of DF's reduced because of polytomies","[number of dof]", commandName, SETDFREDUCTION_CMD)) { if (myStats == null){ MesquiteMessage.warnProgrammer("ScatterOriDiagnostics statPak should not be null"); return null; } int dfReduction = MesquiteInteger.fromFirstToken(arguments, zeroPos); if (!MesquiteInteger.isCombinable(dfReduction)) chartModule.queryDFReduce(myStats, true); else chartModule.setDFReduction(dfReduction); chartModule.setDFQueryDone(true); myStats.setDFReduction(chartModule.getDFReduction()); parametersChanged(); } else if (checker.compare(thisClass,"Sets the query mode to verbose or not", "[on/off]",commandName, SETVERBOSEQUERYMODE_CMD)) { if (StringUtil.blank(arguments)) chartModule.queryVerboseQueryMode(); else chartModule.toggleVerboseQueryMode(parser.getFirstToken(arguments)); } else if (checker.compare(thisClass,"Sets whether to ignore a tritomy at the root ", "[boolean]",commandName, SETIGNOREROOTTRITOMIES_CMD)){ if (StringUtil.blank(arguments)) //not a menu command.. chartModule.queryIgnoreRootTritomies(); else{ String s = parser.getFirstToken(arguments); chartModule.setIgnoreRootTritomies("true".equalsIgnoreCase(s)); } myStats.setIgnoreRootTritomies(chartModule.getIgnoreRootTritomies()); } else return super.doCommand(commandName, arguments, checker); return null; } /*-----------------------------------------*/ public boolean canHireMoreThanOnce () { return false; } /*-----------------------------------------*/ public void setChartModule(PDAPTreeWinAsstC module){ chartModule = module; } public PDAPTreeWinAsstC getChartModule(){ return chartModule; } /** * * gets observed from the chart module; count internal nodes, ZLBs; ask about df reduce */ protected void updateStats(){ if (chartModule != null){ Tree tree = chartModule.getTree(); int root = tree.getRoot(); if (myStats == null){ myStats = sps.getStatPak(); myStats.setDFReduction(0); } //pass the tree 'context' into the statPak so it can properly handle missing data myStats.setTree(tree); myStats.setObserved1((ContinuousDistribution)chartModule.getObserved1()); myStats.setObserved2((ContinuousDistribution)chartModule.getObserved2()); myStats.countInternalNodes(tree, root); // count the internal nodes, // to set number myStats.setIgnoreRootTritomies(chartModule.getIgnoreRootTritomies()); int zlb = ((NoPolyTree)tree).countZLBs(myStats.getIgnoreRootTritomies()); // Zero-Length-Branches are what PDAP calls "polytomies"; count to if (!MesquiteThread.isScripting()){ if (!chartModule.getDFQueryDone() && ((zlb > 0) || chartModule.getVerboseQueryMode())){ chartModule.queryDFReduce(myStats, true); myStats.setDFReduction(chartModule.getDFReduction()); chartModule.setDFQueryDone(true); } } else myStats.setDFReduction(chartModule.getDFReduction()); } } /** * * @return contains summary text for diagnostics chart */ protected String getTextSummary(){ if (myStats!=null) { if (paneHasFICData.getValue()) { FICReportTask.pushConvertSpaces(spaceConvertFICNames.getValue()); String tmp = FICReportTask.reportToString(chartModule.getObserved1(), chartModule.getObserved2(), chartModule.getTree(), "\n", " " ); FICReportTask.popConvertSpaces(); return tmp + "\n\n" + myStats.flst(); } else return myStats.flst(); } else return ""; } /** * This draws the colored line segments for the three different regression models that will * be dumped below. Unlike ScatterRegDiagnostics, these should all go through the origin, so * this method starts the lines at the origin, rather than min[x], which should be positive, * (or rarely zero in real data sets) since contrasts are positivized. * @param g * @param chart */ protected void getDrawing(Graphics g, MesquiteChart chart){ if (myStats==null || !showLines.getValue()) return; final double ls = myStats.getLeastSquaresSlope(); if (!MesquiteDouble.isCombinable(ls)) return; final double min0 = myStats.getMin(0); final double max0 = myStats.getMax(0); final double rma = myStats.getReducedMajorAxis(); final double ma = myStats.getMajorAxis(); final Charter c = chart.getCharter(); final int startX = c.xToPixel(0,chart); final int startYOLS = c.yToPixel(ls*min0,chart); final int endX = c.xToPixel(max0,chart); final int endYOLS = c.yToPixel(ls*max0,chart); final int startYRMA = c.yToPixel(rma*min0,chart); final int endYRMA = c.yToPixel(rma*max0,chart); final int startYMA = c.yToPixel(ma*min0,chart); final int endYMA = c.yToPixel(ma*max0,chart); final int extraLineWidth = 1; g.setColor(Color.red); g.drawLine(startX, startYRMA,endX,endYRMA); // conditional handles drawing thicker lines if (Math.abs(endYRMA-startYRMA)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYRMA,endX+extraLineWidth,endYRMA); else g.drawLine(startX,startYRMA+extraLineWidth,endX,endYRMA+extraLineWidth); g.setColor(Color.green); g.drawLine(startX,startYMA,endX,endYMA); // conditional handles drawing thicker lines if (Math.abs(endYMA-startYMA)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYMA,endX+extraLineWidth,endYMA); else g.drawLine(startX,startYMA+extraLineWidth,endX,endYMA+extraLineWidth); // Draw the OLS line last so if it and the MA line are "almost" the same, the OLS line "wins." g.setColor(Color.black); g.drawLine(startX, startYOLS,endX,endYOLS); if (Math.abs(endYOLS-startYOLS)>(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); } /** * Factory method for creating and initializing ChartExtras * @parm chart * @return a new ChartExtra initialized with chart */ public ChartExtra createExtra(MesquiteChart chart){ ChartExtra s = new SODExtra(this, chart); extras.add(s); return s; } /** */ public void endJob(){ if (extras!=null){ for (int i=0; i(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ return myStats.flst(); } /** @param String commandName specifies the field from the statPak to return @return double the value requested or MesquiteDouble.unassigned */ public double getValue(String commandName) { if (commandName.equals("getCorrelationCoefficient")) { return myStats.getCorrelationCoefficient(); } if (commandName.equals("getPValue")) { return myStats.getPValue(); } else return MesquiteDouble.unassigned; } protected MesquiteNumber[] getWritableResults(){ myStats = statPakSource.getStatPak(); myStats.doCalculations(chart.getXArray(), chart.getYArray(), chart); return myStats.getWritableResults(); } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file +/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterRegDiagnostics; /*~~ */ import java.util.List; import java.awt.*; import java.util.*; import mesquite.lib.*; import mesquite.pdap.lib.*; public class ScatterRegDiagnostics extends PDAPScatterAsst { public void getEmployeeNeeds(){ //This gets called on startup to harvest information; override this and inside, call registerEmployeeNeed EmployeeNeed e = registerEmployeeNeed(StatPakSource.class, getName() + " needs a method to calculate correlations.", "The method to calculate correlations is selected initially"); } private List extras; private StatPakSource sps; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new ArrayList(); sps = (StatPakSource)hireNamedEmployee(StatPakSource.class, "#SPRegDiagnostics"); if(sps == null) return false; return true; } /** @return String containing legend text */ public String getLegendText(){ return "Black line is ordinary least squares regression."; } public boolean suppliesWritableResults(){ return (sps.getStatPak() != null); } public Object getResultsHeading() { return getName(); } /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { if (extras.size() == 1){ SRDExtra extra = (SRDExtra)extras.get(0); return extra.getWritableResults(); } else return sps.getStatPak().getWritableResults(); } /** @return boolean - always false */ public boolean canHireMoreThanOnce () { return false; } /** @param String commandName @param String argments @param CommandChecker checker Dispatches a script command */ public Object doCommand(String commandName, String arguments, CommandChecker checker) { if (checker.compare(this.getClass(), "Gets correl coef", null, commandName, "getCorrelationCoefficient")) { if (extras.size() == 1 && extras.get(0) != null){ SRDExtra extra = (SRDExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else if (checker.compare(this.getClass(), "Gets p value", null, commandName, "getPValue")) { if (extras.size() == 1 && extras.get(0) != null){ SRDExtra extra = (SRDExtra)extras.get(0); return new MesquiteNumber(extra.getValue(commandName)); } } else return super.doCommand(commandName, arguments, checker); return null; } /** */ public ChartExtra createExtra(MesquiteChart chart){ ChartExtra s = new SRDExtra(this, chart, sps); extras.add(s); return s; } /** returns module name */ public String getName(){ return "Scattergram Regression Diagnostics"; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** returns module version */ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*.................................................................................................................*/ public boolean isSubstantive() { return false; } /** returns an explanation of what the module does.*/ public String getExplanation() { return "Calculates statistics and regression lines for values on a scattergram." ; } /*.................................................................................................................*/ /** cleans up extras when the job ends */ public void endJob(){ if (extras != null) { for (int i=0; i(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ return myStats.flst(); } /** @param String commandName specifies the field from the statPak to return @return double the value requested or MesquiteDouble.unassigned */ public double getValue(String commandName) { if (commandName.equals("getCorrelationCoefficient")) { return myStats.getCorrelationCoefficient(); } if (commandName.equals("getPValue")) { return myStats.getPValue(); } else return MesquiteDouble.unassigned; } protected MesquiteNumber[] getWritableResults(){ myStats = statPakSource.getStatPak(); myStats.doCalculations(chart.getXArray(), chart.getYArray(), chart); return myStats.getWritableResults(); } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file diff --git a/src/mesquite/pdap/ScatterResXDiagnostics/ScatterResXDiagnostics.java b/src/mesquite/pdap/ScatterResXDiagnostics/ScatterResXDiagnostics.java index 7adbd12..e17c7ef 100755 --- a/src/mesquite/pdap/ScatterResXDiagnostics/ScatterResXDiagnostics.java +++ b/src/mesquite/pdap/ScatterResXDiagnostics/ScatterResXDiagnostics.java @@ -1 +1 @@ -/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterResXDiagnostics; /*~~ */ import java.awt.*; import java.util.*; import mesquite.lib.*; import mesquite.pdap.lib.*; /** * This class exists to support PDAP diagnostic screen 10, which assumes the * "true" mean of the contrasts (on the X-axis) is zero, and calculates * variances and other statistics accordingly * @author Peter E. Midford * created 2001 * */ public class ScatterResXDiagnostics extends PDAPScatterAsst { private Vector extras; /** * hires the assistant and initializes the extras field @return true (always) */ public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new Vector(); return true; } /** * Returns an empty legend * @return an empty string */ public String getLegendText(){ return ""; //TODO make this legend say something } /** * * @return true if extras (which will provide results) are available */ public boolean suppliesWritableResults(){ return (extras != null); //TODO is this sufficient? } /** * this returns a title for the results * @return the name */ public Object getResultsHeading() { return getName(); } /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { if (extras != null) { SRXDExtra extra = (SRXDExtra)extras.elementAt(0); extra.doCalculations(); return extra.getWritableResults(); } else return null; } /** * This returns false, because there should only be one of these per chart * @return always false */ public boolean canHireMoreThanOnce () { return false; } /** * This shouldn't appear as an option - it is always associated with a PDAP chart * @return always false */ public boolean getUserChooseable(){ return false; } /** * Create an extra and add it to the extras list * @param chart passed to the constructor for ChartExtras */ public ChartExtra createExtra(MesquiteChart chart){ final ChartExtra s = new SRXDExtra(this, chart); extras.addElement(s); return s; } public String getName(){ return "Scattergram Diagnostics for residuals vs. contrasts"; } public String getExplanation() { return "Calculates summary statistics for a plot of contrast residuals against x-value contrasts."; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** returns module version */ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*.................................................................................................................*/ /** * Cleanup when quiting or fired (sort of a destructor method) */ public void endJob(){ if (extras != null) { for (int i=0; i max[0]) max[0] = data0.getDouble(i); if (data1.getDouble(i) > max[1]) max[1] = data1.getDouble(i); if (data0.getDouble(i) < min[0]) min[0] = data0.getDouble(i); if (data1.getDouble(i) < min[1]) min[1] = data1.getDouble(i); } } /** Dummy */ public double getPValue() { return 0.0; // no stats here (yet) } /** Calculate the mean of the y values (contrast residuals) * @param: NumberArray yData */ public void getMean(NumberArray yData, NumberArray xData){ for (int i = 0; i < yData.getSize(); i++) if (yData.isCombinable(i) && xData.isCombinable(i)) // If x is bad, so is y, so don't count it meany += yData.getDouble(i); } /** * This method calculates the variances (honoring the assumption that mean(x) = 0) * @param: NumberArray data0 * @param: NumberArray data1 */ public void getVars(NumberArray data0, NumberArray data1) { for (int i = 0; i < data0.getSize(); i++) if (data0.isCombinable(i) && data1.isCombinable(i)) { double dev0 = data0.getDouble(i); double dev1 = data1.getDouble(i)-meany; // y values have a real mean variance[0] += dev0*dev0; variance[1] += dev1*dev1; corr += dev0*dev1; } } /*............................................................*/ /** This method returns the string that is displayed on the bottom of the window * @return summary statistics string for Mesquite text pane */ public String flst() { StringBuffer results = new StringBuffer(500); results.append("Summary statistics for residuals, which assume a true mean of zero.\n\n"); results.append("Number of contrasts: " + number); results.append("\nMinimum of X,Y coordinates: " + min[0] + ", " + min[1]); results.append("\nMaximum of X,Y coordinates: " + max[0] + ", " + max[1]); results.append("\nMean of X,Y coordinates: zero, " + meany); results.append("\nVariance of X,Y coordinates: " + variance[0] + ", " + variance[1]); results.append("\nCovariance: " + cov); results.append("\nPearson Product-Moment Correlation Coefficient: " + corr + "\n"); return results.toString(); } /** * @return array of Mesquite numbers containing summary results */ public MesquiteNumber[] getWritableResults() { if (writableResults == null){ writableResults = new MesquiteNumber[10]; writableResults[0] = new MesquiteNumber(); writableResults[0].setName("Number of independent contrasts"); writableResults[0].setValue(MesquiteInteger.unassigned); writableResults[1] = new MesquiteNumber(); writableResults[1].setName("Minimum X"); writableResults[1].setValue(MesquiteInteger.unassigned); writableResults[2] = new MesquiteNumber(); writableResults[2].setName("Minimum Y"); writableResults[2].setValue(MesquiteInteger.unassigned); writableResults[3] = new MesquiteNumber(); writableResults[3].setName("Maximum X"); writableResults[3].setValue(MesquiteInteger.unassigned); writableResults[4] = new MesquiteNumber(); writableResults[4].setName("Maximum Y"); writableResults[4].setValue(MesquiteInteger.unassigned); writableResults[5] = new MesquiteNumber(); writableResults[5].setName("Mean Y"); writableResults[5].setValue(MesquiteInteger.unassigned); writableResults[6] = new MesquiteNumber(); writableResults[6].setName("Variance X"); writableResults[6].setValue(MesquiteInteger.unassigned); writableResults[7] = new MesquiteNumber(); writableResults[7].setName("Variance Y"); writableResults[7].setValue(MesquiteInteger.unassigned); writableResults[8] = new MesquiteNumber(); writableResults[8].setName("Covariance" ); writableResults[8].setValue(MesquiteInteger.unassigned); writableResults[9] = new MesquiteNumber(); writableResults[9].setName("Pearson Product-Moment Correlation Coefficient"); writableResults[9].setValue(MesquiteInteger.unassigned); } if (MesquiteDouble.isCombinable(corr)){ writableResults[0].setValue(number); writableResults[1].setValue(min[0]); writableResults[2].setValue(min[1]); writableResults[3].setValue(max[0]); writableResults[4].setValue(max[1]); writableResults[5].setValue(meany); writableResults[6].setValue(variance[0]); writableResults[7].setValue(variance[1]); writableResults[8].setValue(cov); writableResults[9].setValue(corr); } return writableResults; } /** This method returns the string for the legend window. * @return String the legend string for this window */ public String getLegendText() { StringBuffer results = new StringBuffer(100); results.append("Number of contrasts: " + number); results.append("\nPearson Product-Moment Correlation Coefficient: " + corr + "\n"); return results.toString(); } /** * draw on the chart * @param g represents window for drawing * @param chart represents scaling for chart */ public void drawOnChart(Graphics g, MesquiteChart chart){ Charter c = chart.getCharter(); int startX = c.xToPixel(min[0],chart); int startY = c.yToPixel(0,chart); int endX = c.xToPixel(max[0],chart); int endY = c.yToPixel(0,chart); g.setColor(Color.black); g.drawLine(startX, startY,endX,endY); // insert code for thicker lines here } } } \ No newline at end of file +/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterResXDiagnostics; /*~~ */ import java.awt.*; import java.util.*; import mesquite.lib.*; import mesquite.pdap.lib.*; /** * This class exists to support PDAP diagnostic screen 10, which assumes the * "true" mean of the contrasts (on the X-axis) is zero, and calculates * variances and other statistics accordingly * @author Peter E. Midford * created 2001 * */ public class ScatterResXDiagnostics extends PDAPScatterAsst { private Vector extras; /** * hires the assistant and initializes the extras field @return true (always) */ public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new Vector(); return true; } /** * Returns an empty legend * @return an empty string */ public String getLegendText(){ return ""; //TODO make this legend say something } /** * * @return true if extras (which will provide results) are available */ public boolean suppliesWritableResults(){ return (extras != null); //TODO is this sufficient? } /** * this returns a title for the results * @return the name */ public Object getResultsHeading() { return getName(); } /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { if (extras != null) { SRXDExtra extra = (SRXDExtra)extras.elementAt(0); extra.doCalculations(); return extra.getWritableResults(); } else return null; } /** * This returns false, because there should only be one of these per chart * @return always false */ public boolean canHireMoreThanOnce () { return false; } /** * This shouldn't appear as an option - it is always associated with a PDAP chart * @return always false */ public boolean getUserChooseable(){ return false; } /** * Create an extra and add it to the extras list * @param chart passed to the constructor for ChartExtras */ public ChartExtra createExtra(MesquiteChart chart){ final ChartExtra s = new SRXDExtra(this, chart); extras.addElement(s); return s; } public String getName(){ return "Scattergram Diagnostics for residuals vs. contrasts"; } public String getExplanation() { return "Calculates summary statistics for a plot of contrast residuals against x-value contrasts."; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** returns module version */ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*.................................................................................................................*/ /** * Cleanup when quiting or fired (sort of a destructor method) */ public void endJob(){ if (extras != null) { for (int i=0; i max[0]) max[0] = data0.getDouble(i); if (data1.getDouble(i) > max[1]) max[1] = data1.getDouble(i); if (data0.getDouble(i) < min[0]) min[0] = data0.getDouble(i); if (data1.getDouble(i) < min[1]) min[1] = data1.getDouble(i); } } /** Dummy */ public double getPValue() { return 0.0; // no stats here (yet) } /** Calculate the mean of the y values (contrast residuals) * @param: NumberArray yData */ public void getMean(NumberArray yData, NumberArray xData){ for (int i = 0; i < yData.getSize(); i++) if (yData.isCombinable(i) && xData.isCombinable(i)) // If x is bad, so is y, so don't count it meany += yData.getDouble(i); } /** * This method calculates the variances (honoring the assumption that mean(x) = 0) * @param: NumberArray data0 * @param: NumberArray data1 */ public void getVars(NumberArray data0, NumberArray data1) { for (int i = 0; i < data0.getSize(); i++) if (data0.isCombinable(i) && data1.isCombinable(i)) { double dev0 = data0.getDouble(i); double dev1 = data1.getDouble(i)-meany; // y values have a real mean variance[0] += dev0*dev0; variance[1] += dev1*dev1; corr += dev0*dev1; } } /*............................................................*/ /** This method returns the string that is displayed on the bottom of the window * @return summary statistics string for Mesquite text pane */ public String flst() { StringBuffer results = new StringBuffer(500); results.append("Summary statistics for residuals, which assume a true mean of zero.\n\n"); results.append("Number of contrasts: " + number); results.append("\nMinimum of X,Y coordinates: " + min[0] + ", " + min[1]); results.append("\nMaximum of X,Y coordinates: " + max[0] + ", " + max[1]); results.append("\nMean of X,Y coordinates: zero, " + meany); results.append("\nVariance of X,Y coordinates: " + variance[0] + ", " + variance[1]); results.append("\nCovariance: " + cov); results.append("\nPearson Product-Moment Correlation Coefficient: " + corr + "\n"); return results.toString(); } /** * @return array of Mesquite numbers containing summary results */ public MesquiteNumber[] getWritableResults() { if (writableResults == null){ writableResults = new MesquiteNumber[10]; writableResults[0] = new MesquiteNumber(); writableResults[0].setName("Number of independent contrasts"); writableResults[0].setValue(MesquiteInteger.unassigned); writableResults[1] = new MesquiteNumber(); writableResults[1].setName("Minimum X"); writableResults[1].setValue(MesquiteInteger.unassigned); writableResults[2] = new MesquiteNumber(); writableResults[2].setName("Minimum Y"); writableResults[2].setValue(MesquiteInteger.unassigned); writableResults[3] = new MesquiteNumber(); writableResults[3].setName("Maximum X"); writableResults[3].setValue(MesquiteInteger.unassigned); writableResults[4] = new MesquiteNumber(); writableResults[4].setName("Maximum Y"); writableResults[4].setValue(MesquiteInteger.unassigned); writableResults[5] = new MesquiteNumber(); writableResults[5].setName("Mean Y"); writableResults[5].setValue(MesquiteInteger.unassigned); writableResults[6] = new MesquiteNumber(); writableResults[6].setName("Variance X"); writableResults[6].setValue(MesquiteInteger.unassigned); writableResults[7] = new MesquiteNumber(); writableResults[7].setName("Variance Y"); writableResults[7].setValue(MesquiteInteger.unassigned); writableResults[8] = new MesquiteNumber(); writableResults[8].setName("Covariance" ); writableResults[8].setValue(MesquiteInteger.unassigned); writableResults[9] = new MesquiteNumber(); writableResults[9].setName("Pearson Product-Moment Correlation Coefficient"); writableResults[9].setValue(MesquiteInteger.unassigned); } if (MesquiteDouble.isCombinable(corr)){ writableResults[0].setValue(number); writableResults[1].setValue(min[0]); writableResults[2].setValue(min[1]); writableResults[3].setValue(max[0]); writableResults[4].setValue(max[1]); writableResults[5].setValue(meany); writableResults[6].setValue(variance[0]); writableResults[7].setValue(variance[1]); writableResults[8].setValue(cov); writableResults[9].setValue(corr); } return writableResults; } /** This method returns the string for the legend window. * @return String the legend string for this window */ public String getLegendText() { StringBuffer results = new StringBuffer(100); results.append("Number of contrasts: " + number); results.append("\nPearson Product-Moment Correlation Coefficient: " + corr + "\n"); return results.toString(); } /** * draw on the chart * @param g represents window for drawing * @param chart represents scaling for chart */ public void drawOnChart(Graphics g, MesquiteChart chart){ Charter c = chart.getCharter(); int startX = c.xToPixel(min[0],chart); int startY = c.yToPixel(0,chart); int endX = c.xToPixel(max[0],chart); int endY = c.yToPixel(0,chart); g.setColor(Color.black); g.drawLine(startX, startY,endX,endY); // insert code for thicker lines here } } } \ No newline at end of file diff --git a/src/mesquite/pdap/ScatterRootCIPI/ScatterRootCIPI.java b/src/mesquite/pdap/ScatterRootCIPI/ScatterRootCIPI.java index 09ca4d4..a10abe1 100755 --- a/src/mesquite/pdap/ScatterRootCIPI/ScatterRootCIPI.java +++ b/src/mesquite/pdap/ScatterRootCIPI/ScatterRootCIPI.java @@ -1 +1 @@ -/* PDAP:PDTREE package for Mesquite copyright 2001-2010 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterRootCIPI; /*~~ */ import java.awt.*; import java.util.*; import mesquite.lib.*; import mesquite.lib.characters.*; import mesquite.pdap.lib.*; public class ScatterRootCIPI extends ScatterRegisterableAsst { public void getEmployeeNeeds(){ //This gets called on startup to harvest information; override this and inside, call registerEmployeeNeed EmployeeNeed e = registerEmployeeNeed(RootRegressionCalculator.class, getName() + " needs a method to calculate root regressions.", "The method to calculate root regressions is selected initially"); } private Vector extras; RootRegressionCalculator rootStatTask; PDAPTreeWinAsstC chartModule; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new Vector(); rootStatTask = (RootRegressionCalculator)hireNamedEmployee(RootRegressionCalculator.class, "#RootReconstructions"); if (rootStatTask == null) return sorry(getName() + " couldn't start because no calculating module for root regression obtained."); return true; } /*-----------------------------------------*/ /** */ public String getLegendText(){ return ""; } public boolean suppliesWritableResults(){ return (rootStatTask.getStatPak() != null); } public Object getResultsHeading() { return getName(); } /** * */ public MesquiteNumber[] getWritableResults(){ return rootStatTask.getStatPak().getWritableResults(); } /*-----------------------------------------*/ /** * Avoid problems with multiple hiring * @return false */ public boolean canHireMoreThanOnce () { return false; } /*-----------------------------------------*/ /** * @param PDAPTreeWinAsstc */ public void setChartModule(PDAPTreeWinAsstC module){ chartModule = module; rootStatTask.setChartModule(module); } /*-----------------------------------------*/ /** * creates a new chart extra; also attaches the chart to * the rootStatTask which needs to draw * @param MesquiteChart * @return ChartExtra */ public ChartExtra createExtra(MesquiteChart chart){ rootStatTask.setChart(chart); ChartExtra s = new SRDExtra(this, chart); extras.addElement(s); return s; } /*-----------------------------------------*/ /** * @return false */ public boolean getUserChooseable(){ return false; } /*-----------------------------------------*/ /** @return String */ public String getName(){ return "Scattergram Root Reconstruction Confidence Intervals"; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** @return String module version */ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*-----------------------------------------*/ public void endJob(){ if (extras != null) { for (int i=0; i extras; RootRegressionCalculator rootStatTask; PDAPTreeWinAsstC chartModule; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new Vector(); rootStatTask = (RootRegressionCalculator)hireNamedEmployee(RootRegressionCalculator.class, "#RootReconstructions"); if (rootStatTask == null) return sorry(getName() + " couldn't start because no calculating module for root regression obtained."); return true; } /*-----------------------------------------*/ /** */ public String getLegendText(){ return ""; } public boolean suppliesWritableResults(){ return (rootStatTask.getStatPak() != null); } public Object getResultsHeading() { return getName(); } /** * */ public MesquiteNumber[] getWritableResults(){ return rootStatTask.getStatPak().getWritableResults(); } /*-----------------------------------------*/ /** * Avoid problems with multiple hiring * @return false */ public boolean canHireMoreThanOnce () { return false; } /*-----------------------------------------*/ /** * @param PDAPTreeWinAsstc */ public void setChartModule(PDAPTreeWinAsstC module){ chartModule = module; rootStatTask.setChartModule(module); } /*-----------------------------------------*/ /** * creates a new chart extra; also attaches the chart to * the rootStatTask which needs to draw * @param MesquiteChart * @return ChartExtra */ public ChartExtra createExtra(MesquiteChart chart){ rootStatTask.setChart(chart); ChartExtra s = new SRDExtra(this, chart); extras.addElement(s); return s; } /*-----------------------------------------*/ /** * @return false */ public boolean getUserChooseable(){ return false; } /*-----------------------------------------*/ /** @return String */ public String getName(){ return "Scattergram Root Reconstruction Confidence Intervals"; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** @return String module version */ public String getVersion() { return "1.15"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /*-----------------------------------------*/ public void endJob(){ if (extras != null) { for (int i=0; i(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); //Plot the -10..10 points and any user defined points double incr = (max0-min0)/100.0; for(int i = -10; i <= -1; i++){ double x = min0 + incr*i; double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } for(int i = 1; i <= 10; i++){ double x = max0+incr*i; double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } for (int i=0; i < rootStats.getCIPIValuesSize(); i++){ double x = rootStats.CIPIValueAt(i).getValue(); double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } } /* end of drawRegressionCiPiOnChart() */ /** Result of refactoring */ private void showLineSegment(Graphics g, int oldX, int oldYHigh, int plotX, int plotHigh, int oldYLow, int plotLow) { if (MesquiteInteger.isCombinable(oldX)) { g.drawLine(oldX,oldYHigh,plotX,plotHigh); g.drawLine(oldX,oldYLow,plotX,plotLow); } } /** Draw CI/PI line segments (despite method name) for values that don't correspond to tips */ private void showPoint(double x, double yHat, PDAPRootRegStatPak rootStats, MesquiteChart chart, Graphics g) { final double width1 = rootStats.getWidth1(); final double width2 = rootStats.getWidth2(); Charter c = chart.getCharter(); double yCWidth = rootStats.calcCI(x,0,width1); final int plotX = c.xToPixel(x,chart); final int plotLeft = plotX-1; final int plotYHat = c.yToPixel(yHat,chart); double highY = yHat + yCWidth; double lowY = yHat - yCWidth; int plotHigh = c.yToPixel(highY,chart); int plotLow = c.yToPixel(lowY,chart); g.setColor(Color.darkGray); g.drawLine(plotLeft,plotYHat,plotX,plotYHat); g.setColor(Color.red); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); double yPWidth = rootStats.calcPI(x,0,width1); highY = yHat + yPWidth; lowY = yHat - yPWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.green); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); yCWidth = rootStats.calcCI(x,0,width2); highY = yHat + yCWidth; lowY = yHat - yCWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.orange); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); yPWidth = rootStats.calcPI(x,0,width2); highY = yHat + yPWidth; lowY = yHat - yPWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.cyan); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ PDAP2CTStatPak rootStats = ((ScatterRootRegCIPI)ownerModule).rootStatTask.getStatPak(); if (rootStats != null) return rootStats.flst(); else return ""; } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file +/* PDAP:PDTREE package for Mesquite copyright 2001-2009 P. Midford & W. Maddison PDAP:PDTREE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. The web site for PDAP:PDTREE is http://mesquiteproject.org/pdap_mesquite/ This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.pdap.ScatterRootRegCIPI; /*~~ */ import java.util.*; import java.util.List; import java.awt.*; import mesquite.lib.*; import mesquite.lib.characters.*; import mesquite.pdap.RootedRegression.RootedRegression; import mesquite.pdap.lib.*; public class ScatterRootRegCIPI extends ScatterRegisterableAsst { public void getEmployeeNeeds(){ //This gets called on startup to harvest information; override this and inside, call registerEmployeeNeed EmployeeNeed e = registerEmployeeNeed(RootRegressionCalculator.class, getName() + " needs a method to calculate root regressions.", "The method to calculate root regressions is selected initially"); } private List extras; RootRegressionCalculator rootStatTask; PDAPTreeWinAsstC chartModule; public boolean startJob(String arguments, Object condition, boolean hiredByName) { extras = new ArrayList(); rootStatTask = (RootRegressionCalculator)hireNamedEmployee(RootedRegression.class, "#RootedRegression"); if (rootStatTask == null) return sorry(getName() + " couldn't start because no calculating module for root regression obtained."); return true; } /** * @return false - no obvious way to extract the CI file contents for multiple trees. */ public boolean suppliesWritableResults(){ return false; } public Object getResultsHeading() { return getName(); } /** * @return computed values with descriptive strings */ public MesquiteNumber[] getWritableResults() { return null; } /*.................................................................................................................*/ public String getLegendText(){ return ""; } /*.................................................................................................................*/ public boolean getUserChooseable(){ return false; } /*.................................................................................................................*/ public boolean canHireMoreThanOnce () { return false; } /*.................................................................................................................*/ public void setChartModule(PDAPTreeWinAsstC module){ chartModule = module; rootStatTask.setChartModule(module); } /*.................................................................................................................*/ public ChartExtra createExtra(MesquiteChart chart){ rootStatTask.setChart(chart); ChartExtra s = new SRDExtra(this, chart); extras.add(s); return s; } /*.................................................................................................................*/ public String getName(){ return "Tip Scattergram with Root Regression Confidence and Prediction Intervals"; } /*.................................................................................................................*/ public String getAuthors() { return "Peter E. Midford, Ted Garland Jr., and Wayne P. Maddison" ; } /*.................................................................................................................*/ /** returns module version */ public String getVersion() { return "1.12"; } /*.................................................................................................................*/ public boolean isPrerelease() { return false; } /** This makes sure all the extras are turned off if the job is ending */ public void endJob(){ if (extras != null) { for (int i=0; i(endX-startX)) // abs(slope) > 1 g.drawLine(startX+extraLineWidth,startYOLS,endX+extraLineWidth,endYOLS); else g.drawLine(startX,startYOLS+extraLineWidth,endX,endYOLS+extraLineWidth); //Plot the -10..10 points and any user defined points double incr = (max0-min0)/100.0; for(int i = -10; i <= -1; i++){ double x = min0 + incr*i; double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } for(int i = 1; i <= 10; i++){ double x = max0+incr*i; double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } for (int i=0; i < rootStats.getCIPIValuesSize(); i++){ double x = rootStats.CIPIValueAt(i).getValue(); double yHat = ls*x + lsy; showPoint(x,yHat,rootStats,chart,g); } } /* end of drawRegressionCiPiOnChart() */ /** Result of refactoring */ private void showLineSegment(Graphics g, int oldX, int oldYHigh, int plotX, int plotHigh, int oldYLow, int plotLow) { if (MesquiteInteger.isCombinable(oldX)) { g.drawLine(oldX,oldYHigh,plotX,plotHigh); g.drawLine(oldX,oldYLow,plotX,plotLow); } } /** Draw CI/PI line segments (despite method name) for values that don't correspond to tips */ private void showPoint(double x, double yHat, PDAPRootRegStatPak rootStats, MesquiteChart chart, Graphics g) { final double width1 = rootStats.getWidth1(); final double width2 = rootStats.getWidth2(); Charter c = chart.getCharter(); double yCWidth = rootStats.calcCI(x,0,width1); final int plotX = c.xToPixel(x,chart); final int plotLeft = plotX-1; final int plotYHat = c.yToPixel(yHat,chart); double highY = yHat + yCWidth; double lowY = yHat - yCWidth; int plotHigh = c.yToPixel(highY,chart); int plotLow = c.yToPixel(lowY,chart); g.setColor(Color.darkGray); g.drawLine(plotLeft,plotYHat,plotX,plotYHat); g.setColor(Color.red); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); double yPWidth = rootStats.calcPI(x,0,width1); highY = yHat + yPWidth; lowY = yHat - yPWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.green); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); yCWidth = rootStats.calcCI(x,0,width2); highY = yHat + yCWidth; lowY = yHat - yCWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.orange); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); yPWidth = rootStats.calcPI(x,0,width2); highY = yHat + yPWidth; lowY = yHat - yPWidth; plotHigh = c.yToPixel(highY,chart); plotLow = c.yToPixel(lowY,chart); g.setColor(Color.cyan); g.drawLine(plotLeft,plotHigh,plotX,plotHigh); g.drawLine(plotLeft,plotLow,plotX,plotLow); } /**print on the chart*/ public void printOnChart(Graphics g){ drawOnChart(g); } public String writeOnChart(){ PDAP2CTStatPak rootStats = ((ScatterRootRegCIPI)ownerModule).rootStatTask.getStatPak(); if (rootStats != null) return rootStats.flst(); else return ""; } /**to inform ChartExtra that cursor has just entered point*/ public void cursorEnterPoint(int point, int exactPoint, Graphics g){ //Debugg.println("enter point " + point); } /**to inform ChartExtra that cursor has just exited point*/ public void cursorExitPoint(int point, int exactPoint, Graphics g){ //Debugg.println("exit point " + point); } /**to inform ChartExtra that cursor has just touched point*/ public void cursorTouchPoint(int point, int exactPoint, Graphics g){ //Debugg.println("touch point " + point); } } \ No newline at end of file diff --git a/src/mesquite/pdap/lib/PDAPRootRegStatPak.java b/src/mesquite/pdap/lib/PDAPRootRegStatPak.java index 4aa789a..dacbb73 100644 --- a/src/mesquite/pdap/lib/PDAPRootRegStatPak.java +++ b/src/mesquite/pdap/lib/PDAPRootRegStatPak.java @@ -9,6 +9,7 @@ package mesquite.pdap.lib; import java.util.ArrayList; +import java.util.List; import mesquite.cont.lib.ContinuousDistribution; import mesquite.lib.MesquiteDouble; @@ -17,7 +18,7 @@ public abstract class PDAPRootRegStatPak extends PDAPRootStatPak { // Add support for CI/PI - protected ArrayList CIPIValues = null; //Non-generic as Mesquite needs to run under Java 1.4 + protected List CIPIValues = null; // should this be empty rather than null? /*-----------------------------------------*/ /** Set the tree so we can do the contrast calculations internally @@ -66,7 +67,7 @@ public void addCIPIValue(MesquiteDouble x) { /** This allows clearing the list of values (e.g., when a character is changed) */ public void clearCIPIlist() { - CIPIValues = new ArrayList(); + CIPIValues = new ArrayList(); } /**