pal-1.5.1/ 0000755 0000000 0000000 00000000000 11710516471 010773 5 ustar root root pal-1.5.1/src/ 0000755 0000000 0000000 00000000000 11710516471 011562 5 ustar root root pal-1.5.1/src/newmake.bat 0000644 0000000 0000000 00000002550 10001765020 013667 0 ustar root root @rem @rem make in order (contributed by Thomas Keane) mkdir ..\classes cd ..\classes deltree pal deltree org cd ..\src\org\w3c\dom javac -classpath ../../../../classes -d ../../../../classes *.java cd ..\..\..\pal\io javac -classpath ../../../classes -d ../../../classes *.java cd .. javac -classpath ../../classes -d ../../classes math/*.java util/*.java misc/*.java cd datatype javac -classpath ../../../classes -d ../../../classes *.java cd ..\statistics javac -classpath ../../../classes -d ../../../classes *.java cd ..\alignment javac -classpath ../../../classes -d ../../../classes *.java cd ..\ javac -classpath ../../classes -d ../../classes tree/*.java distance/*.java mep/*.java substmodel/*.java cd coalescent javac -deprecation -classpath ../../../classes -d ../../../classes *.java cd ..\popgen javac -classpath ../../../classes -d ../../../classes *.java cd ..\eval javac -classpath ../../../classes -d ../../../classes *.java cd ..\gui javac -classpath ../../../classes -d ../../../classes *.java cd ..\xml javac -classpath ../../../classes;../../../classes/xml.jar -d ../../../classes *.java cd ..\algorithmics javac -classpath ../../../classes -d ../../../classes *.java cd ..\treesearch javac -classpath ../../../classes -d ../../../classes *.java cd ..\supgma javac -classpath ../../../classes -d ../../../classes *.java pause pal-1.5.1/src/makejar-signed.bat 0000644 0000000 0000000 00000000440 07437371336 015143 0 ustar root root @echo off rem ************************************************************ rem This batch file makes and signs the jar file rem ************************************************************ @echo on cd ..\classes jar cvf ..\pal.jar pal org *.class jarsigner ..\pal.jar alexei pal-1.5.1/src/makefile 0000644 0000000 0000000 00000001764 07421755130 013273 0 ustar root root ### VARIABLES ### PACKAGES = \ pal.alignment \ pal.distance \ pal.eval \ pal.gui \ pal.io \ pal.math \ pal.mep \ pal.misc \ pal.popgen \ pal.statistics \ pal.substmodel \ pal.tree \ pal.datatype \ pal.util \ pal.coalescent \ pal.xml \ VERSION = pal-1.4 ### TARGETS ### .PHONY: classes native clean install installclean \ doc docclean zip zipclean fullclean zipsrc distrib classes: (cd pal; $(MAKE) classes) native: (cd pal; $(MAKE) native) clean: (cd pal; $(MAKE) clean) doc: javadoc -d ../doc/api $(PACKAGES) docclean: (rm -r -f ../doc/api/; mkdir ../doc/api) zip: classes zip -r pal pal -n .class -i '*.class' -i '*/' -x '*CVS/' zipclean: rm -f pal.zip fullclean: clean docclean installclean zipclean zipsrc: zip -r -9 pal-src pal -i '*.java' -i '*akefile*' -i '*.html' -i '*/' distrib: (cd ../..; zip -r -9 $(VERSION).zip $(VERSION) -x '*CVS*' -x '*.directory'; cd $(VERSION)/src); pal-1.5.1/src/makeclean.bat 0000644 0000000 0000000 00000003147 07476747422 014217 0 ustar root root @rem @rem make in order cd ..\classes deltree pal deltree org cd ..\src\org\w3c\dom javac -source 1.3 -classpath ../../../../classes -d ../../../../classes *.java cd ..\..\..\pal\io javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\math javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\util javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\misc javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\datatype javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\statistics javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\substmodel javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\mep javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\alignment javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\distance javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\tree javac -source 1.3 -deprecation -classpath ../../../classes -d ../../../classes *.java cd ..\coalescent javac -source 1.3 -deprecation -classpath ../../../classes -d ../../../classes *.java cd ..\popgen javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\eval javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\gui javac -source 1.3 -classpath ../../../classes -d ../../../classes *.java cd ..\xml javac -source 1.3 -classpath ../../../classes;../../../classes/xml.jar -d ../../../classes *.java pal-1.5.1/src/pal/ 0000755 0000000 0000000 00000000000 10141733722 012333 5 ustar root root pal-1.5.1/src/pal/gui/ 0000755 0000000 0000000 00000000000 10141733720 013115 5 ustar root root pal-1.5.1/src/pal/gui/CircularGraphics.java 0000644 0000000 0000000 00000016055 07323721302 017215 0 ustar root root // CircularGraphics.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.gui; import java.awt.*; /** @author Matthew Goode */ public class CircularGraphics { double worldRadius_, worldAngle_; public int screenCentreX; public int screenCentreY; public int screenRadius; final static double TWO_PI = 2*Math.PI; Graphics g_; FontMetrics fm_; Font font_; boolean invertY_; public CircularGraphics(Graphics g, double worldAngle, double worldRadius, int screenX, int screenY, int screenWidth, int screenHeight) { this(g,worldAngle,worldRadius,screenX, screenY, screenWidth, screenHeight,false); } public CircularGraphics(Graphics g, double worldAngle, double worldRadius, int screenX, int screenY, int screenWidth, int screenHeight, boolean invertY) { this.g_ = g; this.invertY_ = invertY; this.worldAngle_ = worldAngle; this.worldRadius_ = worldRadius; screenRadius = Math.min(screenWidth/2, screenHeight/2); screenCentreX = screenX+screenWidth/2; screenCentreY = screenY+screenHeight/2; font_ = g_.getFont(); if(font_!=null) { fm_ = g_.getFontMetrics(font_); } } public void setFont(Font newFont) { g_.setFont(newFont); this.font_ = newFont; fm_ = g_.getFontMetrics(font_); } /** For drawing arbitary lines */ public void drawLine( double angle1, double radius1, double angle2, double radius2) { g_.drawLine(getScreenX(angle1,radius1), getScreenY(angle1, radius1), getScreenX(angle2,radius2),getScreenY(angle2,radius2) ); } /** For drawing arbitary lines */ public void drawLine( double angle, double radiusStart, double radiusEnd) { g_.drawLine(getScreenX(angle,radiusStart), getScreenY(angle, radiusStart), getScreenX(angle,radiusEnd),getScreenY(angle,radiusEnd) ); } /** For drawing arbitary lines */ public void drawLineDegreeAlign( double angle, double radiusStart, double radiusEnd) { angle = ((int)(angle*360/worldAngle_))*worldAngle_/360; g_.drawLine(getScreenX(angle,radiusStart), getScreenY(angle, radiusStart), getScreenX(angle,radiusEnd),getScreenY(angle,radiusEnd) ); } private final double convertRadius(double radius) { //return radius; return worldRadius_ - radius; } /** For drawing arbitary lines */ public void drawArc( double angleStart, double angleEnd, double radius) { int actualRadius = (int)(screenRadius*convertRadius(radius)/worldRadius_); if(actualRadius<1) { return; } int startAngle, endAngle; // if(invertY_) { startAngle = (int)(angleStart*360/worldAngle_); endAngle = (int)(angleEnd*360/worldAngle_); // } else { // startAngle = (int)(angleStart*360/worldAngle_); // endAngle = (int)(angleEnd*360/worldAngle_); // } // if(invertY_) { // g_.drawArc(screenCentreX-actualRadius, screenCentreY+actualRadius, actualRadius*2,-actualRadius*2, startAngle, endAngle-startAngle ); // } else { g_.drawArc(screenCentreX-actualRadius, screenCentreY-actualRadius, actualRadius*2,actualRadius*2, startAngle, endAngle-startAngle ); /*System.out.println(""+(screenCentreX-actualRadius)+ " "+ ( screenCentreY-actualRadius)+ " " + ( actualRadius*2) + " " + ( actualRadius*2 ) + " " + ( startAngle ) + " " + ( endAngle-startAngle )); */ // } } public void setColor(Color c) { g_.setColor(c); } public void drawString(String s, double angle, double radius) { int sX =getScreenX(angle,radius); int sY = getScreenY(angle,radius); FontMetrics fm = g_.getFontMetrics(g_.getFont()); int stringWidth = fm.stringWidth(s); int stringHeight = fm.getHeight(); g_.drawString(s,sX-stringWidth/2,sY+stringHeight/2); } public void drawString(String s, double angle, double radius,int outdent) { int sX =getScreenX(angle,radius,outdent); int sY = getScreenY(angle,radius,outdent); FontMetrics fm = g_.getFontMetrics(g_.getFont()); int stringWidth = fm.stringWidth(s); int stringHeight = fm.getHeight(); g_.drawString(s,sX-stringWidth/2,sY+stringHeight/2); } public void circleString(String s, double angle, double radius,int outdent) { int sX =getScreenX(angle,radius,outdent); int sY = getScreenY(angle,radius,outdent); FontMetrics fm = g_.getFontMetrics(g_.getFont()); int stringWidth = fm.stringWidth(s); int stringHeight = fm.getHeight(); g_.drawString(s,sX-stringWidth/2,sY+stringHeight/2); g_.drawOval(sX-stringWidth/2-5,sY-stringHeight/2-2 ,stringWidth+10, stringHeight+10); } public int getScreenX(double angle, double radius) { return screenCentreX + (int)(convertRadius(radius)*screenRadius*Math.cos(angle*TWO_PI/worldAngle_)/worldRadius_); } public int getScreenX(double angle, double radius, int outdent) { double trigBit = Math.cos(angle*TWO_PI/worldAngle_); return screenCentreX + (int)(outdent*trigBit + convertRadius(radius)*screenRadius*trigBit/worldRadius_); } public int getScreenDeltaX(double angle, double radius) { return (int)(convertRadius(radius)*screenRadius*Math.cos(angle*TWO_PI/worldAngle_ )/worldRadius_ ); } public int getScreenY(double angle, double radius) { int offset = (int)(convertRadius(radius)*screenRadius*Math.sin(angle*TWO_PI/worldAngle_)/worldRadius_); return (invertY_ ? (screenCentreY + offset) : (screenCentreY - offset)); } public int getScreenY(double angle, double radius, int outdent) { double trigBit = Math.sin(angle*TWO_PI/worldAngle_); int offset = (int)(outdent*trigBit + convertRadius(radius)*screenRadius*trigBit/worldRadius_); return (invertY_ ? (screenCentreY + offset) : (screenCentreY - offset)); } public int getScreenDeltaY(double angle, double radius) { return (invertY_ ? 1 : -1 )*(int)(convertRadius(radius)*screenRadius*Math.sin(angle*TWO_PI/worldAngle_)/worldRadius_); } public void fillPoint(double angle, double radius, int size) { int x = getScreenX(angle,radius); int y = getScreenY(angle,radius); g_.fillOval(x-size,y-size,2*size,2*size); } public void drawPoint(double angle, double radius, int size) { int x = getScreenX(angle,radius); int y = getScreenY(angle,radius); g_.drawOval(x-size,y-size,2*size,2*size); } public void drawSymbol(double angle, double radius, int outdent, int width, int symbol) { int halfWidth = width / 2; int x = getScreenX(angle,radius,outdent); int y = getScreenY(angle,radius,outdent); switch (symbol% 6) { case 0: g_.fillRect(x, y, width, width); break; case 1: g_.drawRect(x, y, width, width); break; case 2: g_.fillOval(x, y, width, width); break; case 3: g_.drawOval(x, y, width, width); break; case 4: // draw triangle g_.drawLine(x, y + width, x + halfWidth, y); g_.drawLine(x + halfWidth, y, x + width, y + width); g_.drawLine(x, y + width, x + width, y + width); break; case 5: // draw X g_.drawLine(x, y, x + width, y + width); g_.drawLine(x, y + width, x + width, y); break; } } } pal-1.5.1/src/pal/gui/Painter.java 0000644 0000000 0000000 00000001136 07374505304 015374 0 ustar root root // Painter.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.gui; import java.awt.Graphics; import java.awt.Dimension; /** * An interface for objects which are used for painting themselves in a * general Graphics object * * @author Matthew Goode */ public interface Painter { void paint(Graphics g, int displayWidth, int displayHeight); void paint(Graphics g, int displayWidth, int displayHeight, LayoutTracker lt); Dimension getPreferredSize(); } pal-1.5.1/src/pal/gui/PositionedNode.java 0000644 0000000 0000000 00000003570 07420611326 016713 0 ustar root root // PositionedNode.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.gui; import pal.tree.*; /** * A tree node that has a scalar position for the purposes of drawing the tree. * * @author Alexei Drummond * @version $Id: PositionedNode.java,v 1.6 2002/01/14 04:18:13 matt Exp $ */ public class PositionedNode extends SimpleNode { protected double x; //Please excuse this - it will be returned to its non public state eventually - MG boolean highlight_; Node peer_; /** Builds a tree based on node, but highlights highlightNode */ public PositionedNode(Node node, Node highlightNode) { init(node); this.peer_ = node; if (!node.isLeaf()) { for (int i = 0; i < node.getChildCount(); i++) { addChild(new PositionedNode(node.getChild(i),highlightNode)); } } highlight_ = (node==highlightNode); } public PositionedNode(Node node) { init(node); this.peer_ = node; if (!node.isLeaf()) { for (int i = 0; i < node.getChildCount(); i++) { addChild(new PositionedNode(node.getChild(i))); } } } public void calculatePositions() { double[] currentXPos = {0.0}; calculateXPositions(currentXPos); } public Node getPeer() { return peer_; } private double calculateXPositions(double[] currentXPos) { if (!isLeaf()) { // find average x position x = ((PositionedNode)getChild(0)).calculateXPositions(currentXPos); for (int i = 1; i < getChildCount(); i++) { x += ((PositionedNode)getChild(i)).calculateXPositions(currentXPos); } x /= getChildCount(); } else { x = currentXPos[0]; currentXPos[0] += 1.0; } return x; } public boolean isHighlighted() { return highlight_; } public double getX() { return x; } } pal-1.5.1/src/pal/gui/TreePainterCircular.java 0000644 0000000 0000000 00000010755 07706515310 017705 0 ustar root root // TreePainter.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.gui; import pal.tree.*; import pal.io.*; import pal.misc.*; import java.awt.*; /** * A class that can paint a tree (in a circular fashion) into a Graphics object . * * @version $Id: TreePainterCircular.java,v 1.13 2003/07/20 02:36:08 matt Exp $ * * @author Alexei Drummond, Matthew Goode */ public class TreePainterCircular extends TreePainter { public static final int RIGHTBORDER = 75; public static final int LEFTBORDER = 10; public static final int TOPBORDER = 20; public static final int BOTTOMBORDER = 30; static final int SYMBOL_SIZE = 8; public static final int YSPACER = 20; public static final int XSPACER = 10; double maxAngle_, maxRadius_; public TreePainterCircular(Tree toDisplay, String title, boolean showTitle) { super(toDisplay, title, showTitle); setTreeImpl(toDisplay); } public void setTreeImpl(Tree t) { maxRadius_ = treeNode.getNodeHeight(); maxAngle_ = NodeUtils.getLeafCount(treeNode); } /** * Returns the preferred size for drawing * (that is the size that will show everything nicely) */ public Dimension getPreferredSize() { return new Dimension(100 + LEFTBORDER + RIGHTBORDER, 100+TOPBORDER+ BOTTOMBORDER); } protected void paint(PositionedNode node, CircularGraphics cg) { cg.setColor(FOREGROUND); double angle = node.x; double radius = node.getNodeHeight(); if (node.hasChildren()) { for (int i = 0; i < node.getChildCount(); i++) { paintLeafBranch(node, (PositionedNode)node.getChild(i), cg); } for (int i = 0; i < node.getChildCount(); i++) { paint((PositionedNode)node.getChild(i), cg); } int bootStrapValue = getBootstrapValue(node); if(bootStrapValue>=50) { cg.setColor(BOOTSTRAP_SUPPORT_COLOUR); cg.drawString( bootStrapValue+"", angle,radius, XSPACER); } } else { if ((maxLeafTime > 0.0) && isUsingColor()) { cg.setColor(Color.getHSBColor((float)(maxLeafTime - radius)/(float)maxLeafTime, 1.0f, 1.0f)); } else { cg.setColor(NORMAL_LABEL_COLOR); } if (isUsingColor()) { cg.fillPoint(angle,radius,2); } if (isUsingSymbols() && (getTimeOrderCharacterData() != null)) { cg.drawSymbol(angle,radius, XSPACER, SYMBOL_SIZE, getTimeOrderCharacterData().getTimeOrdinal(getTimeOrderCharacterData().whichIdNumber(node.getIdentifier().getName()))); } else { if(isUsingColor()) { cg.drawString( node.getIdentifier().getName(), angle,radius, XSPACER); if(node.isHighlighted()) { cg.setColor(Color.red); cg.circleString(node.getIdentifier().getName(), angle,radius, XSPACER); } } else { if(node.isHighlighted()) { cg.setColor(Color.red); } cg.drawString( node.getIdentifier().getName(), angle,radius, XSPACER); } } } } private void paintLeafBranch(PositionedNode parentNode, PositionedNode childNode, CircularGraphics g) { // paint join to parent g.drawArc(parentNode.x,childNode.x, parentNode.getNodeHeight() ); // paint branch g.drawLineDegreeAlign(childNode.x, childNode.getNodeHeight(), parentNode.getNodeHeight() ); if (isShowingNodeHeights()) { String label = FormattedOutput.getInstance().getDecimalString(childNode.getNodeHeight(), 4); g.drawString(label, childNode.x, childNode.getNodeHeight(), XSPACER); } } public void paint(Graphics g, int displayWidth, int displayHeight) { paint(g,displayWidth,displayHeight,false,null); } public void paint(Graphics g, int displayWidth, int displayHeight, LayoutTracker lt) { paint(g,displayWidth,displayHeight,false,lt); } public final void paint(Graphics g, int displayWidth, int displayHeight,boolean invert) { paint(g,displayWidth,displayHeight,invert,null); } public final void paint(Graphics g, int displayWidth, int displayHeight,boolean invert, LayoutTracker lt) { CircularGraphics cg = new CircularGraphics(g,maxAngle_,maxRadius_, LEFTBORDER,TOPBORDER, (displayWidth - LEFTBORDER - RIGHTBORDER), (displayHeight - TOPBORDER - BOTTOMBORDER), invert ); cg.setFont(getLabelFont()); g.setColor(BACKGROUND); g.fillRect(0, 0, displayWidth, displayHeight); paint(treeNode, cg); doTitle(g,LEFTBORDER, TOPBORDER - 8); //doScale(g,1,LEFTBORDER,displayHeight - BOTTOMBORDER + 12); } } pal-1.5.1/src/pal/gui/makefile 0000644 0000000 0000000 00000001237 07275407432 014634 0 ustar root root ### VARIABLES ### JIKESOPTS := +P GCJOPTS := # Always check dependencies JIKESOPTS += +M SRC := $(wildcard *.java) CLS := $(patsubst %.java, %.class, $(SRC)) OBJ := $(patsubst %.class, %.o, $(wildcard *.class)) ### RULES ### # Compile Java sources into class files %.class: %.java jikes $(JIKESOPTS) $< # Alternative to using jikes: gcj -C # Compile class files into native code %.o: %.class gcj -c $(GCJOPTS) $< ### TARGETS ### .PHONY: classes native clean classes: $(CLS) ifneq ($(OBJ),) native: $(OBJ) (ar -rv package.a *.o; ranlib package.a) else native: $(OBJ) endif clean: rm -f *.class *.o *.u *.a *~ pal-1.5.1/src/pal/gui/TreePainterNormal.java 0000644 0000000 0000000 00000014625 07717656572 017413 0 ustar root root // TreePainterNormal.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.gui; import pal.tree.*; import pal.io.*; import pal.misc.*; import java.awt.*; /** * A class that can paint a tree into a Graphics object. * * @version $Id: TreePainterNormal.java,v 1.17 2003/08/16 23:48:26 matt Exp $ * * @author Alexei Drummond * @note *
Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author not attributable * @version 1.0 */ public interface Assessor { public double getCurrentValue(); } pal-1.5.1/src/pal/algorithmics/GeneralObjectState.java 0000644 0000000 0000000 00000002771 07742745450 021415 0 ustar root root package pal.algorithmics; /** *Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author not attributable * @version 1.0 */ public class GeneralObjectState implements ObjectState { private final UndoableAction action_; private final StateProvider subject_; private final boolean maximise_; public GeneralObjectState(UndoableAction action, StateProvider subject, boolean maximise) { this.action_ = action; this.subject_ = subject; this.maximise_ = maximise; } /** * Perform an action * @param currentScore the current score before doing the action * @param desparationValue An indication of how desparate we are, values closer to 1 mean more desparate while values towards 0 mean less desparate * @return the current score after doing the action */ public double doAction(double currentScore, double desparationValue) { boolean succeeded = false; double score = currentScore; while(!succeeded) { score = action_.doAction(currentScore,desparationValue); succeeded = action_.isActionSuccessful(); } return score; } /** * * @return true if undo was successful */ public boolean undoAction() { return action_.undoAction(); } public Object getStateReference() { return subject_.getStateReference(); } public void restoreState(Object stateReference) { subject_.restoreState(stateReference); } public boolean isMaximiseScore() { return maximise_; } } pal-1.5.1/src/pal/algorithmics/UndoableAction.java 0000644 0000000 0000000 00000026444 10024070372 020557 0 ustar root root package pal.algorithmics; /** *Title: UndoableAction
*Description: A stateful, single thread object
*Copyright: Copyright (c) 2003
*Company:
* @author Matthew Goode * @version 1.0 */ import java.util.*; public interface UndoableAction { /** * Perform an action * @param currentscore The current score before doing the action * @param desparationValue An indication by the processing machines of willingness to do more extreme actions. A value of 0 means not desparate at all, a value of 1 means very desparate * @return the current score after doing the action (or the input score if not successful) */ public double doAction(double currentScore, double desparationValue); /** * Was the last action deterministic? That is, if it wasn't chosen and state is still as * before is it worth doing it again? * @return true if last action deterministic */ public boolean isActionDeterministic(); /** * Was the last call to doAction() succesful? * @return true if last action successful, false otherwise */ public boolean isActionSuccessful(); /** * Undo the last action (if it was successful) * Users of undoable actions should accept that sometimes it isn't possible. * If an undo was not possible the action should not change any state * @return true if undo was successful */ public boolean undoAction(); // -=-=-==-=--=-==--=-==--=-==---==-=--=-=-=-=-==-=-=-=-=-=-=--==-=-=--==-=--=- // -=-=-= Utils -=-=-=-=-=-=-==--==-=--=-=-=-=-==-=-=-=-=-=-=--==-=-=--==-=--=- // -=-=-==-=--=-==--=-==--=-==---==-=--=-=-=-=-==-=-=-=-=-=-=--==-=-=--==-=--=- public static final class Utils { /** * Create an action that selects uniformly from a number of sub actions * @param subActions * @return */ public static final UndoableAction getSimpleUniformSelection(UndoableAction[] subActions) { return new Multi(subActions); } /** * Create an action that selects uniformly from a number of sub actions * @param subActions * @param acitionProportions * @throws IllegalArgumentException if action array and proportion arrays are different lengths * @return */ public static final UndoableAction getDistributedSelection(UndoableAction[] subActions, double[] actionProportions) { if(subActions.length>actionProportions.length) { throw new IllegalArgumentException("Actions and proportion array different lengths"); } return new DistributedMulti(subActions, actionProportions); } /** * Create an action that combines multiple actions * @param subActions The actions that are do in turn. * @return An action that performs all the sub actions */ public static final UndoableAction getCombined(UndoableAction[] subActions) { return new Combined(subActions); } /** * A simple tool for change actions when things get desparate * @param primaryAction The main action to do when things are going well * @param desparateAction The action to do when things get desparate. The desperation value for the desparate action will be scaled according to how much over the limit we are * @param desparationLimit The desparate value at which we start doing the desparate action * @param desparationInterval The time between desparate actions when we cross the cutoff (a value of one will mean do all the time after desparation value has crossed cutoff) */ public static final UndoableAction getSimpleDesparation(UndoableAction primaryAction, UndoableAction desparateAction, double desparationLimit, int desparationInterval) { return new SimpleDesparation(primaryAction,desparateAction,desparationLimit,desparationInterval); } // -=-==-=--==--=-=-=-=-=-=-==--=-= private static class SimpleDesparation implements UndoableAction { private final UndoableAction primaryAction_; private final UndoableAction desparateAction_; private final double desparationLimit_; private final int desparationInterval_; private int currentDesparateCount_ = 0; private UndoableAction lastAction_ = null; /** * A simple tool for change actions when things get desparate * @param primaryAction The main action to do when things are going well * @param desparateAction The action to do when things get desparate. The desperation value for the desparate action will be scaled according to how much over the limit we are * @param desparationLimit The desparate value at which we start doing the desparate action * @param desparationInterval The time between desparate actions when we cross the cutoff (a value of one will mean do all the time after desparation value has crossed cutoff) */ public SimpleDesparation(UndoableAction primaryAction, UndoableAction desparateAction, double desparationLimit, int desparationInterval) { this.primaryAction_ = primaryAction; this.desparateAction_ = desparateAction; this.desparationLimit_ = desparationLimit; this.desparationInterval_ = desparationInterval; } /** * @return false */ public boolean isActionDeterministic() { return false; } public double doAction(double currentScore, double desparationValue) { if(desparationValue>=desparationLimit_) { currentDesparateCount_++; if(currentDesparateCount_==desparationInterval_) { currentDesparateCount_ = 0; lastAction_ = desparateAction_; desparationValue = (desparationLimit_-desparationValue)/(1-desparationLimit_); } else { lastAction_ = primaryAction_; } } else { lastAction_ = primaryAction_; currentDesparateCount_ = 0; } return lastAction_.doAction(currentScore,desparationValue); } public boolean isActionSuccessful() { if(lastAction_!=null) { return lastAction_.isActionSuccessful(); } throw new RuntimeException("Assertion error : isActionSuccessful() called when no action has been done recently"); } public boolean undoAction() { if(lastAction_!=null) { final boolean successful = lastAction_.undoAction(); lastAction_ = null; return successful; } else { throw new RuntimeException("Assertion error : undoAction() called when no action has been done recently (or has already been undone)"); } } } //End of class Multi // -=-==-=--==--=-=-=-=-=-=-==--=-= private static class Multi implements UndoableAction { private final UndoableAction[] subActions_; private UndoableAction lastAction_ = null; private final Random random_; public Multi(UndoableAction[] subActions) { this.subActions_ = subActions; this.random_ = new Random(); } public double doAction(double currentScore, double desparationValue) { lastAction_ = subActions_[random_.nextInt(subActions_.length)]; return lastAction_.doAction(currentScore,desparationValue); } public boolean isActionSuccessful() { if(lastAction_!=null) { return lastAction_.isActionSuccessful(); } throw new RuntimeException("Assertion error : isActionSuccessful() called when no action has been done recently"); } /** * @return false */ public boolean isActionDeterministic() { return false; } public boolean undoAction() { if(lastAction_!=null) { final boolean successful = lastAction_.undoAction(); lastAction_ = null; return successful; } else { throw new RuntimeException("Assertion error : undoAction() called when no action has been done recently (or has already been undone)"); } } } //End of class Multi // -=-==-=--==--=-=-=-=-=-=-==--=-= private static class DistributedMulti implements UndoableAction { private final UndoableAction[] subActions_; private final double[] probabilities_; private UndoableAction lastAction_ = null; private final Random random_; public DistributedMulti(UndoableAction[] subActions, double[] proportions) { this.subActions_ = subActions; this.probabilities_ = new double[subActions.length]; double total = 0; for(int i = 0 ; i < subActions.length ; i++) { total+=proportions[i]; } for(int i = 0 ; i < subActions.length ; i++) { probabilities_[i] = proportions[i]/total; } this.random_ = new Random(); } /** * @return false */ public boolean isActionDeterministic() { return false; } public double doAction(double currentScore, double desparationValue) { double v = random_.nextDouble(); double total = 0; int index = subActions_.length-1; for(int i = 0 ; i < subActions_.length ; i++) { total+=probabilities_[i]; if(total>v) { index = i; break; } } lastAction_ = subActions_[index]; return lastAction_.doAction(currentScore,desparationValue); } public boolean isActionSuccessful() { if(lastAction_!=null) { return lastAction_.isActionSuccessful(); } throw new RuntimeException("Assertion error : isActionSuccessful() called when no action has been done recently"); } public boolean undoAction() { if(lastAction_!=null) { boolean successful = lastAction_.undoAction(); lastAction_ = null; return successful; } else { throw new RuntimeException("Assertion error : undoAction() called when no action has been done recently (or has already been undone)"); } } } //End of class DistributedMulti // -=-==-=--==--=-=-=-=-=-=-==--=-= private static class Combined implements UndoableAction { private final UndoableAction[] subActions_; private boolean deterministic_ = true; private boolean successful_ = false; public Combined(UndoableAction[] subActions) { this.subActions_ = subActions; } /** * @return false */ public boolean isActionDeterministic() { return deterministic_; } public double doAction(double currentScore, double desparationValue) { boolean d = true; boolean s = true; for(int i = 0 ; i < subActions_.length ; i++) { UndoableAction a = subActions_[i]; double score = a.doAction(currentScore, desparationValue); if(a.isActionSuccessful()) { s = true; currentScore = score; d = d & a.isActionDeterministic(); } } deterministic_ = d; successful_ = s; return currentScore; } public boolean isActionSuccessful() { return successful_; } public boolean undoAction() { boolean result = true; if(successful_) { for(int i = subActions_.length -1 ; i >= 0 ; i++) { UndoableAction a = subActions_[i]; if(a.isActionSuccessful()) { result = result & a.undoAction(); } } successful_ = false; return result; } else { throw new RuntimeException("Assertion error : undoAction() called when not successful"); } } } //End of class Combined } //End of class Utils } pal-1.5.1/src/pal/algorithmics/StateProvider.java 0000644 0000000 0000000 00000000461 07742741016 020467 0 ustar root root package pal.algorithmics; /** *Title:
*Description:
*Copyright: Copyright (c) 2003
*Company:
* @author not attributable * @version 1.0 */ public interface StateProvider { public Object getStateReference(); public void restoreState(Object stateReference); } pal-1.5.1/src/pal/algorithmics/StoppingCriteria.java 0000644 0000000 0000000 00000037536 07762652372 021207 0 ustar root root // StoppingCriteria.java // // (c) 1999-2003 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.algorithmics; /** * Title: StoppingCriteria * Description: A means of deciding when to stop * @author Matthew Goode * @version 1.0 */ import pal.util.AlgorithmCallback; public interface StoppingCriteria extends java.io.Serializable { public boolean isTimeToStop(); /** * Get an indication of how close to stopping we currently are * @return a value between 0 and 1 where zero means not likely to stop soon, and a value of one means likely to stop very soon */ public double getRelativeStoppingRatio(); /** * @param externalStablized if true than other factors have stablized */ public void newIteration(double currentScore, double bestScore, boolean maximising, boolean externalStablized, AlgorithmCallback callback); public void reset(); //=========================================== //=========== Static Factory Class ============= //=========================================== public static interface Factory extends java.io.Serializable { public StoppingCriteria newInstance(); } //=========================================== //=========== Static Util Class ============= //=========================================== public static class Utils { /** * A stopping criteria that stops after a set number of iterations * @param maxIterationCount the maximum number of iterations. */ public static final StoppingCriteria.Factory getIterationCount(int maxIterationCount) { return new IterationCountSC.SCFactory(maxIterationCount); } /** * A stopping criteria that works by counting how many iterations occur at a given score (either the best score or the * current score) and stopping when score does not change after a set number of generations * @param maxIterationCountAtCurrentScore the number of iterations to wait at the current score before stopping * @param matchBestScore if true will examine the best score so far, else will examine the current score so far. */ public static final StoppingCriteria.Factory getUnchangedScore(int maxIterationCountAtCurrentScore, boolean matchBestScore) { return new UnchangedScoreSC.SCFactory(maxIterationCountAtCurrentScore, matchBestScore); } /** * A stopping criteria that works by counting how many iterations occur at a given score (either the best score or the * current score) and stopping when score does not change after a set number of generations * @param maxIterationCountAtCurrentScore the number of iterations to wait at the current score before stopping * @param matchBestScore if true will examine the best score so far, else will examine the current score so far. */ public static final StoppingCriteria.Factory getNonExactUnchangedScore(int maxIterationCountAtCurrentScore, boolean matchBestScore, double tolerance) { return new NonExactUnchangedScoreSC.SCFactory(maxIterationCountAtCurrentScore, matchBestScore, tolerance); } /** * A stopping criteria that is a composite of a set of criteria, stops when at least one * sub criteria wants to stop * @param subCriteria an array of StoppingCriteria to combine */ public static final StoppingCriteria.Factory getCombined(Factory[] subCriteria) { return new CombinedSC.SCFactory(subCriteria); } //Has Serialization code private static class IterationCountSC implements StoppingCriteria { int count_ = 0; int maxIterationCount_; // // Serialization code // private static final long serialVersionUID= -883722345529L; private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeByte(1); //Version number out.writeInt(count_); out.writeInt(maxIterationCount_); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException{ byte version = in.readByte(); switch(version) { default : { count_ = in.readInt(); maxIterationCount_ = in.readInt(); break; } } } public IterationCountSC(int maxIterationCount) { this.maxIterationCount_ = maxIterationCount; } public void reset() { count_ = 0; } /** * Goes up as the count nears maximum * @return */ public double getRelativeStoppingRatio() { return count_/(double)maxIterationCount_; } public boolean isTimeToStop() { return count_>=maxIterationCount_; } /** * @param externalStablized if true than other factors have stablized */ public void newIteration(double currentScore, double bestScore, boolean maximising, boolean externalStablized, AlgorithmCallback callback) { count_++; callback.updateProgress(count_/(double)maxIterationCount_); } // ===== Factory ========== private static class SCFactory implements Factory { private int maxIterationCount_; // // Serialization code // private static final long serialVersionUID = -552478345529L; private void writeObject( java.io.ObjectOutputStream out ) throws java.io.IOException { out.writeByte( 1 ); //Version number out.writeInt(maxIterationCount_); } private void readObject( java.io.ObjectInputStream in ) throws java.io.IOException, ClassNotFoundException { byte version = in.readByte(); switch( version ) { default: { maxIterationCount_ = in.readInt(); break; } } } public SCFactory(int maxIterationCount) { this.maxIterationCount_ = maxIterationCount; } public StoppingCriteria newInstance() { return new IterationCountSC(maxIterationCount_); } } } //Has Serialization code private static class CombinedSC implements StoppingCriteria { private StoppingCriteria[] subCriteria_; // // Serialization code // private static final long serialVersionUID= -847823472529L; private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeByte(1); //Version number out.writeObject(subCriteria_); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException{ byte version = in.readByte(); switch(version) { default : { subCriteria_ = (StoppingCriteria[])in.readObject(); break; } } } public CombinedSC(StoppingCriteria[] subCriteria) { this.subCriteria_ = subCriteria; } public void reset() { for(int i = 0 ; i < subCriteria_.length ; i++) { subCriteria_[i].reset(); } } public double getRelativeStoppingRatio() { double max = 0; for(int i = 0 ; i < subCriteria_.length ; i++) { max = Math.max(max,subCriteria_[i].getRelativeStoppingRatio()); } return max; } public boolean isTimeToStop() { for(int i = 0 ; i < subCriteria_.length ; i++) { if(subCriteria_[i].isTimeToStop()) { return true; } } return false; } /** * @param externalStablized if true than other factors have stablized */ public void newIteration(double currentScore, double bestScore, boolean maximising, boolean externalStablized, AlgorithmCallback callback) { for(int i = 0 ; i < subCriteria_.length ; i++) { subCriteria_[i].newIteration(currentScore,bestScore,maximising,externalStablized, callback); } } // ===== Factory ========== static class SCFactory implements Factory { Factory[] subCriteria_; // // Serialization code // private static final long serialVersionUID = -525566345529L; private void writeObject( java.io.ObjectOutputStream out ) throws java.io.IOException { out.writeByte( 1 ); //Version number out.writeObject(subCriteria_); } private void readObject( java.io.ObjectInputStream in ) throws java.io.IOException, ClassNotFoundException { byte version = in.readByte(); switch( version ) { default: { subCriteria_ = (Factory[])in.readObject(); break; } } } public SCFactory( Factory[] subCriteria ) { this.subCriteria_ = subCriteria; } public StoppingCriteria newInstance() { StoppingCriteria[] subs = new StoppingCriteria[subCriteria_.length]; for(int i = 0 ; i < subs.length ; i++) { subs[i] = subCriteria_[i].newInstance(); } return new CombinedSC(subs); } } } // -=-=-=-= //Has Serialization code private static class UnchangedScoreSC implements StoppingCriteria { private int count_ = 0; private int maxIterationCountAtCurrentScore_; private double lastScore_; private boolean matchBestScore_; // // Serialization code // private static final long serialVersionUID= -3242345529L; private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeByte(1); //Version number out.writeInt(count_); out.writeInt(maxIterationCountAtCurrentScore_); out.writeDouble(lastScore_); out.writeBoolean(matchBestScore_); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException{ byte version = in.readByte(); switch(version) { default : { count_ = in.readInt(); maxIterationCountAtCurrentScore_ = in.readInt(); lastScore_ = in.readDouble(); matchBestScore_ = in.readBoolean(); break; } } } public UnchangedScoreSC(int maxIterationCountAtCurrentScore, boolean matchBestScore) { this.maxIterationCountAtCurrentScore_ = maxIterationCountAtCurrentScore; this.matchBestScore_ = matchBestScore; } public void reset() { count_ = 0; } /** * Goes up as the count nears maximum * @return */ public double getRelativeStoppingRatio() { return count_/(double)maxIterationCountAtCurrentScore_; } public boolean isTimeToStop() { return count_>=maxIterationCountAtCurrentScore_; } /** * @param externalStablized if true than other factors have stablized */ public void newIteration(double currentScore, double bestScore, boolean maximising, boolean externalStablized, AlgorithmCallback callback){ if(!externalStablized) { return; } if(count_==0) { lastScore_ = (matchBestScore_ ? bestScore : currentScore); } else { if(matchBestScore_) { if((!maximising&&(bestScoreTitle: Object State
*Description: A stateful, single thread object, that can act upon itself
* @author Matthew Goode * @version 1.0 */ public interface ObjectState { /** * Perform an action * @param currentScore The current score before doing the action * @param desparationValue An indication by the processing machines of willingness to do more extreme actions. A value of 0 means not desparate at all, a value of 1 means very desparate * @return the current score after doing the action (or the input score if not successful) */ public double doAction(double currentScore, double desparationValue); /** * Undo the previous action if possible * @return true if undo was successful, false otherwise */ /** * Undo the last action (if it was successful) * Users of an ObjectState should accept that sometimes undoing an action isn't possible. * If an undo was not possible the object state should be in the same state as it was previous to the call to undoAction() * @return true if undo was successful */ public boolean undoAction(); /** * * @return An object that can be used to reconstruct the current state of this object */ public Object getStateReference(); /** * Used to restore the state of the this object to that of a previous time point * @param stateReference An object returned by getStateReference() */ public void restoreState(Object stateReference); /** * If true, than a bigger score is better, otherwise a smaller score is better * @return True if the aim is to maximise */ public boolean isMaximiseScore(); } pal-1.5.1/src/pal/algorithmics/Markable.java 0000644 0000000 0000000 00000000702 07742735450 017415 0 ustar root root // Markable.java // // (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.algorithmics; /** *Title: Markable
*Description: An interface for objects that can have their state marked
* @author Matthew Goode * @version 1.0 */ public interface Markable { public void mark(); public void undoToMark(); } pal-1.5.1/src/pal/algorithmics/ProbabilityIterator.java 0000644 0000000 0000000 00000007725 07742735356 021712 0 ustar root root // ProbabilityIterator.java // // (c) 1999-2003 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package pal.algorithmics; /** * A function for obtaining probabilities (that may change over time) * @author Matthew Goode */ public interface ProbabilityIterator { public double getNextProbability(double currentBest, double testValue, boolean maximising); public boolean isStablised(); public static interface Factory { public ProbabilityIterator newInstance(); } public static class Utils { public static final Factory getConstant(double value) { return new Constant.PIFactory(value); } public static final Factory getHillClimb() { return new HillClimb.PIFactory(); } public static final Factory getBoltzman(double initialTemperature, double temperatureDecay, int chainLength) { return new Boltzman.PIFactory(initialTemperature,temperatureDecay,chainLength); } //============================================================= private static class Constant implements ProbabilityIterator { double value_; public Constant(double value ) { this.value_ = value; } public double getNextProbability(double currentBest, double testValue, boolean maximising) { return value_; } public boolean isStablised() { return true; } static class PIFactory implements Factory { Constant intstance_; public PIFactory(double value ) { this.intstance_ = new Constant(value); } public ProbabilityIterator newInstance() { return intstance_; } } } private static class HillClimb implements ProbabilityIterator { public double getNextProbability(double currentBest, double testValue, boolean maximising) { if(maximising) { return(testValue>=currentBest ? 1 : 0); } return(testValue<=currentBest ? 1 : 0); } public boolean isStablised() { return true; } static class PIFactory implements Factory { private static final HillClimb INSTANCE = new HillClimb(); public ProbabilityIterator newInstance() { return INSTANCE; } } } // === Boltzman ==== private static class Boltzman implements ProbabilityIterator{ double initialTemperature_; double temperatureDecay_; int chainLength_; double k_ = 1; double currentTemperature_; int chainPosition_; public Boltzman(double initialTemperature, double temperatureDecay, int chainLength) { this.initialTemperature_ = initialTemperature; this.temperatureDecay_ = temperatureDecay; this.chainLength_ = chainLength; this.currentTemperature_ = initialTemperature_; this.chainPosition_ = 0; } public boolean isStablised() { return currentTemperature_<0.005; } public double getNextProbability(double currentValue, double newValue, boolean maximising) { double toReturn; if(maximising) { if(newValue>currentValue) { toReturn = 1; } else { toReturn = Math.exp(-(currentValue-newValue)/(k_*currentTemperature_)); } } else { if(newValue