changes
[IRC.git] / Robust / src / Benchmarks / SingleTM / 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
233     /*
234      * The core of the clustering
235      */
236
237     int[] cluster_assign = new int[numObjects];
238     int nloops = 1;
239     int len = kms.max_nclusters - kms.min_nclusters + 1;
240
241     KMeans[] km = new KMeans[nthreads];
242     GlobalArgs g_args = new GlobalArgs();
243     g_args.nthreads = nthreads;
244
245     /* Create and Start Threads */
246     for(int i = 1; i<nthreads; i++) {
247       km[i] = new KMeans(i, g_args);
248     }
249
250     for(int i = 1; i<nthreads; i++) {
251       km[i].start();
252     }
253
254     System.out.println("Finished Starting threads......");
255
256     for (int i = 0; i < nloops; i++) {
257       /*
258        * Since zscore transform may perform in cluster() which modifies the
259        * contents of attributes[][], we need to re-store the originals
260        */
261       for(int x = 0; x < numObjects; x++) {
262         for(int y = 0; y < numAttributes; y++) {
263           attributes[x][y] = buf[x][y];
264         }
265       }
266
267       Cluster.cluster_exec(nthreads,
268           numObjects,
269           numAttributes,
270           attributes,             // [numObjects][numAttributes] 
271           kms,                    //main class that holds users inputs from command prompt and output arrays that need to be filled
272           g_args);                // Global arguments common to all threads
273     }
274
275     System.out.println("Printing output......");
276     System.out.println("Best_nclusters= " + kms.best_nclusters);
277
278     /* Output: the coordinates of the cluster centres */
279     {
280       for (int i = 0; i < kms.best_nclusters; i++) {
281         System.out.print(i + " ");
282         for (int j = 0; j < numAttributes; j++) {
283           System.out.print(kms.cluster_centres[i][j] + " ");
284         }
285         System.out.println("\n");
286       }
287     }
288
289     System.out.println("Finished......");
290     System.exit(0);
291   }
292
293   public static void parseCmdLine(String args[], KMeans km) {
294     int i = 0;
295     String arg;
296     while (i < args.length && args[i].startsWith("-")) {
297       arg = args[i++];
298       //check options
299       if(arg.equals("-m")) {
300         if(i < args.length) {
301           km.max_nclusters = new Integer(args[i++]).intValue();
302         }
303       } else if(arg.equals("-n")) {
304         if(i < args.length) {
305           km.min_nclusters = new Integer(args[i++]).intValue();
306         }
307       } else if(arg.equals("-t")) {
308         if(i < args.length) {
309           km.threshold = (float) Double.parseDouble(args[i++]);
310         }
311       } else if(arg.equals("-i")) {
312         if(i < args.length) {
313           km.filename = args[i++];
314         }
315       } else if(arg.equals("-b")) {
316         if(i < args.length) {
317           km.isBinaryFile = new Integer(args[i++]).intValue();
318         }
319       } else if(arg.equals("-z")) {
320         km.use_zscore_transform=0;
321       } else if(arg.equals("-nthreads")) {
322         if(i < args.length) {
323           km.nthreads = new Integer(args[i++]).intValue();
324         }
325       } else if(arg.equals("-h")) {
326         km.usage();
327       }
328     }
329     if(km.nthreads == 0 || km.filename == null) {
330       km.usage();
331     }
332   }
333
334   /**
335    * The usage routine which describes the program options.
336    **/
337   public void usage() {
338     System.out.println("usage: ./kmeans -m <max_clusters> -n <min_clusters> -t <threshold> -i <filename> -nthreads <threads>\n");
339     System.out.println(                   "  -i filename:     file containing data to be clustered\n");
340     System.out.println(                   "  -b               input file is in binary format\n");
341     System.out.println(                   "  -m max_clusters: maximum number of clusters allowed\n");
342     System.out.println(                   "  -n min_clusters: minimum number of clusters allowed\n");
343     System.out.println(                   "  -z             : don't zscore transform data\n");
344     System.out.println(                   "  -t threshold   : threshold value\n");
345     System.out.println(                   "  -nthreads      : number of threads\n");
346   }
347
348   /**
349    * readFromFile()
350    * Read attributes from the input file into an array
351    **/
352   public static void readFromFile(FileInputStream inputFile, String filename, float[][] buf, int MAX_LINE_LENGTH) {
353     inputFile = new FileInputStream(filename);
354     int j;
355     int i = 0;
356
357     byte b[] = new byte[MAX_LINE_LENGTH];
358     int n;
359     byte oldbytes[]=null;
360
361
362     j = -1;
363     while ((n = inputFile.read(b)) != 0) {
364       int x=0;
365
366       if (oldbytes!=null) {
367         //find space
368         boolean cr=false;
369         for (;x < n; x++) {
370           if (b[x] == ' ')
371             break;
372           if (b[x] == '\n') {
373             cr=true;
374             break;
375           }
376         }
377         byte newbytes[]=new byte[x+oldbytes.length];
378         boolean isnumber=false;
379         for(int ii=0;ii<oldbytes.length;ii++) {
380           if (oldbytes[ii]>='0'&&oldbytes[ii]<='9')
381             isnumber=true;
382           newbytes[ii]=oldbytes[ii];
383         }
384         for(int ii=0;ii<x;ii++) {
385           if (b[ii]>='0'&&b[ii]<='9')
386             isnumber=true;
387           newbytes[ii+oldbytes.length]=b[ii];
388         }
389         if (x!=n)
390           x++; //skip past space or cr
391         if (isnumber) {
392           if (j>=0) {
393             buf[i][j]=(float)Double.parseDouble(new String(newbytes, 0, newbytes.length));
394           }
395           j++;
396         }
397         if (cr) {
398           j=-1;
399           i++;
400         }
401         oldbytes=null;
402       }
403
404       while (x < n) {
405         int y=x;
406         boolean cr=false;
407         boolean isnumber=false;
408         for(y=x;y<n;y++) {
409           if ((b[y]>='0')&&(b[y]<='9'))
410             isnumber=true;
411           if (b[y]==' ')
412             break;
413           if (b[y]=='\n') {
414             cr=true;
415             break;
416           }
417         }
418         if (y==n) {
419           //need to continue for another read
420           oldbytes=new byte[y-x];
421           for(int ii=0;ii<(y-x);ii++)
422             oldbytes[ii]=b[ii+x];
423           break;
424         }
425         
426         //otherwise x is beginning of character string, y is end
427         if (isnumber) {
428           if (j>=0) {
429             buf[i][j]=(float)Double.parseDouble(new String(b,x,y-x));
430           }
431           j++;
432         }
433         if (cr) {
434           i++;//skip to next line
435           j = -1;//don't store line number
436           x=y;//skip to end of number
437           x++;//skip past return
438         } else {
439           x=y;//skip to end of number
440           x++;//skip past space
441         }
442       }
443     }
444     inputFile.close();
445   }
446 }
447
448 /* =============================================================================
449  *
450  * End of kmeans.java
451  *
452  * =============================================================================
453  */