changes on KMeans: remove System.exit(). It caused a forced termination so it couldn...
[IRC.git] / Robust / src / Benchmarks / oooJava / kmeans / KMeans.java
1  /* =============================================================================
2  *
3  * kmeans.java
4  *
5  * =============================================================================
6  *
7  * Description:
8  *
9  * Takes as input a file:
10  *   ascii  file: containing 1 data point per line
11  *   binary file: first int is the number of objects
12  *                2nd int is the no. of features of each object
13  *
14  * This example performs a fuzzy c-means clustering on the data. Fuzzy clustering
15  * is performed using min to max clusters and the clustering that gets the best
16  * score according to a compactness and separation criterion are returned.
17  *
18  *
19  * Author:
20  *
21  * Wei-keng Liao
22  * ECE Department Northwestern University
23  * email: wkliao@ece.northwestern.edu
24  *
25  *
26  * Edited by:
27  *
28  * Jay Pisharath
29  * Northwestern University
30  *
31  * Chi Cao Minh
32  * Stanford University
33  *
34  * Port to Java version
35  * Alokika Dash
36  * University of California, Irvine
37  *
38  * =============================================================================
39  *
40  * ------------------------------------------------------------------------
41  * 
42  * For the license of kmeans, please see kmeans/LICENSE.kmeans
43  * 
44  * ------------------------------------------------------------------------
45  * 
46  * Unless otherwise noted, the following license applies to STAMP files:
47  * 
48  * Copyright (c) 2007, Stanford University
49  * All rights reserved.
50  * 
51  * Redistribution and use in source and binary forms, with or without
52  * modification, are permitted provided that the following conditions are
53  * met:
54  * 
55  *     * Redistributions of source code must retain the above copyright
56  *       notice, this list of conditions and the following disclaimer.
57  * 
58  *     * Redistributions in binary form must reproduce the above copyright
59  *       notice, this list of conditions and the following disclaimer in
60  *       the documentation and/or other materials provided with the
61  *       distribution.
62  * 
63  *     * Neither the name of Stanford University nor the names of its
64  *       contributors may be used to endorse or promote products derived
65  *       from this software without specific prior written permission.
66  * 
67  * THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``AS IS'' AND ANY
68  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
70  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE
71  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
72  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
73  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
74  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
75  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
76  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
77  * THE POSSIBILITY OF SUCH DAMAGE.
78  *
79  * =============================================================================
80  */
81
82 public class KMeans /*extends Thread*/ {
83   /**
84    * User input for max clusters
85    **/
86   int max_nclusters;
87
88   /**
89    * User input for min clusters
90    **/
91   int min_nclusters;
92
93   /**
94    * Check for Binary file
95    **/
96   int isBinaryFile;
97
98   /**
99    * Using zscore transformation for cluster center 
100    * deviating from distribution's mean
101    **/
102   int use_zscore_transform;
103
104   /**
105    * Input file name used for clustering
106    **/
107   String filename;
108
109   /**
110    * Total number of threads
111    **/
112   int nthreads;
113
114   /**
115    * threshold until which kmeans cluster continues
116    **/
117   float threshold;
118
119   /**
120    * thread id
121    **/
122   int threadid;
123
124   /**
125    * Global arguments for threads 
126    **/
127   GlobalArgs g_args;
128
129   /**
130    * Output:  Number of best clusters
131    **/
132   int best_nclusters;
133
134   /**
135    * Output: Cluster centers
136    **/
137   float[][] cluster_centres;
138
139   public KMeans() {
140     max_nclusters = 13;
141     min_nclusters = 4;
142     isBinaryFile = 0;
143     use_zscore_transform = 1;
144     threshold = (float) 0.001;
145     best_nclusters=0;
146   }
147
148   public KMeans(int threadid, GlobalArgs g_args) {
149     this.threadid = threadid;
150     this.g_args = g_args;
151   }
152
153   public void run() {
154     while(true) {
155 //      Barrier.enterBarrier();
156       Normal.work(threadid, g_args);
157 //      Barrier.enterBarrier();
158     }
159   }
160
161   /* =============================================================================
162    * main
163    * =============================================================================
164    */
165   public static void main(String[] args) {
166     int nthreads;
167     int MAX_LINE_LENGTH = 1000000; /* max input is 400000 one digit input + spaces */
168
169     /**
170      * Read options fron the command prompt 
171      **/
172     KMeans kms = new KMeans();
173     KMeans.parseCmdLine(args, kms);
174     nthreads = kms.nthreads;
175
176     /* Initiate Barriers */
177 //    Barrier.setBarrier(nthreads);
178
179     if (kms.max_nclusters < kms.min_nclusters) {
180       System.out.println("Error: max_clusters must be >= min_clusters\n");
181       System.exit(0);
182     }
183     
184     float[][] buf;
185     float[][] attributes;
186     int numAttributes = 0;
187     int numObjects = 0;
188
189     /*
190      * From the input file, get the numAttributes (columns in txt file) and numObjects (rows in txt file)
191      */
192     if (kms.isBinaryFile == 1) {
193       System.out.println("TODO: Unimplemented Binary file option\n");
194       System.exit(0);
195     }
196
197     FileInputStream inputFile = new FileInputStream(kms.filename);
198     byte b[] = new byte[MAX_LINE_LENGTH];
199     int n;
200     while ((n = inputFile.read(b)) != 0) {
201       for (int i = 0; i < n; i++) {
202         if (b[i] == '\n')
203           numObjects++;
204       }
205     }
206     inputFile.close();
207     inputFile = new FileInputStream(kms.filename);
208     String line = null;
209     if((line = inputFile.readLine()) != null) {
210       int index = 0;
211       boolean prevWhiteSpace = true;
212       while(index < line.length()) {
213         char c = line.charAt(index++);
214         boolean currWhiteSpace = Character.isWhitespace(c);
215         if(prevWhiteSpace && !currWhiteSpace){
216           numAttributes++;
217         }   
218         prevWhiteSpace = currWhiteSpace;
219       }   
220     }   
221     inputFile.close();
222
223     /* Ignore the first attribute: numAttributes = 1; */
224     numAttributes = numAttributes - 1; 
225     System.out.println("numObjects= " + numObjects + " numAttributes= " + numAttributes);
226
227     /* Allocate new shared objects and read attributes of all objects */
228     buf = new float[numObjects][numAttributes];
229     attributes = new float[numObjects][numAttributes];
230     KMeans.readFromFile(inputFile, kms.filename, buf, MAX_LINE_LENGTH);
231     System.out.println("Finished Reading from file ......");
232     long startT=System.currentTimeMillis();
233     /*
234      * The core of the clustering
235      */
236
237     int nloops = 1;
238     int len = kms.max_nclusters - kms.min_nclusters + 1;
239
240     KMeans[] km = new KMeans[nthreads];
241     GlobalArgs g_args = new GlobalArgs();
242     g_args.nthreads = nthreads;
243
244     /* Create and Start Threads */
245     for(int i = 1; i<nthreads; i++) {
246       km[i] = new KMeans(i, g_args);
247     }
248
249     for(int i = 1; i<nthreads; i++) {
250       km[i].run();
251     }
252
253     System.out.println("Finished Starting threads......");
254
255     for (int i = 0; i < nloops; i++) {
256       /*
257        * Since zscore transform may perform in cluster() which modifies the
258        * contents of attributes[][], we need to re-store the originals
259        */
260       for(int x = 0; x < numObjects; x++) {
261         for(int y = 0; y < numAttributes; y++) {
262           attributes[x][y] = buf[x][y];
263         }
264       }
265
266       Cluster.cluster_exec(nthreads,
267           numObjects,
268           numAttributes,
269           attributes,             // [numObjects][numAttributes] 
270           kms,                    //main class that holds users inputs from command prompt and output arrays that need to be filled
271           g_args);                // Global arguments common to all threads
272     }
273
274     long endT=System.currentTimeMillis();
275     System.out.println("running time="+(endT-startT));
276 //    System.out.println("TIME="+g_args.global_time);
277
278     System.out.println("Printing output......");
279     System.out.println("Best_nclusters= " + kms.best_nclusters);
280
281     /* Output: the coordinates of the cluster centres */
282     /*
283     {
284       for (int i = 0; i < kms.best_nclusters; i++) {
285         System.out.print(i + " ");
286         for (int j = 0; j < numAttributes; j++) {
287           System.out.print(kms.cluster_centres[i][j] + " ");
288         }
289         System.out.println("\n");
290       }
291     }
292     */
293
294     System.out.println("Finished......");
295
296   }
297
298   public static void parseCmdLine(String args[], KMeans km) {
299     int i = 0;
300     String arg;
301     while (i < args.length && args[i].startsWith("-")) {
302       arg = args[i++];
303       //check options
304       if(arg.equals("-m")) {
305         if(i < args.length) {
306           km.max_nclusters = new Integer(args[i++]).intValue();
307         }
308       } else if(arg.equals("-n")) {
309         if(i < args.length) {
310           km.min_nclusters = new Integer(args[i++]).intValue();
311         }
312       } else if(arg.equals("-t")) {
313         if(i < args.length) {
314           km.threshold = (float) Double.parseDouble(args[i++]);
315         }
316       } else if(arg.equals("-i")) {
317         if(i < args.length) {
318           km.filename = args[i++];
319         }
320       } else if(arg.equals("-b")) {
321         if(i < args.length) {
322           km.isBinaryFile = new Integer(args[i++]).intValue();
323         }
324       } else if(arg.equals("-z")) {
325         km.use_zscore_transform=0;
326       } else if(arg.equals("-nthreads")) {
327         if(i < args.length) {
328           km.nthreads = new Integer(args[i++]).intValue();
329         }
330       } else if(arg.equals("-h")) {
331         km.usage();
332       }
333     }
334     if(km.nthreads == 0 || km.filename == null) {
335       km.usage();
336     }
337   }
338
339   /**
340    * The usage routine which describes the program options.
341    **/
342   public void usage() {
343     System.out.println("usage: ./kmeans -m <max_clusters> -n <min_clusters> -t <threshold> -i <filename> -nthreads <threads>\n");
344     System.out.println(                   "  -i filename:     file containing data to be clustered\n");
345     System.out.println(                   "  -b               input file is in binary format\n");
346     System.out.println(                   "  -m max_clusters: maximum number of clusters allowed\n");
347     System.out.println(                   "  -n min_clusters: minimum number of clusters allowed\n");
348     System.out.println(                   "  -z             : don't zscore transform data\n");
349     System.out.println(                   "  -t threshold   : threshold value\n");
350     System.out.println(                   "  -nthreads      : number of threads\n");
351   }
352
353   /**
354    * readFromFile()
355    * Read attributes from the input file into an array
356    **/
357   public static void readFromFile(FileInputStream inputFile, String filename, float[][] buf, int MAX_LINE_LENGTH) {
358     inputFile = new FileInputStream(filename);
359     int j;
360     int i = 0;
361
362     byte b[] = new byte[MAX_LINE_LENGTH];
363     int n;
364     byte oldbytes[]=null;
365
366
367     j = -1;
368     while ((n = inputFile.read(b)) != 0) {
369       int x=0;
370
371       if (oldbytes!=null) {
372         //find space
373         boolean cr=false;
374         for (;x < n; x++) {
375           if (b[x] == ' ')
376             break;
377           if (b[x] == '\n') {
378             cr=true;
379             break;
380           }
381         }
382         byte newbytes[]=new byte[x+oldbytes.length];
383         boolean isnumber=false;
384         for(int ii=0;ii<oldbytes.length;ii++) {
385           if (oldbytes[ii]>='0'&&oldbytes[ii]<='9')
386             isnumber=true;
387           newbytes[ii]=oldbytes[ii];
388         }
389         for(int ii=0;ii<x;ii++) {
390           if (b[ii]>='0'&&b[ii]<='9')
391             isnumber=true;
392           newbytes[ii+oldbytes.length]=b[ii];
393         }
394         if (x!=n)
395           x++; //skip past space or cr
396         if (isnumber) {
397           if (j>=0) {
398             buf[i][j]=(float)Double.parseDouble(new String(newbytes, 0, newbytes.length));
399           }
400           j++;
401         }
402         if (cr) {
403           j=-1;
404           i++;
405         }
406         oldbytes=null;
407       }
408
409       while (x < n) {
410         int y=x;
411         boolean cr=false;
412         boolean isnumber=false;
413         for(y=x;y<n;y++) {
414           if ((b[y]>='0')&&(b[y]<='9'))
415             isnumber=true;
416           if (b[y]==' ')
417             break;
418           if (b[y]=='\n') {
419             cr=true;
420             break;
421           }
422         }
423         if (y==n) {
424           //need to continue for another read
425           oldbytes=new byte[y-x];
426           for(int ii=0;ii<(y-x);ii++)
427             oldbytes[ii]=b[ii+x];
428           break;
429         }
430         
431         //otherwise x is beginning of character string, y is end
432         if (isnumber) {
433           if (j>=0) {
434             buf[i][j]=(float)Double.parseDouble(new String(b,x,y-x));
435           }
436           j++;
437         }
438         if (cr) {
439           i++;//skip to next line
440           j = -1;//don't store line number
441           x=y;//skip to end of number
442           x++;//skip past return
443         } else {
444           x=y;//skip to end of number
445           x++;//skip past space
446         }
447       }
448     }
449     inputFile.close();
450   }
451 }
452
453 /* =============================================================================
454  *
455  * End of kmeans.java
456  *
457  * =============================================================================
458  */