1 /* =============================================================================
5 * =============================================================================
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
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.
22 * ECE Department Northwestern University
23 * email: wkliao@ece.northwestern.edu
29 * Northwestern University
34 * Port to Java version
36 * University of California, Irvine
38 * =============================================================================
40 * ------------------------------------------------------------------------
42 * For the license of kmeans, please see kmeans/LICENSE.kmeans
44 * ------------------------------------------------------------------------
46 * Unless otherwise noted, the following license applies to STAMP files:
48 * Copyright (c) 2007, Stanford University
49 * All rights reserved.
51 * Redistribution and use in source and binary forms, with or without
52 * modification, are permitted provided that the following conditions are
55 * * Redistributions of source code must retain the above copyright
56 * notice, this list of conditions and the following disclaimer.
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
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.
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.
79 * =============================================================================
82 public class KMeans extends Thread {
84 * User input for max clusters
89 * User input for min clusters
94 * Check for Binary file
99 * Using zscore transformation for cluster center
100 * deviating from distribution's mean
102 int use_zscore_transform;
105 * Input file name used for clustering
110 * Total number of threads
115 * threshold until which kmeans cluster continues
125 * Global arguments for threads
130 * Output: Number of best clusters
135 * Output: Cluster centers
137 float[][] cluster_centres;
142 float[][] attributes;
152 use_zscore_transform = 1;
153 threshold = (float) 0.001;
158 public KMeans(int threadid, GlobalArgs g_args) {
159 this.threadid = threadid;
160 this.g_args = g_args;
164 public KMeans(int threadid, GlobalArgs g_args, int nthreads, int use_zscore_transform,
165 int max_nclusters, int min_nclusters, float threshold,
166 float[][] attributes, int numObjects, int numAttributes) {
167 this.threadid = threadid;
168 this.g_args = g_args;
169 //this.nthreads = nthreads;
170 //this.use_zscore_transform = use_zscore_transform;
171 //this.max_nclusters = max_nclusters;
172 //this.min_nclusters = min_nclusters;
173 //this.threshold = threshold;
174 //this.attributes = attributes;
175 //this.numObjects = numObjects;
176 //this.numAttributes = numAttributes;
180 Barrier barr = new Barrier("128.195.136.162");
182 GlobalArgs tmp_g_args;
188 Barrier.enterBarrier(barr);
189 Normal.work(id, tmp_g_args);
190 Barrier.enterBarrier(barr);
194 /* =============================================================================
196 * =============================================================================
198 public static void main(String[] args) {
200 int MAX_LINE_LENGTH = 1000000; /* max input is 400000 one digit input + spaces */
201 int[] mid = new int[8];
202 mid[0] = (128<<24)|(195<<16)|(136<<8)|162; //dc-1.calit2
203 mid[1] = (128<<24)|(195<<16)|(136<<8)|163; //dc-2.calit2
204 mid[2] = (128<<24)|(195<<16)|(136<<8)|164; //dc-3.calit2
205 mid[3] = (128<<24)|(195<<16)|(136<<8)|165; //dc-4.calit2
206 mid[4] = (128<<24)|(195<<16)|(136<<8)|166; //dc-5.calit2
207 mid[5] = (128<<24)|(195<<16)|(136<<8)|167; //dc-6.calit2
208 mid[6] = (128<<24)|(195<<16)|(136<<8)|168; //dc-7.calit2
209 mid[7] = (128<<24)|(195<<16)|(136<<8)|169; //dc-8.calit2
213 * Read options fron the command prompt
217 KMeans.parseCmdLine(args, kms);
218 nthreads = kms.nthreads;
219 System.out.println("nthreads= " + kms.nthreads);
221 /* Initiate Barriers */
222 BarrierServer mybarr;
225 mybarr = global new BarrierServer(nthreads);
227 mybarr.start(mid[0]);
230 if (kms.max_nclusters < kms.min_nclusters) {
231 System.out.println("Error: max_clusters must be >= min_clusters\n");
236 float[][] attributes;
237 int numAttributes = 0;
241 * From the input file, get the numAttributes (columns in txt file) and numObjects (rows in txt file)
243 if (kms.isBinaryFile == 1) {
244 System.out.println("TODO: Unimplemented Binary file option\n");
248 FileInputStream inputFile = new FileInputStream(kms.filename);
249 byte b[] = new byte[MAX_LINE_LENGTH];
251 while ((n = inputFile.read(b)) != 0) {
252 for (int i = 0; i < n; i++) {
258 inputFile = new FileInputStream(kms.filename);
260 if((line = inputFile.readLine()) != null) {
262 boolean prevWhiteSpace = true;
263 while(index < line.length()) {
264 char c = line.charAt(index++);
265 boolean currWhiteSpace = Character.isWhitespace(c);
266 if(prevWhiteSpace && !currWhiteSpace){
269 prevWhiteSpace = currWhiteSpace;
274 /* Ignore the first attribute: numAttributes = 1; */
275 numAttributes = numAttributes - 1;
277 /* Allocate new shared objects and read attributes of all objects */
280 buf = global new float[numObjects][numAttributes];
281 attributes = global new float[numObjects][numAttributes];
284 KMeans.readFromFile(inputFile, kms.filename, tmp_buf, MAX_LINE_LENGTH);
285 System.out.println("Finished Reading from file ......");
288 * The core of the clustering
291 int len = kms.max_nclusters - kms.min_nclusters + 1;
298 km = global new KMeans[nthreads];
299 g_args = global new GlobalArgs();
300 g_args.nthreads = nthreads;
301 for(int x = 0; x < numObjects; x++) {
302 for(int y = 0; y < numAttributes; y++) {
303 attributes[x][y] = buf[x][y];
309 /* Create and Start Threads */
310 for(int i = 1; i<nthreads; i++) {
311 km[i] = global new KMeans(i, g_args, nthreads, kms.use_zscore_transform,
312 kms.max_nclusters, kms.min_nclusters, kms.threshold, attributes, numObjects, numAttributes);
318 boolean waitfordone=true;
326 for(int i = 1; i<nthreads; i++) {
333 System.out.println("Finished Starting threads......");
335 for (int i = 0; i < nloops; i++) {
337 // Since zscore transform may perform in cluster() which modifies the
338 // contents of attributes[][], we need to re-store the originals
340 float[][] tmp_attributes;
341 GlobalArgs tmp_g_args;
343 for(int x = 0; x < numObjects; x++) {
344 for(int y = 0; y < numAttributes; y++) {
345 attributes[x][y] = buf[x][y];
348 tmp_attributes = attributes;
353 Cluster.cluster_exec(nthreads,
356 tmp_attributes, // [numObjects][numAttributes]
357 kms, //main class that holds users inputs from command prompt and output arrays that need to be filled
358 tmp_g_args); // Global arguments common to all threads
361 System.out.println("Printing output......");
362 System.out.println("Best_nclusters= " + kms.best_nclusters);
364 /* Output: the coordinates of the cluster centres */
368 for (int i = 0; i < kms.best_nclusters; i++) {
369 System.out.print(i + " ");
370 for (int j = 0; j < numAttributes; j++) {
371 System.out.print(kms.cluster_centres[i][j] + " ");
373 System.out.println("\n");
378 System.out.println("Finished......\n");
382 public static void parseCmdLine(String args[], KMeans km) {
385 while (i < args.length && args[i].startsWith("-")) {
388 if(arg.equals("-m")) {
389 if(i < args.length) {
390 km.max_nclusters = new Integer(args[i++]).intValue();
392 } else if(arg.equals("-n")) {
393 if(i < args.length) {
394 km.min_nclusters = new Integer(args[i++]).intValue();
396 } else if(arg.equals("-t")) {
397 if(i < args.length) {
398 //km.threshold = new Integer(args[i++]).intValue();
399 km.threshold = (float) Double.parseDouble(args[i++]);
401 } else if(arg.equals("-i")) {
402 if(i < args.length) {
403 km.filename = args[i++];
405 } else if(arg.equals("-b")) {
406 if(i < args.length) {
407 km.isBinaryFile = new Integer(args[i++]).intValue();
409 } else if(arg.equals("-z")) {
410 if(i < args.length) {
413 } else if(arg.equals("-nthreads")) {
414 if(i < args.length) {
415 km.nthreads = new Integer(args[i++]).intValue();
417 } else if(arg.equals("-h")) {
421 if(km.nthreads == 0 || km.filename == null) {
427 * The usage routine which describes the program options.
429 public void usage() {
430 System.out.println("usage: ./kmeans -m <max_clusters> -n <min_clusters> -t <threshold> -i <filename> -nthreads <threads>\n");
431 System.out.println( " -i filename: file containing data to be clustered\n");
432 System.out.println( " -b input file is in binary format\n");
433 System.out.println( " -m max_clusters: maximum number of clusters allowed\n");
434 System.out.println( " -n min_clusters: minimum number of clusters allowed\n");
435 System.out.println( " -z : don't zscore transform data\n");
436 System.out.println( " -t threshold : threshold value\n");
437 System.out.println( " -nthreads : number of threads\n");
442 * Read attributes from the input file into an array
444 public static void readFromFile(FileInputStream inputFile, String filename, float[][] buf, int MAX_LINE_LENGTH) {
445 inputFile = new FileInputStream(filename);
449 byte b[] = new byte[MAX_LINE_LENGTH];
451 byte oldbytes[]=null;
454 atomic { //FIXME: temporary fix Note that this
455 // transaction will never abort because it is only executed
456 // on master machine and therefore the fileread native call is
457 //allowed as a warning
458 while ((n = inputFile.read(b)) != 0) {
462 if (oldbytes!=null) {
468 byte newbytes[]= new byte[x+oldbytes.length];
469 for(int ii=0;ii<oldbytes.length;ii++)
470 newbytes[ii]=oldbytes[ii];
471 for(int ii=0;ii<x;ii++)
472 newbytes[ii+oldbytes.length]=b[ii];
473 x++; //skip past space
475 buf[i][j]=(float)Double.parseDouble(new String(newbytes, 0, newbytes.length));
489 x=y;//push end to current character
493 //need to continue for another read
494 oldbytes=new byte[y-x];
495 for(int ii=0;ii<(y-x);ii++)
496 oldbytes[ii]=b[ii+x];
500 //otherwise x is beginning of character string, y is end
502 buf[i][j]=(float)Double.parseDouble(new String(b,x,y-x));
504 x=y;//skip to end of number
505 x++;//skip past space
514 /* =============================================================================
518 * =============================================================================