Importing release version 322 from old repos

This commit is contained in:
Marcel Kronfeld
2007-12-11 16:38:11 +00:00
parent 8cecdb016d
commit 7ae15be788
668 changed files with 109288 additions and 0 deletions

View File

@@ -0,0 +1,726 @@
/**
* Filename: $RCSfile: DArea.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.Border;
import java.util.Vector;
// zum Drucken:
import java.awt.print.*;
import wsi.ra.print.PagePrinter;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* DArea is the crossing of the <code>JComponent</code>s and the
* <code>DComponent</code>s. It's the <code>DParent</code> which can be added to
* <code>JComponent</code>s
*/
public class DArea extends JComponent implements DParent, Printable
{
private static final boolean under_construction = false;
/**
* the default minimal rectangle which is shown
*/
public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, 2);
/**
* the container in which all DElements of the area are contained except
* the grid
*/
private DContainer container;
/**
* min_rectangle is set, when all elements are removed
* the intersection of visible_rect and max_rectangle is the currently visible
* rectangle
*/
protected DRectangle min_rect = DEFAULT_MIN_RECT,
visible_rect = DEFAULT_MIN_RECT;
protected Double min_x, min_y, max_x, max_y;
/**
* the grid of the area
*/
private DGrid grid;
private boolean auto_focus = false,
auto_grid = false,
grid_to_front = false;
/**
* maximal number of grid lines
*/
private int max_grid = 10;
/**
* the measures of the area
* it calculates the coordinates
*/
private DMeasures measures;
private DBorder dborder = new DBorder();
/**
* initializes the DArea with the initial capacity of 10 components
*/
public DArea(){
this( 10 );
}
/**
* initializes the DArea with the specialized initial capacity of components
* (@see java.util.Vector)
*
* @param the initial capacity
*/
public DArea( int initial_capacity ){
container = new DContainer();
container.setDParent( this );
grid = new DGrid( visible_rect, 1, 1 );
grid.setVisible( false );
grid.setDParent( this );
measures = new DMeasures( this );
}
/**
* returns the currently visible rectangle in DArea coordinates
*
* @return DRectangle the size and position of the visible area
*/
public DRectangle getDRectangle(){
DRectangle rect = (DRectangle)visible_rect.clone();
if( min_x != null ) rect.x = Math.max(rect.x, getMinX() );
if( min_y != null ) rect.y = Math.max(rect.y, getMinY() );
if( max_x != null ) rect.width = Math.min(rect.width, getMaxX() - getMinX());
if( max_y != null ) rect.height = Math.min(rect.height, getMaxY() - getMinY());
return rect;
}
/**
* switches the auto focus of this DArea on or off
*
* @param b on or off
*/
public void setAutoFocus( boolean b ){
boolean old = auto_focus;
auto_focus = b;
if( old != b ) repaint();
}
/**
* returns whether the DArea's auto focus is on or not
*
* @return <code>true</code> or <code>false</code>
*/
public boolean isOnAutoFocus(){ return auto_focus; }
/**
* sets the visible rectangle to this size
*
* @param x the x coordinate of the left border
* @param y the y coordinate of the bottom border
* @param width the width of the area
* @param height the height of the area
*/
public void setVisibleRectangle( double x, double y, double width, double height ){
//System.out.println("DArea.setVisibleRectangle(...)");
setVisibleRectangle( new DRectangle( x, y, width, height ) );
}
/**
* sets the visible rectangle
*
* @param rect the visible <code>DRectangle</code> in DArea coordinates
*/
public void setVisibleRectangle( DRectangle rect ){
if( under_construction )System.out.println("DArea.setVisibleRectangle(DRectangle)");
if( rect.isEmpty() ) throw
new IllegalArgumentException(
"You shopuld never try to set an empty rectangle\n"
+ "as the visible rectangle of an DArea" );
if( !rect.equals( visible_rect ) && rect.width > 0 && rect.height > 0 ){
auto_focus = false;
visible_rect = (DRectangle)rect.clone();
repaint();
}
}
/**
* sets the minimal rectangle
*
* @param x
* @param y
* @param width
* @param height
*/
public void setMinRectangle( double x, double y, double width, double height ){
setMinRectangle( new DRectangle( x, y, width, height ) );
}
/**
* sets the minimal rectangle
*
* @param rect the visible <code>DRectangle</code> in DArea coordinates
*/
public void setMinRectangle( DRectangle rect ){
if( rect.isEmpty() ) min_rect = DEFAULT_MIN_RECT;
else min_rect = (DRectangle)rect.clone();
}
/**
* method returns the minimal rectangle which is set as the visible when all
* elements are removed and the area is on auto focus
*
* @return the minmal rectangle
*/
public DRectangle getMinRectangle(){
return (DRectangle)min_rect.clone();
}
/**
* method sets the maximal rectangle whioch can be viewed with the
* DArea. This method can be used if the area is used with scale functions
* which are not invertible on all reals
*
* @param x the minmal x value
* @param y the minmal y value
* @param width of the maximal rectangle
* @param height of the maximal rectangle
*/
public void setMaxRectangle( double x, double y, double width, double height ){
setMaxRectangle( new DRectangle( x, y, width, height ) );
}
/**
* method sets the maximal rectangle whioch can be viewed with the
* DArea. This method can be used if the area is used with scale functions
* which are not invertible on all reals
*
* @param the rect maximal rectangle of the DArea
* @deprecated see setMinX, setMinY, setMaxX, setMaxY
*/
public void setMaxRectangle( DRectangle rect ){
if( !rect.contains( min_rect ) ) throw
new IllegalArgumentException("Maximal rectangle does not contain minmal rectangle");
setMinX( rect.x );
setMinY( rect.y );
setMaxX( rect.x + rect.width );
setMaxY( rect.y + rect.height );
}
/**
* method returns the maximal rectangle of the area
*
* @return the maximal rectangle
* @deprecated see getMaxX, getMaxY, getMinX, getMinY
*/
public DRectangle getMaxRectangle(){
return new DRectangle(min_x.doubleValue(),
min_y.doubleValue(),
max_x.doubleValue() - min_x.doubleValue(),
max_y.doubleValue() - min_y.doubleValue() );
}
/**
* method sets the minimal x-value which can be displayed by the DArea
* might be helpful, if scale functions are used which are not defined overall
*
* @param mix the minimal x-value
*/
public void setMinX( double mix ){
if( mix > min_rect.x ) throw
new IllegalArgumentException(
"Mimimal y-value axes intersects minmal rectangle.");
min_x = new Double( mix );
}
/**
* method resets the minimal x-value
*/
public void releaseMinX(){
min_x = null;
}
/**
* method returns the minmal x-value which can be displayed in the DArea
*
* @return the minmal x-value
*/
public double getMinX(){
if( min_x != null ) return min_x.doubleValue();
return 0;
}
/**
* method sets the minimal y-value which can be displayed by the DArea
* might be helpful, if scale functions are used which are not defined overall
*
* @param miy the minimal y-value
*/
public void setMinY( double miy ){
if( miy > min_rect.y ) throw
new IllegalArgumentException(
"Mimimal y-value axes intersects minmal rectangle.");
min_y = new Double( miy );
}
/**
* method resets the minimal y-value
*/
public void releaseMinY(){
min_y = null;
}
/**
* method returns the minmal y-value which can be displayed in the DArea
*
* @return the minmal y-value
*/
public double getMinY(){
if( min_y != null ) return min_y.doubleValue();
return 0;
}
/**
* method sets the maximal x-value which can be displayed by the DArea
* might be helpful, if scale functions are used which are not defined overall
*
* @param max the maximal x-value
*/
public void setMaxX( double max ){
if( max < min_rect.x + min_rect.width ) throw
new IllegalArgumentException(
"Maximal x-value axes intersects minmal rectangle.");
max_x = new Double( max );
}
/**
* method resets the maximal x-value
*/
public void releaseMaxX(){
max_x = null;
}
/**
* method returns the maxmal x-value which can be displayed in the DArea
*
* @return the maxmal x-value
*/
public double getMaxX(){
if( max_x != null ) return max_x.doubleValue();
return 0;
}
/**
* method sets the maximal y-values which can be displayed by the DArea
* might be helpful, if scale functions are used which are not defined overall
*
* @param may the maximal y-value
*/
public void setMaxY( double may ){
if( may < min_rect.y + min_rect.height ) throw
new IllegalArgumentException(
"Maximal y-value axes intersects minmal rectangle.");
max_y = new Double( may );
}
/**
* method resets the maximal y-value
*/
public void releaseMaxY(){
max_y = null;
}
/**
* method returns the maximal y-value which can be displayed in the DArea
*
* @return the maximal y-value
*/
public double getMaxY(){
if( max_y != null ) return max_y.doubleValue();
return 0;
}
/**
* paints the DArea by a Graphics object
*
* @param g the java.awt.Graphics object
*/
public void paint( Graphics g ){
if( under_construction ) System.out.println("DArea.paint(Graphics)");
if( auto_focus ) {
container.restore();
visible_rect = (DRectangle)container.getRectangle().clone();
}
if( visible_rect.isEmpty() ) visible_rect = (DRectangle)min_rect.clone();
super.paint( g );
measures.setGraphics( g );
if( grid.isVisible() && !grid_to_front ) paintGrid( measures );
container.paint( measures );
if( grid.isVisible() && grid_to_front ) paintGrid( measures );
}
/**
* repaints a part of the visible area
*
* @param r the rectangle to repaint
*/
public void repaint( DRectangle r ){
if( under_construction ) System.out.println("DArea.repaint(DRectangle)"+r);
if( r == null ) throw
new IllegalArgumentException("Cannot repaint a null DRectangle");
if( r.isAll() || auto_focus ) repaint();
else{
Point p1 = measures.getPoint( r.x, r.y ),
p2 = measures.getPoint( r.x + r.width, r.y + r.height);
if( p1 == null || p2 == null ) repaint();
else {
DBorder b = getDBorder();
repaint( p1.x - b.left,
p2.y - b.top,
p2.x - p1.x + 1 + b.left + b.right,
p1.y - p2.y + 1 + b.top + b.bottom );
}
}
}
/**
* adds a new component to the area
*
* @param e the new DElement
*/
public void addDElement( DElement e ){
container.addDElement( e );
}
/**
* removes a certain element from the area
*
* @param e the element to remove
*/
public boolean removeDElement( DElement e ){
return container.removeDElement( e );
}
/**
* removes all elements from the area
*/
public void removeAllDElements()
{
visible_rect = (DRectangle)min_rect.clone();
container.removeAllDElements();
}
/**
* returnes all DElements in the container
*
* @return the elements of the container
*/
public DElement[] getDElements(){
return container.getDElements();
}
/**
* method returns true, if the given element is contained in the container
*
* @param e the element
* @return if it is contained
*/
public boolean contains( DElement e ){
return container.contains( e );
}
/**
* sets the grid visible or not
*
* @param aFlag visible or not
*/
public void setGridVisible( boolean aFlag ){
if( under_construction ) System.out.println("DArea.setGridVisisble: "+aFlag);
grid.rectangle = getDRectangle();
grid.setVisible( aFlag );
}
/**
* returns if the grid is visible
* <code>true</code> if the grid is visible or <code>false</code> if not
*
* @return true or false
*/
public boolean isGridVisible(){
return grid.isVisible();
}
/**
* sets the grid to the front
* that means that the grid is painted as last element
* default value is <code>false</code>
*
* @param aFlag grid t front or not
*/
public void setGridToFront( boolean aFlag ){
boolean old = grid_to_front;
grid_to_front = aFlag;
if( old != aFlag && grid.isVisible() ) repaint();
}
/**
* sets the grid's horizontal and vertical distance
* that means that the grid's lines will have these distances
* in area coordinates
*
* @param hor_dist the horizontal distance
* @param ver_dist the vertical distance
*/
public void setGrid( double hor_dist, double ver_dist ){
grid = new DGrid( visible_rect, hor_dist, ver_dist );
grid.setDParent( this );
auto_grid = false;
repaint();
}
/**
* sets the auto grid on or off
* if it's on, the grid's distances (@see #setGrid(double, double))
* are automatically calculated
*
* @param b auto grid on or not
*/
public void setAutoGrid( boolean b ){
if( b ) {
grid.rectangle = getDRectangle();
grid.setVisible( true );
}
if( b == auto_grid ) return;
auto_grid = b;
repaint();
}
/**
* returns if the auto grid is switched on
*
* @return true if the grid is on, else false
*/
public boolean hasAutoGrid(){ return auto_grid; }
/**
* sets the color of the grid
*
* @param java.awt.Color
*/
public void setGridColor( Color color ){
grid.setColor( color );
}
/**
* sets the maximal number of grid lines
* default value is 10
*
* @param no maximal number of grid lines
*/
public void setMaxGrid( int no ){
if( no < 1 ) return;
int old = max_grid;
max_grid = no;
if( old != no ) repaint();
}
/**
* prints the area and it's content
* @see java.awt.print.Printable and
* @see java.awt.print.PrintJob
*
* @param g the Graphics object
* @param pf the @see java.awt.print.PageFormat
* @param pi the page index
*
* @return int @see java.awt.print.Printable
*/
public int print( Graphics g, PageFormat pf, int pi ){
if( under_construction ) System.out.println("DArea.print(...)");
if( pi > 0 ) return Printable.NO_SUCH_PAGE;
Border sb = getBorder();
if( !(sb instanceof ScaledBorder) ) sb = null;
else ( (ScaledBorder)sb ).show_outer_border = false;
PagePrinter printer = new PagePrinter( this, g, pf );
int ret = printer.print();
if( sb != null ) ( (ScaledBorder)sb ).show_outer_border = true;
return ret;
}
/**
* sets a new scale function to the x-axis
* That means that not the standard linear scale is shown but the image
* of the linear scale under the given function
*
* @param x_s the scale function for the x-axis
*/
public void setXScale( DFunction x_s ){
if( x_s == null && measures.x_scale == null ) return;
measures.x_scale = x_s;
repaint();
}
/**
* sets a new scale function to the y-axis
* That means that not the standard linear scale is shown but the image
* of the linear scale under the given function
*
* @param y_s the scale function for the y-axis
*/
public void setYScale( DFunction y_s ){
if( y_s == null && measures.y_scale == null ) return;
measures.y_scale = y_s;
repaint();
}
/**
* returns the measures of the DArea
* The DMeasures object calculates the different coodinates and contains a
* Graphics object to paint the DElements of the area
*
* @return the measures of the DArea
*/
public DMeasures getDMeasures(){
return measures;
}
/**
* method 'adds' a certain border around the contained rectangle
* that means that it takes the old border
* and takes the maxima of the old and the new values
*
* @param clip the java.awt.Insets object of the new clip
*/
public void addDBorder( DBorder b ){
dborder.insert(b);
}
/**
* method returns the current border around the rectangle
*
* @return the border
*/
public DBorder getDBorder(){
return dborder;
}
public void restoreBorder(){
dborder = container.getDBorder();
if( under_construction ) System.out.println("DArea.restoreBorder -> "+dborder);
}
/**
* method paints the grid
* how the method paints the grid depends on whether the area is wrapped in a
* <code>ScaledBorder</code> or not and on the auto_grid option
*/
private void paintGrid( DMeasures m ){
if( under_construction ) System.out.println("DArea.paintGrid(DMeasures)");
grid.rectangle = getDRectangle();
if( auto_grid ){
Border b = getBorder();
if( b instanceof ScaledBorder ){
ScaledBorder sb = (ScaledBorder)b;
paintGrid( sb, m );
return;
}
else{
grid.hor_dist = ScaledBorder.aBitBigger( grid.rectangle.width / max_grid );
grid.ver_dist = ScaledBorder.aBitBigger( grid.rectangle.height / max_grid );
}
}
grid.paint( m );
}
/**
* paints the grid when auto_grid is selected and the area is surrounded
* by an instance of ScaledBorder
*
* @param sb the ScaledBorder around the area
* @param m the measures of the area
*/
private void paintGrid(ScaledBorder sb, DMeasures m){
if( under_construction ) System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)");
Dimension d = getSize();
FontMetrics fm = m.getGraphics().getFontMetrics();
grid.hor_dist = sb.getSrcdX(fm, d);
grid.ver_dist = sb.getSrcdY(fm, d);
if( m.x_scale == null && m.y_scale == null ) grid.paint( m );
else{// selber malen
Graphics g = m.g;
g.setColor( grid.getColor() );
DRectangle rect = getDRectangle(),
src_rect = m.getSourceOf( rect );
int x = (int)(src_rect.x / grid.hor_dist),
y = (int)(src_rect.y / grid.ver_dist);
if( x * grid.hor_dist < src_rect.x ) x++;
if( y * grid.ver_dist < src_rect.y ) y++;
DPoint min = new DPoint( rect.x, rect.y ),
max = new DPoint( min.x + rect.width, min.y + rect.height );
double pos;
for( ; (pos = x * grid.hor_dist) < src_rect.x + src_rect.width; x++ ){
if( m.x_scale != null ) pos = m.x_scale.getImageOf( pos );
Point p1 = m.getPoint( pos, min.y ),
p2 = m.getPoint( pos, max.y );
g.drawLine( p1.x, p1.y, p2.x, p2.y );
}
for( ; (pos = y * grid.ver_dist) < src_rect.y + src_rect.height; y++ ){
if( m.y_scale != null ) pos = m.y_scale.getImageOf( pos );
Point p1 = m.getPoint( min.x, pos ),
p2 = m.getPoint( max.x, pos );
g.drawLine( p1.x, p1.y, p2.x, p2.y );
}
}
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,205 @@
package wsi.ra.chart2d;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
*/
/**
* This class stores an array of double values.
* It can be used as data stack for an DPointSet object.
* For that use, it is important to tell the DPoitSet object, when the data has
* been modified.
*/
public class DArray implements DIntDoubleMap{
private int initial_capacity, size;
private double capacity_multiplier = 2, max, min;
private double[] value;
/**
* Constructor for an DArray object with default values for the initial
* capacity (5) and the capacity multiplier (2).
*/
public DArray(){
this(5, 2);
}
/**
* Constructor for an DArray object with default value for the capacity
* multiplier (2).
*
* @param initial_capacity the initial capacity of the array
*/
public DArray(int initial_capacity){
this(initial_capacity, 2);
}
/**
* Constructor for an DArray object
*
* @param initial_capacity the initial capacity of the array
* @param capacity_multiplier the capacity multiplier when the array overflows
*/
public DArray(int initial_capacity, double capacity_multiplier){
if( initial_capacity < 1 ) throw
new IllegalArgumentException("The initial capacity has to be at least 1");
if( capacity_multiplier <= 1 ) throw
new IllegalArgumentException("The capacity multiplier has to be bigger than 1");
this.initial_capacity = initial_capacity;
value = new double[initial_capacity];
this.capacity_multiplier = capacity_multiplier;
}
/**
* method sets the image value to the given source value
*
* @param source the source value
* @param image the image value
*/
public boolean setImage(int source, double image){
if(source<0 || source>=size) throw
new ArrayIndexOutOfBoundsException(source);
boolean min_max_changed = false, restore = false;
if( image < min ){ min = image; min_max_changed = true; }
else if( image > max ){ max = image; min_max_changed = true; }
if( value[source] == min || value[source] == max ) restore = true;
value[source] = image;
if( restore ) min_max_changed = restore() || min_max_changed;
return min_max_changed;
}
/**
* method returns the image value of the given source value
*
* @param source the source value
* @return the image value
*/
// public double getImage(int source){
// if(source<0 || source>=size) throw
// new ArrayIndexOutOfBoundsException(source);
// return value[source];
// }
public double getImage(int source){
if(source<0) new ArrayIndexOutOfBoundsException(source);
if(source>=size && size > 1) return value[size-1];
return value[source];
}
/**
* the given image value becomes the image of (highest source value + 1)
*
* @param image the new image value
* @return <code>true<\code> when the minmal or the maximal image value
* has been changed by this method call, else it returns
* <code>false</code> @see #getMinImageValue(), #getMaxImageValue()
*/
public boolean addImage(double image){
if( size >= value.length ){
int new_length = (int)(value.length * capacity_multiplier);
if( !(new_length > value.length) ) new_length++;
double[] new_val = new double[new_length];
System.arraycopy(value,0,new_val,0,value.length);
value = new_val;
}
boolean min_max_changed = false;
if( size == 0 ){ min = image; max = image; min_max_changed = true;}
else
if( image > max ) { max = image; min_max_changed = true; }
else if( image < min ) { min = image; min_max_changed = true; }
value[size++] = image;
return min_max_changed;
}
/**
* method returns the number of (source,image)-pairs stored in the array
*
* @return the size of the source value set
*/
public int getSize(){
return size;
}
/**
* this method checks if the minimal and the maximal image value has changed
*
* @return <code>true</code> if one of them changed
*/
public boolean restore(){
if( size == 0 ) return false;
double old_min = min, old_max = max;
min = value[0];
max = value[0];
for( int i=1; i<size; i++ )
if( value[i] < min ) min = value[i];
else if( value[i] > max ) max = value[i];
return (old_min != min) || (old_max != max);
}
/**
* throws all information away
*/
public void reset(){
size = 0;
value = new double[initial_capacity];
}
/**
* returns the minmal image value
*
* @return the minmal image value
*/
public double getMinImageValue(){
if( size == 0 ) throw
new IllegalArgumentException("DArray is empty. No minimal value exists");
return min;
}
/**
* returns the maxmal image value
*
* @return the maxmal image value
*/
public double getMaxImageValue(){
if( size == 0 ) throw
new IllegalArgumentException("DArray is empty. No maximal value exists");
return max;
}
/**
* method checks if the given object is equal to this DArray object.
* It looks for differences in the stored image values
*
* @param o the object to compare with
* @return <code>true</code> when the object is an DArray object, containing
* the same values
*/
public boolean equals(Object o){
if( !(o instanceof DArray) ) return false;
DArray comp = (DArray)o;
if( comp.size != size ) return false;
if( comp.max != max ) return false;
if( comp.min != min ) return false;
for( int i=0; i<size; i++ )
if( comp.value[i] != value[i] ) return false;
return true;
}
public String toString(){
String text = "wsi.ra.chart2d.DArray[size:"+size;
if( size < 11 )
for( int i=0; i<size; i++ ) text += ", "+value[i];
text += "]";
return text;
}
public double[] toArray(double[] v){
if( v == null || v.length < size ) v = new double[size];
System.arraycopy(value,0,v,0,size);
return v;
}
}

View File

@@ -0,0 +1,45 @@
/**
* Filename: $RCSfile: DBorder.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
import java.awt.Insets;
public class DBorder extends Insets{
public DBorder(){
this( 0, 0, 0, 0 );
}
public DBorder(int top, int left, int bottom, int right ){
super( top, left, bottom, right );
}
public boolean insert( DBorder b ){
boolean changed = false;
if( b.top > top ){ top = b.top; changed = true; }
if( b.bottom > bottom ){ bottom = b.bottom; changed = true; }
if( b.left > left ){ left = b.left; changed = true; }
if( b.right > right ){ right = b.right; changed = true; }
return changed;
}
public boolean equals( Object o ){
if( o instanceof DBorder )
return super.equals( o );
return false;
}
public String toString(){
return "wsi.ra.chart2d.DBorder[top="+top+",left="+left
+",bottom="+bottom+",right="+right+"]";
}
}

View File

@@ -0,0 +1,159 @@
/**
* Filename: $RCSfile: DComponent.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Color ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* <code>DComponent</code> is the mother of all objects which can be displayed
* by a <code>DArea</code> object, even when it would be also enough to
* implement the <code>DElement</code> interface to an class
*
* DComponent is abstract because the paint method has to be overridden
*/
public abstract class DComponent implements DElement
{
/**
* the color of the component
*/
protected Color color;
/**
* the rectangle in which the component lies
*/
protected DRectangle rectangle;
/**
* the parent of the component which is responsible for repainting
*/
protected DParent parent;
private boolean visible = true;
/**
* this border respresents the additional space around the clip of the
* graphics context, which is calculated by the union of all DRectangles of
* the components. For example it is used by DPointIcons or DLabels.
*/
private DBorder border = new DBorder();
/**
* this constructor is necessary to avoid infinite loops in constructing
* DRectangles
*/
DComponent(boolean is_rect){}
public DComponent(){ rectangle = DRectangle.getEmpty(); }
/**
* returns the rectangle in which the object lies
*/
public DRectangle getRectangle(){
return (DRectangle)rectangle.clone();
}
/**
* method sets a certain border around the contained rectangle
*
* @param b the new DBorder
*/
public void setDBorder( DBorder b ){
if( parent != null ) {
if( border.insert(b) ) { parent.addDBorder( b ); repaint(); }
else { border = b; parent.restoreBorder(); }
}
else border = b;
}
/**
* method returns the current border around the rectangle
*
* @return the DBorder of the DComponent
*/
public DBorder getDBorder(){
return border;
}
/**
* sets the parent of the component, which should take care of painting the
* component to the right time
*/
public void setDParent( DParent parent ){
if( this.parent != null && this.parent != parent ){
this.parent.removeDElement( this );
this.parent.repaint( getRectangle() );
}
this.parent = parent;
}
/**
* returns the parent of the component
*/
public DParent getDParent(){ return parent; }
/**
* invoces the parent to repaint the rectangle in which the component lies
*/
public void repaint(){
//System.out.println("DComponent.repaint()");
if( parent != null ) parent.repaint( getRectangle() );
}
/**
* sets the color of the component
*/
public void setColor( Color color ){
if( this.color == null || !this.color.equals( color ) ) {
this.color = color;
repaint();
}
}
/**
* returns the color of the component
*/
public Color getColor(){ return color; }
/**
* sets the component visible or not
*/
public void setVisible( boolean aFlag ){
boolean changed = ( aFlag != visible );
visible = aFlag;
if( changed ) repaint();
}
/**
* returns if the component should be visible when the parent shows the right
* area
*/
public boolean isVisible(){ return visible; }
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,223 @@
/**
* Filename: $RCSfile: DContainer.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.util.Vector ;
import java.awt.Color ;
import java.awt.Graphics;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DContainer extends DComponent implements DParent{
/**
* the elements of the container and their keys ( Strings )
*/
protected Vector elements, keys;
public DContainer(){ this(10); }
public DContainer(int initial_capacity){
super();
elements = new Vector(initial_capacity);
keys = new Vector(initial_capacity);
}
public void repaint( DRectangle r ){
DParent parent = getDParent();
if( parent != null ) parent.repaint( r );
}
/**
* method adds a new DElement to the container
* if the container already contains this element, the method simply returns
* the method checks whether the DElement is an ancestor of the container
* itself. In that case it throws an IllegalArgumentException.
*
* @param e the new DElement to add
*/
public void addDElement( DElement e ){
addDElement( null, e );
}
/**
* method adds a new DElement to the container by a certain key name
* if the container already contains this element, the method simply returns
* the method checks whether the DElement is an ancestor of the container
* itself. In that case it throws an IllegalArgumentException.
*
* @param key the name of the DElement in the container
* @param e the new DElement to add
*/
public void addDElement( String key, DElement e ){
if( elements.contains( e ) ) return;
if( e instanceof DParent ){
DParent he = (DParent)e, me = (DParent)this;
if( he == me ) throw new
IllegalArgumentException("Adding DParent to itself");
me = getDParent();
while( me != null ){
if( he == me )throw new
IllegalArgumentException("Adding DContainer's parent to itself");
if( me instanceof DElement )
me = ((DElement)me).getDParent();
else me = null;
}
}
elements.add( e );
addDBorder( e.getDBorder() );
keys.add( key );
e.setDParent( this );
DRectangle r = e.getRectangle();
rectangle.insert( r );
if( e.isVisible() ) repaint( r );
}
/**
* method removes a certain DElement from the container an returns whether it
* contained it before
*
* @param e the DElement to remove
* @return if this was possible
*/
public boolean removeDElement( DElement e ){
int index = elements.indexOf( e );
if( index > -1 ){
elements.remove( index );
keys.remove( index );
repaint( e.getRectangle() );
restore();
return true;
}
return false;
}
/**
* method removes all DElements from the container
*/
public void removeAllDElements()
{
elements.removeAllElements();
keys.removeAllElements();
rectangle = DRectangle.getEmpty();
repaint();
}
/**
* method returns all DElements of the container
*
* @return the elements of the container
*/
public DElement[] getDElements(){
DElement[] es = new DElement[ elements.size() ];
elements.toArray(es);
return es;
}
/**
* method returns the first DElement of the contaioner belonging to
* the given key
*
* @param key the name of the DElement in the container
* @return the element when it could be found or null else
*/
public DElement getDElement( String key ){
int index = -1;
for( int i=0; index == -1 && i < keys.size(); i++ )
if( ((String)keys.get(i)).equals( key ) ) index = i;
return (index<keys.size())? (DElement)elements.get(index):(DElement)null;
}
// implementing DComponent:
/**
* method calls all currently visible DElements of the container to paint
* themselves by the given DMeasures object
*
* @param m the DMeasures object
*/
public void paint( DMeasures m ){
DElement e;
for( int i=0; i<elements.size(); i++ ){
e = (DElement)elements.elementAt(i);
if( e.isVisible() && !m.getDRectangle().getIntersection( e.getRectangle() ).isEmpty()){
m.g.setColor( DEFAULT_COLOR );
e.paint( m );
}
}
}
/**
* method returns true, if the given element is contained in the container
*
* @param e the element
* @return if it is contained
*/
public boolean contains( DElement e ){
return elements.contains( e );
}
/**
* method sets the given color to all contained DElements of the container
*
* @param c the new Color of the elements
*/
public void setColor(Color c){
for( int i=0; i<elements.size(); i++ )
((DElement)elements.get(i)).setColor(c);
super.setColor(c);
}
/**
* method adds the given border to the current border of the container
* that means, that if necessary it will enlarge it and tells it to its
* parent
*
* @param b the border to add
*/
public void addDBorder(DBorder b){
if( getDBorder().insert(b) && parent != null ) parent.addDBorder(b);
}
public void restoreBorder(){
DBorder b = new DBorder();
for( int i=0; i<elements.size(); i++ )
b.insert( ((DElement)elements.get(i)).getDBorder() );
setDBorder( b );
}
/**
* restores the container, that means that the rectangle is completely new calculated
* this method is used after removing one of the elements
*/
boolean restore(){
DRectangle old = (DRectangle)rectangle.clone();
rectangle = DRectangle.getEmpty();
setDBorder( new DBorder() );
for( int i=0; i<elements.size(); i++ ){
DElement elt = (DElement)elements.elementAt(i);
rectangle.insert(elt.getRectangle());
addDBorder( elt.getDBorder() );
}
return !old.equals( rectangle );
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,51 @@
/**
* Filename: $RCSfile: DElement.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Color ;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
* some useful methods for objects which should be paintable in a scaled area
*/
public interface DElement
{
Color DEFAULT_COLOR = Color.black;
DRectangle getRectangle();
void setDParent( DParent parent );
DParent getDParent();
void paint( DMeasures m );
void repaint();
void setVisible( boolean aFlag );
boolean isVisible();
void setColor( Color color );
Color getColor();
void setDBorder( DBorder b );
DBorder getDBorder();
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,63 @@
/**
* Filename: $RCSfile: DFunction.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Point ;
import java.awt.Color ;
import java.awt.Graphics ;
/*==========================================================================*
* ABSTRACT CLASS DECLARATION
*==========================================================================*/
public abstract class DFunction extends DComponent
{
public DFunction(){
rectangle = DRectangle.getAll();
}
public abstract boolean isDefinedAt( double source );
public abstract boolean isInvertibleAt( double image );
public abstract double getSourceOf( double image ) throws IllegalArgumentException;
public abstract double getImageOf( double source ) throws IllegalArgumentException;
public void paint( DMeasures m ){
Graphics g = m.getGraphics();
if( color != null ) g.setColor( color );
DRectangle rect = m.getDRectangle(),
src_rect = m.getSourceOf( rect );
Point sw = m.getPoint( rect.x, rect.y ),
ne = m.getPoint( rect.x + rect.width, rect.y + rect.height );
int int_w = ne.x - sw.x;
Point last = null, next;
for( int i = 0; i < int_w; i++ ){
double x_val = src_rect.x + i / (double)int_w * src_rect.width ;
if( m.x_scale != null ) x_val = m.x_scale.getImageOf( x_val );
if( isDefinedAt( x_val ) ){
next = m.getPoint( x_val, getImageOf( x_val ) );
if( last != null ) g.drawLine( last.x, last.y, next.x, next.y );
last = next;
}
else last = null;
}
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,115 @@
/**
* Filename: $RCSfile: DGrid.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Color ;
import java.awt.Graphics ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* this class paints a grid with certain line distances on a DParent
*/
public class DGrid extends DComponent
{
/**
* the distances between the lines
*/
double hor_dist, ver_dist;
private Color DEFAULT_COLOR = Color.lightGray;
/**
* constructor with the size and position of the grid and the line distances
*
* @param rectangle the rectangle around the grid
* @param hor_dist the horizontal distance between the lines in D-coordinates,
* not in pixel coordinates!
* @param ver_dist vertical distance between the lines in D-coordinates,
* not in pixel coordinates!
*/
public DGrid( DRectangle rectangle, double hor_dist, double ver_dist ){
this.rectangle = rectangle;
this.hor_dist = hor_dist;
this.ver_dist = ver_dist;
color = DEFAULT_COLOR;
}
/**
* constructor with the size and position of the grid and the line distances
*
* @param rectangle the rectangle around the grid
* @param hor_dist the horizontal distance between the lines in D-coordinates,
* not in pixel coordinates!
* @param ver_dist the vertical distance between the lines in D-coordinates,
* not in pixel coordinates!
* @param color the color of the grid
* ( can also be set by setColor( java.awt.Color ) )
*/
public DGrid( DRectangle rectangle, double hor_dist, double ver_dist, Color color ){
this.rectangle = rectangle;
this.hor_dist = hor_dist;
this.ver_dist = ver_dist;
this.color = color;
}
/**
* paints the grid...
*
* @param m the <code>DMeasures</code> object to paint the grid
*/
public void paint( DMeasures m ){
Graphics g = m.getGraphics();
if( color != null ) g.setColor( color );
double minX, minY, pos;
DPoint p1, p2;
DLine l;
minX = (int)( rectangle.x / hor_dist );
if( minX * hor_dist <= rectangle.x ) minX++;
minX *= hor_dist;
minY = (int)( rectangle.y / ver_dist );
if( minY * ver_dist <= rectangle.y ) minY++;
minY *= ver_dist;
p1 = new DPoint( 0, rectangle.y );
p2 = new DPoint( 0, rectangle.y + rectangle.height );
for( pos = minX; pos<=rectangle.x + rectangle.width; pos += hor_dist ){
p1.x = p2.x = pos;
l = new DLine( p1, p2, color );
l.paint( m );
}
p1.x = rectangle.x;
p2.x = p1.x + rectangle.width;
for( pos = minY; pos<=rectangle.y + rectangle.height; pos += ver_dist ){
p1.y = p2.y = pos;
l = new DLine( p1, p2, color );
l.paint( m );
}
}
public String toString(){
return "chart2d.DGrid[ hor: "+hor_dist+", ver: "+ver_dist+" ]";
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,88 @@
package wsi.ra.chart2d;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
*/
/**
* This interface is used by DPointSet to store values as images of integer
* values which can be displayed in a DArea. All modifications of the values can
* only be shown by the DArea, when the DPointSet.repaint method is
* called. This should be done in the implementation of the #setImage and
* #addImage method. To get the functionality of the DArea, the methods
* #getMaxImageValue and #getMinImageValue are necessary.
*/
public interface DIntDoubleMap {
/**
* implementation should change the map in that way, that from now the
* image of index is v
*
* @param source the preimage of the image
* @param image the new image of the source value
* @return <code>true<\code> when the minmal or the maximal image value
* has been changed by this method call, else it returns
* <code>false</code> @see #getMinImageValue(), #getMaxImageValue()
*/
boolean setImage(int source, double image);
/**
* implementation should return the image of source
*
* @param source the preimage
* @return the image value
*/
double getImage(int source);
/**
* the image of the highest source value + 1 should be the given image value
*
* @param image the new image value
* @return <code>true<\code> when the minmal or the maximal image value
* has been changed by this method call, else it returns
* <code>false</code> @see #getMinImageValue(), #getMaxImageValue()
*/
boolean addImage(double image);
/**
* implementation should return the number of source values
*
* @return the number of source values
*/
int getSize();
/**
* returns the maximal image value
*
* @return the maximal image value
* @throw an IllegalArgumentException when it has no image values
*/
double getMaxImageValue();
/**
* returns the minimal image value
*
* @return the minmal image value
* @throw an IllegalArgumentException when it has no image values
*/
double getMinImageValue();
/**
* checks the minimal and the maximal image values and returns <code>true</code>
* when at least one of them has changed
*
* @return <code>true</code> when either the maximal image value or the
* minmal image value has changed
*/
boolean restore();
/**
* method removes all image values and sets the size to 0
*/
void reset();
}

View File

@@ -0,0 +1,70 @@
/**
* Filename: $RCSfile: DLine.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DLine extends DComponent
{
DPoint start, end;
public DLine( double x1, double y1, double x2, double y2 ){
this( new DPoint( x1, y1 ), new DPoint( x2, y2 ) );
}
public DLine( DPoint start, DPoint end ){
this.start = start;
this.end = end;
}
public DLine( double x1, double y1, double x2, double y2, Color color ){
this( new DPoint( x1, y1 ), new DPoint( x2, y2 ), color );
}
public DLine( DPoint start, DPoint end, Color color ){
this.start = start;
this.end = end;
this.color = color;
}
public DRectangle getRectangle(){
double x = start.x, y = start.y, width = end.x - x, height = end.y - y;
if( width < 0 ) { x += width; width *= -1; }
if( height < 0 ) { y += height; height *= -1; }
return new DRectangle( x, y, width, height );
}
public void paint( DMeasures m ){
//System.out.println("DLine.paint(Measures): "+this);
Graphics g = m.getGraphics();
if( color != null ) g.setColor( color );
Point p1 = m.getPoint( start ),
p2 = m.getPoint( end ) ;
g.drawLine( p1.x, p1.y, p2.x, p2.y );
}
public String toString(){
return "DLine[("+start.x+","+start.y+") --> ("+end.x+","+end.y+", color: "+color+"]";
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,274 @@
/**
* Filename: $RCSfile: DMeasures.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Point ;
import java.awt.Graphics ;
import java.awt.Dimension ;
import java.awt.Insets ;
import java.awt.Component ;
//import javax.swing.JComponent ;
import java.io.Serializable;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DMeasures implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 243092480517044848L;
private boolean under_construction = false;
// when in use for a DArea:
Graphics g;
// when in use for a ScaledBorder:
ScaledBorder sb;
// for both:
DFunction x_scale, y_scale;
Component comp;
Insets insets;
/**
* package private constructor for the DMeasures object
* the object can be obtained by calling the method getDMeasures of an DArea
* object
*
* @param area the DArea object
*/
DMeasures( DArea area ){
comp = area;
}
DMeasures( ScaledBorder sb ){
this.sb = sb;
}
/**
* method returns the pixel-point which belongs to the DPoint in the
* D-coordinates
* it says where to paint a certain DPoint
* returns <code>null</code> if the double coordinates do not belong to the
* image of the scale functions
*
* @param p the DPoint
* @return the coresponding pixel Point
*/
public Point getPoint( DPoint p ){
//System.out.println("DMeasures.getPoint :"+org );
return getPoint( p.x, p.y );
}
/**
* method returns the pixel-point which belongs to the given D-coordinates
* it says where to paint a certain DPoint
* returns <code>null</code> if the double coordinates do not belong to the
* image of the scale functions
*
* @param x the double x D-coordinate
* @param y the double y D-coordinate
* @return the coresponding pixel Point
*/
public Point getPoint( double x, double y ){
DRectangle rect = getSourceOf( getDRectangle() );
try{
if( x_scale != null ) x = x_scale.getSourceOf( x );
if( y_scale != null ) y = y_scale.getSourceOf( y );
}
catch( IllegalArgumentException e ){ return null; }
Point dp = new Point();
Dimension dim = getInner();
Insets insets = getInsets();
dp.x = (int)( dim.width * (x - rect.x)/(double)rect.width ) + insets.left;
dp.y = (int)( dim.height * (1 - (y - rect.y)/(double)rect.height)) + insets.top;
return dp;
}
/**
* method returns the point in D-coordinates which corresponds to the
* given pixel-point
* returns <code>null</code> if the given coordinates can not be calculated to
* the double coordinates, when they represent a point outside of the definition
* area of the scale functions
*
* @param p Point in pixel coordinates
* @return the coresponding DPoint
*/
public DPoint getDPoint( Point p ){
return getDPoint( p.x, p.y );
}
/**
* method returns the point in D-coordinates which corresponds to the
* given pixel-coordinates
* returns <code>null</code> if the given coordinates can not be calculated to
* the double coordinates, when they represent a point outside of the definition
* area of the scale functions
*
* @param x x-pixel coordinate
* @param y y-pixel coordinate
* @return the coresponding DPoint
*/
public DPoint getDPoint( int x, int y ){
DRectangle rect = getSourceOf( getDRectangle() );
Dimension dim = getInner();
Insets insets = getInsets();
x -= insets.left;
y -= insets.top;
double dx, dy;
dx = rect.x + rect.width * x/(double)dim.width;
dy = rect.y + rect.height * (1 - y/(double)dim.height );
try{
if( x_scale != null ) dx = x_scale.getImageOf( dx );
if( y_scale != null ) dy = y_scale.getImageOf( dy );
}
catch( IllegalArgumentException nde ){ return null; }
return new DPoint( dx, dy );
}
/**
* returns the visible rectangle in D-coordinates of the shown component
*
* return the visible rectangle
*/
public DRectangle getDRectangle(){
if( under_construction ) System.out.println("DMeasures.getDRectangle");
if( sb != null ) return getImageOf( sb.src_rect );
return ((DArea)comp).getDRectangle();
}
/**
* returns the current Graphics object, which might be used by components to
* paint themselves
* the method sets the clipping area of the Graphics object to the currently
* visible rectangle
*
* @return the Graphics object ( or null if no object was set )
*/
public Graphics getGraphics(){
if( under_construction ) System.out.println("DMeasures.getGraphics");
if( g != null ){
Dimension d = comp.getSize();
Insets insets = getInsets();
g.setClip( insets.left + 1, // dann sieht man noch was von der linken Achse
insets.top,
d.width - insets.left - insets.right,
d.height - insets.top - insets.bottom);
}
return g;
}
/**
* used by DArea to set a new Graphics object
*/
void setGraphics( Graphics g ){
if( under_construction ) System.out.println("DMeasures.setGraphics");
this.g = g;
}
/**
* used by ScaledBorder to update the DMeasures object
*
* @param c the parent component the border
*/
void update( Component c, Insets insets ){
this.comp = c;
this.insets = insets;
x_scale = sb.x_scale;
y_scale = sb.y_scale;
}
private Dimension getInner(){
Dimension d = comp.getSize();
Insets insets = getInsets();
d.width -= insets.left + insets.right;
d.height -= insets.top + insets.bottom;
return d;
}
/**
* method returns the source rectangle of the given rectangle
* they differ if there are scale functions selected which are not the identity
* if the given rectangle does not belong to the image area of the scale
* functions, the method returns <code>null</code>
*
* @param rect the image rectangle
* @return the source of it
*/
DRectangle getSourceOf( DRectangle rect ){
if( under_construction ) System.out.println("DMeasures.getSourceOf: "+rect);
if( !getDRectangle().contains( rect ) ) throw
new IllegalArgumentException("The rectangle lies not in the currently painted rectangle");
if( x_scale == null && y_scale == null ) return rect;
if( rect.isEmpty() ) return (DRectangle)rect.clone();
DPoint p1 = new DPoint( rect.x, rect.y ),
p2 = new DPoint( rect.x + rect.width, rect.y + rect.height );
try{
if( x_scale != null ){
p1.x = x_scale.getSourceOf( p1.x );
p2.x = x_scale.getSourceOf( p2.x );
}
if( y_scale != null ){
p1.y = y_scale.getSourceOf( p1.y );
p2.y = y_scale.getSourceOf( p2.y );
}
}
catch( IllegalArgumentException nde ){ return null; }
return new DRectangle( p1.x, p1.y, p2.x - p1.x, p2.y - p1.y );
}
/**
* method returns the image rectangle of the given rectangle
* they differ if there are scale functions selected which are not the identity
* if the given rectangle does not belong to the defintion area of the scale
* functions, the method returns <code>null</code>
*
* @param rect the source rectangle
* @return the source of it
*/
DRectangle getImageOf( DRectangle rect ){
if( under_construction ) System.out.println("DMeasures.getImageOf: "+rect);
if( x_scale == null && y_scale == null ) return rect;
if( rect.isEmpty() ) return (DRectangle)rect.clone();
DPoint p1 = new DPoint( rect.x, rect.y ),
p2 = new DPoint( rect.x + rect.width, rect.y + rect.height );
try{
if( x_scale != null ){
p1.x = x_scale.getImageOf( p1.x );
p2.x = x_scale.getImageOf( p2.x );
}
if( y_scale != null ){
p1.y = y_scale.getImageOf( p1.y );
p2.y = y_scale.getImageOf( p2.y );
}
}
catch( IllegalArgumentException nde ){ return null; }
return new DRectangle( p1.x, p1.y, p2.x - p1.x, p2.y - p1.y );
}
private Insets getInsets(){
if( sb != null ) return insets;
return ((DArea)comp).getInsets();
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,34 @@
/**
* Filename: $RCSfile: DParent.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
import java.awt.Graphics;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
public interface DParent
{
void addDElement( DElement e );
boolean removeDElement( DElement e );
void repaint( DRectangle r );
DElement[] getDElements();
boolean contains( DElement e );
void addDBorder( DBorder b );
void restoreBorder();
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,99 @@
/**
* Filename: $RCSfile: DPoint.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:42 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DPoint extends DComponent
{
public double x, y;
public String label;
protected DPointIcon icon = null;
public DPoint( ){
}
public void initpoint( double x, double y ){
this.x = x;
this.y = y;
rectangle = new DRectangle( x, y, 0, 0 );
}
public DPoint( double x, double y ){
this.x = x;
this.y = y;
rectangle = new DRectangle( x, y, 0, 0 );
}
public void paint( DMeasures m ){
Graphics g = m.getGraphics();
if( color != null ) g.setColor( color );
Point dp = m.getPoint( this );
if( label != null ){
FontMetrics fm = g.getFontMetrics();
g.drawString( label,
dp.x - fm.stringWidth( label ) / 2,
dp.y + fm.getAscent()
);
}
if( icon == null )
g.drawRect( dp.x, dp.y, 1, 1 );
else{
g.translate( dp.x, dp.y );
icon.paint( g );
g.translate( -dp.x, -dp.y );
}
}
/**
* method sets an icon for a better displaying of the point
*
* @param icon the DPointIcon
*/
public void setIcon( DPointIcon icon ){
this.icon = icon;
if( icon == null ) setDBorder(new DBorder(1,1,1,1));
else setDBorder( icon.getDBorder() );
}
/**
* method returns the current icon of the point
*
* @return the DPointIcon
*/
public DPointIcon getIcon(){
return icon;
}
public Object clone(){
DPoint copy = new DPoint( x, y );
copy.color = color;
return copy;
}
public String toString(){
String text = "DPoint[";
if( label != null ) text += label+", ";
text += "x: "+x+", y: "+y+", color: "+color+"]";
return text;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,38 @@
package wsi.ra.chart2d;
/**
* Filename: $RCSfile: DPointIcon.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version:
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
import java.awt.Graphics;
/**
* A simple interface which can be used to paint certain icons at DPoints
* ( @see chart2d.DPoint.setIcon or chart2d.DPointSet.setIcon ).
* Different points may be easier recognized in a complex graph.
* The container does not guarantee that the whole icon is visible in the graph
* because the icon does not concern the DRectangle of the DElement.
*/
public interface DPointIcon {
/**
* this method has to be overridden to paint the icon. The point itself lies
* at coordinates (0, 0)
*/
void paint( Graphics g );
/**
* the border which is necessary to be paint around the DPoint that the whole
* icon is visible
*
* @return the border
*/
DBorder getDBorder();
}

View File

@@ -0,0 +1,350 @@
/**
* Filename: $RCSfile: DPointSet.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:42 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
import wsi.ra.tool.IntegerArrayList;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DPointSet extends DComponent
{
protected DPointIcon icon = null;
/*-------------------------------------------------------------------------*
* private member variables
*-------------------------------------------------------------------------*/
protected DIntDoubleMap x, y;
protected boolean connected;
protected Stroke stroke = new BasicStroke();
protected JumpManager jumper = new JumpManager();
/*-------------------------------------------------------------------------*
* constructor
*-------------------------------------------------------------------------*/
public DPointSet(){
this(10, 2);
}
public DPointSet( int initial_capacity ){
this(initial_capacity, 2);
}
public DPointSet( int initial_capacity, int length_multiplier ){
this( new DArray(initial_capacity, length_multiplier),
new DArray(initial_capacity, length_multiplier) );
}
public DPointSet(DIntDoubleMap x_values, DIntDoubleMap y_values){
if( x_values.getSize() != y_values.getSize() ) throw
new IllegalArgumentException(
"The number of x-values has to be the same than the number of y-values"
);
x = x_values;
y = y_values;
restore();
setDBorder(new DBorder(1,1,1,1));
}
/*-------------------------------------------------------------------------*
* public methods
*-------------------------------------------------------------------------*/
public void paint( DMeasures m ){
Graphics2D g = (Graphics2D)m.getGraphics();
g.setStroke(stroke);
if( color != null ) g.setColor( color );
int size = getSize();
if( connected && size > 1 ){
jumper.restore();
while( jumper.hasMoreIntervals() ){
int[] interval = jumper.nextInterval();
Point p1 = null, p2;
for( int i=interval[0]; i<interval[1]; i++ ){
p2 = m.getPoint( x.getImage(i), y.getImage(i) );
if( p1 != null)
g.drawLine( p1.x, p1.y, p2.x, p2.y );
if( icon != null ){
g.setStroke( new BasicStroke() );
g.translate(p2.x, p2.y);
icon.paint(g);
g.translate(-p2.x, -p2.y);
g.setStroke( stroke );
}
p1 = p2;
}
}
}
else{
Point p;
for( int i=0; i<size; i++ ){
p = m.getPoint( x.getImage(i), y.getImage(i) );
if( icon == null ){
g.drawLine(p.x - 1, p.y - 1, p.x + 1, p.y + 1);
g.drawLine(p.x + 1, p.y - 1, p.x - 1, p.y + 1);
}
else{
g.setStroke( new BasicStroke() );
g.translate(p.x, p.y);
icon.paint(g);
g.translate(-p.x, -p.y);
}
}
}
g.setStroke( new BasicStroke() );
}
public void addDPoint( DPoint p ){
x.addImage(p.x);
y.addImage(p.y);
rectangle.insert(p);
repaint();
}
public void addDPoint( double x, double y ){
addDPoint(new DPoint(x, y));
}
/**
* method causes the DPointSet to interupt the connected painting at the
* current position
*/
public void jump(){
jumper.addJump();
}
/**
* method removes all jump positions
* if the DPointSet is connected, all points will be painted connected to
* their following point
*/
public void removeJumps(){
jumper.reset();
}
/**
* method returns the DPoint at the given index
*
* @param index the index of the DPoint
* @return the DPoint at the given index
*/
public DPoint getDPoint( int index ){
if( index >= x.getSize() ) {
System.out.println("getDPoint() index"+index);
System.out.println("x.getSize() "+x.getSize());
throw new ArrayIndexOutOfBoundsException(index);
}
DPoint p = new DPoint( x.getImage( index ), y.getImage( index ) );
p.setIcon( icon );
p.setColor( color );
return p;
}
/**
* method puts the given DPoint at the given position in the set
*
* @param index the index of the point
* @param p the point to insert
*/
public void setDPoint( int index, DPoint p ){
if( index >= x.getSize() ) throw new ArrayIndexOutOfBoundsException(index);
rectangle.insert(p);
x.setImage(index,p.x);
y.setImage(index,p.y);
restore();
repaint();
}
/**
* method sets an icon for a better displaying of the point set
*
* @param icon the DPointIcon
*/
public void setIcon( DPointIcon icon ){
this.icon = icon;
if( icon == null ) setDBorder(new DBorder(1,1,1,1));
else setDBorder( icon.getDBorder() );
}
/**
* method returns the current icon of the point set
*
* @return the DPointIcon
*/
public DPointIcon getIcon(){
return icon;
}
/**
* method sets the stroke of the line
* if the points were not connected, they now will be connected
*
* @param s the new stroke
*/
public void setStroke( Stroke s ){
if( s == null ) s = new BasicStroke();
stroke = s;
repaint();
}
/**
* method returns the current stroke of the line
*
* @return the stroke
*/
public Stroke getStroke(){
return stroke;
}
public void setConnected( boolean aFlag ){
boolean changed = !( aFlag == connected );
connected = aFlag;
if( changed ) repaint();
}
public void removeAllPoints(){
if( x.getSize() == 0 ) return;
x.reset();
y.reset();
jumper.reset();
repaint();
rectangle = DRectangle.getEmpty();
}
public String toString(){
String text = "wsi.ra.chart2d.DPointSet[size:"+getSize();
for( int i=0; i<x.getSize(); i++ )
text += ",("+x.getImage(i)+","+y.getImage(i)+")";
text += "]";
return text;
}
/**
* method returns the index to the nearest <code>DPoint</code> in this <code>DPointSet</code>.
*
* @return the index to the nearest <code>DPoint</code>. -1 if no nearest <code>DPoint</code> was found.
*/
public int getNearestDPointIndex(DPoint point){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for( int i=0; i<x.getSize(); i++ ){
double dx = point.x - x.getImage(i);
double dy = point.y - y.getImage(i);
double dummy = dx*dx + dy*dy;
if (dummy < minValue){
minValue = dummy;
minIndex = i;
}
}
return minIndex;
}
/**
* method returns the nearest <code>DPoint</code> in this <code>DPointSet</code>.
*
* @return the nearest <code>DPoint</code>
*/
public DPoint getNearestDPoint(DPoint point){
int minIndex = getNearestDPointIndex(point);
if(minIndex == -1) return null;
else return new DPoint(x.getImage(minIndex), y.getImage(minIndex));
}
// public int getSize(){
// int size = x.getSize();
// if( size != y.getSize() ) throw
// new ArrayStoreException(
// "The number of x-values is not equal to the number of y-values.\n"
// +"The size of the DPointSet isn<73>t clear."
// );
// return size;
// }
/**
*
*/
public int getSize(){ // testhu
int size = x.getSize();
if( size <= y.getSize() )
return size;
return x.getSize();
}
protected void restore(){
if( getSize() == 0){
rectangle = DRectangle.getEmpty();
return;
}
double min_x = x.getMinImageValue(),
max_x = x.getMaxImageValue(),
min_y = y.getMinImageValue(),
max_y = y.getMaxImageValue();
rectangle = new DRectangle(min_x, min_y, max_x - min_x, max_y - min_y );
}
/**
* this class stores the jump positions (see this.jump)
*/
class JumpManager{
protected IntegerArrayList jumps = new IntegerArrayList();
protected int index = -1;
public void addJump(){
jumps.add(getSize());
}
public int[] nextInterval(){
int no_jumps = jumps.size();
if( index >= no_jumps ) throw
new ArrayIndexOutOfBoundsException("No more intervals in JumpManager");
int[] inter = new int[2];
if( index == -1 ) inter[0] = 0;
else inter[0] = jumps.get(index);
index++;
if( index < no_jumps ) inter[1] = jumps.get(index);
else inter[1] = getSize();
return inter;
}
public boolean hasMoreIntervals(){
return index < jumps.size();
}
public void restore(){
index = -1;
}
public void reset(){
index = -1;
jumps.clear();
}
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,207 @@
/**
* Filename: $RCSfile: DRectangle.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:42 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class DRectangle extends DComponent
{
public double x, y, width, height;
public static final int PART = 0, ALL = 1, EMPTY = 2;
protected int status;
protected Color fillColor;
private DRectangle( int status ){
super(true);
this.status = status;
}
public DRectangle( double x, double y, double width, double height ){
super(true);
this.x = x;
this.y = y;
if( width < 0 ) throw
new IllegalArgumentException("Width of a DRectangle has to be >= 0");
this.width = width;
if( height < 0 ) throw
new IllegalArgumentException("Height of a DRectangle has to be >= 0");
this.height = height;
status = PART;
}
public DRectangle getRectangle(){ return this; }
public void paint( DMeasures m ){
if( isEmpty() ) return;
Graphics g = m.getGraphics();
Color old_color = g.getColor();
DRectangle rect = m.getDRectangle();
rect = rect.getIntersection( this );
Point p1 = m.getPoint( rect.x, rect.y ),
p2 = m.getPoint( rect.x + rect.width, rect.y + rect.height );
if( fillColor != null ){
g.setColor( fillColor );
g.fillRect( p1.x, p2.y, p2.x - p1.x, p1.y - p2.y );
}
if( !isAll() ){
if( color != null ) g.setColor( color );
else g.setColor( DEFAULT_COLOR );
g.drawRect( p1.x, p2.y, p2.x - p1.x, p1.y - p2.y );
}
g.setColor( old_color );
}
public boolean contains( DPoint p ){
if( status == ALL ) return true;
if( status == EMPTY ) return false;
if( p.x < x ) return false;
if( p.y < y ) return false;
if( p.x > x + width ) return false;
if( p.y > y + height ) return false;
return true;
}
public boolean contains( DRectangle rect ){
if( status == ALL || rect.isEmpty() ) return true;
if( status == EMPTY || rect.isAll() ) return false;
if( !contains( new DPoint( rect.x, rect.y ) ) ) return false;
if( !contains( new DPoint( rect.x + rect.width, rect.y + rect.height ) ) ) return false;
return true;
}
public DRectangle getIntersection( DRectangle r ){
if( status == ALL ) return (DRectangle)r.clone();
if( status == EMPTY ) return DRectangle.getEmpty();
if( r.status == ALL ) return (DRectangle)clone();
if( r.status == EMPTY ) return DRectangle.getEmpty();
DRectangle s = (DRectangle)this.clone();
if( s.x < r.x ){
s.x = r.x;
s.width -= r.x - s.x;
}
if( s.y < r.y ){
s.y = r.y;
s.height -= r.y - s.y;
}
if( s.x + s.width > r.x + r.width )
s.width = r.x + r.width - s.x;
if( s.y + s.height > r.y + r.height )
s.height = r.y + r.height - s.y;
if( s.width < 0 || s.height < 0 ) return DRectangle.getEmpty();
else return s;
}
/**
* method resizes the rectangle to insert p
*
* @param the dPoint p to insert
* @return true when the size of the rectangle changed
*/
public boolean insert( DPoint p ){
if( p.x == Double.NaN || p.y == Double.NaN ) return false;
if( isAll() ) return false;
if( contains( p ) ) return false;
if( isEmpty() ){
x = p.x; y = p.y; width = height = 0;
status = PART;
return true;
}
if( p.x < x ) {
width += x - p.x;
x = p.x;
}
else if( p.x > x + width ) width = p.x - x;
if( p.y < y ) {
height += y - p.y;
y = p.y;
}
else if( p.y > y + height ) height = p.y - y;
return true;
}
/**
* method inserts the given rectangle to this instance of it
* and returns true when the size changed
*
* @param rect the rectangle to inserts
* @return true if the size changed
*/
public boolean insert( DRectangle rect ){
if( isAll() || rect.isEmpty() ) return false;
if( rect.isAll() ){ status = ALL; return true; }
if( isEmpty() ){
x = rect.x; y = rect.y; width = rect.width; height = rect.height;
status = PART;
return true;
}
boolean changed = false;
changed = insert( new DPoint( rect.x, rect.y ) );
changed = insert( new DPoint( rect.x + rect.width, rect.y + rect.height ) )? true : changed;
return changed;
}
public Object clone(){
DRectangle copy = new DRectangle( x, y, width, height );
copy.status = status;
if( color != null ) copy.color = new Color( color.getRGB() );
return copy;
}
public String toString(){
String text = "DRectangle[ ";
switch( status ){
case ALL : text += "all"; break;
case EMPTY : text += "empty"; break;
case PART : text += x+", "+y+", "+width+", "+height;
}
text += " ]";
return text;
}
public boolean equals( DRectangle r ){
if( r.status != status ) return false;
if( r.x != x ) return false;
if( r.y != y ) return false;
if( r.width != width ) return false;
if( r.height != height ) return false;
return true;
}
public void setFillColor( Color fill_color ){
if( fillColor == null || !fillColor.equals( fill_color ) ){
fillColor = fill_color;
repaint();
}
}
public Color getFillColor(){
return fillColor;
}
public static DRectangle getAll(){ return new DRectangle( ALL ); }
public boolean isAll(){ return status == ALL; }
public static DRectangle getEmpty(){ return new DRectangle( EMPTY ); }
public boolean isEmpty(){ return status == EMPTY; }
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,493 @@
/**
* Filename: $RCSfile: ScaledBorder.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:42 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.chart2d;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
import javax.swing.BorderFactory;
import javax.swing.border.* ;
import java.awt.geom.AffineTransform ;
import java.text.NumberFormat;
import java.text.DecimalFormat;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* ScaledBorder puts an border around Components
* ( especially around DrawingAreas ) with scaled and labeled axes
*/
public class ScaledBorder implements Border
{
private boolean under_construction = false;
/**
* length of the distance markers on the axes in pixels
*/
int marker_length = 2;
/**
* length in pixels of the arrows at the ends of the axes
*/
int arrow_length = 10;
/**
* a flag if the arrows should be visible
*/
public boolean show_arrows = true;
/**
* distance between the x-values in digits
*/
int x_value2value = 2;
/**
* distance between y-label and y-values in digit width
*/
int y_label2values = 1;
/**
* distance between y-values and y-axis markers in parts of the digit width
*/
int y_values2marker = 2;
/**
* distance between values and arrows in pixels
*/
int x_values2arrow = 10,
y_values2arrow = 10;
/**
* distance between arrows and outer border
*/
int axis2border = 4;
/**
* distance between labels and the border in pixels
*/
public int x_label2border = 6,
y_label2border = 6;
/**
* the size of the source rectangle
* that means before the values are mdified by scale functions
*/
DRectangle src_rect;
/**
* the minimal increment of the scales
*/
public double minimal_increment;
/**
* the displayed labels
*/
public String x_label, y_label;
/**
* foreground and background colors
*/
public Color foreground, background;
/**
* the border which is shown around the scaled border
*/
Border outer_border;
/**
* flag if the outer border should be displayed
*/
boolean show_outer_border = true;
/**
* scale functions if, for example, an logarithmic function is needed instead
* of a linear.
*/
public DFunction x_scale, y_scale;
/**
* formatters of the x- and y-axis numbers
* @see java.text.NumberFormat
*/
public NumberFormat format_x = new DecimalFormat(),
format_y = new DecimalFormat();
private double src_dX = -1, src_dY = -1;
private boolean do_refresh,
auto_scale_x = true,
auto_scale_y = true;
private Insets old_insets;
private DMeasures m;
/**
* constructor creates a default ScaledBorder inside of a lowered BevelBorder
*/
public ScaledBorder(){
this(
BorderFactory.createBevelBorder(
BevelBorder.LOWERED,
Color.white,
Color.lightGray,
Color.black,
Color.lightGray
)
);
}
/**
* constructor creates a new <code>ScaledBorder<code/>
* surrounded by the specified <code>Border<code/>
*/
public ScaledBorder( Border outer ){
outer_border = outer;
m = new DMeasures( this );
}
/**
* method tells the border to calculate the differences between displayed
* x-values by itself
*/
public void setAutoScaleX(){ auto_scale_x = true; }
/**
* method tells the border to calculate the differences between displayed
* y-values by itself
*/
public void setAutoScaleY(){ auto_scale_y = true; }
/**
* method sets the differences between source x-values of the displayed values
* @see setAutoScaleX().
* If scale functions are used there might be a difference between the shown values
* and the source values
*/
public void setSrcdX(double dX){
auto_scale_x = false;
src_dX = dX;
}
/**
* method sets the differences between source y-values of the displayed values
* @see setAutoScaleY().
* If scale functions are used there might be a difference between the shown values
* and the source values
*/
public void setSrcdY(double dY){
auto_scale_y = false;
src_dY = dY;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height){
if( under_construction ) System.out.println("ScaledBorder.paintBorder()");
if( foreground == null ) foreground = c.getForeground();
if( background == null ) background = c.getBackground();
Color old_color = g.getColor();
g.setColor( background );
g.fillRect( x, y, width, height );
g.setColor( old_color );
Insets outer_insets = new Insets( 0, 0, 0, 0);// insets of the outer border
if( show_outer_border ) {
outer_border.paintBorder( c, g, x, y, width, height );
outer_insets = outer_border.getBorderInsets( c );
}
do_refresh = true;
Insets inner_insets = getBorderInsets(c);
Dimension d = c.getSize(),
cd = new Dimension( d.width - inner_insets.left - inner_insets.right,
d.height - inner_insets.top - inner_insets.bottom );
FontMetrics fm = g.getFontMetrics();
int fontAsc = fm.getAscent();
do_refresh = false;
m.update(c, inner_insets);
// axes
g.setColor( foreground );
g.drawLine( inner_insets.left, inner_insets.top,
inner_insets.left, inner_insets.top + cd.height );
g.drawLine( inner_insets.left, inner_insets.top + cd.height,
inner_insets.left + cd.width, inner_insets.top + cd.height );
if( show_arrows ){
g.drawLine( inner_insets.left, inner_insets.top,
inner_insets.left, inner_insets.top - y_values2arrow );
g.drawLine( inner_insets.left - marker_length, inner_insets.top - y_values2arrow,
inner_insets.left, inner_insets.top - y_values2arrow - arrow_length );
g.drawLine( inner_insets.left + marker_length, inner_insets.top - y_values2arrow,
inner_insets.left, inner_insets.top - y_values2arrow - arrow_length);
g.drawLine( inner_insets.left - marker_length, inner_insets.top - y_values2arrow,
inner_insets.left + marker_length, inner_insets.top - y_values2arrow );
g.drawLine( inner_insets.left + cd.width , inner_insets.top + cd.height,
inner_insets.left + cd.width + x_values2arrow, inner_insets.top + cd.height );
g.drawLine( inner_insets.left + cd.width + x_values2arrow,
inner_insets.top + cd.height - marker_length,
inner_insets.left + cd.width + x_values2arrow + arrow_length,
inner_insets.top + cd.height );
g.drawLine( inner_insets.left + cd.width + x_values2arrow,
inner_insets.top + cd.height + marker_length,
inner_insets.left + cd.width + x_values2arrow + arrow_length,
inner_insets.top + cd.height );
g.drawLine( inner_insets.left + cd.width + x_values2arrow,
inner_insets.top + cd.height - marker_length,
inner_insets.left + cd.width + x_values2arrow,
inner_insets.top + cd.height + marker_length );
}
if( y_label != null ) {
Dimension yld = new Dimension(fm.getAscent()+fm.getDescent(), fm.stringWidth(y_label));
AffineTransform T = new AffineTransform(0, -1, 1, 0, 0, 0);
Font old = g.getFont(), f = old.deriveFont( T );
g.setFont( f );
g.drawString( y_label, y_label2border + fm.getAscent(), inner_insets.top + ( cd.height + yld.height )/ 2 );
g.setFont( old );
}
if( x_label != null )
g.drawString(
x_label, inner_insets.left + ( cd.width - fm.stringWidth( x_label ) ) / 2,
d.height - outer_insets.bottom - x_label2border - fm.getDescent() );
if( src_rect.x == 0 && src_rect.y == 0 ){
int v2m = fm.stringWidth("0") / y_values2marker;
g.drawString( "0", inner_insets.left - fm.stringWidth( "0" ) - v2m - marker_length,
inner_insets.top + cd.height + fontAsc );
g.drawLine( inner_insets.left, inner_insets.top + cd.height + fm.getAscent(),
inner_insets.left, inner_insets.top + cd.height);
g.drawLine( inner_insets.left, inner_insets.top + cd.height,
inner_insets.left - fm.stringWidth( "0" ) - v2m - marker_length,
inner_insets.top + cd.height );
}
drawYValues( g, inner_insets, cd );
drawXValues( g, inner_insets, cd );
g.setColor( old_color );
}
private void drawYValues( Graphics g, Insets insets, Dimension cd ){
if( under_construction ) System.out.println("ScaledBorder.drawYValues()");
FontMetrics fm = g.getFontMetrics();
int n, fontAsc = fm.getAscent(), v2m = fm.stringWidth("0") / y_values2marker;
n = (int)( src_rect.y / src_dY );
if( n * src_dY < src_rect.y || ( src_rect.x == 0 && src_rect.y == 0 ) ) n++;
double v, minx = src_rect.x;
if( x_scale != null ) minx = x_scale.getImageOf( minx );
for(; (v = n * src_dY) <= src_rect.y + src_rect.height; n++ ){
if( y_scale != null ) v = y_scale.getImageOf( v );
String text = format_y.format(v);
try{ v = format_y.parse(text).doubleValue(); }
catch( java.text.ParseException ex ){ }
Point p = m.getPoint( minx, v );
if( p != null ){
g.drawString( text,
insets.left - fm.stringWidth( text ) - v2m - marker_length,
p.y + fontAsc / 2 );
g.drawLine( insets.left - marker_length, p.y, insets.left, p.y );
}
}
}
public double getSrcdY( FontMetrics fm, Dimension cd ){
if( under_construction ) System.out.println("ScaledBorder.getSrcdY()");
if( (!do_refresh && src_dY != -1) || !auto_scale_y ) return src_dY;
int max = cd.height / fm.getHeight();
double minsrc_dY = 2 * src_rect.height / (double)max; // die 2 einfach mal so eingesetzt <--------------------------
src_dY = aBitBigger( minsrc_dY );
if( src_dY < minimal_increment ) src_dY = minimal_increment;
return src_dY;
}
private void drawXValues( Graphics g, Insets insets, Dimension cd ){
if( under_construction ) System.out.println("ScaledBorder.drawXValues()");
FontMetrics fm = g.getFontMetrics();
double mx = cd.width / src_rect.width;
int n, labelX,
xnull = insets.left + (int)( - src_rect.x * mx );
n = (int)( src_rect.x / src_dX );
if( n * src_dX < src_rect.x || ( src_rect.x == 0 && src_rect.y == 0 ) ) n++;
int fontAsc = fm.getAscent(), xLineY = insets.top + cd.height;
labelX = xnull + (int)(n * src_dX * mx);
while( n * src_dX <= src_rect.x + src_rect.width ){
double v = n * src_dX;
if( x_scale != null ) v = x_scale.getImageOf(v);
String text = format_x.format(v);
try{ v = format_x.parse(text).doubleValue(); }
catch( java.text.ParseException ex ){ }
int strW = fm.stringWidth( text );
g.drawString( text, labelX - strW / 2, xLineY + fontAsc );
g.drawLine( labelX, xLineY, labelX, xLineY + marker_length );
n++;
labelX = xnull + (int)( n * src_dX * mx);
}
}
public double getSrcdX( FontMetrics fm, Dimension cd ){
if( under_construction ) System.out.println("ScaledBorder.getSrcdX()");
if( (!do_refresh && src_dX != - 1) || !auto_scale_x ) return src_dX;
int digit_width = fm.stringWidth("0"),
max = cd.width / ( digit_width * ( x_value2value + 1 ) );
src_dX = src_rect.width / (double)max;
int n, labelX, olsrc_dX;
boolean ok = false;
while( !ok ){
src_dX = aBitBigger( src_dX );
n = (int)( src_rect.x / src_dX );
if( n * src_dX < src_rect.x ) n++;
olsrc_dX = 0;
boolean suits = true, first = true;
while( suits && n * src_dX <= src_rect.x + src_rect.width ){
double v = n * src_dX;
if( x_scale != null ) v = x_scale.getImageOf( v );
String text = format_x.format(v);
int strW = fm.stringWidth( text );
labelX = (int)((( n * src_dX - src_rect.x ) / src_rect.width ) * cd.width ) - strW / 2;
if( !first && labelX <= olsrc_dX + digit_width * x_value2value ) suits = false;
else{
olsrc_dX = labelX + strW;
n++;
}
first = false;
}
if( !suits ) ok = false;
else ok = true;
}
if( src_dX < minimal_increment ) src_dX = minimal_increment;
return src_dX;
}
/**
* method returns to a certain minimal value the next higher value which can be
* displayed, which looks a bit nicer
* it returns values like ... 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, ...
*
* @param the double value next to which the displayable value should be found
* @return the displayable value
*/
public static double aBitBigger( double min ){
if( min <= 0 ) return 1;
double d = 1;
if( min < d ){
while( d * .5 > min ) {
d *= .5;
if( d * .4 > min ) d *= .4;
if( d * .5 > min ) d *= .5;
}
}
else{
while( d <= min ) {
d *= 2;
if( d <= min ) d *= 2.5;
if( d <= min ) d *= 2;
}
}
return d;
}
public boolean isBorderOpaque(){
return outer_border.isBorderOpaque();
}
//
// private String stringOf( double v ){
// if( (int)v == v ) return String.valueOf( (int)v );
// return String.valueOf( v );
// }
public Insets getBorderInsets(Component c){
if( under_construction ) System.out.println("ScaledBorder.getBorderInsets()");
if( !do_refresh && old_insets != null ) return old_insets;
Graphics g = c.getGraphics();
Insets insets = new Insets(0, 0, 0, 0);
if( show_outer_border ) insets = outer_border.getBorderInsets( c );
if( g == null ) return insets;
FontMetrics fm = g.getFontMetrics();
// int fontAsc = fm.getAscent();
int fontHeight = fm.getHeight(),
digit_width = fm.stringWidth("0");
if( c instanceof DArea ){
DArea area = (DArea)c;
DMeasures m = area.getDMeasures();
DRectangle rect = m.getSourceOf( area.getDRectangle() );
src_rect = (DRectangle)rect.clone();
x_scale = area.getDMeasures().x_scale;
y_scale = area.getDMeasures().y_scale;
}
// left:
if( y_label != null ) insets.left += fm.getAscent() + fm.getDescent();
insets.left += y_label2values * digit_width;
getSrcdY( fm, c.getSize() );
int n, maxWidth = 0;
n = (int)( src_rect.y / src_dY );
if( n * src_dY < src_rect.y ) n++;
while( n * src_dY <= src_rect.y + src_rect.height ){
// TODO here might be a bug for mean values
double v = n * src_dY;
if( y_scale != null ) v = y_scale.getImageOf( v );
int w = fm.stringWidth( format_y.format(v) );
if( w > maxWidth ) maxWidth = w;
n++;
}
insets.left += 1 + y_label2border + maxWidth + digit_width / y_values2marker + marker_length;
// bottom:
insets.bottom += 1 + fontHeight + x_label2border;
if( x_label != null ) insets.bottom += fontHeight;
// top:
if( show_arrows ) insets.top += y_values2arrow + arrow_length;
insets.top += axis2border;
// right:
if( show_arrows ) insets.right += x_values2arrow + arrow_length;
insets.right += axis2border;
getSrcdX( fm, c.getSize() );
n = (int)( src_rect.x + src_rect.width / src_dX );
if( n < 0 ) n ++;
int w = fm.stringWidth( format_x.format(n * src_dX) );
if( w / 2 > insets.right ) insets.right = w / 2;
old_insets = insets;
return insets;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,156 @@
/**
* Filename: $RCSfile: ColorBarCalculator.java,v $
* Purpose: Calculates the color values for a legend-style color bar.
* Language: Java
* Compiler: JDK 1.2
* Authors: Badreddin Abolmaali, Fred Rapp, Simon Wiest
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:41 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.diagram;
/*============================================================================
* IMPORTS
*============================================================================*/
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
import wsi.ra.math.*;
/*============================================================================
* CLASS DECLARATION
*============================================================================*/
/**
* Calculates the color values for a legend-style color bar.
*/
public class ColorBarCalculator
{
/*--------------------------------------------------------------------------
* static public final member variables
*--------------------------------------------------------------------------*/
static public final int BLUE_TO_RED = 0;
static public final int GREY_SCALE = 1;
static public final int BLUE_SCALE = 2;
static public final int ALL_COLORS = 3;
// GREY_SCALE returns luminance values in [0.1;0.9], GREY_EXTENDED_SCALE in [0.0;1.0]
static public final int GREY_EXTENDED_SCALE = 4;
/*--------------------------------------------------------------------------
* private member variables
*--------------------------------------------------------------------------*/
private int color_scale = BLUE_TO_RED;
private boolean inverseScale = false;
/*--------------------------------------------------------------------------
* constructor
*--------------------------------------------------------------------------*/
public ColorBarCalculator(int color_scale)
{
this.color_scale = color_scale;
}
/*--------------------------------------------------------------------------
* public methods
*--------------------------------------------------------------------------*/
public void setColorScale(int color_scale) { this.color_scale = color_scale; }
/**
* Returns color for the given float-value, which must be in the range from 0 to 1.
* Warning: Creates new color object, better use the method 'getRGB' if possible.
*/
public Color getColor(float value)
{
return new Color( getRGB(value) );
}
/**
* Returns color RGB-value for the given float-value, which must be in the range from 0 to 1.
*/
public int getRGB(float value)
{
int rgbValue = 0;
if(inverseScale) {
value = 1 - value;
}
switch (color_scale)
{
case BLUE_TO_RED:
float hue = value * (value + value * 0.8F) / 2.65F - 1F;
rgbValue = Color.HSBtoRGB(hue, 0.6F, 1F);
break;
case GREY_SCALE:
rgbValue = Color.HSBtoRGB(0F, 0F, (value * 0.8F) + 0.1F);
break;
case BLUE_SCALE:
int rg = (int) (value * 0.95F * 256);
int b = (int) ((value/2.0F + 0.45F) * 256);
rgbValue = rg * 0x10000 + rg * 0x100 + b;
break;
case ALL_COLORS:
rgbValue = Color.HSBtoRGB(value, 0.6F, 1F);
break;
case GREY_EXTENDED_SCALE:
rgbValue = Color.HSBtoRGB(0F, 0F, value );
break;
}
return rgbValue;
}
/**
* Reverts color scale (e.g. black will be white and vice versa).
* @param isInverse Color scale is inverted, if <code>isInverse</code> is set to true.
*/
public void setInverseScale(boolean isInverse) {
inverseScale = isInverse;
}
/**
* Returns current scale mode.
* @return <code>true</code> if scale is inverted, else <code>false</code>.
*/
public boolean isInverseScale() {
return inverseScale;
}
/*--------------------------------------------------------------------------
* static public methods
*--------------------------------------------------------------------------*/
/**
* Returns color for the given float-value, which must be in the range from 0 to 1.
* Warning: Creates new color object, better use the method 'getRGB' if possible.
*/
static public Color getDefaultColor(float value)
{
return new Color( getDefaultRGB(value) );
}
/**
* Returns color RGB-value for the given float-value, which must be in the range from 0 to 1.
*/
static public int getDefaultRGB(float value)
{
float hue = value * (value + value * 0.8F) / 2.65F - 1F;
return Color.HSBtoRGB(hue, 0.6F, 1F);
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,639 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.3 $
* $Date: 2004/04/28 07:50:32 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import javaeva.tools.Serializer;
/**
*
*/
public class ComAdapter {
static final public boolean TRACE = false;
static final public int PORT = 1099;
static final public String SEP = "_";
static protected ComAdapter m_instance = null;
public Registry m_Registry = null;
private ArrayList<RMIConnection> m_Connections = new ArrayList<RMIConnection>();
private String m_ownHostName;
private ArrayList<String> m_HostNameList = new ArrayList<String>();
private ArrayList<String> m_AvailableHostNameList = new ArrayList<String>();
// private String m_RemoteAdapterName;
private String m_UserName;
private int m_ownHostIndex = 0;
protected RMIServer m_RMIServer;
private String serverListSeparator = ",";
private boolean gettingRegistry;
/**
*
*/
public static ComAdapter getInstance() {
if (m_instance != null)
return m_instance;
m_instance = new ComAdapter();
return m_instance;
}
/**
*
*/
protected ComAdapter() {
if (TRACE) System.out.println("constructor ComAdapter");
m_UserName = System.getProperty("user.name");
m_ownHostName = "localhost"; //"192.168.0.1";
System.setProperty("java.security.policy", "server.policy");
launchRMIRegistry(false);
if (!m_HostNameList.contains("localhost")) {
// make sure localhost is in the list
m_HostNameList.add("localhost");
}
}
/**
* Parse a string of server names. The comma "," must be used as separator.
*
* @param serverList
*/
public void addServersFromString(String serverList) {
if (serverList != null) {
// parse the servernames
StringTokenizer st = new StringTokenizer(serverList, serverListSeparator);
while (st.hasMoreTokens()) {
String current = st.nextToken().trim();
if (!m_HostNameList.contains(current)) {
if (TRACE) System.out.println("adding server " + current);
m_HostNameList.add(current);
} else {
if (TRACE) System.out.println("server " + current + " was already in list");
}
}
}
}
/**
* Add a server list from a Properties instance. The key used is "ServerList".
*
* @param props
*/
public void addServersFromProperties(Properties props) {
String servs = props.getProperty("ServerList");
addServersFromString(servs);
}
/**
* Set the separator for the server list string.
*
* @return
*/
public void setServerListSeparator(String sep) {
serverListSeparator = sep;
}
/**
* The separator for the server list string.
*
* @return
*/
public String getServerListSeparator() {
return serverListSeparator;
}
/**
*
* @param c
* @param host
* @return
*/
public void setServerList(String[] server){
m_HostNameList.clear();
for (int i=0;i<server.length;i++)
m_HostNameList.add(server[i]);
}
/**
*
*
*/
public RMIInvocationHandler getRMIHandler(Object c, String host) {
System.out.println("ComAdapter.getRMIHandler() for host " + host);
m_ownHostName = host;
RMIInvocationHandler ret = null;
while (ret == null) {
ret = getConnection(m_ownHostName).getRMIHandler(c);
if (ret == null)
System.out.println("Error in getRMIHandler");
}
return ret;
}
/**
*
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object c, String host) {
if (TRACE)
System.out.println("ComAdapter.getRMIThreadHandler()");
m_ownHostName = host;
RMIThreadInvocationHandler ret = null;
while (ret == null) {
ret = getConnection(m_ownHostName).getRMIThreadHandler(c);
if (ret == null)
System.err.println("Error in getRMIThreadHandler");
}
return ret;
}
/**
*
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object c) {
if (TRACE)
System.out.println("RMIThreadInvokationHandler getRMIThreadHandler");
RMIThreadInvocationHandler ret = null;
if (m_AvailableHostNameList.size() == 0) {
evalAvailableHostNameList();
m_ownHostIndex = 0;
}
m_ownHostIndex++;
if (m_ownHostIndex >= m_AvailableHostNameList.size())
m_ownHostIndex = 0;
m_ownHostName = (String) m_AvailableHostNameList.get(m_ownHostIndex);
ret = getRMIThreadHandler(c, m_ownHostName);
return ret;
}
/**
*
*
*/
public RMIInvocationHandler getRMIHandler(Object c) {
if (TRACE)
System.out.println("RMIThreadInvokationHandler getRMIHandler");
RMIInvocationHandler ret = null;
while (m_AvailableHostNameList.size() == 0) {
evalAvailableHostNameList();
if (m_AvailableHostNameList.size() == 0)
System.err.println("no host availabe waiting !!");
m_ownHostIndex = 0;
}
m_ownHostIndex++;
if (m_ownHostIndex >= m_AvailableHostNameList.size())
m_ownHostIndex = 0;
m_ownHostName = (String) m_AvailableHostNameList.get(m_ownHostIndex);
ret = getRMIHandler(c, m_ownHostName);
return ret;
}
// /**
// *
// */
// public String getLoad() {
// if (TRACE)
// System.out.println("ComAdapter.getLoad()");
// String Load = null;
// Load = getConnection(m_ownHostName).getExecOutput("rup " + m_ownHostName);
// if (TRACE)
// System.out.println("Load of Modules on Server !! :" + Load);
//// if (m_LogPanel != null)
//// m_LogPanel.logMessage("Load of Modules on Server !! :" + Load);
// return Load;
// }
// /**
// *
// */
// public String gettokens() {
// if (TRACE)
// System.out.println("ComAdapter.gettokens()");
// String Tokens = null;
// Tokens = getConnection(m_ActualHostName).getExecOutput("tokens");
// if (TRACE)
// System.out.println("tokens on Server !! :" + Tokens);
// Tokens = getConnection(m_ActualHostName).getExecOutput(
// "klog -principal ulmerh -password ");
// if (TRACE)
// System.out.println("KLOG !!! !! :" + Tokens);
// Tokens = getConnection(m_ActualHostName).getExecOutput("tokens");
// if (TRACE)
// System.out.println("tokens on Server !! :" + Tokens);
// return Tokens;
// }
/**
*
*/
public void evalAvailableHostNameList() {
long time = System.currentTimeMillis();
if (TRACE)
System.out.println("ComAdapter.getAvailableHostNameList()");
m_AvailableHostNameList.clear();
for (int i = 0; i < m_HostNameList.size(); i++) {
if (rmiPing((String) m_HostNameList.get(i)) == true)
m_AvailableHostNameList.add((String) m_HostNameList.get(i));
String testurl = (String) m_HostNameList.get(i);
for (int j = 1; j < 3; j++) {
if (rmiPing(testurl + "_" + j) == true) {
if (TRACE) System.out.println("found EvAServer on: " + testurl);
m_AvailableHostNameList.add(testurl + "_" + j);
}
}
}
time = System.currentTimeMillis() - time;
if (TRACE) System.out.println("getAvailableHostNameList: " + m_AvailableHostNameList.size() + " found time " + time);
}
/**
*
*/
public String[] getAvailableHostNameList() {
if (m_AvailableHostNameList.size() == 0)
evalAvailableHostNameList();
String[] ret = new String[m_AvailableHostNameList.size()];
m_AvailableHostNameList.toArray(ret);
return ret;
}
/**
*
*/
public String[] getHostNameList() {
String[] x = new String[m_HostNameList.size()];
m_HostNameList.toArray(x);
return x;
}
/**
*
*/
public String getHostName() {
return m_ownHostName;
}
/**
*
*/
public void setHostName(String newHost) {
m_ownHostName = newHost;
Serializer.storeString("hostname.ser", m_ownHostName);
}
/**
* Creates a RMI-MainAdapter to host.
* @return
*/
protected MainAdapter createRMIMainConnect(String HostToConnect) {
if (TRACE)
System.out.println("RMIMainConnect.RMIMainConnect() =" + HostToConnect);
int len = HostToConnect.indexOf(SEP);
String Host = HostToConnect;
String Number = SEP + "0";
if (len != -1) {
StringTokenizer st = new StringTokenizer(HostToConnect, SEP);
Host = st.nextToken().trim();
Number = SEP + st.nextToken().trim();
}
String MainAdapterName = m_UserName + MainAdapterImpl.MAIN_ADAPTER_NAME + Number; // attention
logInfo(" RMIConnect to " + HostToConnect);
MainAdapter MainRemoteObject = null;
try {
try {
try {
//System.out.println("--> ComAdapter: "+"rmi://"+Host+":"+MainAdapterImpl.PORT+"/"+MainAdapterName);
// String[] list = Naming.list("rmi://" + Host + ":" +
// MainAdapterImpl.PORT);
//for (int i=0;i<list.length;i++)
// System.out.println("RMIName: "+list[i]);
//m_NumberOfVM = getNumberOfVM(list);
if (TRACE) System.out.println("getMain:" + "rmi://" + Host + ":" +
MainAdapterImpl.PORT + "/" + MainAdapterName);
RMIInvocationHandler invocHandler = (RMIInvocationHandler) Naming.lookup(
"rmi://" + Host + ":" + MainAdapterImpl.PORT + "/" +
MainAdapterName);
//System.out.println(" x ="+x.getClass().getName());
MainRemoteObject = getMainAdapter(invocHandler);
//MainRemoteObject = (MainAdapter)Naming.lookup("rmi://"+HostToConnect+":"+MainAdapterImpl.PORT+"/"+MainAdapterImpl.MAIN_ADAPTER_NAME);
//MainRemoteObject = (MainAdapter)LogProxy.newInstance(MainRemoteObject);
MainRemoteObject.setBuf("Ok.");
logInfo(" RMIConnect " + MainRemoteObject.getBuf());
} catch (MalformedURLException ex) {
System.err.println("MalformedURLException: Error while looking up " +
ex.getMessage());
}
} catch (NotBoundException ex) {
System.err.println("NotBoundException: Error while looking up " +
ex.getMessage());
ex.printStackTrace();
}
if (TRACE)
System.out.println("Connect to " + HostToConnect + " works fine");
} catch (RemoteException e) {
logInfo("Error while connecting Host: " + HostToConnect +
" \n ERROR: " + e.getMessage());
System.err.println("Error while connecting Host: " + HostToConnect +
" \n ERROR: " + e.getMessage());
return null;
}
return MainRemoteObject;
}
protected MainAdapter getMainAdapter(RMIInvocationHandler invocHandler) throws RemoteException {
return (MainAdapter) invocHandler.getWrapper();
}
protected void logInfo(String msg) {
System.out.println("ComAdapter-Log: " + msg);
}
/**
*
*/
protected int getNumberOfServersonHost(String testurl) {
// String MainAdapterName = m_UserName + MainAdapterImpl.MAIN_ADAPTER_NAME;
String[] list = null;
try {
list = Naming.list("rmi://" + testurl + ":" + MainAdapterImpl.PORT);
} catch (Exception e) {
//if (TRACE && m_LogPanel!=null) m_LogPanel.logMessage ("No connecting to : "+testurl );
//if (TRACE) System.out.println ("No connecting to : "+testurl );
System.err.println ("Exception : "+testurl );
return 0;
}
int ret = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1)
ret++;
}
System.err.println("error in ComAdapter.getNumberOfServersonHost");
//System.out.println(" ret === "+ret);
return ret;
}
/**
*
*/
private boolean rmiPing(String testurl) {
if (TRACE)
System.out.println("ComAdapter.rmiPing " + testurl);
MainAdapter Test = null;
// String Load = null;
int len = testurl.indexOf(SEP);
String Host = testurl;
String Number = "_0";
if (len != -1) {
StringTokenizer st = new StringTokenizer(testurl, SEP);
Host = st.nextToken().trim();
Number = SEP + st.nextToken().trim();
}
String MainAdapterName = m_UserName + MainAdapterImpl.MAIN_ADAPTER_NAME +
Number;
try {
if (TRACE)
System.out.println("ping:" + "rmi://" + Host + ":" +
MainAdapterImpl.PORT + "/" + MainAdapterName);
RMIInvocationHandler x = (RMIInvocationHandler) Naming.lookup("rmi://" +
Host + ":" + MainAdapterImpl.PORT + "/" + MainAdapterName); // attention !!
Test = (MainAdapter) x.getWrapper();
// if (Test != null) {
// Load = Test.getExecOutput("rup " + testurl);
// }
} catch (Exception e) {
if (TRACE) {
logInfo("No connection to : " + testurl);
System.out.println("ComAdapter.rmiPing false " + e.getMessage());
}
return false;
}
if (Test != null) {
if (TRACE) logInfo("ping succeeded");
}
if (TRACE)
System.out.println("ComAdapter.rmiPing true");
return true;
}
/**
*
*/
public void killServer(String ServerToKill) {
if (TRACE)
System.out.println("ComAdapter.Killing Server :" + ServerToKill);
RMIConnection myConnection = getConnection(ServerToKill);
myConnection.killServer();
this.m_Connections.remove(myConnection);
}
/**
*
*/
public void killAllServers() {
if (TRACE)
System.out.println("ComAdapter.Killing All Servers :");
for (int i = 0; i < m_AvailableHostNameList.size(); i++) {
RMIConnection myConnection = getConnection((String)
m_AvailableHostNameList.get(i));
myConnection.killServer();
this.m_Connections.remove(myConnection);
}
}
/**
*
*/
public void restartServerAllServer() {
if (TRACE) System.out.println("ComAdapter.restartServerAllServer :");
for (int i = 0; i < m_AvailableHostNameList.size(); i++) {
RMIConnection myConnection = getConnection((String)
m_AvailableHostNameList.get(i));
myConnection.restartServer();
m_Connections.remove(myConnection);
}
}
/**
*
*/
public void restartServer(String host) {
m_ownHostName = host;
restartServer();
}
/**
*
*/
public void restartServer() {
if (TRACE)
System.out.println("ComAdapter.restartServer");
if (TRACE)
System.out.println("m_ActualHostName = " + m_ownHostName);
// System.out.println("m_ActualHostName = " + m_ActualHostName);
if (m_ownHostName.equals("localhost")) { // TODO whats this?
return;
}
if (TRACE == true)
System.out.println("ComAdapter.restartServer Server :" + m_ownHostName);
RMIConnection x = getConnection(m_ownHostName);
x.restartServer();
m_Connections.remove(x);
try {
Thread.sleep(3000);
} catch (Exception e) {
System.err.println("Error in sleep of ExitThread");
}
}
public void setRMIRegistry(Registry reg) {
m_Registry = reg;
gettingRegistry = false;
}
/**
* Install RMIregistry on default port !!
*/
protected void launchRMIRegistry(boolean ownThread) {
if (ownThread) {
Thread t = new Thread(new RMIRegistration(this));
gettingRegistry = true;
t.start();
} else {
RMIRegistration rmiReg = new RMIRegistration(this);
gettingRegistry = true;
rmiReg.run();
}
}
/**
*
*/
public void setLocalRMIServer(RMIServer Server) {
m_RMIServer = Server;
}
/**
* Just the main for testing the class.
*/
public static void main(String[] args) {
ComAdapter TestApp = ComAdapter.getInstance();
TestApp.evalAvailableHostNameList();
TestApp.killAllServers();
//TestApp.restartServerAllServer();
}
/**
*
*/
protected RMIConnection getConnection(String Host) {
if (TRACE) System.out.println("ComAdapter.getConnection for host :" + Host);
for (int i = 0; i < this.m_Connections.size(); i++) {
// search for an already established connection to the given host
// and return it if found
RMIConnection ret = (RMIConnection) m_Connections.get(i);
if (Host.equals(ret.getHostName())) return ret;
}
// else create and add new RMIConnection
RMIConnection ret = null;
if (Host.equals("localhost") && m_RMIServer != null) {
// this uses rmi on the localhost
ret = createRMIConnection(Host, m_RMIServer.getMainRemoteObject(),
new MainAdapterClientImpl("localhost"));
} else {
MainAdapter Adapter = (MainAdapter)createRMIMainConnect(Host);
if (Adapter != null)
ret = createRMIConnection(Host, Adapter,
(MainAdapterClient) RMIProxyLocal.newInstance(new MainAdapterClientImpl(Host)));
}
if (ret != null) m_Connections.add(ret);
else System.err.println("Warning no valid connection !!");
return ret;
}
protected RMIConnection createRMIConnection(String Host, MainAdapter mainRemoteObject, MainAdapterClient client) {
return new RMIConnection(Host, mainRemoteObject, client);
}
// private RMIConnection getConnection(String Host) {
// if (TRACE == true) System.out.println("ComAdapter.getConnection for host :" + Host);
// RMIConnection ret = null;
// for (int i = 0; i < this.m_Connections.size(); i++) {
// ret = (RMIConnection) m_Connections.get(i);
// if (Host.equals(ret.getHostName()) == true)
// return ret;
// }
// // create and add new RMIConnection
// if (Host.equals("localhost") && (m_RMIServer != null)) {
// ret = new RMIConnection(Host, m_RMIServer.getMainRemoteObject(),
// new MainAdapterClientImpl());
// } else {
// MainAdapter Adapter = createRMIMainConnect(Host);
// if (Adapter != null)
// ret = new RMIConnection(Host, Adapter,
// (MainAdapterClient)
// RMIProxyLocal.newInstance(new MainAdapterClientImpl()));
// }
// if (ret != null) m_Connections.add(ret);
// else System.err.println("Warning no valid connection !!");
// return ret;
// }
}
class RMIRegistration implements Runnable {
ComAdapter comAd = null;
private boolean TRACE = false;
Registry reg = null;
public RMIRegistration(ComAdapter comAdapter) {
comAd = comAdapter;
}
public void run() {
if (TRACE)
System.out.println("LaunchRMIRegistry on Client on PORT " + ComAdapter.PORT);
try {
reg = java.rmi.registry.LocateRegistry.createRegistry(ComAdapter.PORT);
}
catch (Throwable e) {
if (TRACE) System.out.println("Registry notcreated !!" + e.getMessage());
reg = null;
}
if (reg == null) {
if (TRACE) System.out.println("Try to get registry with getRegistry on PORT " + ComAdapter.PORT);
try {
reg = java.rmi.registry.LocateRegistry.getRegistry(ComAdapter.PORT);
}
catch (Throwable e) {
if (TRACE) System.out.println("registry not created !!" + e.getMessage());
reg = null;
}
}
if (reg != null && TRACE) System.out.println("--> got RMIREGISTRY");
comAd.setRMIRegistry(reg);
}
}

View File

@@ -0,0 +1,113 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:29 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.io.Serializable;
import java.util.ArrayList;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class JProxyRemoteThread implements InvocationHandler,
Serializable {
private static ComAdapter m_ComAdapter;
private Object m_Object;
private RMIThreadInvocationHandler m_RMIThreadHandler;
private String m_ObjectName;
/**
*
*/
public static Object newInstance(Serializable object, String host) throws NO_RMIServerAvailable {
return Proxy.newProxyInstance(
object.getClass().getClassLoader(),
object.getClass().getInterfaces(),
new JProxyRemoteThread(object, host));
}
/**
*
*/
public static Object newInstance(Serializable object) throws NO_RMIServerAvailable {
return Proxy.newProxyInstance(
object.getClass().getClassLoader(),
object.getClass().getInterfaces(),
new JProxyRemoteThread(object));
}
/**
*
* @param c
* @return
*/
public static String[] getServerList() {
if (m_ComAdapter == null) {
//try {
m_ComAdapter = ComAdapter.getInstance();
// } catch (NO_RMIServerAvailable ex) {
// ex.printStackTrace();
//
// }
}
m_ComAdapter.evalAvailableHostNameList();
return m_ComAdapter.getAvailableHostNameList();
}
/**
*
*/
public static void setComAdaper(ComAdapter x) {
m_ComAdapter = x;
}
/**
*
*/
private JProxyRemoteThread(Serializable object, String host) throws NO_RMIServerAvailable {
if (m_ComAdapter == null)
m_ComAdapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object, host);
}
/**
*
*/
private JProxyRemoteThread(Serializable object) throws NO_RMIServerAvailable {
if (m_ComAdapter == null)
m_ComAdapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object);
}
/**
*
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object ret = null;
if (method.getName().equals("getServerName")) {
ret = m_RMIThreadHandler.getServerName();
} else {
ret = m_RMIThreadHandler.invoke(method.getName(), args);
}
//long finish = System.currentTimeMillis();
//System.out.println("Calling :"+m.getName()+" of "+m_ObjectName+ " time :"+(finish-start));
return ret;
}
}

View File

@@ -0,0 +1,31 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:29 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface MainAdapter {
public String getExecOutput(String command);
public void setBuf(String s);
public void killServer();
public void restartServer();
public String getBuf();
public RMIInvocationHandler getRMIHandler(Object obj);
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj);
public void setRemoteThis (MainAdapter x);
}

View File

@@ -0,0 +1,25 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface MainAdapterClient {
public RMIInvocationHandler getRMIHandler(Object obj);
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj);
public String getHostName();
}

View File

@@ -0,0 +1,76 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.net.InetAddress;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class MainAdapterClientImpl implements MainAdapterClient {
static final public String MAIN_ADAPTER_CLIENT_NAME = "Main_Remote_Object_Client_Name";
static public boolean TRACE = false;
private String m_HostName = "not__defined__";
/**
*
*/
public MainAdapterClientImpl() {
try {
m_HostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
System.out.println("ERROR getting HostName MainAdapterClientImpl "+e.getMessage());
}
}
/**
*
*/
public MainAdapterClientImpl(String hostName) {
m_HostName = hostName;
}
/**
*
*/
public RMIInvocationHandler getRMIHandler(Object obj) {
if (TRACE) System.out.println("MainAdapterClientImpl.getRMIHandler");
RMIInvocationHandler ret = null;
try {
ret = new RMIInvocationHandlerImpl(obj);
} catch (Exception e) {
System.out.println(" Error ret= new RMIInvokationHandlerImpl(obj);"+e.getMessage());
}
return ret;
}
/**
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj) {
if (TRACE) System.out.println("MainAdapterClientImpl.getRMIThreadHandler");
RMIThreadInvocationHandler ret = null;
try {
ret = new RMIThreadInvocationHandlerImpl(obj);
} catch (Exception e) {
System.out.println(" Error ret= new getRMIThreadHandler(obj);"+e.getMessage());
}
return ret;
}
/**
*
*/
public String getHostName () {
return m_HostName;
}
}

View File

@@ -0,0 +1,154 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class MainAdapterImpl implements MainAdapter {
static final public String MAIN_ADAPTER_NAME = "MainRemoteObjectName";
static final public int PORT = 1099;
static public boolean TRACE = false;
private String m_Buf = "";
private MainAdapter m_RemoteThis;
/**
*
*/
public MainAdapterImpl() {
if (TRACE) System.out.println("Constructor MainAdapterImpl !!!!!!");
m_RemoteThis = this;
}
/**
*
*/
public void setBuf(String s) {
if (TRACE) System.out.println("MainAdapterImpl.setBuf:"+s);
m_Buf = s;
}
/**
*
*/
public void restartServer() {
System.out.println("Received message to restartServer !!!!");
try {
String Out ="";
String command = "java -cp .:../lib/jdom.jar:../lib/log4j.jar javaeva.server.EvAServer &";
System.out.println("Calling the command:"+"java javaeva.server.EvAServer");
Process pro = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader ( new InputStreamReader (pro.getInputStream()));
// String line = null;
// while((line = in.readLine()) != null ) {
// System.out.println(line);
// Out = Out + line;
// }
System.out.println("command="+command);
} catch (Exception e) {
System.out.println("Error in calling the command:"+e.getMessage());
}
killServer();
}
/**
*
*/
public void killServer() {
//Mail.SendMail("Received message to kill EvAServer");
System.out.println("Received message to kill EvAServer !!!!");
KillThread x = new KillThread();
x.start();
return;
}
/**
*
*/
public String getBuf() {
return m_Buf;
}
/**
*
*/
public String getExecOutput(String command) {
String Out= new String();
try {
BufferedReader in = null;
Process pro = null;
if (TRACE) System.out.println("Calling the command:"+command);
pro = Runtime.getRuntime().exec(command);
in = new BufferedReader ( new InputStreamReader (pro.getInputStream()));
String line = null;
while((line = in.readLine()) != null ) {
if (TRACE) System.out.println(line);
Out = Out + line;
}
} catch (Exception e) {
System.err.println("Error in calling the command:"+e.getMessage());
}
return Out;
}
/**
*
*/
public RMIInvocationHandler getRMIHandler(Object obj) {
System.out.println("getRMIHandler");
RMIInvocationHandler ret = null;
try {
ret = new RMIInvocationHandlerImpl(obj);
}
catch (Exception e) {
System.out.println("Error: RMIInvokationHandler getRMIHandler");
}
return ret;
}
/**
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj) {
if (TRACE) System.out.println("getRMIThreadHandler");
RMIThreadInvocationHandler ret = null;
try {
ret = new RMIThreadInvocationHandlerImpl(obj);
}
catch (Exception e) {
System.out.println("Error: RMIThreadInvokationHandler getRMIThreadHandler");
}
return ret;
}
/**
*
*/
public void setRemoteThis (MainAdapter x) {
m_RemoteThis = x;
}
}
/**
*
*/
class KillThread extends Thread {
/**
*
*/
public void run() {
try {sleep(3000);}
catch(Exception e) {
System.out.println("Error in sleep");
}
System.exit(-1);
}
}

View File

@@ -0,0 +1,24 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/**
* This exception will be thrown when no
* RMIServer con be found by the ComAdapter.
*/
public class NO_RMIServerAvailable extends Exception {
NO_RMIServerAvailable() {
printStackTrace();
}
}

View File

@@ -0,0 +1,98 @@
package wsi.ra.jproxy;
/**
*
*/
public class RMIConnection {
public static boolean TRACE = false;
private String m_HostName;
protected MainAdapter m_MainAdapter;
protected MainAdapterClient m_MainAdapterClient;
/**
*
*/
public RMIConnection(String HostName, MainAdapter Adapter,
MainAdapterClient AdapterClient) {
m_MainAdapter = Adapter;
m_HostName = HostName;
m_MainAdapterClient = AdapterClient;
}
/**
*
*/
public String getHostName() {
return m_HostName;
}
/**
*
*/
public MainAdapter getMainAdapter() {
return m_MainAdapter;
}
/**
*
*/
public void killServer() {
try {
m_MainAdapter.killServer();
} catch (Exception e) {
System.out.println("Error while killing server: " + e.getMessage());
}
}
/**
*
*/
public void restartServer() {
try {
m_MainAdapter.restartServer();
} catch (Exception e) {
System.out.println("Error while restartServer server: " + e.getMessage());
}
}
/**
*
*/
public RMIInvocationHandler getRMIHandler(Object c) {
RMIInvocationHandler ret = null;
try {
ret = m_MainAdapter.getRMIHandler(c);
} catch (Exception e) {
System.out.println("Error while getRMIHandler server: " + e.getMessage());
e.printStackTrace();
}
return ret;
}
/**
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object c) {
RMIThreadInvocationHandler ret = null;
try {
ret = m_MainAdapter.getRMIThreadHandler(c);
} catch (Exception e) {
System.out.println("Error while RMIThreadInvokationHandler server: " +
e.getMessage());
}
return ret;
}
/**
*
*/
public String getExecOutput(String command) {
String ret = null;
try {
ret = m_MainAdapter.getExecOutput(command);
} catch (Exception e) {
System.out.println("Error while getExecOutput server: " + e.getMessage());
}
return ret;
}
}

View File

@@ -0,0 +1,27 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.rmi.Remote;
import java.rmi.RemoteException;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface RMIInvocationHandler extends Remote {
public Object invoke (String m, Object[] args)throws RemoteException;
public Object getWrapper () throws RemoteException;
public void setWrapper(Object Wrapper) throws RemoteException;
}

View File

@@ -0,0 +1,128 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/07/31 20:02:09 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import wsi.ra.math.RNG;
import java.rmi.RemoteException;
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIInvocationHandlerImpl extends UnicastRemoteObject implements RMIInvocationHandler {
public static final boolean TRACE = false;
private Object m_Object;
private String m_AdapterName;
private Object m_Wrapper;
private Method[] m_list;// m_Object.getClass().getMethods();
/**
*
*/
public RMIInvocationHandlerImpl(Object obj) throws RemoteException {
if (TRACE) System.out.println("RMIInvokationHandlerImpl");
m_AdapterName = obj.getClass().getName()+"_"+RNG.randomInt(0,10000);
try {
m_Object = obj;
m_list = m_Object.getClass().getMethods();
if (TRACE) System.out.println(" --> rebind : "+m_AdapterName+" RMIInvokationHandlerImpl of object "+obj.getClass().getName());
Naming.rebind(m_AdapterName,this);
} catch (Exception e) {
System.err.println(" Naming.rebind --> ERROR" + e.getMessage());
e.printStackTrace();
}
}
/**
*
*/
public RMIInvocationHandlerImpl(Object obj,String AdapterName) throws RemoteException {
m_AdapterName = AdapterName;
try {
m_Object = obj;
m_list = m_Object.getClass().getMethods();
if (TRACE) System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName());
Naming.rebind(m_AdapterName,this);
} catch (Exception e) {
System.err.println(" Naming.rebind --> ERROR " + obj + " " + e.getMessage());
e.printStackTrace();
}
}
/**
*
*/
public void setWrapper(Object Wrapper) throws RemoteException {
m_Wrapper = Wrapper;
}
/**
*
*/
public Object getWrapper () throws RemoteException {
return m_Wrapper;
}
/**
*
*/
public Object invoke (String m, Object[] args) throws RemoteException {
Object ret=null;
String Name = "";
//System.out.println("calling "+m);
if (TRACE) Name = Thread.currentThread().getName();
try {
if (TRACE) System.out.println( Name+" Before invoke on server :" +m);
//Method[] list = m_Object.getClass().getMethods();
boolean invoked = false;
for (int i=0;i<m_list.length;i++) {
if (TRACE) System.out.println(Name+" list[i].getName() "+m_list[i].getName());
// if (m.equals("free")==true) {
// System.out.println("called free !!!!!!!!!!!!!!!!!!!!!!!!!"+m_AdapterName);
// String[] list = Naming.list("rmi://localhost:" + MainAdapterImpl.PORT);
// System.out.println("-->list :"+list.length);
// for (int j = 0; j < list.length; j++){
// System.out.println("list="+list[j]+"--"+m_AdapterName);
// if (list[j].lastIndexOf(m_AdapterName)!=-1) {
// System.out.println("unbind !!!!!!!!!!!!!!!!!!!!!!!!!!");
// Naming.unbind(list[j]);
//
// return null;
// }
// }
// System.out.println("Object not found !!!!!");
// return null;
// }
if (m.equals(m_list[i].getName())==true) {
if (TRACE) System.out.println(Name+" find "+m);
//if (args==null) System.out.println(Name+" args==null ");
ret = m_list[i].invoke(m_Object,args);
invoked= true;
break;
}
}
if (invoked==false) System.out.println(Name+ " No memberfunction found !!!!!!!!!!!!!!!!!");
}
catch ( InvocationTargetException e) {
e.printStackTrace();
System.out.println(Name+" RMIInvokationHandlerImpl InvocationTargetException "+e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
System.out.println(Name+" Exception :"+e.getMessage());
}
return ret;
}
}

View File

@@ -0,0 +1,111 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/04/15 12:28:34 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIProxyLocal implements InvocationHandler, Serializable {
private RMIInvocationHandler m_RMIHandler;
public static boolean TRACE = false;
private Class originalClass = null;
/**
*
*/
public static Object newInstance (Object c, String RMIName) {
if (TRACE) System.out.println("RMIProxyLocal:"+c.getClass().getName());
RMIProxyLocal proxyLocal = new RMIProxyLocal(c,RMIName);
Object ret = java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
proxyLocal);
proxyLocal.setWrapper(ret);
proxyLocal.setOriginalClass(c.getClass());
if (TRACE) System.out.println(" --> " + ret.getClass());
return ret;
}
/**
*
*/
public static Object newInstance (Object c) {
if (TRACE) System.out.println("RMIProxyLocal:"+c.getClass().getName());
RMIProxyLocal proxyLocal = new RMIProxyLocal(c);
Object ret = java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
proxyLocal);
proxyLocal.setWrapper(ret);
proxyLocal.setOriginalClass(c.getClass());
if (TRACE) System.out.println(" --> " + ret.getClass());
return ret;
}
/**
*
*/
private RMIProxyLocal (Object c) {
if (TRACE) System.out.println("RMIProxyLocal:"+c.getClass().getName());
try {
m_RMIHandler = new RMIInvocationHandlerImpl(c);
} catch (Exception e) {
System.err.println("Error in m_RMIHandler = new RMIInvokationHandlerImpl(c)");
e.printStackTrace();
}
}
/**
*
*/
private RMIProxyLocal (Object c,String RMIName) {
try {
m_RMIHandler = new RMIInvocationHandlerImpl(c,RMIName);
} catch (Exception e) {
System.out.println("Error in m_RMIHandler = new RMIInvokationHandlerImpl(c)");
e.printStackTrace();
}
}
/**
*
*/
public void setWrapper(Object Wrapper) {
try {
m_RMIHandler.setWrapper(Wrapper);
} catch (Exception e) {
System.out.println("Error in setWrapper "+e.getMessage());
}
}
/**
*
*/
public Object invoke (Object proxy, Method m, Object[] args) throws Throwable {
return m_RMIHandler.invoke(m.getName(),args);
}
/**
* @return the originalClass
*/
public Class getOriginalClass() {
return originalClass;
}
/**
* @param originalClass the originalClass to set
*/
public void setOriginalClass(Class originalClass) {
if (TRACE) System.out.println("setting original proxy class "+originalClass.getName());
this.originalClass = originalClass;
}
}

View File

@@ -0,0 +1,116 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIProxyLocalThread implements InvocationHandler,Serializable {
private RMIInvocationHandler m_RMIHandler;
private final static boolean TRACE = true;
/**
*
*/
public static Object newInstance (Object c,String RMIName) {
//System.out.println("RMIProxyLocal.newInstance !!!!!!!!!!!!!!!");
RMIProxyLocalThread Proxy = new RMIProxyLocalThread(c,RMIName);
Object ret = java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
Proxy);
Proxy.setWrapper(ret);
if (TRACE) System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass());
return ret;
}
/**
*
*/
public static Object newInstance (Object c) {
RMIProxyLocalThread Proxy = new RMIProxyLocalThread(c);
Object ret = java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
Proxy);
Proxy.setWrapper(ret);
if (TRACE) System.out.println("RMIProxyLocalThread "+c.getClass() + " ret " + ret.getClass());
return ret;
}
/**
*
*/
private RMIProxyLocalThread (Object c) {
System.out.println("RMIProxyLocal:"+c.getClass().getName());
try {
m_RMIHandler = new RMIInvocationHandlerImpl(ThreadProxy.newInstance(c));
} catch (Exception e) {
System.out.println("Error in m_RMIHandler = new RMIInvokationHandlerImpl(c)");
e.printStackTrace();
}
}
/**
*
*/
private RMIProxyLocalThread (Object c,String RMIName) {
System.out.println("RMIProxyLocal:"+RMIName);
System.out.println("RMIProxyLocal:"+c.getClass().getName());
try {
m_RMIHandler = new RMIInvocationHandlerImpl(ThreadProxy.newInstance(c),RMIName);
} catch (Exception e) {
System.out.println("Error in m_RMIHandler = new RMIInvokationHandlerImpl(c)");
e.printStackTrace();
}
}
/**
*
*/
public void setWrapper(Object Wrapper) {
try {
m_RMIHandler.setWrapper(Wrapper);
} catch (Exception e) {
System.out.println("Error in setWrapper "+e.getMessage());
}
}
/**
*
*/
public Object invoke (Object proxy, Method m, Object[] args) throws Throwable {
//long start = System.currentTimeMillis();
//System.out.println("Before invoke:" +m.getName());
//Object ret = m_RMIHandler.invoke(m.getName(),args);
//long finish = System.currentTimeMillis();
//System.out.println("Calling :"+m.getName()+" of "+m_ObjectName+ " time :"+(finish-start));
//return ret;
return m_RMIHandler.invoke(m.getName(),args);
}
/**
*
*/
public static void main(String[] args) {
//
//Doit x = new DoitImpl();
// Doit xx = (Doit) RMIProxyRemote.newInstance(x,"primergy4.informatik.uni-tuebingen.de");
// Doit2 yy = (Doit2) RMIProxyLocal.newInstance(new Doit2Impl());
// System.out.println(" jhdfjldf");
// yy.doit();
// yy.doit();
// xx.newdoit(yy);
}
}

View File

@@ -0,0 +1,116 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIProxyRemote implements InvocationHandler,Serializable {
private static ComAdapter m_Adapter;
private static boolean TRACE = true;
private Object m_Object;
private String m_ObjectName;
private RMIInvocationHandler m_RMIHandler=null;
private long m_counter=0;
/**
*
*/
public static Object newInstance (Object c,MainAdapterClient Client) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemote(c,Client));
}
/**
*
*/
public static Object newInstance (Object c,String host) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemote(c,host));
}
/**
*
*/
public static Object newInstance (Object c) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemote(c));
}
/**
*
*/
public static void setComAdaper(ComAdapter x) {
m_Adapter = x;
}
/**
*
*/
private RMIProxyRemote (Object c, String host) {
m_ObjectName = c.getClass().getName();
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_RMIHandler = m_Adapter.getRMIHandler(c,host);
if (TRACE) System.out.println("creating RMIProxyRemote " + c.getClass() + " " + host);
}
/**
*
*/
private RMIProxyRemote (Object c, MainAdapterClient Client) {
m_ObjectName = c.getClass().getName();
try {
m_RMIHandler = Client.getRMIHandler(c);
} catch (Exception e) {
System.out.println("RMIProxyRemote error ex "+e.getMessage());
e.printStackTrace();
}
if (TRACE) System.out.println("creating RMIProxyRemote " + c.getClass() + " " + Client.getClass());
}
/**
*
*/
private RMIProxyRemote (Object c) {
m_ObjectName = c.getClass().getName();
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_RMIHandler = m_Adapter.getRMIHandler(c);
}
/**
*
*/
public Object invoke (Object proxy, Method m, Object[] args) throws Throwable {
long start = System.currentTimeMillis();
++m_counter;
//System.out.println("Before invoke:" +m.getName());
Object ret = m_RMIHandler.invoke(m.getName(),args);
long finish = System.currentTimeMillis();
//System.out.println("Calling :"+m.getName()+" of "+m_ObjectName+ " time :"+(finish-start));
return ret;
}
/**
*
*/
// public static void main(String[] args) {
// Doit remotex = (Doit) RMIProxyRemote.newInstance(new DoitImpl(),"primergy4.informatik.uni-tuebingen.de");
// remotex.doit();
// remotex.doit();
// remotex.doit();
// remotex.doit();
// }
}

View File

@@ -0,0 +1,136 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/04/28 07:50:33 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIProxyRemoteThread implements InvocationHandler,
Serializable {
private static ComAdapter m_Adapter;
private Object m_Object;
private String m_ObjectName;
private RMIThreadInvocationHandler m_RMIThreadHandler;
/**
*
*/
public static Object newInstance (Object c,MainAdapterClient Client) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemoteThread(c,Client));
}
/**
*
*/
public static Object newInstance (Object c,String host) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemoteThread(c,host));
}
/**
*
* @param c
* @return
*/
public static String[] getServerList() {
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_Adapter.evalAvailableHostNameList();
return m_Adapter.getAvailableHostNameList();
}
public static void setServerList(String[] servers ) {
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_Adapter.setServerList(servers);
m_Adapter.evalAvailableHostNameList();
}
/**
*
*/
public static Object newInstance (Object c) {
return java.lang.reflect.Proxy.newProxyInstance (
c.getClass().getClassLoader(),
c.getClass().getInterfaces(),
new RMIProxyRemoteThread(c));
}
/**
*
*/
public static void setComAdaper(ComAdapter x) {
m_Adapter = x;
}
/**
*
*/
private RMIProxyRemoteThread (Object c, String host) {
m_ObjectName = c.getClass().getName();
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_Adapter.getRMIThreadHandler(c,host);
}
/**
*
*/
private RMIProxyRemoteThread (Object c, MainAdapterClient Client) {
m_ObjectName = c.getClass().getName();
try {
m_RMIThreadHandler = Client.getRMIThreadHandler(c);
} catch (Exception e) {
System.out.println("RMIProxyRemoteThreaderror ex "+e.getMessage());
e.printStackTrace();
}
}
/**
*
*/
private RMIProxyRemoteThread (Object c) {
m_ObjectName = c.getClass().getName();
if (m_Adapter==null) m_Adapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_Adapter.getRMIThreadHandler(c);
}
/**
*
*/
public Object invoke (Object proxy, Method m, Object[] args) throws Throwable {
//long start = System.currentTimeMillis();
//System.out.println("Before invoke:" +m.getName());
Object ret = null;
if (m.getName().equals("getServerName")) {
ret = m_RMIThreadHandler.getServerName();
} else {
ret = m_RMIThreadHandler.invoke(m.getName(), args);
}
//long finish = System.currentTimeMillis();
//System.out.println("Calling :"+m.getName()+" of "+m_ObjectName+ " time :"+(finish-start));
return ret;
}
/**
*
*/
// public static void main(String[] args) {
// Doit remotex = (Doit) RMIProxyRemoteThread.newInstance(new DoitImpl(),
// "ranode1.informatik.uni-tuebingen.de");
// remotex.doit();
// remotex.doit();
// remotex.doit();
// remotex.doit();
// }
}

View File

@@ -0,0 +1,194 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:31 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
///////////////////////////////////////////////////////////////
// -Xrunhprof:cpu=times
// -Djava.security.policy=server.policy
///////////////////////////////////////////////////////////////
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIServer {
/* Version string of the server application. */
public static boolean TRACE = false;
// public static Registry m_Registry;
protected static RMIServer m_instance;
/* Name of host on which the server is running. */
private String m_MyHostName = "undefined";
/* IP of host on which the server is running. */
private String m_MyHostIP = "undefined";
/* MainAdapterImp object. This is need for the first
connection between the server and the client program. */
public MainAdapter m_MainRemoteObject;
/* String describing the properties of the enviroment. */
// private ComAdapter m_ComAdapter;
public static String m_UserName;
public static int m_NumberOfVM = 0;
Registry m_Registry = null;
/**
*
*/
public static RMIServer getInstance() {
if (m_instance == null) {
m_instance = new RMIServer();
}
return m_instance;
}
/**
* Constructor of EvAServer.
* Calls RMIConnection().
*/
protected RMIServer() {
m_UserName = System.getProperty("user.name");
//System.out.println(EVAHELP.getSystemPropertyString());
initConnection();
// m_ComAdapter = ComAdapter.getInstance();
}
/**
* Main method of this class.
* Is the starting point of the server application.
*/
static public void main(String[] args) {
System.out.println("Start RMIServer !");
RMIServer Application = RMIServer.getInstance();
}
/**
* Launchs the RMIRegistry and makes the registration
* of the MainAdapterImpl class at the rmiregistry.
* @param
*/
private void initConnection() {
String MainAdapterName = m_UserName + MainAdapterImpl.MAIN_ADAPTER_NAME;
System.setProperty("java.security.policy", "server.policy");
launchRMIRegistry();
try {
m_MyHostIP = InetAddress.getLocalHost().getHostAddress();
m_MyHostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
System.out.println("ERROR getting HostName (RMIServer.initConnection)" + e.getMessage());
}
System.out.println("Start of EvA RMI-Server on host " + m_MyHostName + " = " + m_MyHostIP);
// Object test = null;
try {
try {
String[] list =
Naming.list("rmi://localhost:" + MainAdapterImpl.PORT);
// System.out.println("-->list");
// for (int i = 0; i < list.length; i++)
// System.out.println("-->RMIName" + list[i]);
m_NumberOfVM = getNumberOfVM(list);
} catch (RemoteException e) {
System.err.println("no RMI registry available yet...");
if (TRACE)
System.out.println(
"RemoteException OK IAM the first server for this rmiregistry: "
+ e.getMessage());
}
} catch (MalformedURLException ex) {
System.out.println(
"MalformedURLException: Error while looking up "
+ ex.getMessage());
}
createMainRemoteObject(MainAdapterName);
System.out.println("End of RMI-Server Initialisation");
System.out.println(" --> OK on Host: " + m_MyHostName + " = " + m_MyHostIP + ", adapter name is " + MainAdapterName);
System.out.println("Waiting for a client ..............");
}
protected void createMainRemoteObject(String mainAdapterName) {
try {
m_MainRemoteObject = new MainAdapterImpl();
m_MainRemoteObject =
(MainAdapter) RMIProxyLocal.newInstance(m_MainRemoteObject,mainAdapterName + "_" + m_NumberOfVM);
m_MainRemoteObject.setRemoteThis(m_MainRemoteObject);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
public MainAdapter getMainRemoteObject() {
return m_MainRemoteObject;
}
/**
* Install RMIregistry on default port !!
*/
private void launchRMIRegistry() {
if (TRACE)
System.out.println(
"LaunchRMIRegistry on Server on PORT " + MainAdapterImpl.PORT);
try {
m_Registry =
java.rmi.registry.LocateRegistry.createRegistry(
MainAdapterImpl.PORT);
} catch (Throwable e) {
if (TRACE)
System.out.println("Registry not created !!" + e.getMessage());
m_Registry = null;
}
if (m_Registry == null) {
System.out.println(
"Try to get registry with getRegistry on PORT "
+ MainAdapterImpl.PORT);
try {
m_Registry =
java.rmi.registry.LocateRegistry.getRegistry(
MainAdapterImpl.PORT);
if (TRACE)
System.out.println(
"m_Registry.REGISTRY_PORT=" + m_Registry.REGISTRY_PORT);
} catch (Throwable e) {
if (TRACE)
System.out.println(
"registry notcreated !!" + e.getMessage());
m_Registry = null;
}
}
if (m_Registry == null) {
System.err.println("--> got no RMIREGISTRY");
} else if (TRACE) System.out.println("--> got RMIREGISTRY");
}
/**
*
*/
private int getNumberOfVM(String[] list) {
int ret = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1)
ret++;
}
if (TRACE)
System.out.println(" getNumberOfVM() NumberOfVM =" + ret);
return ret;
}
}

View File

@@ -0,0 +1,27 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:31 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.rmi.Remote;
import java.rmi.RemoteException;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface RMIThreadInvocationHandler extends Remote {
public Object invoke (String m, Object[] args)throws RemoteException;
public Object getWrapper () throws RemoteException;
public void setWrapper(Object Wrapper) throws RemoteException;
public String getServerName()throws RemoteException;
}

View File

@@ -0,0 +1,147 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/04/15 12:28:34 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import wsi.ra.math.RNG;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RMIThreadInvocationHandlerImpl extends UnicastRemoteObject implements RMIThreadInvocationHandler {
public static final boolean TRACE = false;
private Object m_Object;
private String m_AdapterName;
private Object m_Wrapper;
private Method[] m_list;
private String m_hostname;
/**
*
* @return
*/
public String getServerName() {
return m_hostname;
}
/**
*
*/
public RMIThreadInvocationHandlerImpl(Object obj) throws RemoteException {
try {
m_hostname = InetAddress.getLocalHost().getHostName();
}
catch (Exception e) {
System.out.println("ERROR getting HostName (RMIThreadInvokationHandlerImpl(obj))" + e.getMessage());
}
m_AdapterName = obj.getClass().getName()+"_"+RNG.randomInt(0,10000);
try {
m_Object = ThreadProxy.newInstance(obj);
m_list = m_Object.getClass().getMethods();
if (TRACE) System.out.println(" --> rebind : "+m_AdapterName+" RMIThreadInvokationHandlerImpl of object "+obj.getClass().getName());
Naming.rebind(m_AdapterName,this);
} catch (Exception e) {
System.out.println(" Naming.rebind --> ERROR" + e.getMessage());
e.printStackTrace();
}
}
/**
*
*/
public RMIThreadInvocationHandlerImpl(Object obj,String AdapterName) throws RemoteException {
try {
m_hostname = InetAddress.getLocalHost().getHostName();
}
catch (Exception e) {
System.out.println("ERROR getting HostName (RMIThreadInvokationHandlerImpl(obj,adapt))" + e.getMessage());
}
m_AdapterName = AdapterName;
try {
m_Object = ThreadProxy.newInstance(obj);
m_list = m_Object.getClass().getMethods();
if (TRACE) System.out.println(" -----> rebind : "+m_AdapterName+" "+this.getClass().getName()+" of object "+obj.getClass().getName());
Naming.rebind(m_AdapterName,this);
} catch (Exception e) {
System.out.println(" Naming.rebind --> ERROR" + e.getMessage());
}
}
/**
*
*/
public void setWrapper(Object Wrapper) throws RemoteException {
m_Wrapper = Wrapper;
}
/**
*
*/
public Object getWrapper () throws RemoteException {
return m_Wrapper;
}
/**
*
*/
public Object invoke (String m, Object[] args) throws RemoteException {
Object ret=null;
String Name = "";
if (TRACE) Name = Thread.currentThread().getName();
try {
if (TRACE) System.out.println( Name+" Before invoke on server :" +m);
//Method[] list = m_Object.getClass().getMethods();
boolean invoked = false;
for (int i=0;i<m_list.length;i++) {
//if (TRACE) System.out.println(Name+" list[i].getName() "+list[i].getName());
if (m.startsWith("free") == true) {
// System.out.println("called free !!!!!!!!!!!!!!!!!!!!!!!!!" + m_AdapterName);
String[] list = Naming.list("rmi://localhost:" + MainAdapterImpl.PORT);
// System.out.println("-->list :" + list.length);
for (int j = 0; j < list.length; j++) {
// System.out.println("list=" + list[j] + "--" + m_AdapterName);
if (list[j].lastIndexOf(m_AdapterName) != -1) {
// System.out.println("unbind !!!!!!!!!!!!!!!!!!!!!!!!!!");
Naming.unbind(list[j]);
return null;
}
}
System.out.println("Object not found !!!!!");
return null;
}
if (m.equals(m_list[i].getName())==true) {
//if (TRACE)System.out.println(Name+" find "+m);
//if (args==null) System.out.println(Name+" args==null ");
ret = m_list[i].invoke(m_Object,args);
invoked= true;
break;
}
}
if (invoked==false) System.out.println(Name+ " No memberfunction found !!!!!!!!!!!!!!!!!");
}
catch ( InvocationTargetException e) {
e.printStackTrace();
System.out.println(Name+" RMIThreadInvokationHandlerImpl InvocationTargetException "+e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
System.out.println(Name+" Exception :"+e.getMessage());
}
return ret;
}
}

View File

@@ -0,0 +1,27 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.1 $
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface RemoteStateListener {
public void performedStop();
public void performedStart(String infoString);
public void performedRestart(String infoString);
public void updateProgress(final int percent);
}

View File

@@ -0,0 +1,96 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/04/28 07:50:33 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class ThreadProxy implements InvocationHandler,
Serializable {
private Object m_Object;
private ThreadWrapper m_ThreadWrapper;
private int m_maxthreads = 8;
/**
*
*/
public static Object newInstance (Object obj) {
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new ThreadProxy(obj));
}
/**
*
*/
public static Object newInstance (Object obj,int maxthreads) {
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new ThreadProxy(obj,maxthreads));
}
/**
*
*/
public ThreadProxy (Object obj) {
m_Object = obj;
}
/**
*
*/
public ThreadProxy (Object obj,int maxthreads) {
m_Object = obj;
m_maxthreads = maxthreads;
}
/**
*
*/
public Object invoke (Object proxy,Method method,Object[] args) throws Throwable {
Class rettype = method.getReturnType();
if (rettype.equals(Void.TYPE)== true) {
if (m_ThreadWrapper == null) {
m_ThreadWrapper = new ThreadWrapper(m_maxthreads);
}
else {
m_ThreadWrapper.pleasewait();
}
m_ThreadWrapper.invoke(m_Object,method,args);
return null;
}
Object ret = null;
try {
if (method.getName().equals("isAlive")) {
if (m_ThreadWrapper != null) {
Boolean rret = new Boolean(m_ThreadWrapper.isAlive());
// System.out.println("calling is alive" +rret);
return rret;
}
}
if (m_ThreadWrapper != null)
m_ThreadWrapper.pleasewait();
ret = method.invoke(m_Object, args);
} catch (Exception e) {
System.out.println("ERROR +" + e.getMessage());
e.printStackTrace();
}
return ret;
}
}

View File

@@ -0,0 +1,83 @@
package wsi.ra.jproxy;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 1.2 $
* $Date: 2004/04/28 07:50:33 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.io.Serializable;
/*
* ==========================================================================*
* CLASS DECLARATION
* ==========================================================================
*/
public class ThreadWrapper extends ArrayList {
private int m_counter = 0;
private ArrayList m_ThreadContainer = new ArrayList();
private static int m_numberofMAXThreads = 4;
/**
*
*/
public ThreadWrapper(int number) {
m_numberofMAXThreads = number;
}
/**
*
*/
public ThreadWrapper() {
}
/**
*
*/
public synchronized void invoke(Object x, String Method, Object[] Para) {
m_ThreadContainer.add(XThread.getXThread(x, Method, Para, m_numberofMAXThreads));
// System.out.println("ADDED to THREADWRAPPER LIST" + m_ThreadContainer.size());
}
/**
*
*/
public synchronized void invoke(Object x, Method m, Object[] Para) {
m_ThreadContainer.add(XThread.getXThread(x, m, Para, m_numberofMAXThreads));
// System.out.println("ADDED to THREADWRAPPER LIST" + m_ThreadContainer.size());
}
/**
*
*/
public synchronized void pleasewait() {
for (int i = 0; i < m_ThreadContainer.size(); i++) {
try {
((Thread) m_ThreadContainer.get(i)).join();
m_ThreadContainer.remove(i); // testhu
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error");
}
}
}
/**
*
*/
public synchronized boolean isAlive() {
for (int i = 0; i < m_ThreadContainer.size(); i++) {
boolean alive = ((Thread) m_ThreadContainer.get(i)).isAlive();
if (alive == true)
return true;
}
return false;
}
}

View File

@@ -0,0 +1,257 @@
package wsi.ra.jproxy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.io.Serializable;
/*
* ==========================================================================*
* CLASS DECLARATION
* ==========================================================================
*/
public class XThread extends Thread implements Serializable {
private Object m_Object;
private volatile Method m_Method;
private volatile Object[] m_Para;
//private static byte m_instances = 0;
private static XThread[] m_Instances;
private static int m_MAXinstances = 10;
private static int m_index = 0;
public static void init(int x) {
m_MAXinstances = x;
m_Instances = new XThread[m_MAXinstances];
m_index = 0;
}
// private static void instup() {
// m_instances++;
// }
//
// private static void instdown() {
// m_instances--;
// }
public static int get() {
int ret =0;
if (m_Instances==null) return ret;
for (int i=0;i<m_Instances.length;i++) {
if (m_Instances[i]==null) continue;
if (m_Instances[i].isAlive() == true)
ret++;
}
return ret;
}
/**
*
*/
public static XThread getXThread(Object x, Method m, Object[] Para, int MAXinstances) {
System.out.println("getXThread2 CALLLED");
//System.out.println("waiting "+m_instances+ " on "+x.hashCode()+ " m "+m.getName()+" m_MAXinstances " +MAXinstances);
XThread ret = null;
if (m_Instances == null)
init(MAXinstances);
if (m_index >= m_Instances.length)
m_index = 0;
if (m_Instances[m_index] == null) {
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
int w = 1;
while (true) {
for (int i = 0; i < m_Instances.length; i++) {
if (m_Instances[i] == null) {
m_index = i;
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
if (m_Instances[i].isAlive() == false) {
m_index = i;
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
}
try {
Thread.sleep(w);
w = 2 * w; //System.out.println(""+i);
} catch (Exception e) {
System.out.println("Error in sleep of XThread");
}
} // end of while true
// int i=1;
// while (m_instances >= MAXinstances) {
// // if (i>200)
// // System.out.println(i+ " waiting "+m_instances+ " on "+x.hashCode()+ " m "+m.getName()+" m_MAXinstances " +MAXinstances);
// // pleasewait();
// try {
// Thread.sleep(i);
// i=2*i; //System.out.println(""+i);
// } catch (Exception e) {
// System.out.println("Error in sleep of XThread");
// }
// }
// instup();//m_instances++;
// if (
// XThread ret = new XThread(x, m, Para);
// // m_ThreadContainer.add(ret);
// return ret;
}
/**
*
*/
public static XThread getXThread(Object x, String m, Object[] Para, int MAXinstances) {
System.out.println("getXThread1 CALLLED");
// while (m_instances >= MAXinstances) {
// //System.out.println("waiting "+m_instances);
// //pleasewait();
// try {
// Thread.sleep(50);
// } catch (Exception e) {
// System.out.println("Error in sleep of XThread");
// }
// }
// instup(); //m_instances++;
// //System.out.println("XThread ++"+m_instances+" m_MAXinstances " +m_MAXinstances);
// XThread ret = new XThread(x, Method, Para);
// // m_ThreadContainer.add(ret);
// return ret;
XThread ret = null;
if (m_Instances == null)
init(MAXinstances);
if (m_index >= m_Instances.length)
m_index = 0;
if (m_Instances[m_index] == null) {
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
int w = 1;
while (true) {
for (int i = 0; i < m_Instances.length; i++) {
if (m_Instances[i] == null) {
m_index = i;
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
if (m_Instances[i].isAlive() == false) {
m_index = i;
ret = new XThread(x, m, Para);
m_Instances[m_index] = ret;
m_index++;
return ret;
}
}
try {
Thread.sleep(w);
w = 2 * w; //System.out.println(""+i);
} catch (Exception e) {
System.out.println("Error in sleep of XThread");
}
} // end of while true
}
/**
*
*/
// public static synchronized void pleasewait() {
// for (int i = 0; i < m_ThreadContainer.size(); i++) {
// try {
// if (((Thread) m_ThreadContainer.get(i)).isAlive()==false)
// m_ThreadContainer.remove(i);
// } catch (InterruptedException e) {
// e.printStackTrace();
// System.out.println("Error");
// }
// }
// }
private void removemyself() {
for (int i = 0; i < m_Instances.length; i++) {
System.out.println("TRYING TO REMOVE");
if (this.m_Instances[i] == this) {
this.m_Instances[i] = null;
System.out.println("REMOVED");
return;
}
}
System.out.println("DANGER!!!!!!!!! XTHREAD ->NOT<- REMOVED");
}
/**
*
*/
private XThread(Object object, Method method, Object[] Para) {
System.out.println("XTHREAD INSTANZIERT");
m_Object = object;
m_Para = Para;
m_Method = method;
start();
}
/**
*
*/
private XThread(Object x, String method, Object[] Para) {
System.out.println("XTHREAD INSTANZIERT");
m_Object = x;
m_Para = Para;
try {
Method[] methods = x.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(method) == true) {
m_Method = methods[i];
break;
}
}
} catch (Exception e) {
System.out.println(" ERROR in XTHREAD +" + e.getMessage());
e.printStackTrace();
}
start();
}
/**
*
*/
public void run() {
System.out.println("XTHREAD CALLED RUN");
if (m_Method != null) {
//setPriority(Thread.MAX_PRIORITY);
try {
System.out.println("XTHREAD calling m_Method"+m_Method.getName());
//System.out.print("--->");
//this.setPriority(Thread.MAX_PRIORITY);
m_Method.invoke(m_Object, m_Para);
//instdown(); //m_instances--;
//System.out.println("<--");
//System.out.println("XThread --"+m_instances+" m_MAXinstances " +m_MAXinstances);
} catch (Exception e) {
System.out.println("ERROR +" + e.getMessage());
e.printStackTrace();
}
} else {
System.out.println("Warning Method == null !!!!! in ThreadWrapper");
}
removemyself();
}
}

View File

@@ -0,0 +1,182 @@
package wsi.ra.math.Jama;
/** Cholesky Decomposition.
<P>
For a symmetric, positive definite matrix A, the Cholesky decomposition
is an lower triangular matrix L so that A = L*L'.
<P>
If the matrix is not symmetric or positive definite, the constructor
returns a partial decomposition and sets an internal flag that may
be queried by the isSPD() method.
*/
public class CholeskyDecomposition implements java.io.Serializable {
/* ------------------------
Class variables
* ------------------------ */
/** Array for internal storage of decomposition.
@serial internal array storage.
*/
private double[][] L;
/** Row and column dimension (square matrix).
@serial matrix dimension.
*/
private int n;
/** Symmetric and positive definite flag.
@serial is symmetric and positive definite flag.
*/
private boolean isspd;
/* ------------------------
Constructor
* ------------------------ */
/** Cholesky algorithm for symmetric and positive definite matrix.
@param A Square, symmetric matrix.
@return Structure to access L and isspd flag.
*/
public CholeskyDecomposition (Matrix Arg) {
// Initialize.
double[][] A = Arg.getArray();
n = Arg.getRowDimension();
L = new double[n][n];
isspd = (Arg.getColumnDimension() == n);
// Main loop.
for (int j = 0; j < n; j++) {
double[] Lrowj = L[j];
double d = 0.0;
for (int k = 0; k < j; k++) {
double[] Lrowk = L[k];
double s = 0.0;
for (int i = 0; i < k; i++) {
s += Lrowk[i]*Lrowj[i];
}
Lrowj[k] = s = (A[j][k] - s)/L[k][k];
d = d + s*s;
isspd = isspd & (A[k][j] == A[j][k]);
}
d = A[j][j] - d;
isspd = isspd & (d > 0.0);
L[j][j] = Math.sqrt(Math.max(d,0.0));
for (int k = j+1; k < n; k++) {
L[j][k] = 0.0;
}
}
}
// \** Right Triangular Cholesky Decomposition.
// <P>
// For a symmetric, positive definite matrix A, the Right Cholesky
// decomposition is an upper triangular matrix R so that A = R'*R.
// This constructor computes R with the Fortran inspired column oriented
// algorithm used in LINPACK and MATLAB. In Java, we suspect a row oriented,
// lower triangular decomposition is faster. We have temporarily included
// this constructor here until timing experiments confirm this suspicion.
// *\
private transient double[][] R;
public CholeskyDecomposition (Matrix Arg, int rightflag) {
// Initialize.
double[][] A = Arg.getArray();
n = Arg.getColumnDimension();
R = new double[n][n];
isspd = (Arg.getColumnDimension() == n);
// Main loop.
for (int j = 0; j < n; j++) {
double d = 0.0;
for (int k = 0; k < j; k++) {
double s = A[k][j];
for (int i = 0; i < k; i++) {
s = s - R[i][k]*R[i][j];
}
R[k][j] = s = s/R[k][k];
d = d + s*s;
isspd = isspd & (A[k][j] == A[j][k]);
}
d = A[j][j] - d;
isspd = isspd & (d > 0.0);
R[j][j] = Math.sqrt(Math.max(d,0.0));
for (int k = j+1; k < n; k++) {
R[k][j] = 0.0;
}
}
}
public Matrix getR () {
return new Matrix(R,n,n);
}
/** Is the matrix symmetric and positive definite?
@return true if A is symmetric and positive definite.
*/
public boolean isSPD () {
return isspd;
}
/** Return triangular factor.
@return L
*/
public Matrix getL () {
return new Matrix(L,n,n);
}
/** Solve A*X = B
@param B A Matrix with as many rows as A and any number of columns.
@return X so that L*L'*X = B
@exception IllegalArgumentException Matrix row dimensions must agree.
@exception RuntimeException Matrix is not symmetric positive definite.
*/
public Matrix solve (Matrix B) {
if (B.getRowDimension() != n) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!isspd) {
throw new RuntimeException("Matrix is not symmetric positive definite.");
}
// Copy right hand side.
double[][] X = B.getArrayCopy();
int nx = B.getColumnDimension();
// Solve L*Y = B;
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*L[i][k];
}
}
for (int j = 0; j < nx; j++) {
X[k][j] /= L[k][k];
}
}
// Solve L'*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= L[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*L[k][i];
}
}
}
return new Matrix(X,n,nx);
}
}

View File

@@ -0,0 +1,956 @@
package wsi.ra.math.Jama;
import wsi.ra.math.Jama.util.Maths;
/** Eigenvalues and eigenvectors of a real matrix.
<P>
If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is
diagonal and the eigenvector matrix V is orthogonal.
I.e. A = V.times(D.times(V.transpose())) and
V.times(V.transpose()) equals the identiCty matrix.
<P>
If A is not symmetric, then the eigenvalue matrix D is block diagonal
with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues,
lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The
columns of V represent the eigenvectors in the sense that A*V = V*D,
i.e. A.times(V) equals V.times(D). The matrix V may be badly
conditioned, or even singular, so the validity of the equation
A = V*D*inverse(V) depends upon V.cond().
**/
public class EigenvalueDecomposition implements java.io.Serializable {
/* ------------------------
Class variables
* ------------------------ */
/** Row and column dimension (square matrix).
@serial matrix dimension.
*/
private int n;
/** Symmetry flag.
@serial internal symmetry flag.
*/
private boolean issymmetric;
/** Arrays for internal storage of eigenvalues.
@serial internal storage of eigenvalues.
*/
private double[] d, e;
/** Array for internal storage of eigenvectors.
@serial internal storage of eigenvectors.
*/
private double[][] V;
/** Array for internal storage of nonsymmetric Hessenberg form.
@serial internal storage of nonsymmetric Hessenberg form.
*/
private double[][] H;
/** Working storage for nonsymmetric algorithm.
@serial working storage for nonsymmetric algorithm.
*/
private double[] ort;
/* ------------------------
Private Methods
* ------------------------ */
// Symmetric Householder reduction to tridiagonal form.
private void tred2 () {
// This is derived from the Algol procedures tred2 by
// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
for (int j = 0; j < n; j++) {
d[j] = V[n-1][j];
}
// Householder reduction to tridiagonal form.
for (int i = n-1; i > 0; i--) {
// Scale to avoid under/overflow.
double scale = 0.0;
double h = 0.0;
for (int k = 0; k < i; k++) {
scale = scale + Math.abs(d[k]);
}
if (scale == 0.0) {
e[i] = d[i-1];
for (int j = 0; j < i; j++) {
d[j] = V[i-1][j];
V[i][j] = 0.0;
V[j][i] = 0.0;
}
} else {
// Generate Householder vector.
for (int k = 0; k < i; k++) {
d[k] /= scale;
h += d[k] * d[k];
}
double f = d[i-1];
double g = Math.sqrt(h);
if (f > 0) {
g = -g;
}
e[i] = scale * g;
h = h - f * g;
d[i-1] = f - g;
for (int j = 0; j < i; j++) {
e[j] = 0.0;
}
// Apply similarity transformation to remaining columns.
for (int j = 0; j < i; j++) {
f = d[j];
V[j][i] = f;
g = e[j] + V[j][j] * f;
for (int k = j+1; k <= i-1; k++) {
g += V[k][j] * d[k];
e[k] += V[k][j] * f;
}
e[j] = g;
}
f = 0.0;
for (int j = 0; j < i; j++) {
e[j] /= h;
f += e[j] * d[j];
}
double hh = f / (h + h);
for (int j = 0; j < i; j++) {
e[j] -= hh * d[j];
}
for (int j = 0; j < i; j++) {
f = d[j];
g = e[j];
for (int k = j; k <= i-1; k++) {
V[k][j] -= (f * e[k] + g * d[k]);
}
d[j] = V[i-1][j];
V[i][j] = 0.0;
}
}
d[i] = h;
}
// Accumulate transformations.
for (int i = 0; i < n-1; i++) {
V[n-1][i] = V[i][i];
V[i][i] = 1.0;
double h = d[i+1];
if (h != 0.0) {
for (int k = 0; k <= i; k++) {
d[k] = V[k][i+1] / h;
}
for (int j = 0; j <= i; j++) {
double g = 0.0;
for (int k = 0; k <= i; k++) {
g += V[k][i+1] * V[k][j];
}
for (int k = 0; k <= i; k++) {
V[k][j] -= g * d[k];
}
}
}
for (int k = 0; k <= i; k++) {
V[k][i+1] = 0.0;
}
}
for (int j = 0; j < n; j++) {
d[j] = V[n-1][j];
V[n-1][j] = 0.0;
}
V[n-1][n-1] = 1.0;
e[0] = 0.0;
}
// Symmetric tridiagonal QL algorithm.
private void tql2 () {
// This is derived from the Algol procedures tql2, by
// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
for (int i = 1; i < n; i++) {
e[i-1] = e[i];
}
e[n-1] = 0.0;
double f = 0.0;
double tst1 = 0.0;
double eps = Math.pow(2.0,-52.0);
for (int l = 0; l < n; l++) {
// Find small subdiagonal element
tst1 = Math.max(tst1,Math.abs(d[l]) + Math.abs(e[l]));
int m = l;
while (m < n) {
if (Math.abs(e[m]) <= eps*tst1) {
break;
}
m++;
}
// If m == l, d[l] is an eigenvalue,
// otherwise, iterate.
if (m > l) {
int iter = 0;
do {
iter = iter + 1; // (Could check iteration count here.)
// Compute implicit shift
double g = d[l];
double p = (d[l+1] - g) / (2.0 * e[l]);
double r = Maths.hypot(p,1.0);
if (p < 0) {
r = -r;
}
d[l] = e[l] / (p + r);
d[l+1] = e[l] * (p + r);
double dl1 = d[l+1];
double h = g - d[l];
for (int i = l+2; i < n; i++) {
d[i] -= h;
}
f = f + h;
// Implicit QL transformation.
p = d[m];
double c = 1.0;
double c2 = c;
double c3 = c;
double el1 = e[l+1];
double s = 0.0;
double s2 = 0.0;
for (int i = m-1; i >= l; i--) {
c3 = c2;
c2 = c;
s2 = s;
g = c * e[i];
h = c * p;
r = Maths.hypot(p,e[i]);
e[i+1] = s * r;
s = e[i] / r;
c = p / r;
p = c * d[i] - s * g;
d[i+1] = h + s * (c * g + s * d[i]);
// Accumulate transformation.
for (int k = 0; k < n; k++) {
h = V[k][i+1];
V[k][i+1] = s * V[k][i] + c * h;
V[k][i] = c * V[k][i] - s * h;
}
}
p = -s * s2 * c3 * el1 * e[l] / dl1;
e[l] = s * p;
d[l] = c * p;
// Check for convergence.
} while (Math.abs(e[l]) > eps*tst1);
}
d[l] = d[l] + f;
e[l] = 0.0;
}
// Sort eigenvalues and corresponding vectors.
for (int i = 0; i < n-1; i++) {
int k = i;
double p = d[i];
for (int j = i+1; j < n; j++) {
if (d[j] < p) {
k = j;
p = d[j];
}
}
if (k != i) {
d[k] = d[i];
d[i] = p;
for (int j = 0; j < n; j++) {
p = V[j][i];
V[j][i] = V[j][k];
V[j][k] = p;
}
}
}
}
// Nonsymmetric reduction to Hessenberg form.
private void orthes () {
// This is derived from the Algol procedures orthes and ortran,
// by Martin and Wilkinson, Handbook for Auto. Comp.,
// Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutines in EISPACK.
int low = 0;
int high = n-1;
for (int m = low+1; m <= high-1; m++) {
// Scale column.
double scale = 0.0;
for (int i = m; i <= high; i++) {
scale = scale + Math.abs(H[i][m-1]);
}
if (scale != 0.0) {
// Compute Householder transformation.
double h = 0.0;
for (int i = high; i >= m; i--) {
ort[i] = H[i][m-1]/scale;
h += ort[i] * ort[i];
}
double g = Math.sqrt(h);
if (ort[m] > 0) {
g = -g;
}
h = h - ort[m] * g;
ort[m] = ort[m] - g;
// Apply Householder similarity transformation
// H = (I-u*u'/h)*H*(I-u*u')/h)
for (int j = m; j < n; j++) {
double f = 0.0;
for (int i = high; i >= m; i--) {
f += ort[i]*H[i][j];
}
f = f/h;
for (int i = m; i <= high; i++) {
H[i][j] -= f*ort[i];
}
}
for (int i = 0; i <= high; i++) {
double f = 0.0;
for (int j = high; j >= m; j--) {
f += ort[j]*H[i][j];
}
f = f/h;
for (int j = m; j <= high; j++) {
H[i][j] -= f*ort[j];
}
}
ort[m] = scale*ort[m];
H[m][m-1] = scale*g;
}
}
// Accumulate transformations (Algol's ortran).
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
V[i][j] = (i == j ? 1.0 : 0.0);
}
}
for (int m = high-1; m >= low+1; m--) {
if (H[m][m-1] != 0.0) {
for (int i = m+1; i <= high; i++) {
ort[i] = H[i][m-1];
}
for (int j = m; j <= high; j++) {
double g = 0.0;
for (int i = m; i <= high; i++) {
g += ort[i] * V[i][j];
}
// Double division avoids possible underflow
g = (g / ort[m]) / H[m][m-1];
for (int i = m; i <= high; i++) {
V[i][j] += g * ort[i];
}
}
}
}
}
// Complex scalar division.
private transient double cdivr, cdivi;
private void cdiv(double xr, double xi, double yr, double yi) {
double r,d;
if (Math.abs(yr) > Math.abs(yi)) {
r = yi/yr;
d = yr + r*yi;
cdivr = (xr + r*xi)/d;
cdivi = (xi - r*xr)/d;
} else {
r = yr/yi;
d = yi + r*yr;
cdivr = (r*xr + xi)/d;
cdivi = (r*xi - xr)/d;
}
}
// Nonsymmetric reduction from Hessenberg to real Schur form.
private void hqr2 () {
// This is derived from the Algol procedure hqr2,
// by Martin and Wilkinson, Handbook for Auto. Comp.,
// Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
// Initialize
int nn = this.n;
int n = nn-1;
int low = 0;
int high = nn-1;
double eps = Math.pow(2.0,-52.0);
double exshift = 0.0;
double p=0,q=0,r=0,s=0,z=0,t,w,x,y;
// Store roots isolated by balanc and compute matrix norm
double norm = 0.0;
for (int i = 0; i < nn; i++) {
if (i < low | i > high) {
d[i] = H[i][i];
e[i] = 0.0;
}
for (int j = Math.max(i-1,0); j < nn; j++) {
norm = norm + Math.abs(H[i][j]);
}
}
// Outer loop over eigenvalue index
int iter = 0;
while (n >= low) {
// Look for single small sub-diagonal element
int l = n;
while (l > low) {
s = Math.abs(H[l-1][l-1]) + Math.abs(H[l][l]);
if (s == 0.0) {
s = norm;
}
if (Math.abs(H[l][l-1]) < eps * s) {
break;
}
l--;
}
// Check for convergence
// One root found
if (l == n) {
H[n][n] = H[n][n] + exshift;
d[n] = H[n][n];
e[n] = 0.0;
n--;
iter = 0;
// Two roots found
} else if (l == n-1) {
w = H[n][n-1] * H[n-1][n];
p = (H[n-1][n-1] - H[n][n]) / 2.0;
q = p * p + w;
z = Math.sqrt(Math.abs(q));
H[n][n] = H[n][n] + exshift;
H[n-1][n-1] = H[n-1][n-1] + exshift;
x = H[n][n];
// Real pair
if (q >= 0) {
if (p >= 0) {
z = p + z;
} else {
z = p - z;
}
d[n-1] = x + z;
d[n] = d[n-1];
if (z != 0.0) {
d[n] = x - w / z;
}
e[n-1] = 0.0;
e[n] = 0.0;
x = H[n][n-1];
s = Math.abs(x) + Math.abs(z);
p = x / s;
q = z / s;
r = Math.sqrt(p * p+q * q);
p = p / r;
q = q / r;
// Row modification
for (int j = n-1; j < nn; j++) {
z = H[n-1][j];
H[n-1][j] = q * z + p * H[n][j];
H[n][j] = q * H[n][j] - p * z;
}
// Column modification
for (int i = 0; i <= n; i++) {
z = H[i][n-1];
H[i][n-1] = q * z + p * H[i][n];
H[i][n] = q * H[i][n] - p * z;
}
// Accumulate transformations
for (int i = low; i <= high; i++) {
z = V[i][n-1];
V[i][n-1] = q * z + p * V[i][n];
V[i][n] = q * V[i][n] - p * z;
}
// Complex pair
} else {
d[n-1] = x + p;
d[n] = x + p;
e[n-1] = z;
e[n] = -z;
}
n = n - 2;
iter = 0;
// No convergence yet
} else {
// Form shift
x = H[n][n];
y = 0.0;
w = 0.0;
if (l < n) {
y = H[n-1][n-1];
w = H[n][n-1] * H[n-1][n];
}
// Wilkinson's original ad hoc shift
if (iter == 10) {
exshift += x;
for (int i = low; i <= n; i++) {
H[i][i] -= x;
}
s = Math.abs(H[n][n-1]) + Math.abs(H[n-1][n-2]);
x = y = 0.75 * s;
w = -0.4375 * s * s;
}
// MATLAB's new ad hoc shift
if (iter == 30) {
s = (y - x) / 2.0;
s = s * s + w;
if (s > 0) {
s = Math.sqrt(s);
if (y < x) {
s = -s;
}
s = x - w / ((y - x) / 2.0 + s);
for (int i = low; i <= n; i++) {
H[i][i] -= s;
}
exshift += s;
x = y = w = 0.964;
}
}
iter = iter + 1; // (Could check iteration count here.)
// Look for two consecutive small sub-diagonal elements
int m = n-2;
while (m >= l) {
z = H[m][m];
r = x - z;
s = y - z;
p = (r * s - w) / H[m+1][m] + H[m][m+1];
q = H[m+1][m+1] - z - r - s;
r = H[m+2][m+1];
s = Math.abs(p) + Math.abs(q) + Math.abs(r);
p = p / s;
q = q / s;
r = r / s;
if (m == l) {
break;
}
if (Math.abs(H[m][m-1]) * (Math.abs(q) + Math.abs(r)) <
eps * (Math.abs(p) * (Math.abs(H[m-1][m-1]) + Math.abs(z) +
Math.abs(H[m+1][m+1])))) {
break;
}
m--;
}
for (int i = m+2; i <= n; i++) {
H[i][i-2] = 0.0;
if (i > m+2) {
H[i][i-3] = 0.0;
}
}
// Double QR step involving rows l:n and columns m:n
for (int k = m; k <= n-1; k++) {
boolean notlast = (k != n-1);
if (k != m) {
p = H[k][k-1];
q = H[k+1][k-1];
r = (notlast ? H[k+2][k-1] : 0.0);
x = Math.abs(p) + Math.abs(q) + Math.abs(r);
if (x != 0.0) {
p = p / x;
q = q / x;
r = r / x;
}
}
if (x == 0.0) {
break;
}
s = Math.sqrt(p * p + q * q + r * r);
if (p < 0) {
s = -s;
}
if (s != 0) {
if (k != m) {
H[k][k-1] = -s * x;
} else if (l != m) {
H[k][k-1] = -H[k][k-1];
}
p = p + s;
x = p / s;
y = q / s;
z = r / s;
q = q / p;
r = r / p;
// Row modification
for (int j = k; j < nn; j++) {
p = H[k][j] + q * H[k+1][j];
if (notlast) {
p = p + r * H[k+2][j];
H[k+2][j] = H[k+2][j] - p * z;
}
H[k][j] = H[k][j] - p * x;
H[k+1][j] = H[k+1][j] - p * y;
}
// Column modification
for (int i = 0; i <= Math.min(n,k+3); i++) {
p = x * H[i][k] + y * H[i][k+1];
if (notlast) {
p = p + z * H[i][k+2];
H[i][k+2] = H[i][k+2] - p * r;
}
H[i][k] = H[i][k] - p;
H[i][k+1] = H[i][k+1] - p * q;
}
// Accumulate transformations
for (int i = low; i <= high; i++) {
p = x * V[i][k] + y * V[i][k+1];
if (notlast) {
p = p + z * V[i][k+2];
V[i][k+2] = V[i][k+2] - p * r;
}
V[i][k] = V[i][k] - p;
V[i][k+1] = V[i][k+1] - p * q;
}
} // (s != 0)
} // k loop
} // check convergence
} // while (n >= low)
// Backsubstitute to find vectors of upper triangular form
if (norm == 0.0) {
return;
}
for (n = nn-1; n >= 0; n--) {
p = d[n];
q = e[n];
// Real vector
if (q == 0) {
int l = n;
H[n][n] = 1.0;
for (int i = n-1; i >= 0; i--) {
w = H[i][i] - p;
r = 0.0;
for (int j = l; j <= n; j++) {
r = r + H[i][j] * H[j][n];
}
if (e[i] < 0.0) {
z = w;
s = r;
} else {
l = i;
if (e[i] == 0.0) {
if (w != 0.0) {
H[i][n] = -r / w;
} else {
H[i][n] = -r / (eps * norm);
}
// Solve real equations
} else {
x = H[i][i+1];
y = H[i+1][i];
q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
t = (x * s - z * r) / q;
H[i][n] = t;
if (Math.abs(x) > Math.abs(z)) {
H[i+1][n] = (-r - w * t) / x;
} else {
H[i+1][n] = (-s - y * t) / z;
}
}
// Overflow control
t = Math.abs(H[i][n]);
if ((eps * t) * t > 1) {
for (int j = i; j <= n; j++) {
H[j][n] = H[j][n] / t;
}
}
}
}
// Complex vector
} else if (q < 0) {
int l = n-1;
// Last vector component imaginary so matrix is triangular
if (Math.abs(H[n][n-1]) > Math.abs(H[n-1][n])) {
H[n-1][n-1] = q / H[n][n-1];
H[n-1][n] = -(H[n][n] - p) / H[n][n-1];
} else {
cdiv(0.0,-H[n-1][n],H[n-1][n-1]-p,q);
H[n-1][n-1] = cdivr;
H[n-1][n] = cdivi;
}
H[n][n-1] = 0.0;
H[n][n] = 1.0;
for (int i = n-2; i >= 0; i--) {
double ra,sa,vr,vi;
ra = 0.0;
sa = 0.0;
for (int j = l; j <= n; j++) {
ra = ra + H[i][j] * H[j][n-1];
sa = sa + H[i][j] * H[j][n];
}
w = H[i][i] - p;
if (e[i] < 0.0) {
z = w;
r = ra;
s = sa;
} else {
l = i;
if (e[i] == 0) {
cdiv(-ra,-sa,w,q);
H[i][n-1] = cdivr;
H[i][n] = cdivi;
} else {
// Solve complex equations
x = H[i][i+1];
y = H[i+1][i];
vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
vi = (d[i] - p) * 2.0 * q;
if (vr == 0.0 & vi == 0.0) {
vr = eps * norm * (Math.abs(w) + Math.abs(q) +
Math.abs(x) + Math.abs(y) + Math.abs(z));
}
cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi);
H[i][n-1] = cdivr;
H[i][n] = cdivi;
if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {
H[i+1][n-1] = (-ra - w * H[i][n-1] + q * H[i][n]) / x;
H[i+1][n] = (-sa - w * H[i][n] - q * H[i][n-1]) / x;
} else {
cdiv(-r-y*H[i][n-1],-s-y*H[i][n],z,q);
H[i+1][n-1] = cdivr;
H[i+1][n] = cdivi;
}
}
// Overflow control
t = Math.max(Math.abs(H[i][n-1]),Math.abs(H[i][n]));
if ((eps * t) * t > 1) {
for (int j = i; j <= n; j++) {
H[j][n-1] = H[j][n-1] / t;
H[j][n] = H[j][n] / t;
}
}
}
}
}
}
// Vectors of isolated roots
for (int i = 0; i < nn; i++) {
if (i < low | i > high) {
for (int j = i; j < nn; j++) {
V[i][j] = H[i][j];
}
}
}
// Back transformation to get eigenvectors of original matrix
for (int j = nn-1; j >= low; j--) {
for (int i = low; i <= high; i++) {
z = 0.0;
for (int k = low; k <= Math.min(j,high); k++) {
z = z + V[i][k] * H[k][j];
}
V[i][j] = z;
}
}
}
/* ------------------------
Constructor
* ------------------------ */
/** Check for symmetry, then construct the eigenvalue decomposition
@param A Square matrix
@return Structure to access D and V.
*/
public EigenvalueDecomposition (Matrix Arg) {
double[][] A = Arg.getArray();
n = Arg.getColumnDimension();
V = new double[n][n];
d = new double[n];
e = new double[n];
issymmetric = true;
for (int j = 0; (j < n) & issymmetric; j++) {
for (int i = 0; (i < n) & issymmetric; i++) {
issymmetric = (A[i][j] == A[j][i]);
}
}
if (issymmetric) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
V[i][j] = A[i][j];
}
}
// Tridiagonalize.
tred2();
// Diagonalize.
tql2();
} else {
H = new double[n][n];
ort = new double[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
H[i][j] = A[i][j];
}
}
// Reduce to Hessenberg form.
orthes();
// Reduce Hessenberg to real Schur form.
hqr2();
}
}
/* ------------------------
Public Methods
* ------------------------ */
/** Return the eigenvector matrix
@return V
*/
public Matrix getV () {
return new Matrix(V,n,n);
}
/** Return the real parts of the eigenvalues
@return real(diag(D))
*/
public double[] getRealEigenvalues () {
return d;
}
/** Return the imaginary parts of the eigenvalues
@return imag(diag(D))
*/
public double[] getImagEigenvalues () {
return e;
}
/** Return the block diagonal eigenvalue matrix
@return D
*/
public Matrix getD () {
Matrix X = new Matrix(n,n);
double[][] D = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
D[i][j] = 0.0;
}
D[i][i] = d[i];
if (e[i] > 0) {
D[i][i+1] = e[i];
} else if (e[i] < 0) {
D[i][i-1] = e[i];
}
}
return X;
}
}

View File

@@ -0,0 +1,318 @@
package wsi.ra.math.Jama;
/** LU Decomposition.
<P>
For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
unit lower triangular matrix L, an n-by-n upper triangular matrix U,
and a permutation vector piv of length m so that A(piv,:) = L*U.
If m < n, then L is m-by-m and U is m-by-n.
<P>
The LU decompostion with pivoting always exists, even if the matrix is
singular, so the constructor will never fail. The primary use of the
LU decomposition is in the solution of square systems of simultaneous
linear equations. This will fail if isNonsingular() returns false.
*/
public class LUDecomposition implements java.io.Serializable {
/* ------------------------
Class variables
* ------------------------ */
/** Array for internal storage of decomposition.
@serial internal array storage.
*/
private double[][] LU;
/** Row and column dimensions, and pivot sign.
@serial column dimension.
@serial row dimension.
@serial pivot sign.
*/
private int m, n, pivsign;
/** Internal storage of pivot vector.
@serial pivot vector.
*/
private int[] piv;
/* ------------------------
Constructor
* ------------------------ */
/** LU Decomposition
@param A Rectangular matrix
@return Structure to access L, U and piv.
*/
public LUDecomposition (Matrix A) {
// Use a "left-looking", dot-product, Crout/Doolittle algorithm.
// System.out.println("A=");
// A.print(A.getRowDimension(),A.getColumnDimension());
LU = A.getArrayCopy();
m = A.getRowDimension();
n = A.getColumnDimension();
piv = new int[m];
for (int i = 0; i < m; i++) {
piv[i] = i;
}
pivsign = 1;
double[] LUrowi;
double[] LUcolj = new double[m];
// Outer loop.
for (int j = 0; j < n; j++) {
// Make a copy of the j-th column to localize references.
for (int i = 0; i < m; i++) {
LUcolj[i] = LU[i][j];
}
// Apply previous transformations.
for (int i = 0; i < m; i++) {
LUrowi = LU[i];
// Most of the time is spent in the following dot product.
int kmax = Math.min(i,j);
double s = 0.0;
for (int k = 0; k < kmax; k++) {
s += LUrowi[k]*LUcolj[k];
}
LUrowi[j] = LUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
int p = j;
for (int i = j+1; i < m; i++) {
if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
p = i;
}
}
if (p != j) {
for (int k = 0; k < n; k++) {
double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t;
}
int k = piv[p]; piv[p] = piv[j]; piv[j] = k;
pivsign = -pivsign;
}
// Compute multipliers.
if (j < m & LU[j][j] != 0.0) {
for (int i = j+1; i < m; i++) {
LU[i][j] /= LU[j][j];
}
}
}
}
/* ------------------------
Temporary, experimental code.
------------------------ *\
\** LU Decomposition, computed by Gaussian elimination.
<P>
This constructor computes L and U with the "daxpy"-based elimination
algorithm used in LINPACK and MATLAB. In Java, we suspect the dot-product,
Crout algorithm will be faster. We have temporarily included this
constructor until timing experiments confirm this suspicion.
<P>
@param A Rectangular matrix
@param linpackflag Use Gaussian elimination. Actual value ignored.
@return Structure to access L, U and piv.
*\
public LUDecomposition (Matrix A, int linpackflag) {
// Initialize.
LU = A.getArrayCopy();
m = A.getRowDimension();
n = A.getColumnDimension();
piv = new int[m];
for (int i = 0; i < m; i++) {
piv[i] = i;
}
pivsign = 1;
// Main loop.
for (int k = 0; k < n; k++) {
// Find pivot.
int p = k;
for (int i = k+1; i < m; i++) {
if (Math.abs(LU[i][k]) > Math.abs(LU[p][k])) {
p = i;
}
}
// Exchange if necessary.
if (p != k) {
for (int j = 0; j < n; j++) {
double t = LU[p][j]; LU[p][j] = LU[k][j]; LU[k][j] = t;
}
int t = piv[p]; piv[p] = piv[k]; piv[k] = t;
pivsign = -pivsign;
}
// Compute multipliers and eliminate k-th column.
if (LU[k][k] != 0.0) {
for (int i = k+1; i < m; i++) {
LU[i][k] /= LU[k][k];
for (int j = k+1; j < n; j++) {
LU[i][j] -= LU[i][k]*LU[k][j];
}
}
}
}
}
\* ------------------------
End of temporary code.
* ------------------------ */
/* ------------------------
Public Methods
* ------------------------ */
/** Is the matrix nonsingular?
@return true if U, and hence A, is nonsingular.
*/
public boolean isNonsingular () {
for (int j = 0; j < n; j++) {
//System.out.println("LU[j][j]"+LU[j][j]);
if (LU[j][j] == 0)
return false;
}
return true;
}
/** Return lower triangular factor
@return L
*/
public Matrix getL () {
Matrix X = new Matrix(m,n);
double[][] L = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
L[i][j] = LU[i][j];
} else if (i == j) {
L[i][j] = 1.0;
} else {
L[i][j] = 0.0;
}
}
}
return X;
}
/** Return upper triangular factor
@return U
*/
public Matrix getU () {
Matrix X = new Matrix(n,n);
double[][] U = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i <= j) {
U[i][j] = LU[i][j];
} else {
U[i][j] = 0.0;
}
}
}
return X;
}
/** Return pivot permutation vector
@return piv
*/
public int[] getPivot () {
int[] p = new int[m];
for (int i = 0; i < m; i++) {
p[i] = piv[i];
}
return p;
}
/** Return pivot permutation vector as a one-dimensional double array
@return (double) piv
*/
public double[] getDoublePivot () {
double[] vals = new double[m];
for (int i = 0; i < m; i++) {
vals[i] = (double) piv[i];
}
return vals;
}
/** Determinant
@return det(A)
@exception IllegalArgumentException Matrix must be square
*/
public double det () {
if (m != n) {
throw new IllegalArgumentException("Matrix must be square.");
}
double d = (double) pivsign;
for (int j = 0; j < n; j++) {
d *= LU[j][j];
}
return d;
}
/** Solve A*X = B
@param B A Matrix with as many rows as A and any number of columns.
@return X so that L*U*X = B(piv,:)
@exception IllegalArgumentException Matrix row dimensions must agree.
@exception RuntimeException Matrix is singular.
*/
public Matrix solve (Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
//System.out.println("B=");
//B.print(B.getRowDimension(),B.getColumnDimension());
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,218 @@
package wsi.ra.math.Jama;
import wsi.ra.math.Jama.util.Maths;
/** QR Decomposition.
<P>
For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
orthogonal matrix Q and an n-by-n upper triangular matrix R so that
A = Q*R.
<P>
The QR decompostion always exists, even if the matrix does not have
full rank, so the constructor will never fail. The primary use of the
QR decomposition is in the least squares solution of nonsquare systems
of simultaneous linear equations. This will fail if isFullRank()
returns false.
*/
public class QRDecomposition implements java.io.Serializable {
/* ------------------------
Class variables
* ------------------------ */
/** Array for internal storage of decomposition.
@serial internal array storage.
*/
private double[][] QR;
/** Row and column dimensions.
@serial column dimension.
@serial row dimension.
*/
private int m, n;
/** Array for internal storage of diagonal of R.
@serial diagonal of R.
*/
private double[] Rdiag;
/* ------------------------
Constructor
* ------------------------ */
/** QR Decomposition, computed by Householder reflections.
@param A Rectangular matrix
@return Structure to access R and the Householder vectors and compute Q.
*/
public QRDecomposition (Matrix A) {
// Initialize.
QR = A.getArrayCopy();
m = A.getRowDimension();
n = A.getColumnDimension();
Rdiag = new double[n];
// Main loop.
for (int k = 0; k < n; k++) {
// Compute 2-norm of k-th column without under/overflow.
double nrm = 0;
for (int i = k; i < m; i++) {
nrm = Maths.hypot(nrm,QR[i][k]);
}
if (nrm != 0.0) {
// Form k-th Householder vector.
if (QR[k][k] < 0) {
nrm = -nrm;
}
for (int i = k; i < m; i++) {
QR[i][k] /= nrm;
}
QR[k][k] += 1.0;
// Apply transformation to remaining columns.
for (int j = k+1; j < n; j++) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*QR[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
QR[i][j] += s*QR[i][k];
}
}
}
Rdiag[k] = -nrm;
}
}
/* ------------------------
Public Methods
* ------------------------ */
/** Is the matrix full rank?
@return true if R, and hence A, has full rank.
*/
public boolean isFullRank () {
for (int j = 0; j < n; j++) {
if (Rdiag[j] == 0)
return false;
}
return true;
}
/** Return the Householder vectors
@return Lower trapezoidal matrix whose columns define the reflections
*/
public Matrix getH () {
Matrix X = new Matrix(m,n);
double[][] H = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i >= j) {
H[i][j] = QR[i][j];
} else {
H[i][j] = 0.0;
}
}
}
return X;
}
/** Return the upper triangular factor
@return R
*/
public Matrix getR () {
Matrix X = new Matrix(n,n);
double[][] R = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i < j) {
R[i][j] = QR[i][j];
} else if (i == j) {
R[i][j] = Rdiag[i];
} else {
R[i][j] = 0.0;
}
}
}
return X;
}
/** Generate and return the (economy-sized) orthogonal factor
@return Q
*/
public Matrix getQ () {
Matrix X = new Matrix(m,n);
double[][] Q = X.getArray();
for (int k = n-1; k >= 0; k--) {
for (int i = 0; i < m; i++) {
Q[i][k] = 0.0;
}
Q[k][k] = 1.0;
for (int j = k; j < n; j++) {
if (QR[k][k] != 0) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*Q[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
Q[i][j] += s*QR[i][k];
}
}
}
}
return X;
}
/** Least squares solution of A*X = B
@param B A Matrix with as many rows as A and any number of columns.
@return X that minimizes the two norm of Q*R*X-B.
@exception IllegalArgumentException Matrix row dimensions must agree.
@exception RuntimeException Matrix is rank deficient.
*/
public Matrix solve (Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isFullRank()) {
throw new RuntimeException("Matrix is rank deficient.");
}
// Copy right hand side
int nx = B.getColumnDimension();
double[][] X = B.getArrayCopy();
// Compute Y = transpose(Q)*B
for (int k = 0; k < n; k++) {
for (int j = 0; j < nx; j++) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*X[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
X[i][j] += s*QR[i][k];
}
}
}
// Solve R*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= Rdiag[k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*QR[i][k];
}
}
}
return (new Matrix(X,n,nx).getMatrix(0,n-1,0,nx-1));
}
}

View File

@@ -0,0 +1,540 @@
package wsi.ra.math.Jama;
import wsi.ra.math.Jama.util.*;
/** Singular Value Decomposition.
<P>
For an m-by-n matrix A with m >= n, the singular value decomposition is
an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
an n-by-n orthogonal matrix V so that A = U*S*V'.
<P>
The singular values, sigma[k] = S[k][k], are ordered so that
sigma[0] >= sigma[1] >= ... >= sigma[n-1].
<P>
The singular value decompostion always exists, so the constructor will
never fail. The matrix condition number and the effective numerical
rank can be computed from this decomposition.
*/
public class SingularValueDecomposition implements java.io.Serializable {
/* ------------------------
Class variables
* ------------------------ */
/** Arrays for internal storage of U and V.
@serial internal storage of U.
@serial internal storage of V.
*/
private double[][] U, V;
/** Array for internal storage of singular values.
@serial internal storage of singular values.
*/
private double[] s;
/** Row and column dimensions.
@serial row dimension.
@serial column dimension.
*/
private int m, n;
/* ------------------------
Constructor
* ------------------------ */
/** Construct the singular value decomposition
@param A Rectangular matrix
@return Structure to access U, S and V.
*/
public SingularValueDecomposition (Matrix Arg) {
// Derived from LINPACK code.
// Initialize.
double[][] A = Arg.getArrayCopy();
m = Arg.getRowDimension();
n = Arg.getColumnDimension();
int nu = Math.min(m,n);
s = new double [Math.min(m+1,n)];
U = new double [m][nu];
V = new double [n][n];
double[] e = new double [n];
double[] work = new double [m];
boolean wantu = true;
boolean wantv = true;
// Reduce A to bidiagonal form, storing the diagonal elements
// in s and the super-diagonal elements in e.
int nct = Math.min(m-1,n);
int nrt = Math.max(0,Math.min(n-2,m));
for (int k = 0; k < Math.max(nct,nrt); k++) {
if (k < nct) {
// Compute the transformation for the k-th column and
// place the k-th diagonal in s[k].
// Compute 2-norm of k-th column without under/overflow.
s[k] = 0;
for (int i = k; i < m; i++) {
s[k] = Maths.hypot(s[k],A[i][k]);
}
if (s[k] != 0.0) {
if (A[k][k] < 0.0) {
s[k] = -s[k];
}
for (int i = k; i < m; i++) {
A[i][k] /= s[k];
}
A[k][k] += 1.0;
}
s[k] = -s[k];
}
for (int j = k+1; j < n; j++) {
if ((k < nct) & (s[k] != 0.0)) {
// Apply the transformation.
double t = 0;
for (int i = k; i < m; i++) {
t += A[i][k]*A[i][j];
}
t = -t/A[k][k];
for (int i = k; i < m; i++) {
A[i][j] += t*A[i][k];
}
}
// Place the k-th row of A into e for the
// subsequent calculation of the row transformation.
e[j] = A[k][j];
}
if (wantu & (k < nct)) {
// Place the transformation in U for subsequent back
// multiplication.
for (int i = k; i < m; i++) {
U[i][k] = A[i][k];
}
}
if (k < nrt) {
// Compute the k-th row transformation and place the
// k-th super-diagonal in e[k].
// Compute 2-norm without under/overflow.
e[k] = 0;
for (int i = k+1; i < n; i++) {
e[k] = Maths.hypot(e[k],e[i]);
}
if (e[k] != 0.0) {
if (e[k+1] < 0.0) {
e[k] = -e[k];
}
for (int i = k+1; i < n; i++) {
e[i] /= e[k];
}
e[k+1] += 1.0;
}
e[k] = -e[k];
if ((k+1 < m) & (e[k] != 0.0)) {
// Apply the transformation.
for (int i = k+1; i < m; i++) {
work[i] = 0.0;
}
for (int j = k+1; j < n; j++) {
for (int i = k+1; i < m; i++) {
work[i] += e[j]*A[i][j];
}
}
for (int j = k+1; j < n; j++) {
double t = -e[j]/e[k+1];
for (int i = k+1; i < m; i++) {
A[i][j] += t*work[i];
}
}
}
if (wantv) {
// Place the transformation in V for subsequent
// back multiplication.
for (int i = k+1; i < n; i++) {
V[i][k] = e[i];
}
}
}
}
// Set up the final bidiagonal matrix or order p.
int p = Math.min(n,m+1);
if (nct < n) {
s[nct] = A[nct][nct];
}
if (m < p) {
s[p-1] = 0.0;
}
if (nrt+1 < p) {
e[nrt] = A[nrt][p-1];
}
e[p-1] = 0.0;
// If required, generate U.
if (wantu) {
for (int j = nct; j < nu; j++) {
for (int i = 0; i < m; i++) {
U[i][j] = 0.0;
}
U[j][j] = 1.0;
}
for (int k = nct-1; k >= 0; k--) {
if (s[k] != 0.0) {
for (int j = k+1; j < nu; j++) {
double t = 0;
for (int i = k; i < m; i++) {
t += U[i][k]*U[i][j];
}
t = -t/U[k][k];
for (int i = k; i < m; i++) {
U[i][j] += t*U[i][k];
}
}
for (int i = k; i < m; i++ ) {
U[i][k] = -U[i][k];
}
U[k][k] = 1.0 + U[k][k];
for (int i = 0; i < k-1; i++) {
U[i][k] = 0.0;
}
} else {
for (int i = 0; i < m; i++) {
U[i][k] = 0.0;
}
U[k][k] = 1.0;
}
}
}
// If required, generate V.
if (wantv) {
for (int k = n-1; k >= 0; k--) {
if ((k < nrt) & (e[k] != 0.0)) {
for (int j = k+1; j < nu; j++) {
double t = 0;
for (int i = k+1; i < n; i++) {
t += V[i][k]*V[i][j];
}
t = -t/V[k+1][k];
for (int i = k+1; i < n; i++) {
V[i][j] += t*V[i][k];
}
}
}
for (int i = 0; i < n; i++) {
V[i][k] = 0.0;
}
V[k][k] = 1.0;
}
}
// Main iteration loop for the singular values.
int pp = p-1;
int iter = 0;
double eps = Math.pow(2.0,-52.0);
while (p > 0) {
int k,kase;
// Here is where a test for too many iterations would go.
// This section of the program inspects for
// negligible elements in the s and e arrays. On
// completion the variables kase and k are set as follows.
// kase = 1 if s(p) and e[k-1] are negligible and k<p
// kase = 2 if s(k) is negligible and k<p
// kase = 3 if e[k-1] is negligible, k<p, and
// s(k), ..., s(p) are not negligible (qr step).
// kase = 4 if e(p-1) is negligible (convergence).
for (k = p-2; k >= -1; k--) {
if (k == -1) {
break;
}
if (Math.abs(e[k]) <= eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) {
e[k] = 0.0;
break;
}
}
if (k == p-2) {
kase = 4;
} else {
int ks;
for (ks = p-1; ks >= k; ks--) {
if (ks == k) {
break;
}
double t = (ks != p ? Math.abs(e[ks]) : 0.) +
(ks != k+1 ? Math.abs(e[ks-1]) : 0.);
if (Math.abs(s[ks]) <= eps*t) {
s[ks] = 0.0;
break;
}
}
if (ks == k) {
kase = 3;
} else if (ks == p-1) {
kase = 1;
} else {
kase = 2;
k = ks;
}
}
k++;
// Perform the task indicated by kase.
switch (kase) {
// Deflate negligible s(p).
case 1: {
double f = e[p-2];
e[p-2] = 0.0;
for (int j = p-2; j >= k; j--) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
if (j != k) {
f = -sn*e[j-1];
e[j-1] = cs*e[j-1];
}
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][p-1];
V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1];
V[i][j] = t;
}
}
}
}
break;
// Split at negligible s(k).
case 2: {
double f = e[k-1];
e[k-1] = 0.0;
for (int j = k; j < p; j++) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
f = -sn*e[j];
e[j] = cs*e[j];
if (wantu) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][k-1];
U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1];
U[i][j] = t;
}
}
}
}
break;
// Perform one qr step.
case 3: {
// Calculate the shift.
double scale = Math.max(Math.max(Math.max(Math.max(
Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])),
Math.abs(s[k])),Math.abs(e[k]));
double sp = s[p-1]/scale;
double spm1 = s[p-2]/scale;
double epm1 = e[p-2]/scale;
double sk = s[k]/scale;
double ek = e[k]/scale;
double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
double c = (sp*epm1)*(sp*epm1);
double shift = 0.0;
if ((b != 0.0) | (c != 0.0)) {
shift = Math.sqrt(b*b + c);
if (b < 0.0) {
shift = -shift;
}
shift = c/(b + shift);
}
double f = (sk + sp)*(sk - sp) + shift;
double g = sk*ek;
// Chase zeros.
for (int j = k; j < p-1; j++) {
double t = Maths.hypot(f,g);
double cs = f/t;
double sn = g/t;
if (j != k) {
e[j-1] = t;
}
f = cs*s[j] + sn*e[j];
e[j] = cs*e[j] - sn*s[j];
g = sn*s[j+1];
s[j+1] = cs*s[j+1];
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][j+1];
V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1];
V[i][j] = t;
}
}
t = Maths.hypot(f,g);
cs = f/t;
sn = g/t;
s[j] = t;
f = cs*e[j] + sn*s[j+1];
s[j+1] = -sn*e[j] + cs*s[j+1];
g = sn*e[j+1];
e[j+1] = cs*e[j+1];
if (wantu && (j < m-1)) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][j+1];
U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1];
U[i][j] = t;
}
}
}
e[p-2] = f;
iter = iter + 1;
}
break;
// Convergence.
case 4: {
// Make the singular values positive.
if (s[k] <= 0.0) {
s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
if (wantv) {
for (int i = 0; i <= pp; i++) {
V[i][k] = -V[i][k];
}
}
}
// Order the singular values.
while (k < pp) {
if (s[k] >= s[k+1]) {
break;
}
double t = s[k];
s[k] = s[k+1];
s[k+1] = t;
if (wantv && (k < n-1)) {
for (int i = 0; i < n; i++) {
t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t;
}
}
if (wantu && (k < m-1)) {
for (int i = 0; i < m; i++) {
t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t;
}
}
k++;
}
iter = 0;
p--;
}
break;
}
}
}
/* ------------------------
Public Methods
* ------------------------ */
/** Return the left singular vectors
@return U
*/
public Matrix getU () {
return new Matrix(U,m,Math.min(m+1,n));
}
/** Return the right singular vectors
@return V
*/
public Matrix getV () {
return new Matrix(V,n,n);
}
/** Return the one-dimensional array of singular values
@return diagonal of S.
*/
public double[] getSingularValues () {
return s;
}
/** Return the diagonal matrix of singular values
@return S
*/
public Matrix getS () {
Matrix X = new Matrix(n,n);
double[][] S = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
S[i][j] = 0.0;
}
S[i][i] = this.s[i];
}
return X;
}
/** Two norm
@return max(S)
*/
public double norm2 () {
return s[0];
}
/** Two norm condition number
@return max(S)/min(S)
*/
public double cond () {
return s[0]/s[Math.min(m,n)-1];
}
/** Effective numerical matrix rank
@return Number of nonnegligible singular values.
*/
public int rank () {
double eps = Math.pow(2.0,-52.0);
double tol = Math.max(m,n)*s[0]*eps;
int r = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] > tol) {
r++;
}
}
return r;
}
}

View File

@@ -0,0 +1,21 @@
package wsi.ra.math.Jama.util;
public class Maths {
/** sqrt(a^2 + b^2) without under/overflow. **/
public static double hypot(double a, double b) {
double r;
double aa = Math.abs(a);
double bb = Math.abs(b);
if (aa > bb) {
r = b/a;
r = aa*Math.sqrt(1+r*r);
} else if (b != 0) {
r = a/b;
r = bb*Math.sqrt(1+r*r);
} else
r = 0.0;
return r;
}
}

184
src/wsi/ra/math/RNG.java Normal file
View File

@@ -0,0 +1,184 @@
package wsi.ra.math;
/**
* Title: JavaEvA
* Description:
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher
* @version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:40 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.util.Random;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class RNG extends Random {
private static Random random;
private static long randomSeed;
/**
*
*/
static {
randomSeed=System.currentTimeMillis();
random=new Random(randomSeed);
}
/**
*
*/
public static void setseed(long x) {
randomSeed=x;
if (x==0)
randomSeed=System.currentTimeMillis();
if (x==999)
return;
random=new Random(randomSeed);
}
/**
*
*/
public static void setRandomseed() {
randomSeed=System.currentTimeMillis();
random=new Random(randomSeed);
}
/**
*
*/
public static void setRandom(Random base_random) {
random=base_random;
}
/**
*
*/
public static void setRandomSeed(long new_seed){
randomSeed=new_seed;
random.setSeed(randomSeed);
}
/**
*
*/
public static long getRandomSeed() {
return randomSeed;
}
/**
*
*/
public static int randomInt() {
return randomInt(0,1);
}
public static int randomInt(int lo,int hi) {
return (Math.abs(random.nextInt())%(hi-lo+1))+lo;
}
/**
*
*/
public static long randomLong() {
return randomLong(0,1);
}
/**
*
*/
public static long randomLong(long lo,long hi) {
return (Math.abs(random.nextLong())%(hi-lo+1))+lo;
}
/**
*
*/
public static float randomFloat() {
return random.nextFloat();
}
/**
*
*/
public static float randomFloat(float lo,float hi) {
return (hi-lo)*random.nextFloat()+lo;
}
/**
*
*/
public static double randomDouble() {
return random.nextDouble();
}
/**
*
*/
public static double randomDouble(double lo,double hi) {
return (hi-lo)*random.nextDouble()+lo;
}
/**
*
*/
public static double[] randomDoubleArray(double[] lo,double[] hi) {
double[] xin = new double[lo.length];
for (int i=0;i<lo.length;i++)
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i];
return xin;
}
/**
*
*/
public static double[] randomDoubleArray(double lo,double hi,int size) {
double[] xin = new double[size];
for (int i=0;i<size;i++)
xin[i] = (hi-lo)*random.nextDouble()+lo;
return xin;
}
/**
*
*/
public static double[] randomDoubleArray(double[] lo,double[] hi,double[] xin) {
for (int i=0;i<lo.length;i++)
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i];
return xin;
}
/**
*
*/
public static boolean randomBoolean() {
return (randomInt()==1);
}
/**
*
*/
public static int randomBit() {
return randomInt();
}
/**
*
*/
public static boolean flipCoin(double p) {
return (randomDouble()<p ? true : false);
}
/**
*
*/
public static float gaussianFloat(float dev) {
return (float)random.nextGaussian()*dev;
}
/**
*
*/
public static double gaussianDouble(double dev) {
return random.nextGaussian()*dev;
}
/**
*
*/
public static float exponentialFloat(float mean) {
return (float)(-mean*Math.log(randomDouble()));
}
/**
*
*/
public static double exponentialDouble(double mean) {
return -mean*Math.log(randomDouble());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: AbstractDataModifier.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:24:58 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* The minimal set of functions which should implemented in a data modifier for
* <code>AbstractDataSet</code>.
*/
public abstract class AbstractDataModifier
{
/*-------------------------------------------------------------------------*
* abstract methods
*-------------------------------------------------------------------------*/
/**
* Modifies the X data.
*/
public abstract void modifyX(double[] setX);
/**
* Modifies the Y data.
*/
public abstract void modifyY(double[] setY);
/**
* Modifies the data.
*/
public abstract void modify(double[] setX, double[] setY);
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,116 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: AbstractDataSet.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:04 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public abstract class AbstractDataSet
{
/*-------------------------------------------------------------------------*
* public member variables
*-------------------------------------------------------------------------*/
/*--------------------------------------------------------------o-----------*
* protected member variables
*-------------------------------------------------------------------------*/
/**
* double array of X data.
*
* @see #yDoubleData
*/
protected double[] xDoubleData = { -1, 1 };
/**
* double array of Y data.
*
* @see #xDoubleData
*/
protected double[] yDoubleData = { 1, 1 };
/*-------------------------------------------------------------------------*
* abstract methods
*-------------------------------------------------------------------------*/
/**
* Returns the length of the data set
* @return the length of the data set
*/
public int getLength()
{
return xDoubleData.length;
}
/**
* Returns an array of the X data
* @return the array of the X data
*/
public double[] getXData()
{
return xDoubleData;
}
/**
* Returns an array of the Y data
* @return the array of the Y data
*/
public double[] getYData()
{
return yDoubleData;
}
/**
* Returns the X label of the data set
* @return the X label of the data set
*/
public abstract String getXLabel();
/**
* Returns the Y label of the data set
* @return the Y label of the data set
*/
public abstract String getYLabel();
/**
* Modifies the X data.
*
* @param the data modifier
*/
public void modifyXData(AbstractDataModifier modifier)
{
modifier.modifyX(xDoubleData);
}
/**
* Modifies the Y data.
*
* @param the data modifier
*/
public void modifyYData(AbstractDataModifier modifier)
{
modifier.modifyY(yDoubleData);
}
/**
* Modifies the data.
*
* @param the data modifier
*/
public void modifyData(AbstractDataModifier modifier)
{
modifier.modify(xDoubleData, yDoubleData);
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,100 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: BasicDataSet.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:11 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
import wsi.ra.sort.XYDoubleArray;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/**
* The minimum wrapper class for an <code>AbstractDataSet</code>.
*/
public class BasicDataSet extends AbstractDataSet
{
/*-------------------------------------------------------------------------*
* protected member variables
*-------------------------------------------------------------------------*/
protected int dataType = -1;
protected String xLabel = null;
protected String yLabel = null;
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
public BasicDataSet()
{
this(null, null, null, null);
}
public BasicDataSet(XYDoubleArray data)
{
this(data.x, data.y, null, null);
}
public BasicDataSet(XYDoubleArray data, String xLabel, String yLabel)
{
this(data.x, data.y, xLabel, yLabel);
}
public BasicDataSet(
double[] xDoubleData,
double[] yDoubleData,
int dataType)
{
this(xDoubleData, yDoubleData, null, null);
}
public BasicDataSet(
double[] xDoubleData,
double[] yDoubleData,
String xLabel,
String yLabel)
{
this.xDoubleData = xDoubleData;
this.yDoubleData = yDoubleData;
this.xLabel = xLabel;
this.yLabel = yLabel;
}
/*-------------------------------------------------------------------------*
* public methods
*-------------------------------------------------------------------------*/
public int getDataType()
{
return dataType;
}
public String getXLabel()
{
return xLabel;
}
public String getYLabel()
{
return yLabel;
}
public String getAdditionalInformation(String parm1)
{
return new String();
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,44 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: InterpolationException.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:17 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* Exception for interpolation error.
*/
public class InterpolationException extends Exception
{
public InterpolationException()
{
super();
}
public InterpolationException(String s)
{
super(s);
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,573 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: LinearInterpolation.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Original author: Charles S. Stanton
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:23 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
//import cern.jet.stat.*;
/**
* Defines the routines for the spline interpolation of data.
*/
public class LinearInterpolation
{
AbstractDataSet abstractDataSet = null;
private double[] x, y;
//vectors of x,y
private double sumX = 0;
private double sumY = 0;
private double sumXY = 0;
private double sumXsquared = 0;
private double sumYsquared = 0;
private double Sxx, Sxy, Syy, n;
private double a = 0, b = 0;
//coefficients of regression
private int dataLength;
private double[][] residual;
// residual[0][i] = x[i], residual[1][i]= residual
private double maxAbsoluteResidual = 0.0;
private double SSR = 0.0;
//regression sum of squares
private double SSE = 0.0;
//error sum of squares
private double minX = Double.POSITIVE_INFINITY;
private double maxX = Double.NEGATIVE_INFINITY;
private double minY = Double.POSITIVE_INFINITY;
private double maxY = Double.NEGATIVE_INFINITY;
//MISC
String xName, yName;
double aCILower, aCIUpper, bCILower, bCIUpper; //confidence interval
double t, bSE, aSE;
double MSE, F;
static double[] t025 =
{
Double.NaN,
12.706,
4.303,
3.182,
2.776,
2.571,
2.447,
2.365,
2.306,
2.262,
2.228,
2.201,
2.179,
2.160,
2.145,
2.131,
2.120,
2.110,
2.101,
2.093,
2.086,
2.080,
2.075,
2.069,
2.064,
2.060,
2.056,
2.052,
2.048,
2.045,
1.960 };
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
/**
* Initializes this class.
*/
public LinearInterpolation() throws InterpolationException
{
this.abstractDataSet = null;
}
/**
* Constructor for regression calculator.
*
* @param x is the array of x data
* @param y is the array of y data
*/
public LinearInterpolation(double[] x, double[] y)
{
this.x = x;
this.y = y;
if (x.length != y.length)
{
System.out.println("x, y vectors must be of same length");
}
else
{
dataLength = x.length;
doStatistics();
}
}
/**
* Initializes this class and calculates the second derivative of the spline.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
*/
public LinearInterpolation(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.setAbstractDataSet(abstractDataSet);
}
public void setAbstractDataSet(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.abstractDataSet = abstractDataSet;
x = abstractDataSet.getXData();
y = abstractDataSet.getYData();
if (x.length != y.length)
{
System.out.println("x, y vectors must be of same length");
}
else
{
dataLength = x.length;
doStatistics();
}
}
/**
* Find the p value for a given value of F.
* Requires the COLT high performance library:
* http://hoschek.home.cern.ch/hoschek/colt/
*
* @param fValue the value for the CDF
* @return The P value
*/
// public double getP(double fValue) {
// double answer;
// double y1;
// double y2;
// //nu1 = 1;
// //x2 =1
// double nu2 = n - 2;
// y1 = nu2 / (nu2 + fValue);
// y2 = 0.0;
// answer = Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y1)
// - Gamma.incompleteBeta(nu2 / 2.0, 1 / 2.0, y2);
// return answer;
// }
/*
* Here are the accessor methods
*
*/
/**
* Gets the intercept of the regression line.
*
* @return The intercept.
*/
public double getIntercept()
{
return a;
}
/**
* Gets the Slope of the regression line.
*
* @return The slope.
*/
public double getSlope()
{
return b;
}
/**
* Gets the residuals of the regression.
*
* @return The residuals.
*/
public double[][] getResiduals()
{
return residual;
}
/**
* Gets the x data for the regression.
*
* @return The array of x values.
*/
public double[] getDataX()
{
return x;
}
/**
* Gets the y data for the regression.
*
* @return The array of y values.
*/
public double[] getDataY()
{
return y;
}
/**
* Gets the minimum of the x values.
*
* @return The minimum.
*/
public double getMinX()
{
return minX;
}
/**
* Gets the maximum of the x values.
*
* @return The maximum.
*/
public double getMaxX()
{
return maxX;
}
/**
* Gets the minimum of the y values.
*
* @return The minumum.
*/
public double getMinY()
{
return minY;
}
/**
* Gets the maximum of the y values.
*
* @return The maximum.
*/
public double getMaxY()
{
return maxY;
}
/**
* Gets the maximum absolute residual.
*
* @return The maximum.
*/
public double getMaxAbsoluteResidual()
{
return maxAbsoluteResidual;
}
/**
* Gets the sum of the square x deviations from mean of x.
*
* @return The Sxx value
*/
public double getSxx()
{
return Sxx;
}
/**
* Gets the sum of the square y deviations from mean of y.
*
* @return The Syy value
*/
public double getSyy()
{
return Syy;
}
/**
* Gets SSR = Sxy * Sxy / Sxx;
*
* @return The SSR value
*/
public double getSSR()
{
return SSR;
}
/**
* Gets SSE = Syy - SSR.
*
* @return The SSE value
*/
public double getSSE()
{
return SSE;
}
/**
* Gets the mean square error MSE.
*
* @return The MSE value
*/
public double getMSE()
{
return SSE / (n - 2);
}
/**
* Gets the mean XBar of x.
*
* @return The XBar value
*/
public double getXBar()
{
return sumX / n;
}
/**
* Gets the mean YBar of y.
*
* @return The YBar value
*/
public double getYBar()
{
return sumY / n;
}
/**
* Gets the sample size.
*
* @return The sample size.
*/
public int getDataLength()
{
return x.length;
}
/**
* Gets the Pearson R statistic of the regression.
*
* @return The PearsonR value
*/
public double getPearsonR()
{
return Sxy / Math.sqrt(Sxx * Syy);
}
/**
* Gets the sum of the x squared values.
*
* @return The sum of the x squared values.
*/
public double getSumXSquared()
{
return sumXsquared;
}
/**
* reset data to 0
*/
public void reset()
{
x = new double[0];
y = new double[0];
dataLength = 0;
n = 0.0;
residual = new double[0][0];
sumX = 0;
sumXsquared = 0;
sumY = 0;
sumYsquared = 0;
sumXY = 0;
}
/**
* Adds a new point to the regression (for interactive use).
*
* @param xValue The new x value
* @param yValue The new y value
*/
public void addPoint(double xValue, double yValue)
{
dataLength++;
double[] xNew = new double[dataLength];
double[] yNew = new double[dataLength];
System.arraycopy(x, 0, xNew, 0, dataLength - 1);
System.arraycopy(y, 0, yNew, 0, dataLength - 1);
xNew[dataLength - 1] = xValue;
yNew[dataLength - 1] = yValue;
x = xNew;
y = yNew;
updateStatistics(xValue, yValue);
}
private void doStatistics()
{
//Find sum of squares for x,y and sum of xy
for (int i = 0; i < dataLength; i++)
{
minX = Math.min(minX, x[i]);
maxX = Math.max(maxX, x[i]);
minY = Math.min(minY, y[i]);
maxY = Math.max(maxY, y[i]);
sumX += x[i];
sumY += y[i];
sumXsquared += x[i] * x[i];
sumYsquared += y[i] * y[i];
sumXY += x[i] * y[i];
}
//Caculate regression coefficients
n = (double) dataLength;
Sxx = sumXsquared - sumX * sumX / n;
Syy = sumYsquared - sumY * sumY / n;
Sxy = sumXY - sumX * sumY / n;
b = Sxy / Sxx;
a = (sumY - b * sumX) / n;
SSR = Sxy * Sxy / Sxx;
SSE = Syy - SSR;
calculateResiduals();
}
private void calculateResiduals()
{
residual = new double[2][dataLength];
maxAbsoluteResidual = 0.0;
for (int i = 0; i < dataLength; i++)
{
residual[0][i] = x[i];
residual[1][i] = y[i] - (a + b * x[i]);
maxAbsoluteResidual =
Math.max(maxAbsoluteResidual, Math.abs(y[i] - (a + b * x[i])));
}
}
//update statistics for a single additional data point
private void updateStatistics(double xValue, double yValue)
{
//Find sum of squares for x,y and sum of xy
n++;
sumX += xValue;
sumY += yValue;
sumXsquared += xValue * xValue;
sumYsquared += yValue * yValue;
sumXY += xValue * yValue;
//Caculate regression coefficients
n = (double) dataLength;
Sxx = sumXsquared - sumX * sumX / n;
Syy = sumYsquared - sumY * sumY / n;
Sxy = sumXY - sumX * sumY / n;
b = Sxy / Sxx;
a = (sumY - b * sumX) / n;
SSR = Sxy * Sxy / Sxx;
SSE = Syy - SSR;
calculateResiduals();
}
/**
* regression line y = a + bx.
*
* @param x
* @return double
* @throws InterpolationException
*/
public double getY(double x) throws InterpolationException
{
return a + b * x;
}
public String toString()
{
StringBuffer sb = new StringBuffer(1000);
sb.append("Regression Statistics for " + yName + " = a + b*" + xName);
sb.append("");
sb.append("Sample Statistics");
int n = this.getDataLength();
sb.append("Sample size n = " + n);
sb.append("Mean of " + yName + " Y bar = " + this.getYBar());
sb.append("s_Y");
sb.append("= " + Math.sqrt(this.getSyy() / ((float) (n - 1))));
sb.append("Pearson correlation R = " + this.getPearsonR());
sb.append("");
sb.append("Coefficient Estimates");
a = this.getIntercept();
b = this.getSlope();
sb.append("a = " + a);
sb.append("b = " + b);
sb.append("");
sb.append("95% Confidence Intervals");
if (n > 32)
{
t = t025[30];
}
else if (n > 2)
{
t = t025[n - 2];
}
else
{
t = Double.NaN;
}
MSE = this.getMSE();
if (n > 2)
{
bSE = Math.sqrt(MSE / this.getSxx());
}
else
{
bSE = Double.NaN;
}
aSE = bSE * Math.sqrt(this.getSumXSquared() / n);
aCILower = a - t * aSE;
aCIUpper = a + t * aSE;
sb.append("a : (" + aCILower + ", " + aCIUpper + ")");
bCILower = b - t * bSE;
bCIUpper = b + t * bSE;
sb.append("b : (" + bCILower + ", " + bCIUpper + ")");
sb.append("");
sb.append("Analysis of Variance");
sb.append("Source Degrees Freedom Sum of Squares");
sb.append("");
SSR = this.getSSR();
//allow one degree of freedom for mean
sb.append(
"model 1 "
+ SSR);
sb.append(
"error "
+ (n - 2)
+ " "
+ this.getSSE());
sb.append(
"total(corrected) "
+ (n - 1)
+ " "
+ this.getSyy());
sb.append("");
sb.append("MSE =" + MSE);
F = SSR / MSE;
sb.append("F = " + F + " ");
//sb.append("p = " + this.getP(F));
return sb.toString();
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,453 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: PolyInterpolation.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:30 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/**
* Defines the routines for the interpolation of data.
*/
public class PolyInterpolation
{
AbstractDataSet abstractDataSet = null;
boolean sloppy = true;
double[] polynomialCoefficients = null;
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
/**
* Initializes this class.
*/
public PolyInterpolation() throws InterpolationException
{
this.abstractDataSet = null;
sloppy = true;
polynomialCoefficients = null;
}
/**
* Initializes this class and calculates the coefficients of the polynom.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
*/
public PolyInterpolation(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.abstractDataSet = abstractDataSet;
sloppy = true;
this.polynomialCoefficients = calculatePolynomialCoefficients();
}
/**
* Initializes this class and calculates the coefficients of the polynom.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
* @param sloppy if <code>true</code> Neville's algorithm which is used in the
* <code>polynomialInterpolation</code>-routines does only print a
* warning message on the screen and does not throw an
* <code>Exception</code> if two x values are identical.
*/
public PolyInterpolation(AbstractDataSet abstractDataSet, boolean sloppy)
throws InterpolationException
{
this.abstractDataSet = abstractDataSet;
this.sloppy = sloppy;
this.polynomialCoefficients = calculatePolynomialCoefficients();
}
/**
* Sets the new <code>AbstractDataSet</code> and calculates the coefficients
* of the polynom.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
*/
public void setAbstractDataSet(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.abstractDataSet = abstractDataSet;
this.polynomialCoefficients = calculatePolynomialCoefficients();
}
/**
* Uses the polynom with the calculated coefficients to calculate the
* <code>y</code> value. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 5, pages 173-176.</a><br>
* The Neville's algorithm which is used in the <code>polynomialInterpolation</code>-
* routines returns also the error of this interpolated point.
*
* @param x the x value
* @return the interpolated y value
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getYandDerivatives(double, int)
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
*/
public double getY(double x)
{
int n = polynomialCoefficients.length - 1;
double y = polynomialCoefficients[n];
for (int j = n - 1; j >= 0; j--)
y = y * x + polynomialCoefficients[j];
return y;
}
/**
* Uses the polynom with the calculated coefficients to calculate the
* <code>y</code> value and the derivatives at the point <code>x</code>,
* <code>y</code>. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 5, pages 173-176.</a><br>
* The Neville's algorithm which is used in the <code>polynomialInterpolation</code>-
* routines returns also the error of this interpolated point.
*
* @param x the x value
* @param ndDerivateNumber the number of the calculated derivatives
* @return the interpolated y value at ...[0], the 1st derivativ value at
* ...[1], the 2nd derivativ at ...[2] and so on ...
* @see #getY(double)
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
*/
public double[] getYandDerivatives(double x, int ndDerivateNumber)
throws InterpolationException
{
if (ndDerivateNumber < 0)
throw new InterpolationException("Negative derivative numbers make no sense.");
else if (ndDerivateNumber == 0)
{
double[] pd = new double[1];
pd[0] = getY(x);
return pd;
}
int nnd, j, i;
int nc = polynomialCoefficients.length - 1;
double[] pd = new double[ndDerivateNumber + 1];
double cnst = 1.0;
pd[0] = polynomialCoefficients[nc];
for (j = 1; j <= ndDerivateNumber; j++)
pd[j] = 0.0;
for (i = nc - 1; i >= 0; i--)
{
nnd = (ndDerivateNumber < (nc - i) ? ndDerivateNumber : nc - i);
for (j = nnd; j >= 1; j--)
pd[j] = pd[j] * x + pd[j - 1];
pd[0] = pd[0] * x + polynomialCoefficients[i];
}
for (i = 2; i <= ndDerivateNumber; i++)
{
cnst *= i;
pd[i] *= cnst;
}
return pd;
}
/**
* Neville's interpolation algorithm. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @param x the x value
* @return the interpolated y value and the interpolation error
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
*/
public PolynomialInterpolationResult polynomialInterpolation(double x)
throws InterpolationException
{
if (abstractDataSet == null)
throw new InterpolationException(
"No data." + " The AbstractDataSet was not defined.");
return polynomialInterpolation(
abstractDataSet.getXData(),
abstractDataSet.getYData(),
x);
}
/**
* Neville's interpolation algorithm. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @param abstractDataSet the <code>AbstractDataSet</code>
* @param x the x value
* @return the interpolated y value and the interpolation error
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
*/
public PolynomialInterpolationResult polynomialInterpolation(
AbstractDataSet abstractDataSet,
double x)
throws InterpolationException
{
if (abstractDataSet == null)
throw new InterpolationException(
"No data." + " The AbstractDataSet was not defined.");
return polynomialInterpolation(
abstractDataSet.getXData(),
abstractDataSet.getYData(),
x);
}
/**
* Neville's interpolation algorithm. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @param xa the array of x values
* @param ya the array of y values
* @param x the x value
* @return the interpolated y value and the interpolation error
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
*/
public PolynomialInterpolationResult polynomialInterpolation(
double[] xa,
double[] ya,
double x)
throws InterpolationException
{
if (xa == null || ya == null)
throw new InterpolationException("No data.");
int i, m, ns = 1;
double den, dif, dift, ho, hp, w;
double[] c = new double[xa.length + 1];
double[] d = new double[xa.length + 1];
PolynomialInterpolationResult result =
new PolynomialInterpolationResult();
dif = Math.abs(x - xa[1 - 1]);
for (i = 1; i <= xa.length; i++)
{
if ((dift = Math.abs(x - xa[i - 1])) < dif)
{
ns = i;
dif = dift;
}
c[i] = ya[i - 1];
d[i] = ya[i - 1];
//System.out.println("x"+xa[i-1]+" y"+ya[i-1]);
}
result.y = ya[ns - 1];
//System.out.println("y="+result.y+" ns="+ns);
ns--;
for (m = 1; m < xa.length; m++)
{
for (i = 1; i <= xa.length - m; i++)
{
ho = xa[i - 1] - x;
hp = xa[i + m - 1] - x;
w = c[i + 1] - d[i];
if ((den = ho - hp) == 0.0)
{
if (sloppy)
{
System.out.println(
"Two identical x values. The values must be distinct.");
den = 1.0;
}
else
throw new InterpolationException("Two identical x values.");
}
den = w / den;
d[i] = hp * den;
c[i] = ho * den;
}
result.y
+= (result.yError =
(2 * ns < (xa.length - m) ? c[ns + 1] : d[ns--]));
}
return result;
}
/**
* Calculates the coefficients of a polynom of the grade <code>N-1</code>. This
* interpolation algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @return the array with the polynomial coefficients y = ...[0] +
* ...[1]*x<SUP>2</SUP> + ...[2]*x<SUP>3</SUP> + ...
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #calculatePolynomialCoefficients(double[], double[])
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
*/
public double[] calculatePolynomialCoefficients()
throws InterpolationException
{
if (abstractDataSet == null)
throw new InterpolationException(
"No data." + " The AbstractDataSet was not defined.");
return calculatePolynomialCoefficients(
abstractDataSet.getXData(),
abstractDataSet.getYData());
}
/**
* Calculates the coefficients of a polynom of the grade <code>N-1</code>. This
* interpolation algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @param abstractDataSet the <code>AbstractDataSet</code>
* @return the array with the polynomial coefficients y = ...[0] +
* ...[1]*x<SUP>2</SUP> + ...[2]*x<SUP>3</SUP> + ...
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(double[], double[])
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
*/
public double[] calculatePolynomialCoefficients(AbstractDataSet abstractDataSet)
throws InterpolationException
{
if (abstractDataSet == null)
throw new InterpolationException(
"No data." + " The AbstractDataSet was not defined.");
return calculatePolynomialCoefficients(
abstractDataSet.getXData(),
abstractDataSet.getYData());
}
/**
* Calculates the coefficients of a polynom of the grade <code>N-1</code>. This
* interpolation algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 108-122.</a><br>
*
* @param x the array of x values
* @param y the array of y values
* @return the array with the polynomial coefficients y = ...[0] +
* ...[1]*x<SUP>2</SUP> + ...[2]*x<SUP>3</SUP> + ...
* @see #calculatePolynomialCoefficients()
* @see #calculatePolynomialCoefficients(AbstractDataSet)
* @see #polynomialInterpolation(double)
* @see #polynomialInterpolation(AbstractDataSet, double)
* @see #polynomialInterpolation(double[], double[], double)
* @see #getY(double)
* @see #getYandDerivatives(double, int)
*/
public double[] calculatePolynomialCoefficients(double x[], double y[])
{
int k, j, i, n = x.length - 1;
double phi, ff, b;
double[] s = new double[n + 1];
double[] cof = new double[n + 1];
for (i = 0; i <= n; i++)
{
s[i] = cof[i] = 0.0;
}
s[n] = -x[0];
for (i = 1; i <= n; i++)
{
for (j = n - i; j <= n - 1; j++)
{
s[j] -= x[i] * s[j + 1];
}
s[n] -= x[i];
}
for (j = 0; j < n; j++)
{
phi = n + 1;
for (k = n; k >= 1; k--)
{
phi = k * s[k] + x[j] * phi;
}
ff = y[j] / phi;
b = 1.0;
for (k = n; k >= 0; k--)
{
cof[k] += b * ff;
b = s[k] + x[j] * b;
}
}
return cof;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,56 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: PolynomialInterpolationResult.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:36 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* The result data for a polynomial interpolation.
*/
public class PolynomialInterpolationResult
{
/*-------------------------------------------------------------------------*
* public member variables
*-------------------------------------------------------------------------*/
public double y = Double.NaN;
public double yError = Double.NaN;
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
public PolynomialInterpolationResult()
{
y = Double.NaN;
yError = Double.NaN;
}
public PolynomialInterpolationResult(double y, double yError)
{
this.y = y;
this.yError = yError;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,299 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: SplineInterpolation.java,v $
// Purpose: Some interpolation stuff.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2003/07/22 19:25:42 $
// $Author: wegnerj $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.math.interpolation;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/**
* Defines the routines for the spline interpolation of data.
*/
public class SplineInterpolation
{
AbstractDataSet abstractDataSet = null;
double[] secondDerivative = null;
double[] xArray = null;
double[] yArray = null;
boolean ascendingData = true;
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
/**
* Initializes this class.
*/
public SplineInterpolation() throws InterpolationException
{
this.abstractDataSet = null;
this.secondDerivative = null;
}
/**
* Initializes this class and calculates the second derivative of the spline.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
*/
public SplineInterpolation(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.setAbstractDataSet(abstractDataSet);
}
/**
* Sets the new <code>AbstractDataSet</code> and calculates the second
* derivative of the spline.
*
* @param abstractDataSet the <code>AbstractDataSet</code>
*/
public void setAbstractDataSet(AbstractDataSet abstractDataSet)
throws InterpolationException
{
this.abstractDataSet = abstractDataSet;
double[] x = abstractDataSet.getXData();
double[] y = abstractDataSet.getYData();
boolean ascending = false;
boolean descending = false;
int n = x.length;
xArray = new double[n];
yArray = new double[n];
xArray[n - 1] = x[0];
yArray[n - 1] = y[0];
for (int i = 0; i < n - 1; i++)
{
xArray[i] = x[n - i - 1];
yArray[i] = y[n - i - 1];
if (x[i] < x[i + 1])
{
//if(descending)throw new InterpolationException("The x values must be"+
// " in continous ascending/descending order.");
ascending = true;
}
else
{
//if(ascending)throw new InterpolationException("The x values must be"+
// " in continous ascending/descending order.");
descending = true;
}
}
ascendingData = ascending;
if (ascendingData)
{
xArray = null;
yArray = null;
xArray = abstractDataSet.getXData();
yArray = abstractDataSet.getYData();
}
this.secondDerivative =
spline(
xArray,
yArray,
(yArray[1] - yArray[0]) / (xArray[1] - xArray[0]),
(yArray[n - 1] - yArray[n - 2]) / (xArray[1] - xArray[n - 2]));
}
/**
* Uses the spline with the calculated second derivative values to calculate
* the <code>y</code> value. This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 5, pages 173-176.</a><br>
*/
public double getY(double x) throws InterpolationException
{
return splineInterpolation(xArray, yArray, secondDerivative, x);
}
public double getDerivative(double x) throws InterpolationException
{
return splineInterpolatedDerivative(
xArray,
yArray,
secondDerivative,
x);
}
/**
* Calculates the second derivative of the data. It's important that the
* x<sub>i</sub> values of the function y<sub>i</sub>=f(x<sub>i</sub>) are
* in ascending order, as x<sub>0</sub>&lt;x<sub>1</sub>&lt;x<sub>2</sub>&lt;... .
* This algorithm was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 113-116.</a><br>
*/
public double[] spline(double[] x, double[] y, double yp0, double ypn)
throws InterpolationException
{
if (x[0] > x[1])
throw new InterpolationException(
"The x values must be" + " in ascending order.");
int n = x.length;
double[] y2 = new double[n];
double[] u = new double[n - 1];
int i, k;
double p, qn, sig, un;
if (yp0 > 0.99e30)
y2[0] = u[0] = 0.0;
else
{
y2[0] = -0.5;
u[0] =
(3.0 / (x[1] - x[0])) * ((y[1] - y[0]) / (x[1] - x[0]) - yp0);
}
for (i = 2; i <= n - 1; i++)
{
sig = (x[i - 1] - x[i - 2]) / (x[i] - x[i - 2]);
p = sig * y2[i - 2] + 2.0;
y2[i - 1] = (sig - 1.0) / p;
u[i - 1] =
(y[i] - y[i - 1]) / (x[i] - x[i - 1])
- (y[i - 1] - y[i - 2]) / (x[i - 1] - x[i - 2]);
u[i - 1] =
(6.0 * u[i - 1] / (x[i] - x[i - 2]) - sig * u[i - 2]) / p;
}
if (ypn > 0.99e30)
{
qn = un = 0.0;
}
else
{
qn = 0.5;
un =
(3.0 / (x[n - 1] - x[n - 2]))
* (ypn - (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]));
}
y2[n - 1] = (un - qn * u[n - 2]) / (qn * y2[n - 2] + 1.0);
for (k = n - 1; k >= 1; k--)
{
y2[k - 1] = y2[k - 1] * y2[k] + u[k - 1];
}
return y2;
}
/**
* Calculates the second derivative of the data. This algorithm
* was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 113-116.</a><br>
*/
public double splineInterpolation(
double[] xa,
double[] ya,
double[] y2a,
double x)
throws InterpolationException
{
int n = xa.length;
if (n != ya.length || n != y2a.length)
{
throw new InterpolationException("Arrays have different lengths.");
}
double y;
int klo, khi, k;
double h, b, a;
klo = 0;
khi = n - 1;
while (khi - klo > 1)
{
k = (khi + klo) >> 1;
if (xa[k] > x)
khi = k;
else
klo = k;
}
h = xa[khi] - xa[klo];
//System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]);
if (h == 0.0)
throw new InterpolationException("Two identical x values. The values must be distinct.");
a = (xa[khi] - x) / h;
b = (x - xa[klo]) / h;
y =
a * ya[klo]
+ b * ya[khi]
+ ((a * a * a - a) * y2a[klo] + (b * b * b - b) * y2a[khi])
* (h * h)
/ 6.0;
return y;
}
/**
* Calculates the second derivative of the data. This algorithm
* was taken from:<br>
* <a href="http://www.ulib.org/webRoot/Books/Numerical_Recipes/" target="_top">
* William H. Press, Saul A. Teukolosky, William T. Vetterling, Brian P. Flannery,
* "Numerical Recipes in C - The Art of Scientific Computing", Second Edition,
* Cambridge University Press,
* ISBN 0-521-43108-5,
* chapter 3, pages 113-116.</a><br>
*/
public double splineInterpolatedDerivative(
double[] xa,
double[] ya,
double[] y2a,
double x)
throws InterpolationException
{
int n = xa.length;
if (n != ya.length || n != y2a.length)
{
throw new InterpolationException("Arrays have different lengths.");
}
double dydx;
int klo, khi, k;
double h, b, a;
klo = 0;
khi = n - 1;
while (khi - klo > 1)
{
k = (khi + klo) >> 1;
if (xa[k] > x)
khi = k;
else
klo = k;
}
h = xa[khi] - xa[klo];
//System.out.println(""+x+" between "+xa[khi]+" "+xa[klo]);
if (h == 0.0)
throw new InterpolationException("Two identical x values. The values must be distinct.");
a = (xa[khi] - x) / h;
b = (x - xa[klo]) / h;
dydx =
(ya[khi] - ya[klo]) / h
- ((3 * (a * a) - 1) * h * y2a[klo]) / 6.0
+ ((3 * (b * b) - 1) * h * y2a[khi]) / 6.0;
return dydx;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,156 @@
/**
* Filename: $RCSfile: PagePrinter.java,v $
* Purpose:
* Language: Java
* Compiler: JDK 1.3
* Authors: Fabian Hennecke
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:40 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.print;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.* ;
import java.awt.print.* ;
import java.awt.image.BufferedImage ;
import javax.swing.* ;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class PagePrinter
{
Component c;
Graphics g;
PageFormat pf;
public boolean fit_in_possible = true;
public PagePrinter( Component c, Graphics g, PageFormat pf ) {
this.c = c;
this.g = g;
this.pf = pf;
}
public int print(){
Dimension old = c.getSize();
int x = (int)pf.getImageableX(),
y = (int)pf.getImageableY();
g.translate( x, y );
double w = (int)pf.getImageableWidth(),
h = (int)pf.getImageableHeight();
if( old.width > w || old.height > h ){
boolean rec_turn = false, rec_fit_in = false;
if( ( old.width > old.height && h > w ) ||
( old.width < old.height && h < w ) ) {
rec_turn = true;
if( old.width > h || old.height > w ) rec_fit_in = true;
}
else rec_fit_in = true;
JLabel[] text = new JLabel[4];
text[0] = new JLabel("The component which should be printed");
text[1] = new JLabel("is too large.");
text[2] = new JLabel("You can choose if the component should be");
JCheckBox cbFitIn = new JCheckBox("fitted-in", rec_fit_in),
cbTurn = new JCheckBox("turned", rec_turn );
text[3] = new JLabel("(Recommended choice is pre-selected)");
if( !fit_in_possible ){
cbFitIn.setEnabled( false );
cbFitIn.setSelected( false );
}
GridBagLayout gbl = new GridBagLayout();
JPanel panel = new JPanel( gbl );
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = gbc.gridy = 0;
gbc.weightx = gbc.weighty = .5;
gbc.gridwidth = 2;
gbl.setConstraints( text[0], gbc );
panel.add( text[0] );
gbc.gridy++;
gbl.setConstraints( text[1], gbc );
panel.add( text[1] );
gbc.gridy++;
gbl.setConstraints( text[2], gbc );
panel.add( text[2] );
gbc.gridy++;
gbc.gridwidth = 1;
gbl.setConstraints( cbFitIn, gbc );
panel.add( cbFitIn );
gbc.gridx++;
gbl.setConstraints( cbTurn, gbc );
panel.add( cbTurn );
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.gridy++;
gbl.setConstraints( text[3], gbc);
panel.add( text[3] );
int choice = JOptionPane.showOptionDialog( c, panel, "Fit-in",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null );
if( choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.CLOSED_OPTION )
return Printable.NO_SUCH_PAGE;
else if( choice == JOptionPane.OK_OPTION ){
if( cbTurn.isSelected() ){
BufferedImage img;
if( cbFitIn.isSelected() ){
double m = Math.min( h / (double)old.width, w / (double)old.height );
img = (BufferedImage)c.createImage( (int)( old.height * m ), (int)( old.width * m ) );
Graphics2D g2 = img.createGraphics();
g2.rotate( Math.toRadians( 90 ) );
g2.translate( 0, - old.height * m );
c.setSize( (int)( old.width * m ), (int)( old.height * m ) );
c.paint( g2 );
c.setSize( old );
}
else{
img = (BufferedImage)c.createImage( old.height, old.width );
Graphics2D g2 = img.createGraphics();
g2.rotate( Math.toRadians( 90 ) );
g2.translate( 0, - old.height );
c.paint( g2 );
}
g.drawImage( img, 0, 0, c.getBackground(), c );
}
else{
if( cbFitIn.isSelected() ){
double m = Math.min( w / (double)old.width, h / (double)old.height );
c.setSize( (int)( old.width * m ), (int)( old.height * m ) );
c.paint( g );
c.setSize( old );
}
else c.paint( g );
}
}
}
else c.paint( g );
return Printable.PAGE_EXISTS;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,114 @@
/**
* Filename: $RCSfile: XYDoubleArray.java,v $
* Purpose: A description of the contents of this file.
* Language: Java
* Compiler: JDK 1.4
* Authors: Joerg K. Wegner
* Version: $Revision: 1.6 $
* $Date: 2001/10/17 11:37:42 $
* $Author: wegnerj $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
/*==========================================================================*
* PACKAGE
*==========================================================================*/
package wsi.ra.sort;
/*==========================================================================*
* IMPORTS
*==========================================================================*/
//import wsi.ra.jchart2d.*;
import java.util.*;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* Defines two <code>double[]</code> arrays.
*
* @version $Revision: 1.6 $, $Date: 2001/10/17 11:37:42 $
*
*/
public class XYDoubleArray implements Cloneable{
/*-------------------------------------------------------------------------*
* public member variables
*-------------------------------------------------------------------------*/
//public static final int TABLE_OUTPUT=JChart2DUtils.TABLE_OUTPUT;
//public static final int VECTOR_OUTPUT=JChart2DUtils.VECTOR_OUTPUT;
public double[] x=null;
public double[] y=null;
/*-------------------------------------------------------------------------*
* constructor
*-------------------------------------------------------------------------*/
public XYDoubleArray(int length)
{
this.x=new double[length];
this.y=new double[length];
}
public XYDoubleArray(double[] x, double[] y)
{
this.x=x;
this.y=y;
}
/*-------------------------------------------------------------------------*
* public methods
*-------------------------------------------------------------------------*/
public final void swap(int a, int b)
{
double xx = x[a]; x[a] = x[b]; x[b] = xx;
double yy = y[a]; y[a] = y[b]; y[b] = yy;
}
/*public final void sortX(){
QuickInsertSort quickInsertSort = new QuickInsertSort();
quickInsertSort.sortX(this);
}
public final void sortY(){
QuickInsertSort quickInsertSort = new QuickInsertSort();
quickInsertSort.sortY(this);
}*/
//
// uses jchart2d methods !;-(
//
/*public String toString(){
return toString(TABLE_OUTPUT);
}
private String toString(int output){
if(x==null || y==null)return null;
BasicDataSet data=new BasicDataSet(x, y,
AbstractDataSet.CONTINUOUS_DATA,
"x",
"y");
String s=JChart2DUtils.writeDataSetToString(data, output);
return s;
}*/
public Object clone()
{
double[] newX=new double[x.length];
double[] newY=new double[y.length];
XYDoubleArray newArray=new XYDoubleArray(newX, newY);
for(int i=0;i<x.length;i++){
newArray.x[i]=x[i];
newArray.y[i]=y[i];
}
return newArray;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,589 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: BasicResourceLoader.java,v $
// Purpose: Atom representation.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg Kurt Wegner, Gerd Mueller
// Version: $Revision: 1.3 $
// $Date: 2005/02/17 16:48:44 $
// $Author: wegner $
//
// Copyright OELIB: OpenEye Scientific Software, Santa Fe,
// U.S.A., 1999,2000,2001
// Copyright JOELIB/JOELib2: Dept. Computer Architecture, University of
// Tuebingen, Germany, 2001,2002,2003,2004,2005
// Copyright JOELIB/JOELib2: ALTANA PHARMA AG, Konstanz, Germany,
// 2003,2004,2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.tool;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import wsi.ra.tool.DummyCategory;
/**
* Loads resource file from directory OR jar file. Now it is easier possible to
* access resource files in a directory structure or a .jar/.zip file.
*
* @.author Marcel Kronfeld
* @.author wegnerj
* @.author Robin Friedman, rfriedman@TriadTherapeutics.com
* @.author Gerd Mueller
* @.license GPL
* @.cvsversion $Revision: 1.3 $, $Date: 2005/02/17 16:48:44 $
*/
public class BasicResourceLoader implements ResourceLoader
{
//~ Static fields/initializers /////////////////////////////////////////////
/**
* Obtain a suitable logger.
*/
private static DummyCategory logger = DummyCategory.getInstance(
BasicResourceLoader.class.getName());
private static BasicResourceLoader resourceLoader;
//~ Constructors ///////////////////////////////////////////////////////////
/**
* Constructor for the ResourceLoader object
*/
private BasicResourceLoader()
{
}
//~ Methods ////////////////////////////////////////////////////////////////
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public static synchronized BasicResourceLoader instance()
{
if (resourceLoader == null)
{
resourceLoader = new BasicResourceLoader();
}
return resourceLoader;
}
/**
* Description of the Method
*
* @param resourceFile Description of the Parameter
* @return Description of the Return Value
*/
public static List readLines(String resourceFile)
{
return readLines(resourceFile, false);
}
/**
* Description of the Method
*
* @param resourceFile Description of the Parameter
* @param ignoreComments Description of the Parameter
* @return Description of the Return Value
*/
public static List readLines(String resourceFile,
boolean ignoreCommentedLines)
{
return readLines(resourceFile, new String[] {"#"}, 0, -1);
}
/**
* Description of the Method
*
* @param resourceFile Description of the Parameter
* @param ignorePrefix array of prefixes which mark a line to be ignored
* @param lOffset offset of the first line to read
* @param lCnt number of lines to read, if <= 0, all lines are read
* @return Description of the Return Value
*/
public static List readLines(String resourceFile,
String[] ignorePrefix, int lOffset, int lCnt)
{
if (resourceFile == null)
{
return null;
}
byte[] bytes = BasicResourceLoader.instance()
.getBytesFromResourceLocation(
resourceFile);
if (bytes == null)
{
return null;
}
ByteArrayInputStream sReader = new ByteArrayInputStream(bytes);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(
sReader));
String line;
ArrayList<String> lineData = new ArrayList<String>(100);
int lineCnt = 0;
try
{
while ((line = lnr.readLine()) != null)
{
line = line.trim();
if (strStartsWithPrefix(line, ignorePrefix) < 0) {
if (lineCnt >= lOffset) lineData.add(line);
lineCnt++;
if ((lCnt > 0) && (lineData.size() == lCnt)) break;
}
// if (line.trim().length() > 0) {
// if ((ignorePrefix == null) || (strStartsWithPrefix(line, ignorePrefix) < 0)) {
// // if there are no prefixes given or none of them fits, add the line
// lineData.add(line);
// }
// }
}
}
catch (IOException ex)
{
logger.error(ex.getMessage());
}
return lineData;
}
/**
* Parse columns of a data array containing double data. Columns may be selected by giving their
* indices in an int array. If selectedCols is null, all columns are selected. All selected columns
* are expected to contain double data and to be of same length. If rawData is null, null is returned.
*
* @param rawData Strings containing an array with double data columns
* @param colSplit String regexp for the splitting of a line
* @param selectedCols indices of the columns to retrieve, null for all.
* @return
*/
public static double[][] parseDoubleArray(ArrayList<String> rawData, String colSplit, int[] selectedCols) {
String[] entries;
double dat[][] = null;
if (rawData != null) {
try {
for (int i=0; i<rawData.size(); i++) {
entries = rawData.get(i).split(colSplit);
if (i == 0) { // at the first pass
dat = new double[rawData.size()][(selectedCols == null) ? entries.length : selectedCols.length];
}
fillLine(dat, i, entries, selectedCols);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
return dat;
}
/**
* Walk through a 2-d-array and retrieve the first bunch of lines for which the given column data lies
* within start and end limits, both inclusively. The original array is not altered.
*
* @param data data array to search
* @param col column to inspect
* @param start first value to start retrieving from
* @param end last value to retrieve
* @return
*/
public static double[][] getLinesByCol(double[][] data, int col, double start, double end) {
int cnt = 0;
int startIndex = 0;
for (int i=0; i<data.length; i++) {
if ((data[i][col] >= start) && (data[i][col] <= end)) {
if (cnt == 0) startIndex = i;
cnt++;
} else if (cnt > 0) break;
}
double[][] selData = new double[cnt][data[0].length];
System.arraycopy(data, startIndex, selData, 0, cnt);
return selData;
}
/**
* Load double data from a text file. An ignore list of prefixes may be specified. The start line and number of lines
* to read may be specified, if lCnt is -1, as many lines as possible are read. The cols array may contain an integer
* list of columns to be read. If null, as many columns as possible are read.
* The data file is expected to be uniform, meaning that all lines which are not ignored, contain double data values
* in all columns.
*
* @param fname file name to read
* @param ignorePrefix lines starting with any of these Strings will be ignored
* @param colSplit String regexp for the splitting of a line
* @param lOffset start at a certain line (0 for top)
* @param lCnt read as many lines, -1 or 0 for all (from offset). Ignored lines are not counted!
* @param selectedCols indices of the columns to retrieve, null for all.
* @return
*/
public static double[][] loadDoubleData(String fname, String[] ignorePrefix, String colSplit, int lOffset, int lCnt, int[] selectedCols) {
return parseDoubleArray((ArrayList<String>)readLines(fname, ignorePrefix, lOffset, lCnt), colSplit, selectedCols);
}
/**
* Fill a line of an array with double values parsed from a String array. A subset of
* Columns may be selected by giving their indeces in an integer array cols. If cols
* is null, all are converted.
*
* @param dest
* @param lineCnt
* @param entries
* @param cols
*/
public static void fillLine(double[][] dest, int lineCnt, String[] entries, int[] cols) {
if (((cols == null) && (dest[lineCnt].length != entries.length)) || (cols != null && (dest[lineCnt].length != cols.length))) {
System.err.println("error, array dimensions dont match! (SIFTComparisonMatrix");
}
if (cols == null) {
for (int i=0; i<entries.length; i++) {
dest[lineCnt][i] = Double.valueOf(entries[i]);
}
} else {
for (int i=0; i<cols.length; i++) {
dest[lineCnt][i] = Double.valueOf(entries[cols[i]]);
}
}
}
/**
* Test a string for prefixes. If a prefix matches, return its index, else return -1.
* @param str
* @param pref
* @return
*/
public static int strStartsWithPrefix(String str, String[] pref) {
int i=0;
if (pref != null) {
for (String prefix : pref) {
if (str.startsWith(prefix)) return i;
i++;
}
}
return -1;
}
/**
* Gets the byte data from a file at the given resource location.
*
* @param rawResrcLoc Description of the Parameter
* @return the byte array of file.
*/
public byte[] getBytesFromResourceLocation(String rawResrcLoc)
{
String resourceLocation = rawResrcLoc.replace('\\', '/');
//System.out.println("Try to get: "+resourceLocation);
if (resourceLocation == null)
{
return null;
}
// to avoid hours of debugging non-found-files under linux with
// some f... special characters at the end which will not be shown
// at the console output !!!
resourceLocation = resourceLocation.trim();
// is a relative path defined ?
// this can only be possible, if this is a file resource loacation
if (resourceLocation.startsWith("..") ||
resourceLocation.startsWith("/") ||
resourceLocation.startsWith("\\") ||
((resourceLocation.length() > 1) &&
(resourceLocation.charAt(1) == ':')))
{
return getBytesFromFile(resourceLocation);
}
InputStream in = ClassLoader.getSystemResourceAsStream(resourceLocation);
if (in == null)
{
// try again for web start applications
in = this.getClass().getClassLoader().getResourceAsStream(
resourceLocation);
}
if (in == null)
{
return null;
}
if (logger.isDebugEnabled())
{
logger.debug("Stream opened for " + resourceLocation);
}
byte[] bytes = getBytesFromStream(in);
return bytes;
}
/**
* Gets the byte data from a file contained in a JAR or ZIP file.
*
* @param urlToZipArchive Description of the Parameter
* @param internalArchivePath Description of the Parameter
* @return the byte array of the file.
*/
private byte[] getBytesFromArchive(String urlToZipArchive,
String internalArchivePath)
{
URL url = null;
int size = -1;
byte[] b = null;
try
{
url = new URL(urlToZipArchive);
// extracts just sizes only.
ZipFile zf = new ZipFile(url.getFile());
Enumeration e = zf.entries();
while (e.hasMoreElements())
{
ZipEntry ze = (ZipEntry) e.nextElement();
if (ze.getName().equals(internalArchivePath))
{
if (ze.isDirectory())
{
return null;
}
// only files with <65536 bytes are allowed
if (ze.getSize() > 65536)
{
System.out.println(
"Resource files should be smaller than 65536 bytes...");
}
size = (int) ze.getSize();
}
}
zf.close();
FileInputStream fis = new FileInputStream(url.getFile());
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis);
ZipEntry ze = null;
while ((ze = zis.getNextEntry()) != null)
{
if (ze.getName().equals(internalArchivePath))
{
b = new byte[(int) size];
int rb = 0;
int chunk = 0;
while (((int) size - rb) > 0)
{
chunk = zis.read(b, rb, (int) size - rb);
if (chunk == -1)
{
break;
}
rb += chunk;
}
}
}
}
catch (Exception e)
{
logger.error(e.getMessage());
return null;
}
return b;
}
/**
* Gets the byte data from a file.
*
* @param fileName Description of the Parameter
* @return the byte array of the file.
*/
private byte[] getBytesFromFile(String fileName)
{
if (fileName.startsWith("/cygdrive/"))
{
int length = "/cygdrive/".length();
fileName = fileName.substring(length, length + 1) + ":" +
fileName.substring(length + 1);
}
if (logger.isDebugEnabled())
{
logger.debug("Trying to get file from " + fileName);
}
File file = new File(fileName);
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
}
catch (Exception e)
{
logger.error(e.getMessage());
return null;
}
BufferedInputStream bis = new BufferedInputStream(fis);
// only files with <65536 bytes are allowed
//if( file.length() > 65536 ) System.out.println("Resource files should be smaller than 65536 bytes...");
int size = (int) file.length();
byte[] b = new byte[size];
int rb = 0;
int chunk = 0;
try
{
while (((int) size - rb) > 0)
{
chunk = bis.read(b, rb, (int) size - rb);
if (chunk == -1)
{
break;
}
rb += chunk;
}
}
catch (Exception e)
{
logger.error(e.getMessage());
return null;
}
return b;
}
/**
* Gets the byte data from a file.
*
* @param fileName Description of the Parameter
* @return the byte array of the file.
*/
private byte[] getBytesFromStream(InputStream stream)
{
if (stream == null)
{
return null;
}
if (logger.isDebugEnabled())
{
logger.debug("Trying to get file from stream.");
}
BufferedInputStream bis = new BufferedInputStream(stream);
try
{
int size = (int) bis.available();
byte[] b = new byte[size];
int rb = 0;
int chunk = 0;
while (((int) size - rb) > 0)
{
chunk = bis.read(b, rb, (int) size - rb);
if (chunk == -1)
{
break;
}
rb += chunk;
}
return b;
}
catch (Exception e)
{
logger.error(e.getMessage());
return null;
}
}
/**
*
*/
public static Properties readProperties(String resourceName) throws Exception {
// if (TRACE)
// System.out.println("EvAClient.readProperties of " + resourceName);
Properties prop = new Properties();
BasicResourceLoader loader = BasicResourceLoader.instance();
byte bytes[] = loader.getBytesFromResourceLocation(resourceName);
if (bytes != null) {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
prop.load(bais);
}
if (prop != null)
return prop;
/////////////
int slInd = resourceName.lastIndexOf('/');
if (slInd != -1)
resourceName = resourceName.substring(slInd + 1);
Properties userProps = new Properties();
File propFile = new File(File.separatorChar + "resources" + File.separatorChar + resourceName);
if (propFile.exists()) {
try {
userProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
System.out.println("Problem reading user properties: " + propFile);
}
}
return userProps;
}
}

View File

@@ -0,0 +1,41 @@
package wsi.ra.tool;
/**
* Dummy class replacing the log4j Category because log4j couldnt be included in a clean
* way and seemingly wasnt used in the main classes anyways.
*
* @author mkron, mpaly
*
*/
public class DummyCategory {
static DummyCategory dummy = new DummyCategory();
static boolean bDebugEnabled = false;
public void error() {
System.err.println("Error");
}
public void error(String msg) {
System.err.println(msg);
}
public static DummyCategory getInstance(String str) {
return dummy;
}
public boolean isDebugEnabled() {
return bDebugEnabled;
}
public void debug(String str) {
System.err.println(str);
}
public void info(String str) {
System.err.println(str);
}
public void warn(String str) {
System.err.println(str);
}
}

View File

@@ -0,0 +1,161 @@
/**
* Filename: $RCSfile: IntegerArrayList.java,v $
* Purpose: This class is similar to 'java.util.ArrayList', except that it can
* only hold and manage integer values.
* Language: Java
* Compiler: JDK 1.2
* Authors: Fred Rapp
* Version: $Revision: 1.1.1.1 $
* $Date: 2003/07/03 14:59:40 $
* $Author: ulmerh $
* Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
*/
package wsi.ra.tool;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* This class is similar to 'java.util.ArrayList', except that it can
* only hold and manage integer values.
*/
public class IntegerArrayList
{
/*-------------------------------------------------------------------------*
* private member variables
*-------------------------------------------------------------------------*/
private int[] integerArray = null;
private int integerCount = 0;
private int initialSize;
private int incrementFactor;
/*------------------------------------------------------------------------*
* constructor
*------------------------------------------------------------------------*/
public IntegerArrayList()
{
// call other constructor with default values
this(100, 3);
}
public IntegerArrayList(int initialSize, int incrementFactor)
{
this.initialSize = initialSize;
this.incrementFactor = incrementFactor;
// create new integer array of initial size
integerArray = new int[initialSize];
}
public void destroy() { integerArray = null; integerCount = 0; }
/*-------------------------------------------------------------------------*
* public methods
*-------------------------------------------------------------------------*/
/**
* Clears the contents of this integer list and sets it back to it's initial state.
*/
public void clear() { integerArray = new int[initialSize]; integerCount = 0; }
/**
* Returns the number of components in this list.
*/
public int size() { return integerCount; }
/**
* Parses given string to integer and adds it to the integer list.
* @return true if parsing was successful, false if an error occured.
*/
public boolean add(String stringValue)
{
boolean success = false;
try {
int value = Integer.parseInt(stringValue);
add(value);
success = true;
}
catch (Exception e) {}
return success;
}
/**
* Adds a new integer value to the integer list.
*/
public void add(int value)
{
// check integer array size
if (integerCount == integerArray.length)
{
// increase size of int array
int old_length = integerArray.length;
int new_length = incrementFactor * old_length;
int[] new_array = new int[new_length];
for (int i=0; i<old_length; i++) {
new_array[i] = integerArray[i];
}
integerArray = new_array;
}
// add given value to array
integerArray[integerCount++] = value;
}
/**
* Returns the integer value at the given position or 'min-value' if out of array bounds.
*/
public int get(int index)
{
if ((index < 0) || (index >= integerCount)) { return Integer.MIN_VALUE; }
return integerArray[index];
}
/**
* Returns the contents of this list as an array of integer values.
* @param exactLength determines if the returned array should have the exactly right length, or if longer arrays are allowed
*/
public int[] getIntegerArray(boolean exactLength)
{
// check if we can simply return our internal integer array
if (!exactLength || (integerArray.length == integerCount)) { return integerArray; }
// make a copy of the array with the exactly right length
int size = integerCount;
int[] new_array = new int[ size];
for (int i=0; i< size; i++) { new_array[i] = integerArray[i]; }
return new_array;
}
/**
* Returns the contents of this list as an array of double values.
*/
public double[] getDoubleArray()
{
// make a copy of the array
int size = integerCount;
double[] new_array = new double[ size];
for (int i=0; i< size; i++) { new_array[i] = integerArray[i]; }
return new_array;
}
/**
* Returns the contents of this list as an array of strings.
*/
public String[] getStringArray()
{
// make a copy of the array
int size = integerCount;
String[] new_array = new String[ size];
for (int i=0; i<size; i++) { new_array[i] = "" + integerArray[i]; }
return new_array;
}
}
/****************************************************************************
* END OF FILE
****************************************************************************/

View File

@@ -0,0 +1,52 @@
///////////////////////////////////////////////////////////////////////////////
//Filename: $RCSfile: ResourceLoader.java,v $
//Purpose: TODO description.
//Language: Java
//Compiler: JDK 1.5
//Created: Jan 16, 2005
//Authors: Joerg Kurt Wegner
//Version: $Revision: 1.8 $
// $Date: 2005/02/17 16:48:44 $
// $Author: wegner $
//
// Copyright OELIB: OpenEye Scientific Software, Santa Fe,
// U.S.A., 1999,2000,2001
// Copyright JOELIB/JOELib2: Dept. Computer Architecture, University of
// Tuebingen, Germany, 2001,2002,2003,2004,2005
// Copyright JOELIB/JOELib2: ALTANA PHARMA AG, Konstanz, Germany,
// 2003,2004,2005
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation version 2 of the License.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.tool;
/**
* TODO description.
*
* @.author wegnerj
* @.license GPL
* @.cvsversion $Revision: 1.8 $, $Date: 2005/02/17 16:48:44 $
*/
public interface ResourceLoader
{
//~ Methods ////////////////////////////////////////////////////////////////
/**
* Gets the byte data from a file at the given resource location.
*
* @param rawResrcLoc Description of the Parameter
* @return the byte array of file.
*/
byte[] getBytesFromResourceLocation(String rawResrcLoc);
}
///////////////////////////////////////////////////////////////////////////////
//END OF FILE.
///////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,534 @@
///////////////////////////////////////////////////////////////////////////////
// Filename: $RCSfile: StatisticUtils.java,v $
// Purpose: Interface definition for calling external programs from JOELib.
// Language: Java
// Compiler: JDK 1.4
// Authors: Joerg K. Wegner
// Version: $Revision: 1.1 $
// $Date: 2004/02/28 17:19:28 $
// $Author: ulmerh $
//
// Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
//
///////////////////////////////////////////////////////////////////////////////
package wsi.ra.tool;
/**
* Statistic utils.
*/
public class StatisticUtils
{
/** The natural logarithm of 2. */
public static double log2 = Math.log(2);
/** The small deviation allowed in double comparisons */
public static double SMALL = 1e-6;
/**
* Returns the correlation coefficient of two double vectors.
*
* @param y1 double vector 1
* @param y2 double vector 2
* @param n the length of two double vectors
* @return the correlation coefficient
*/
public final static double correlation(double y1[],double y2[],int n) {
int i;
double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c;
if (n <= 1) {
return 1.0;
}
for (i = 0; i < n; i++) {
av1 += y1[i];
av2 += y2[i];
}
av1 /= (double) n;
av2 /= (double) n;
for (i = 0; i < n; i++) {
y11 += (y1[i] - av1) * (y1[i] - av1);
y22 += (y2[i] - av2) * (y2[i] - av2);
y12 += (y1[i] - av1) * (y2[i] - av2);
}
if (y11 * y22 == 0.0) {
c=1.0;
} else {
c = y12 / Math.sqrt(Math.abs(y11 * y22));
}
return c;
}
/**
* Computes differential shannon entropy
*
* @return DSE=SE(AB)-0.5*[SE(A)+SE(B)]
*/
public static double differentialShannon(int counts1[],int counts2[], int n, int countsSum1, int countsSum2)
{
double seA=0.0;
double seB=0.0;
double seAB=0.0;
double c=0.0;
int AB;
int allSum = countsSum1+countsSum2;
for(int i=0;i<n;i++)
{
AB = counts1[i] + counts2[i];
seA -= xlogx(((double)counts1[i])/((double)countsSum1));
seB -= xlogx(((double)counts2[i])/((double)countsSum2));
seAB -= xlogx(((double)AB)/((double)allSum));
}
c= seAB - 0.5*(seA+seB);
return c;
}
/**
* Computes entropy for an array of integers.
*
* @param counts array of counts
* @return - a log2 a - b log2 b - c log2 c + (a+b+c) log2 (a+b+c)
* when given array [a b c]
*/
public static double info(int counts[]) {
int total = 0;
int c;
double x = 0;
for (int j = 0; j < counts.length; j++) {
x -= xlogx(counts[j]);
total += counts[j];
}
return x + xlogx(total);
}
/**
* Computes shannon entropy for an array of integers.
*
* @param counts array of counts
* @return - a log2 a - b log2 b - c log2 c
* when given array [a b c]
*/
public static double shannon(int counts[], int countsSum) {
double x = 0;
for (int j = 0; j < counts.length; j++) {
x -= xlogx( ((double)counts[j])/ ((double)countsSum));
}
return x;
}
/**
* Returns the logarithm of a for base 2.
*
* @param a a double
*/
public static final double log2(double a) {
return Math.log(a) / log2;
}
/**
* Returns index of maximum element in a given
* array of doubles. First maximum is returned.
*
* @param doubles the array of doubles
* @return the index of the maximum element
*/
public static int maxIndex(double [] doubles) {
double maximum = 0;
int maxIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || (doubles[i] > maximum)) {
maxIndex = i;
maximum = doubles[i];
}
}
return maxIndex;
}
/**
* Returns index of maximum element in a given
* array of integers. First maximum is returned.
*
* @param ints the array of integers
* @return the index of the maximum element
*/
public static int maxIndex(int [] ints) {
int maximum = 0;
int maxIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] > maximum)) {
maxIndex = i;
maximum = ints[i];
}
}
return maxIndex;
}
/**
* Computes the mean for an array of doubles.
*
* @param vector the array
* @return the mean
*/
public static double mean(double[] vector) {
double sum = 0;
if (vector.length == 0) {
return 0;
}
for (int i = 0; i < vector.length; i++) {
sum += vector[i];
}
return sum / (double) vector.length;
}
/**
* Returns index of minimum element in a given
* array of integers. First minimum is returned.
*
* @param ints the array of integers
* @return the index of the minimum element
*/
public static int minIndex(int [] ints) {
int minimum = 0;
int minIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] < minimum)) {
minIndex = i;
minimum = ints[i];
}
}
return minIndex;
}
/**
* Returns index of minimum element in a given
* array of doubles. First minimum is returned.
*
* @param doubles the array of doubles
* @return the index of the minimum element
*/
public static int minIndex(double [] doubles) {
double minimum = 0;
int minIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || (doubles[i] < minimum)) {
minIndex = i;
minimum = doubles[i];
}
}
return minIndex;
}
/**
* Normalizes the doubles in the array by their sum.
*
* @param doubles the array of double
* @exception IllegalArgumentException if sum is Zero or NaN
*/
public static void normalize(double[] doubles) {
double sum = 0;
for (int i = 0; i < doubles.length; i++) {
sum += doubles[i];
}
normalize(doubles, sum);
}
/**
* Normalizes the doubles in the array using the given value.
*
* @param doubles the array of double
* @param sum the value by which the doubles are to be normalized
* @exception IllegalArgumentException if sum is zero or NaN
*/
public static void normalize(double[] doubles, double sum) {
if (Double.isNaN(sum)) {
throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
}
if (sum == 0) {
// Maybe this should just be a return.
throw new IllegalArgumentException("Can't normalize array. Sum is zero.");
}
for (int i = 0; i < doubles.length; i++) {
doubles[i] /= sum;
}
}
/**
* Computes the variance for an array of doubles.
*
* @param vector the array
* @return the variance
*/
public static double variance(double[] vector) {
double sum = 0, sumSquared = 0;
if (vector.length <= 1) {
return 0;
}
for (int i = 0; i < vector.length; i++) {
sum += vector[i];
sumSquared += (vector[i] * vector[i]);
}
double result = (sumSquared - (sum * sum / (double) vector.length)) /
(double) (vector.length - 1);
// We don't like negative variance
if (result < 0) {
return 0;
} else {
return result;
}
}
/**
* Computes the sum of the elements of an array of doubles.
*
* @param doubles the array of double
* @return the sum of the elements
*/
public static double sum(double[] doubles) {
double sum = 0;
for (int i = 0; i < doubles.length; i++) {
sum += doubles[i];
}
return sum;
}
/**
* Computes the sum of the elements of an array of integers.
*
* @param ints the array of integers
* @return the sum of the elements
*/
public static int sum(int[] ints) {
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
return sum;
}
/**
* Returns c*log2(c) for a given integer value c.
*
* @param c an integer value
* @return c*log2(c) (but is careful to return 0 if c is 0)
*/
public static final double xlogx(int c) {
if (c == 0) {
return 0.0;
}
return c * StatisticUtils.log2((double) c);
}
/**
* Returns c*log2(c) for a given value c.
*
* @param c an integer value
* @return c*log2(c) (but is careful to return 0 if c is 0)
*/
public static final double xlogx(double c) {
if (c == 0) {
return 0.0;
}
return c * StatisticUtils.log2( c);
}
/**
* Tests if a is equal to b.
*
* @param a a double
* @param b a double
*/
public static final boolean eq(double a, double b){
return (a - b < SMALL) && (b - a < SMALL);
}
/**
* Tests if a is smaller or equal to b.
*
* @param a a double
* @param b a double
*/
public static final boolean smOrEq(double a,double b) {
return (a-b < SMALL);
}
/**
* Tests if a is greater or equal to b.
*
* @param a a double
* @param b a double
*/
public static final boolean grOrEq(double a,double b) {
return (b-a < SMALL);
}
/**
* Tests if a is smaller than b.
*
* @param a a double
* @param b a double
*/
public static final boolean sm(double a,double b) {
return (b-a > SMALL);
}
/**
* Tests if a is greater than b.
*
* @param a a double
* @param b a double
*/
public static final boolean gr(double a,double b) {
return (a-b > SMALL);
}
/**
* returns root mean square error.
*/
public static final double rmsError(double array1[], double array2[])
{
if ((array1 == null) || (array2 == null)) { return -1.0; }
double errorValueRMS = 0;
for (int i=0; i<array1.length; i++)
{
// add squared error value
errorValueRMS += (array1[i] - array2[i]) * (array1[i] - array2[i]);
}
// calculate mean and root of the sum of the squared error values
errorValueRMS = Math.sqrt(errorValueRMS / (double) array1.length);
return errorValueRMS;
}
/**
* Returns the correlation coefficient r^2.
*
* Correlation ("Statistik", 7 Aufl., Hartung, 1989, Kapitel 9 und 10, S.546-608):
* a=yMess[i];
* b=yWahr[i];
* aa=a*a;
* bb=b*b;
* ab=a*b;
* numerator=sumAB-(sumA*sumB/n);
* denominator=sqrt[(sumAA-(sumA*sumA/n))*(sumBB-(sumB*sumB/n))];
* R=correlationcoefficient=numerator/denominator;
*
* @author Joerg K. Wegner
*/
public static double getCorrelationCoefficient(double array1[], double array2[])
{
if ((array1 == null) || (array2 == null)) { return -2.0; }
double sumA = 0;
double sumB = 0;
double sumAB = 0;
double sumAA = 0;
double sumBB = 0;
for (int i=0; i<array1.length; i++)
{
double a = array1[i];
double b = array2[i];
sumA += a;
sumB += b;
sumAA += a*a;
sumBB += b*b;
sumAB += a*b;
}
double n = (double) array1.length;
double numerator = sumAB - (sumA*sumB/n);
double denominator = Math.sqrt((sumAA - (sumA*sumA/n)) * (sumBB - (sumB*sumB/n)));
double corrCoefficient = numerator / denominator;
corrCoefficient *= corrCoefficient;
return corrCoefficient;
}
/**
* Main method for testing this class.
*/
public static void main(String[] ops) {
// System.out.println("test (0.5, 100): " +
// StatisticUtils.test(100));
}
// The following methods got mysteriously lost maybe during cvs-svn refactoring.
// For the time being I add method thunks which give a warning when called. (mkron)
public static double quadratic_entropy(double[] ds) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
public static double mutual_information(double[] ds, double[] ds2, int nbins) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
public static double quadratic_mutinf(double[] feature, double[] labels) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
public static double quadratic_mutinf(double[] feature, double[] labels, int[] classes) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
public static double SUquadratic(double[] feature, double[] labels) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
public static double SUquadratic(double[] feature, double[] labels, int[] classes) {
// TODO Auto-generated method stub
System.err.println("warning, not implemented!");
return 0;
}
}

View File

@@ -0,0 +1,481 @@
/*****************************************************************************
* JMatLink *
******************************************************************************
* (c) 1999-2001 Stefan Mueller (email: stefan@held-mueller.de) *
******************************************************************************
* 19.01.1999 beginning (reuse of HelloWorld example, Java Tutorial) (0.01) *
* 06.02.1999 separation from gui (0.02) *
* 27.03.1999 engGetScalar, engGetVector, engGetArray (0.03) *
* engGetScalar already working *
* 01.04.1999 engGetArray: hints from bwymans@home.com *
* 02.05.1999 engGetArray is working now (0.04) *
* 20.05.1999 begin of engPutArray *
* 13.08.1999 renamed all native methods to ...NATIVE (0.05) *
* 30.08.1999 beginning to include some failure checks (0.06) *
* 31.08.1999 increased BUFSIZE to account for larger outputs (0.07) *
* 11.09.1999 get char arrays from workspace (0.08) *
* 10.10.1999 engPutArray[][] completed (0.10) *
* 04/07/2001 restart work on JMatLink (0.11) *
* 05/24/2001 engOpenSingleUse (0.11) *
* Introduce pool of engine pointers *
* Removed engPutArray, engPutArray[], always use engPutArray[][] *
* 07/31/01 Code Cleanup *
* 08/11/01 Moved to new version numer (1.00) *
******************************************************************************/
/* **** ToDo ****
* complex number support
*
*/
#include <jni.h>
#include "JMatLink.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "engine.h"
#define V5_COMPAT
#define BUFSIZE 2560
mxArray *T = NULL;
mxArray *result = NULL;
char buffer[BUFSIZE];
double *TP;
mxArray *arrayP;
jdouble scalar;
int engOpenMarkerI = 0; // Remember the engine that was opened with
// engOpen-command
#define enginePMax 10 // Maximum number of engines opened at the
// same time.
Engine *engineP[ enginePMax ]; // Array of pointers to engines
// Element 0 is reserved
jboolean debugB = JNI_FALSE; // No debug messages from start
/******************************************************************************/
int getUnusedEnginePointer()
{
/* Find unsed entry in array of pointers to engine */
/* j=0 is reserved!! */
int j;
for (j=1; j<enginePMax; j++)
{
if ( engineP[j] == NULL )
{
if (debugB) printf("engOpen %i", j);
return j; // Unused entry in array
}
else
{
}
}
if (debugB) printf("engOpen: getUnusedEnginePointer no more pointers available");
return 0; // all entries in use
}
void delEnginePointer(int p)
{
if ( ( p < 1 )
|| ( p >= enginePMax )
)
{
return; // pointer out of allowed region
}
// free entry in array
engineP[p] = 0;
}
JNIEXPORT void JNICALL Java_wsi_ra_tool_matlab_JMatLink_setDebugNATIVE
(JNIEnv *env, jobject obj, jboolean d)
{
if (d) debugB = JNI_TRUE;
else debugB = JNI_FALSE;
}
/********************************************************************************/
/********************************************************************************/
/******************** int engOpenNATIVE( startcmd ) *********************/
/********************************************************************************/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engOpenNATIVE__Ljava_lang_String_2
(JNIEnv *env, jobject obj, jstring startCmdS_JNI)
{
int engineI;
const char *openS;
if (engOpenMarkerI != 0) return engOpenMarkerI; // engOpen already used before
// return handle valid connection
openS = (*env)->GetStringUTFChars(env, startCmdS_JNI, 0);
/* find unused entry in engine array */
engineI = getUnusedEnginePointer();
if (engineI==0) return 0; // no more pointers available
if (!(engineP[engineI] = engOpen(openS)) )
{
if (debugB) fprintf(stderr, "\nCan't start MATLAB engine\n");
(*env)->ReleaseStringUTFChars(env, startCmdS_JNI, openS); // free memory
delEnginePointer(engineI);
return 0;
}
engOpenMarkerI = engineI; // Remember engine that was opened with engOpen()
(*env)->ReleaseStringUTFChars(env, startCmdS_JNI, openS); // free memory
return engineI;
}
/********************************************************************************/
/**************** int engOpenSingleUseNATIVE( startcmd ) ****************/
/********************************************************************************/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engOpenSingleUseNATIVE
(JNIEnv *env, jobject obj, jstring startCmdS_JNI)
{
const char *openS = (*env)->GetStringUTFChars(env, startCmdS_JNI, 0);
int retStatus = 0;
int engineI;
/* find unused entry in engine array */
engineI = getUnusedEnginePointer();
if (engineI==0) return 0; // no more pointers avaiblable
if (!(engineP[engineI] = engOpenSingleUse(openS, NULL, &retStatus)))
{
if (debugB) fprintf(stderr, "\nCan't start MATLAB engine\n");
(*env)->ReleaseStringUTFChars(env, startCmdS_JNI, openS); // free memory
delEnginePointer(engineI);
return 0;
}
(*env)->ReleaseStringUTFChars(env, startCmdS_JNI, openS); // free memory
return engineI;
}
/********************************************************************************/
/**************** int engCloseNATIVE( int epI ) ****************/
/********************************************************************************/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engCloseNATIVE__I
(JNIEnv *env, jobject obj, jint engine)
{
int retValI;
// Check if engine pointer is within allowed region
if (( engine < 1 ) || ( engine >= enginePMax ))
{
return 0; // Pointer is out of allowed region
}
if ( engineP[ engine ] != NULL )
{
retValI = engClose(engineP[ engine ]);
delEnginePointer( engine );
if (engine == engOpenMarkerI)
{
// This engine was opened with engOpen() before
engOpenMarkerI = 0;
}
if (debugB) printf("\n engClose \n");
}
else
{
return 0;
}
}
/********************************************************************************/
/*********** int engEvalStringNATIVE( int epI, String evalS ) *************/
/********************************************************************************/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engEvalStringNATIVE__ILjava_lang_String_2
(JNIEnv *env, jobject obj, jint engine, jstring evalS_JNI)
{
int retValI = 0;
const char *evalS = (*env)->GetStringUTFChars(env, evalS_JNI, 0);
// Check if engine pointer is within allowed region
if (( engine < 1 ) || ( engine >= enginePMax ))
{
return 0; // Pointer is out of allowed region
}
retValI = engEvalString(engineP[ engine ], evalS);
//printf("evalString %i",OpenB);
(*env)->ReleaseStringUTFChars(env, evalS_JNI, evalS); // free memory
return retValI;
}
/********************************************************************************/

View File

@@ -0,0 +1,149 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class wsi_ra_tool_matlab_JMatLink */
#ifndef _Included_wsi_ra_tool_matlab_JMatLink
#define _Included_wsi_ra_tool_matlab_JMatLink
#ifdef __cplusplus
extern "C" {
#endif
/* Inaccessible static: threadInitNumber */
/* Inaccessible static: stopThreadPermission */
#undef wsi_ra_tool_matlab_JMatLink_MIN_PRIORITY
#define wsi_ra_tool_matlab_JMatLink_MIN_PRIORITY 1L
#undef wsi_ra_tool_matlab_JMatLink_NORM_PRIORITY
#define wsi_ra_tool_matlab_JMatLink_NORM_PRIORITY 5L
#undef wsi_ra_tool_matlab_JMatLink_MAX_PRIORITY
#define wsi_ra_tool_matlab_JMatLink_MAX_PRIORITY 10L
#undef wsi_ra_tool_matlab_JMatLink_idleI
#define wsi_ra_tool_matlab_JMatLink_idleI 0L
#undef wsi_ra_tool_matlab_JMatLink_engOpenI
#define wsi_ra_tool_matlab_JMatLink_engOpenI 1L
#undef wsi_ra_tool_matlab_JMatLink_engCloseI
#define wsi_ra_tool_matlab_JMatLink_engCloseI 2L
#undef wsi_ra_tool_matlab_JMatLink_engEvalStringI
#define wsi_ra_tool_matlab_JMatLink_engEvalStringI 3L
#undef wsi_ra_tool_matlab_JMatLink_engGetScalarI
#define wsi_ra_tool_matlab_JMatLink_engGetScalarI 4L
#undef wsi_ra_tool_matlab_JMatLink_engGetVectorI
#define wsi_ra_tool_matlab_JMatLink_engGetVectorI 5L
#undef wsi_ra_tool_matlab_JMatLink_engGetArrayI
#define wsi_ra_tool_matlab_JMatLink_engGetArrayI 6L
#undef wsi_ra_tool_matlab_JMatLink_engPutArray2dI
#define wsi_ra_tool_matlab_JMatLink_engPutArray2dI 9L
#undef wsi_ra_tool_matlab_JMatLink_engOutputBufferI
#define wsi_ra_tool_matlab_JMatLink_engOutputBufferI 10L
#undef wsi_ra_tool_matlab_JMatLink_engGetCharArrayI
#define wsi_ra_tool_matlab_JMatLink_engGetCharArrayI 11L
#undef wsi_ra_tool_matlab_JMatLink_destroyJMatLinkI
#define wsi_ra_tool_matlab_JMatLink_destroyJMatLinkI 12L
#undef wsi_ra_tool_matlab_JMatLink_engOpenSingleUseI
#define wsi_ra_tool_matlab_JMatLink_engOpenSingleUseI 13L
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: displayHelloWorld
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_wsi_ra_tool_matlab_JMatLink_displayHelloWorld
(JNIEnv *, jobject);
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: engTestNATIVE
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_wsi_ra_tool_matlab_JMatLink_engTestNATIVE
(JNIEnv *, jobject);
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: engOpenNATIVE
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engOpenNATIVE
(JNIEnv *, jobject, jstring);
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: engOpenSingleUseNATIVE
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engOpenSingleUseNATIVE
(JNIEnv *, jobject, jstring);
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: engCloseNATIVE
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engCloseNATIVE
(JNIEnv *, jobject, jint);
/*
* Class: wsi_ra_tool_matlab_JMatLink
* Method: engEvalStringNATIVE
* Signature: (ILjava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_wsi_ra_tool_matlab_JMatLink_engEvalStringNATIVE
(JNIEnv *, jobject, jint, jstring);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
# This makefile builds JMatLink library on RH7.3.
# Joerg K. Wegner 27/09/02
#
# for using this feature
# setenv MATLAB /afs/informatik.uni-tuebingen.de/i386_rh62/ra/Matlab-6.1
# setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:$MATLAB/extern/lib/glnx86/
CC = gcc
LD = ld
# MATLAB
MATLAB = /afs/informatik.uni-tuebingen.de/i386_rh62/ra/Matlab-6.1
MLIB = -L$(MATLAB)/extern/lib/glnx86
MINCLUDE = -I$(MATLAB)/extern/include