Saturday, 1 December 2012

Magic Square code



import Jama.*;
import java.util.Date;

/** Example of use of Matrix Class, featuring magic squares. **/

public class MagicSquareExample {

   /** Generate magic square test matrix. **/

   public static Matrix magic (int n) {

      double[][] M = new double[n][n];

      // Odd order

      if ((n % 2) == 1) {
         int a = (n+1)/2;
         int b = (n+1);
         for (int j = 0; j < n; j++) {
            for (int i = 0; i < n; i++) {
               M[i][j] = n*((i+j+a) % n) + ((i+2*j+b) % n) + 1;
            }
         }

      // Doubly Even Order

      } else if ((n % 4) == 0) {
         for (int j = 0; j < n; j++) {
            for (int i = 0; i < n; i++) {
               if (((i+1)/2)%2 == ((j+1)/2)%2) {
                  M[i][j] = n*n-n*i-j;
               } else {
                  M[i][j] = n*i+j+1;
               }
            }
         }

      // Singly Even Order

      } else {
         int p = n/2;
         int k = (n-2)/4;
         Matrix A = magic(p);
         for (int j = 0; j < p; j++) {
            for (int i = 0; i < p; i++) {
               double aij = A.get(i,j);
               M[i][j] = aij;
               M[i][j+p] = aij + 2*p*p;
               M[i+p][j] = aij + 3*p*p;
               M[i+p][j+p] = aij + p*p;
            }
         }
         for (int i = 0; i < p; i++) {
            for (int j = 0; j < k; j++) {
               double t = M[i][j]; M[i][j] = M[i+p][j]; M[i+p][j] = t;
            }
            for (int j = n-k+1; j < n; j++) {
               double t = M[i][j]; M[i][j] = M[i+p][j]; M[i+p][j] = t;
            }
         }
         double t = M[k][0]; M[k][0] = M[k+p][0]; M[k+p][0] = t;
         t = M[k][k]; M[k][k] = M[k+p][k]; M[k+p][k] = t;
      }
      return new Matrix(M);
   }

   /** Shorten spelling of print. **/

   private static void print (String s) {
      System.out.print(s);
   }
 
   /** Format double with Fw.d. **/

   public static String fixedWidthDoubletoString (double x, int w, int d) {
      java.text.DecimalFormat fmt = new java.text.DecimalFormat();
      fmt.setMaximumFractionDigits(d);
      fmt.setMinimumFractionDigits(d);
      fmt.setGroupingUsed(false);
      String s = fmt.format(x);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
   }

   /** Format integer with Iw. **/

   public static String fixedWidthIntegertoString (int n, int w) {
      String s = Integer.toString(n);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
   }


   public static void main (String argv[]) {

   /*
    | Tests LU, QR, SVD and symmetric Eig decompositions.
    |
    |   n       = order of magic square.
    |   trace   = diagonal sum, should be the magic sum, (n^3 + n)/2.
    |   max_eig = maximum eigenvalue of (A + A')/2, should equal trace.
    |   rank    = linear algebraic rank,
    |             should equal n if n is odd, be less than n if n is even.
    |   cond    = L_2 condition number, ratio of singular values.
    |   lu_res  = test of LU factorization, norm1(L*U-A(p,:))/(n*eps).
    |   qr_res  = test of QR factorization, norm1(Q*R-A)/(n*eps).
    */

      print("\n    Test of Matrix Class, using magic squares.\n");
      print("    See MagicSquareExample.main() for an explanation.\n");
      print("\n      n     trace       max_eig   rank        cond      lu_res      qr_res\n\n");

      Date start_time = new Date();
      double eps = Math.pow(2.0,-52.0);
      for (int n = 3; n <= 32; n++) {
         print(fixedWidthIntegertoString(n,7));

         Matrix M = magic(n);

         int t = (int) M.trace();
         print(fixedWidthIntegertoString(t,10));

         EigenvalueDecomposition E =
            new EigenvalueDecomposition(M.plus(M.transpose()).times(0.5));
         double[] d = E.getRealEigenvalues();
         print(fixedWidthDoubletoString(d[n-1],14,3));

         int r = M.rank();
         print(fixedWidthIntegertoString(r,7));

         double c = M.cond();
         print(c < 1/eps ? fixedWidthDoubletoString(c,12,3) :
            "         Inf");

         LUDecomposition LU = new LUDecomposition(M);
         Matrix L = LU.getL();
         Matrix U = LU.getU();
         int[] p = LU.getPivot();
         Matrix R = L.times(U).minus(M.getMatrix(p,0,n-1));
         double res = R.norm1()/(n*eps);
         print(fixedWidthDoubletoString(res,12,3));

         QRDecomposition QR = new QRDecomposition(M);
         Matrix Q = QR.getQ();
         R = QR.getR();
         R = Q.times(R).minus(M);
         res = R.norm1()/(n*eps);
         print(fixedWidthDoubletoString(res,12,3));

         print("\n");
      }
      Date stop_time = new Date();
      double etime = (stop_time.getTime() - start_time.getTime())/1000.;
      print("\nElapsed Time = " +
         fixedWidthDoubletoString(etime,12,3) + " seconds\n");
     
   }
}


----------------------------------------------------------------------------------------------------------------------------------
ENd of the code
in case you want the package or have any doubts mail me at kushiitian@gmail.com

Kmeans algorithm in JAVA

first the Point class
--------------------------------------------------------

package KmeansPractice;

public class Point {

private float X;
private float Y;

public Point()
{
this.X=0;
this.Y=0;
}
public boolean same(Point p1,Point p2)
{
int i1 = Float.compare(p1.getX(),p2.getX());
int i2 = Float.compare(p1.getY(),p2.getY());
if(i1==0 && i2==0)
return true;
else
return false;

}
public Point(float x, float y)
{
System.out.println(x+","+y);
this.X=x;
this.Y=y;
}

public float getX()
{
return X;
}

public float getY()
{
return Y;
}
    public void putX(float x)
    {
    this.X=x;
    }
    public void putY(float y)
    {
    this.Y=y;
    }
   
    public String toString()
    {
      return "("+this.X+","+this.Y+")";
    }
}

---------------------------------------------------------------
Now the cluster class
---------------------------------------------------------------
package KmeansPractice;
import java.util.*;

import KmeansPractice.Point;
public class Cluster {

private ArrayList<Point> cluster;
Point mean;
Cluster()
{
cluster=new ArrayList<Point>();
mean = new Point();
}
public void setMean(Point p)
{
mean=p;
}
public boolean exists(Point p)
{
if(cluster.contains(p))
 return true;
else return false;
}
    public void add(Point p)
    {
    cluster.add(p);
    }
    public void delete(Point p)
    {
    cluster.remove(p);
    }
public Point getMean()
{
return mean;
}
public Point calMean()
{
float X=0,Y=0;
for(Point p:cluster)
{
X = X+p.getX();
Y = Y+p.getY();
}
X=X/cluster.size();
Y=Y/cluster.size();
mean=new Point(X,Y);
return mean;
}
public String toString()
{
String S="";
for(Point p:cluster)
   {
S+=p.toString();
   }
return S;
}
}

-------------------------------------------------------
Now the KMEANS ALGORITHM
--------------------------------------------------------

package KmeansPractice;
import java.util.*;


import KmeansPractice.Point;
import KmeansPractice.Cluster;

public class Kmeans {
ArrayList<Cluster> C = new ArrayList<Cluster>();
ArrayList<Point> P=new ArrayList<Point>();
ArrayList<Point> means=new ArrayList<Point>();
int N;
Kmeans(int N)
{
this.N=N;
}
public void initialize()
{
Random rand=new Random();  
 
  for(int i=0;i<10;i++)
  {
  Point p=new Point((float)(rand.nextInt()%10),(float)(rand.nextInt()%10));
      P.add(p);
      //System.out.println(p.toString());
   } 
  Cluster C1=new Cluster();
  C1.setMean(P.get(0));
        C.add(C1);
  Cluster C2=new Cluster();
  C2.setMean(P.get(1));
  C.add(C2);
  Cluster C3=new Cluster();
  C3.setMean(P.get(2));
  C.add(C3);
}
public boolean AlgoKmeans()
{
System.out.println("entered algokmeans func");
Scanner sc = new Scanner(System.in);
float Mindist,CurrDist;
int index=0;
System.out.println("present clusters:");
means = new ArrayList<Point>();
for(Cluster c:C)
{
System.out.println(c.toString());
means.add(c.getMean());
}
System.out.println("present means:");
for(Cluster c:C)
{
System.out.println(c.getMean());
// means.add(c.getMean());
}
sc.nextInt();
//calculate mean and distance
 for(int i=0;i<10;i++)
 {  Mindist=999;
 for(int j=0;j<N;j++)
   {CurrDist=EDistance(P.get(i),C.get(j).getMean()); 
 
   if(C.get(j).exists(P.get(i)))
    {C.get(j).delete(P.get(i));}
    if(Mindist>CurrDist)
    {
    Mindist=CurrDist;
    index=j;
    }
   }
 C.get(index).add(P.get(i)); 
 
 }
 System.out.println("printing clusters before calculated means");
 for(Cluster c:C)
 {
 System.out.println(c.toString());
 }
 System.out.println("printing calculated means");
 for(int i=0;i<N;i++)
{
C.get(i).calMean();
System.out.println(C.get(i).getMean());
System.out.println("check:"+means.get(i).toString() + C.get(i).getMean().toString());
if(((C.get(i).getMean()).same(means.get(i),C.get(i).getMean())))
{
 
}
else
return false;
}
 System.out.println("printing clusters before calculated means");
 for(Cluster c:C)
 {
 System.out.println(c.toString());
 }
 return true;
}
public void print()
{
System.out.println("entered print func");
for(Cluster c:C)
   {
 System.out.println(c.toString());
   }
}
public float EDistance(Point p1, Point p2)
{  return (float)Math.sqrt((p1.getX()-p2.getX())*(p1.getX()-p2.getX())+(p1.getY()-p2.getY())*(p1.getY()-p2.getY()));
}
public static void main(String args[])
{
/*Point p1 = new Point((float)3.5,(float)4.5);
Point p2 = new Point((float)3.5,(float)4.5);
System.out.println(p1.same(p1,p2));
*/
Kmeans k =new Kmeans(3);
k.initialize();
   while(!k.AlgoKmeans())
  k.AlgoKmeans();
   k.print();
}
}

----------------------------------------------------------------------------------------------------------------------------------End of the code
in case you want package or have any doubts contact at kushiitian@gmail.com

DBSCAN algorithm coded in JAVA


package DBSCAN;
import java.util.*;

public class DBSCAN {
  float[][] distance=new float[10][10];
  int[] neighbours=new int[10];
  float[] distanceFromCore=new float[10];
  ArrayList<Point> corePoints;
  ArrayList<Point> dbscan ;
  private static int minPoints;
  private static int Radius;
 
  DBSCAN(int p,int r)
  {   minPoints=p;
      Radius=r;
 dbscan=new ArrayList<Point>();
 corePoints=new ArrayList<Point>();

  }
 
  public void Initialize()
  {System.out.println("reached here");
 Random rand=new Random(20);
 for (int i=0;i<10;i++)
  {
 Point p=new Point(rand.nextFloat()*10,rand.nextFloat()*10);
 dbscan.add(p);
 System.out.println(p.toString());
  }
  }
 
  public void algoDBSCAN()
  {
 //calculate distance of all
 for(int i=0;i<10;i++)
 {
 for(int j=0;j<10;j++)
 {
distance[i][j]=Edistance(dbscan.get(i),dbscan.get(j));
System.out.println("distances   "+distance[i][j]);
 }
 }
int count;
    for(int k=0;k<10;k++)
    {count=0;
    for(int l=0;l<10;l++)
    {
    if(distance[k][l]<Radius)
    {
    count++;
    }
    }
    neighbours[k]=count;
    System.out.println("neighbours presents are   "+neighbours[k]);
    isCore(k);
    }
   
    for(int m=0;m<10;m++)
    {
    if(!isCore(m))
     {isBoundary(m);}
    }
    for(int n=0;n<10;n++)
    {
    if(!isBoundary(n))
     {isOutlier(n);}
    }
  }
  public boolean isCore(int k)
  { if(neighbours[k]>=minPoints)
 {System.out.println("Core point : "+dbscan.get(k).toString() );
 corePoints.add(dbscan.get(k));
 return true;}
  else
 return false;
     
  }
  public boolean isBoundary(int k)
  {
 if(neighbours[k]<minPoints)
     {
 for(int i=0;i<10;i++)
 {
 distanceFromCore[i]=Edistance(dbscan.get(k),corePoints.get(i));
     if(distanceFromCore[i]<=Radius)
     {System.out.println("Boundary point: "+dbscan.get(k).toString() );
       return true;
     }
 }

      }
 return false;
  }
  public boolean isOutlier(int k)
  { if(neighbours[k]<minPoints&& !isBoundary(k))
      {System.out.println("Outlier : "+dbscan.get(k).toString() );
      return true;
       }
      return false;
  }
  public float Edistance(Point p1,Point p2)
  {return (float)Math.sqrt((p1.getX()-p2.getX())*(p1.getX()-p2.getX())+(p1.getY()-p2.getY())*(p1.getY()-p2.getY()));
   }
 
  public void Print()
  {
 System.out.println("radius is"+Radius+" "+","+" "+"Minimum points are"+minPoints);
  }
 
  public static void main(String args[])
  {
 DBSCAN db=new DBSCAN(3,4);

 db.Initialize();
 db.algoDBSCAN();
 db.Print();
  }
}



THIS WAS DBSCAN ALGORITHM
next class is the point data type class

//--------------------------------
package DBSCAN;

public class Point {

private float X;
private float Y;
boolean isCore;
boolean isBound;
boolean isOutlier;
Point()
{
X=0; Y=0;
}
Point(float x,float y)
{
X=x;
Y=y;
}
public float getX() {
return X;
}
public void setX(float x) {
X = x;
}
public float getY() {
return Y;
}
public void setY(float y) {
Y = y;
}
public String toString()
{
return "("+this.X+","+this.Y+")";
}
}


----------------------------------------------------------------------------------------------------------------------
end of the code.

if u want package or have any sort of doubts please contact at kushiitian@gmail.com