-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfinal_code.c
More file actions
1303 lines (1146 loc) · 37 KB
/
final_code.c
File metadata and controls
1303 lines (1146 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Created on: Jul 12, 2014
* Author: Hasan Asfoor
* *****************************************************************************
* In this version, the same dataset file is assumed to be local to both master and slave. This is the final version of the code.
* This is the final version.
*/
#include<pthread.h>
#include<stdlib.h>
#include <math.h>
#include<float.h>
#include <mpi.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <omp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <err.h>
#include <ctype.h>
# define errno (*__errno_location ())
# define STRING_ATTR_SIZE 100
/*
* A structure representing a set of parsed rows
*/
typedef struct {
int numOfStringAttr;
int numOfNumericAttr;
double* attrN;
char* attrS;
long numOfRows;
} Rows;
/*
* Arguments used to be passed to a function when computing min and max for ranges
*/
typedef struct {
long numOfColumns;
double* max;
double* min;
} RangesArguments;
/*
* Argument used to be passed to the loop parallel function
*/
typedef struct {
long start, end, increment;
void* args;
int (*function)(long, long, long, int, void*);
int threadId;
} LoopArguments;
/*
* Argument used to be passed to the row processing function
*/
typedef struct {
Rows currentRow;
double* ranges;
Rows rows;
int numOfColumns;
long numOfRows;
int numOfClasses;
long chunkSize;
long startIndex;
long endIndex;
double* uApprox;
double* lApprox;
double* cvector;
int numOfThreads;
long rowsCompleted;
long startLine;
char* lines;
int* indices;
int rank;
time_t* start_time;//, now, end_time;
} ProcessRowArgs;
int isNumeric (const char * s)
{
if (s == NULL || *s == '\0' || isspace(*s))
return 0;
char * p;
strtod (s, &p);
return *p == '\0';
}
/*
* INitializes a set of rows
*/
static int initRows(Rows* rows, long numOfRows, int numOfStrAttr, int numOfNumericAttr)
{
rows->numOfRows = numOfRows;
rows->numOfNumericAttr = numOfNumericAttr;
rows->attrN = malloc(sizeof(double)*numOfNumericAttr*numOfRows);
memset(rows->attrN,0,sizeof(double)*numOfNumericAttr*numOfRows);
rows->numOfStringAttr = numOfStrAttr;
rows->attrS = malloc(sizeof(char*)*numOfStrAttr*STRING_ATTR_SIZE*numOfRows);
memset(rows->attrS,0,sizeof(char*)*numOfStrAttr*STRING_ATTR_SIZE*numOfRows);
return 1;
}
/*
* frees the content of a Rows structure
*/
static int freeRowsContent(Rows* rows)
{
free(rows->attrN);
free(rows->attrS);
return 1;
}
/*
* add a numberic attribute value to a Rows structure
*/
static int addNumericAttr(Rows* rows, long rowNum, double attrVal, int attrIndex)
{
rows->attrN[rowNum * rows->numOfNumericAttr + attrIndex] = attrVal;
return 1;
}
/*
* add a string attribute value to a Rows structure
*/
static int addStringAttr(Rows* rows, long rowNum, char* attrVal, int attrIndex)
{
char* ptr = rows->attrS + rowNum * rows->numOfStringAttr * STRING_ATTR_SIZE + attrIndex * STRING_ATTR_SIZE;
sprintf(ptr, "%s",attrVal);
return 1;
}
static char* getStrAttrOfRow(Rows* rows, long rowNum, int attrNum)
{
char* ptr = rows->attrS;
ptr+=rowNum * rows->numOfStringAttr * STRING_ATTR_SIZE + attrNum * STRING_ATTR_SIZE;
return ptr;
}
//attrNum represents the numeric attribute number
static double getNumAttrOfRow(Rows* rows,long rowNum, int attrNum)
{
double result = -1;
result = rows->attrN[rowNum * rows->numOfNumericAttr + attrNum];
return result;
}
/*
* parse a string line and add it to a Rows structure
*/
static int addLineToRows(Rows* rows, int rowNum, char* line, double* ranges)
{
int numAttrs = rows->numOfNumericAttr;
int strAttrs = rows->numOfStringAttr;
int numOfColumns = numAttrs+ strAttrs;
char *token, *saveptr;
double numVal;
long i = 0,j=0;
char buff[strlen(line) + 1];
strcpy(buff, line);
token = strtok_r(buff, ",", &saveptr);
while (token != NULL && i+j < numOfColumns) {
if(isNumeric(token))
{
sscanf(token, "%lf", &numVal);
numVal = numVal*ranges[i];
addNumericAttr(rows,rowNum,numVal,i);
i++;
}
else
{
addStringAttr(rows,rowNum,token,j);
j++;
}
token = strtok_r(NULL, ",", &saveptr);
}
//printf("done tokenizing\n");*/
return 1;
}
static int getRowAt(Rows* rows, int rowNum, Rows* result)
{
result->numOfRows = 1;
result->numOfNumericAttr = rows->numOfNumericAttr;
result->numOfStringAttr = rows->numOfStringAttr;
//optimize 5: need to find a way to reduce the multiplications here
result->attrN = rows->attrN + rowNum * rows->numOfNumericAttr;
result->attrS = rows->attrS + rowNum * rows->numOfStringAttr * STRING_ATTR_SIZE;
return 1;
}
static int printRow(Rows* rows, int rowNum)
{
int i=0;
for (; i < rows->numOfNumericAttr; i++) {
printf("%.2lf",rows->attrN[rowNum * rows->numOfNumericAttr + i]);
if(i < rows->numOfNumericAttr -1)
printf(",");
}
if(rows->numOfStringAttr>0)
printf(",");
char* strptr = rows->attrS + rowNum * rows->numOfStringAttr * STRING_ATTR_SIZE;
for (i = 0; i < rows->numOfStringAttr; i++) {
strptr +=i*STRING_ATTR_SIZE;
printf("%s", strptr);
if (i < rows->numOfStringAttr - 1)
printf(",");
}
printf("\n");
return 1;
}
static int printAllRows(Rows* rows)
{
long i=0;
for(;i<rows->numOfRows;i++)
printRow(rows,i);
return 1;
}
/*
* executes a thread
*/
static int runThreads(void* args) {
//printf("runTHread\n");
LoopArguments *arg = (LoopArguments*) args;
long start = arg->start;
long end = arg->end;
long increment = arg->increment;
void* userArg = arg->args;
int (*function)(long, long, long, int, void*) = arg->function;
int tid = arg->threadId;
function(start, end, increment, tid, userArg);
pthread_exit(0);
return 0;
}
/*
* Runs several iterations of a loop in parallel by multiple threads
*/
static int parallelLoop(long start, long end, long increment, long numOfThreads, int (*function)(long, long, long, int, void*), void* args) {
pthread_t thread[numOfThreads];
pthread_attr_t attr;
int rc;
long t;
void *status;
LoopArguments loopArgs[numOfThreads];
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int iterPerThread = (end - start) / numOfThreads;
iterPerThread -= (iterPerThread % increment);
for (t = 0; t < numOfThreads; t++) {
loopArgs[t].increment = increment;
loopArgs[t].args = args;
loopArgs[t].function = function;
loopArgs[t].threadId = t;
loopArgs[t].start = start + t * iterPerThread;
if (t == numOfThreads - 1)
loopArgs[t].end = end;
else {
loopArgs[t].end = loopArgs[t].start + iterPerThread;
if (loopArgs[t].end > end)
loopArgs[t].end = end;
}
rc = pthread_create(&thread[t], &attr, runThreads, (&loopArgs[t]));
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for (t = 0; t < numOfThreads; t++) {
rc = pthread_join(thread[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
return 1;
}
static int initArray(double* arr, double value, long size) {
long ind = 0;
for (ind = 0; ind < size; ind++) {
arr[ind] = value;
}
return 1;
}
static int printArray(double* arr, long size, char* arrName, int rank) {
long ind = 0;
for (ind = 0; ind < size; ind++) {
printf("rank%d: %s[%d]=%lf\n", rank, arrName, ind, arr[ind]);
}
return 1;
}
static long determine_file_size(char *filename) {
FILE *fd;
long size = 0;
fd = fopen(filename, "r");
if (fd == NULL) {
printf("%s: Could not open %s to read - (%s)\n", __func__, filename, strerror(errno));
return (long) errno;
}
fseek(fd, 0L, SEEK_END);
size = ftell(fd);
rewind(fd);
fclose(fd);
return size;
}
/*
* Read all lines of a file and pass each line to a function
*/
static int readLines(int fd, const char * fname, int (*call_back)(int, long, const char*, void*), void* param, int rank) {
struct stat fs;
char *buf, *buf_end;
char *begin, *end, c;
char line[1000000];
//printf("param=%d\n",param);
long lineNumber = 0;
if (fd == -1) {
err(1, "open: %s", fname);
return 0;
}
if (fstat(fd, &fs) == -1) {
err(1, "stat: %s", fname);
return 0;
}
/* fs.st_size could have been 0 actually */
buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (buf == (void*) -1) {
err(1, "mmap: %s", fname);
close(fd);
return 0;
}
buf_end = buf + fs.st_size;
begin = end = buf;
while (1) {
if (!(*end == '\r' || *end == '\n')) {
if (++end < buf_end)
continue;
} else if (1 + end < buf_end) {
/* see if we got "\r\n" or "\n\r" here */
c = *(1 + end);
if ((c == '\r' || c == '\n') && c != *end)
++end;
}
/* call the call back and check error indication. Announce
error here, because we didn't tell call_back the file name */
//memcpy(begin, line, end - begin);
//int ind = end - begin;
strncpy(line, begin, end - begin);
line[end - begin] = '\0';
//write(fileno(stdout), begin, end - begin + 1);
if (!call_back(rank, lineNumber, line, param)) {
err(1, "[callback] %s", fname);
break;
}
if ((begin = ++end) >= buf_end)
break;
lineNumber++;
}
munmap(buf, fs.st_size);
//close(fd);
return 1;
}
/*
* Read multiple lines starting at an index and pass each of the read lines to a function
*/
static int readMLinesAt(long startIndex, long numLines, const char * fname, int (*call_back)(int, long, const char*, void*, int, int*), void* param, int rank) {
struct stat fs;
char *buf, *buf_end;
char *begin, *end, c;
char lines[1000000];
int indices[numLines];
//printf("param=%d\n",param);
long lineNumber = 0;
int fd = open(fname, O_RDONLY);
if (fd == -1) {
err(1, "open: %s", fname);
return 0;
}
if (fstat(fd, &fs) == -1) {
err(1, "stat: %s", fname);
return 0;
}
/* fs.st_size could have been 0 actually */
buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (buf == (void*) -1) {
err(1, "mmap: %s", fname);
close(fd);
return 0;
}
buf_end = buf + fs.st_size;
begin = end = buf;
int i=0;
long count = 0;
long indexCount=1;
indices[count] = end-begin;
char* startChar;
char* endChar;
while (1) {
if (!(*end == '\r' || *end == '\n')) {
if (++end < buf_end)
continue;
} else if (1 + end < buf_end) {
/* see if we got "\r\n" or "\n\r" here */
c = *(1 + end);
if ((c == '\r' || c == '\n') && c != *end)
++end;
}
if(count == startIndex)
{
startChar = begin;
}
if(count == startIndex+numLines-1)
{
endChar = end;
//printf("start=%d; end=%d\n",startChar, endChar);
strncpy(lines, startChar, endChar-startChar);
lines[endChar-startChar] = '\0';
for(i=0;lines[i]!='\0';i++)
{
if(lines[i] == '\n')
{
printf("char=%c; i=%d\n", lines[i], i);
//lines[i] = '\0';
indices[indexCount] = i+1;
indexCount++;
}
}
if (!call_back(rank, lineNumber, lines, param, count, indices)) {
err(1, "[callback] %s", fname);
break;
}
break;
}
if (begin >= buf_end || end >= buf_end) {
//printf("hi");
break;
}
count++;
begin=++end;
}
munmap(buf, fs.st_size);
close(fd);
return 1;
}
/*
* Read a number of lines equal to "numLines" and starts at "startIndex" and stores it on "lines"
* startIndex: the row index to start at
* numLines: the number of lines to be read
* lines: the buffer on which lines are to be stored
* fname: the filename from which the function reads
* rank: the rank of the slave node calling the function
*/
static int readChunkFromFile(long startIndex, long numLines, char* lines, const char * fname, int rank) {
struct stat fs;
char *buf, *buf_end;
char *begin, *end, c;
int fd = open(fname, O_RDONLY);
if (fd == -1) {
err(1, "open: %s", fname);
return 0;
}
if (fstat(fd, &fs) == -1) {
err(1, "stat: %s", fname);
return 0;
}
/* fs.st_size could have been 0 actually */
buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (buf == (void*) -1) {
err(1, "mmap: %s", fname);
close(fd);
return 0;
}
buf_end = buf + fs.st_size;
begin = end = buf;
long count = 0;
char* startChar;
char* endChar;
while (1) {
if (!(*end == '\r' || *end == '\n')) {
if (++end < buf_end)
continue;
} else if (1 + end < buf_end) {
/* see if we got "\r\n" or "\n\r" here */
c = *(1 + end);
if ((c == '\r' || c == '\n') && c != *end)
++end;
}
if(count == startIndex)
{
startChar = begin;
}
if(count == startIndex+numLines-1)
{
endChar = end;
//printf("start=%d; end=%d\n",startChar, endChar);
strncpy(lines, startChar, endChar-startChar);
lines[endChar-startChar] = '\0';
//printf(lines);
break;
}
if (begin >= buf_end || end >= buf_end) {
break;
}
count++;
begin=++end;
}
munmap(buf, fs.st_size);
close(fd);
return 1;
}
/*
* parse a line and store it on "row"
*/
static int parseLine(char* line, double* row, int numOfColumns) {
char *token, *saveptr;
double temp;
long i = 0;
char buff[strlen(line) + 1];
strcpy(buff, line);
token = strtok_r(buff, ",", &saveptr);
while (token != NULL && i < numOfColumns) {
sscanf(token, "%lf", &temp);
row[i] = temp;
i++;
token = strtok_r(NULL, ",", &saveptr);
}
//printf("done tokenizing\n");
return 1;
}
static double min(double x, double y) {
if (x < y)
return x;
return y;
}
static double fuzzyAnd(double x, double y) {
return min(x, y);
}
static double max(double x, double y) {
if (x > y)
return x;
return y;
}
static double fuzzyImply(double x, double y) {
return max(1 - x, y);
}
static double distanceS(char* str1, char* str2) {
int result = strcmp(str1, str2);
if(result == 0)
return 1;
else
return 0;
}
/*
* Compute the similarity value of row1 and row2
*/
static double getSimilarityOfRows(Rows* row1, Rows* row2) {
int i = 0;
double result = 0;
int numOfColumns = row1->numOfNumericAttr + row1->numOfStringAttr;
for (i=0; i < row1->numOfNumericAttr; i++) {
result += fabs(row1->attrN[i]-row2->attrN[i]) ;//* ranges[i];
}
result = row1->numOfNumericAttr - result;
for (i=0; i < row1->numOfStringAttr; i++) {
result += distanceS(getStrAttrOfRow(row1,0,i), getStrAttrOfRow(row2,0,i));
}
return result / numOfColumns;
}
/*
* reads the content of a file and store it on buffer
*/
static int readEntireFile(char *filename, long size, char **buffer, int rank) {
size_t nr_read = 0;
FILE *fh;
printf("rank%d: %s: filename to open: %s\n", rank, __func__, filename);
fh = fopen(filename, "r");
if (fh == NULL) {
printf("rank%d: %s: Could not open %s to read - (%s)\n", rank, __func__, filename, strerror(errno));
return -1;
}
nr_read = fread(*buffer, size, 1, fh);
if (nr_read < 1)
printf("%s: Read %ld out of 1 elements for %s (%s)\n", __func__, nr_read, filename, strerror(errno));
fclose(fh);
return 0;
}
/*
* This function loads all the class vectors in the "path" parameter and store them on "cvector"
* path: this is the path to the class vector files. It is not the location of a file. Rather, it is a path to a set of file with names classvector1, classvector2...
* numOfRows: this is the total number of rows in the dataset.
* numOfClasses: this is the number of class vectors
* cvector: this is a vector to contain the classvectors. It should be initialized before being passed to this function.
*/
static int loadClassvector(char* path, double* cvector, long numOfRows, int numOfClasses) {
char tempName[400];
memset(tempName, 0, 400);
char* buffer;
int i = 0,j=0;
long size = 0;
long index=-1;
char *token, *saveptr;
double temp;
//Determine the maximum vector size needed to be initialized.
for (i = 0; i < numOfClasses; i++) {
sprintf(tempName, "%s%s%d", path, "classvector", i + 1);
size = max(determine_file_size(tempName), size);
}
//allocate memory for the buffer
buffer = malloc(size);
//read each class file, parse it and store it on "cvector"
for (i = 0; i < numOfClasses; i++) {
sprintf(tempName, "%s%s%d", path, "classvector", i + 1);
size = determine_file_size(tempName);
readEntireFile(tempName, size, &buffer, 0);
token = strtok_r(buffer, "\n", &saveptr);
j=0;
while (token != NULL && j < numOfRows) {
sscanf(token, "%lf", &temp);
index = i*numOfRows+j;
cvector[i*numOfRows+j] = (double) temp;
j++;
token = strtok_r(NULL, "\n", &saveptr);
}
}
return 1;
}
/*
* This function computes mins and maxs for one line and stores the result in param->max and param->mins. This is a prep step for computing the ranges
*/
static int computeRanges(int rank, long ln, char* line, void* param) {
RangesArguments* args = (RangesArguments*) param;
double *maxs = args->max; //initially store maximums here
double *mins = args->min;
int numOfColumns = args->numOfColumns;
double row[numOfColumns];
memset(row, 0, numOfColumns);
parseLine(line, row, numOfColumns);
int i = 0;
for (; i < numOfColumns; i++) {
if (ln == 0) {
mins[i] = row[i];
maxs[i] = row[i];
} else {
mins[i] = min(mins[i], row[i]);
maxs[i] = max(maxs[i], row[i]);
}
}
return 1;
}
/*
* This function runs the master program which basically loads the class vectors and broadcast them. It also broadcast the ranges to slaves as well.
* dataPath: this is the location of the input dataset file.
* cvectorPath: this is the path to the class vector files. It is not the location of a file. Rather, it is a path to a set of file with names classvector1, classvector2...
* numOfRows: this is the total number of rows in the dataset.
* numOfColumns: this is the number of condition attributes in the dataset.
* numOfSlaves: this is the number of slave nodes in the cluster
* numOfClasses: this is the number of class vectors
* cvector: this is a vector to contain the classvectors. It should be initialized before being passed to this function.
*/
void masters(char* dataPath, char* cvectorPath, long numOfRows, int numOfColumns, int numOfSlaves, int numOfClasses, double* cvector) {
double mins[numOfColumns];
double maxs[numOfColumns];
double ranges[numOfColumns];
//Load class vectors
loadClassvector(cvectorPath, cvector, numOfRows, numOfClasses);
//broadcast the classvectors
MPI_Bcast(cvector, numOfRows * numOfClasses, MPI_DOUBLE, 0, MPI_COMM_WORLD);
printf("rank:%d: Class vectors successfully broadcasted..\n", 0);
//initialize the ranges vector
initArray(ranges,DBL_MAX,numOfColumns);
//reduce the mins computed at the slave nodes into the mins vector
MPI_Reduce(ranges, mins, numOfColumns, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);
initArray(ranges,-1 * DBL_MAX,numOfColumns);
//reduce the max values computed at the slave nodes into the maxs vector
MPI_Reduce(ranges, maxs, numOfColumns, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
//Compute the ranges given the maxs and mins
int i = 0;
for (; i < numOfColumns; i++) {
ranges[i] = 1/(maxs[i] - mins[i]);
}
//broadcast the ranges
MPI_Bcast(ranges, numOfColumns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
printf("rank:%d: Ranges successfully computed..\n", 0);
}
static int setNumOfAttrs(char* line, int* numAttrs,int* strAttrs, int numOfColumns)
{
char *token, *saveptr;
long i = 0;
char buff[strlen(line) + 1];
strcpy(buff, line);
token = strtok_r(buff, ",", &saveptr);
int na=0,sa=0;
while (token != NULL && i<numOfColumns) {
if(isNumeric(token))
na++;
else
sa++;
i++;
token = strtok_r(NULL, ",", &saveptr);
}
//printf("na=%d; sa=%d\n", na, sa);
*numAttrs = na;
*strAttrs = sa;
//printf("done tokenizing\n");
return 1;
}
/*
* This function loads the partition Pk assigned to the current slave node and keeps it in memory throughout the execution of the program.
* this function assumes that each line 400 characters or less.
* dataPath: this is the location of the input dataset file.
* rank: the rank of the slave node
* rows: This is a structure to store the loaded rows.
* chunkIndex: the row index at which the partition Pk starts
* chunkSize: the number of rows contained in the Pk partition
* ranges: this is the ranges vector which is used to divide by every value that gets loaded. This is an optimization step to avoid division inside a later big loop
* numOfColumns: this is the number of condition attributes in the dataset.
*/
static int loadDataChunk(char* dataPath, int rank, Rows* rows, int numOfColumns, long chunkIndex, long chunkSize, double* ranges) {
long size = sizeof(char) * 400 * chunkSize;
char* buffer = malloc(size);
//read a number of lines equal to chunkSize and starting at chunkIndex from the dataPath and store them on buffer
readChunkFromFile(chunkIndex,chunkSize,buffer,dataPath,rank);
char *token, *saveptr;
long i = 0;
token = strtok_r(buffer, "\n", &saveptr);
int numAttrs, strAttrs;
//Compute the number of string attributes and number of numeric attributes in the file
setNumOfAttrs(token, &numAttrs,&strAttrs,numOfColumns);
initRows(rows,chunkSize,strAttrs,numAttrs);
//Go over each row, parse it and store it on "rows"
while (token != NULL && i < chunkSize) {
addLineToRows(rows,i,token,ranges);
i++;
token = strtok_r(NULL, "\n", &saveptr);
}
free(buffer);
return 1;
}
/*
* Process one row by computing partial upper and lower approx values.
* rank: the rank of the slave node
* rows: a structure representing the rows in the Pk partition loaded in memory of the slave
* row: the row to be processed
* numOfRows: this is the total number of rows in the dataset.
* numOfColumns: this is the number of condition attributes in the dataset.
* numOfSlaves: this is the number of slave nodes in the cluster
* numOfClasses: this is the number of class vectors
* numOfThreads: this is the number of threads to run in parallel per slave node
* cvector: this is a vector to contain the classvectors. It should be initialized before being passed to this function.
* uApprox: a vector that stores the partial upper approximation values. All such vectors at all slave nodes are meant to be reduced into one final vector.
* lApprox: a vector that stores the partial lower approximation values. All such vectors at all slave nodes are meant to be reduced into one final vector.
* chunkSize: the number of rows in the Pk partition loaded in memory
* startIndex: the index of the first row in Pk
* approxIndex: the index of the row being processed
*/
static int processFuzzyRow(Rows* localRows, Rows* row, int numOfColumns, long numOfRows, int numOfClasses, long chunkSize, long startIndex, long approxIndex, double* uApprox, double* lApprox, double* cvector, int numOfThreads,int rank) {
long i = 0;
Rows localRow;
double simVal = -1;
double uApproxVal[numOfClasses];
initArray(uApproxVal,-1,numOfClasses);
double lApproxVal[numOfClasses];
initArray(lApproxVal,1,numOfClasses);
int c=0;
double fuzzyConj = -1;
//for each row in Pk
for (i = 0; i < chunkSize; i++) {
getRowAt(localRows, i, &localRow);
if (startIndex + i == approxIndex) //if are comparing the row with itself then the similarity value = 1
simVal = 1;
else //else compute the similarity value between the two rows
simVal = getSimilarityOfRows(&localRow, row);
//compute the upper approx and lower approx values for all classvectors
for (c = 0; c < numOfClasses; c++) {
fuzzyConj = fuzzyAnd(simVal, cvector[c * numOfRows + startIndex + i]);
uApproxVal[c] = max(uApproxVal[c], fuzzyConj);
lApproxVal[c] = min(lApproxVal[c], fuzzyImply(simVal, cvector[c * numOfRows + startIndex + i]));
}
}
//update upper and lower approx values at approxIndex for all classes
for (c = 0; c < numOfClasses; c++) {
uApprox[c * numOfRows + approxIndex] = uApproxVal[c];
lApprox[c * numOfRows + approxIndex] = lApproxVal[c];
}
return 1;
}
/*
* Processes one line by computing its partial lower and upper approximation values
* rank: rank of the calling slave node
* ln: line number
* line: line content
* param: params to be passed to the processFuzzyRow function
*/
static int processOneLine(int rank, long ln, char* line, void* param) {
ProcessRowArgs* args = (ProcessRowArgs*)param;
long startIndex = args->startIndex;
Rows currentRow = args->currentRow;
double* ranges = args->ranges;
Rows rows = args->rows;
int numOfColumns = args->numOfColumns;
long numOfRows = args->numOfRows;
int numOfClasses = args->numOfClasses;
long chunkSize = args->chunkSize;
double* uApprox = args->uApprox;
double* lApprox = args->lApprox;
double* cvector = args->cvector;
int numOfThreads = args->numOfThreads;
//parse the line
addLineToRows(¤tRow, 0, line, ranges);
//process the line and update the uApprox and lApprox vectors
processFuzzyRow(&rows, ¤tRow, numOfColumns, numOfRows, numOfClasses, chunkSize, startIndex, ln, uApprox, lApprox, cvector, numOfThreads, rank);
return 1;
}
/*
* prints the progress status of the program
*/
static int printProgress(long rowsCompleted, long numOfRows, time_t* start_time, int rank) {
time_t end_time; // = args->end_time;
time_t now; // = args->now;
time(&now);
char percentChar = 37; //this is the percent character
double totalTime;
double completed = 100.0 * rowsCompleted / numOfRows;
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
if (rowsCompleted > 0 && rowsCompleted % 1000 == 0) {
time(&end_time);
totalTime = difftime(end_time, *start_time);
printf("%s-rank%d: %.2lf%c done. Total time=%.2lf\n", hostname,rank, completed, percentChar, totalTime);
time(&now);
}
return 1;
}
/*
* This function is called by the multi-threaded loop. It processes one line.
*/
static int processOneLineP(long start, long end, long increment, int threadId, void* param)
{
int i = 0;
ProcessRowArgs* args = (ProcessRowArgs*) param;
long ln = args->startLine + start;
char* lines = args->lines;
int* indices = args->indices;
int rank = args->rank;
char* line;
long numOfRows = args->numOfRows;
time_t start_time = *(args->start_time);
for (i = start; i < end; i++, ln++) {
long startIndex = args->startIndex;
long endIndex = args->endIndex;
if (!(ln >= startIndex && ln < endIndex)) {
line = lines + indices[i];
processOneLine(rank, ln, line, param);
}
else
{
Rows currentLocalRow;
Rows rows = args->rows;
int numOfColumns = args->numOfColumns;
long numOfRows = args->numOfRows;
int numOfClasses = args->numOfClasses;
long chunkSize = args->chunkSize;
double* uApprox = args->uApprox;
double* lApprox = args->lApprox;
double* cvector = args->cvector;
int numOfThreads = args->numOfThreads;
int rank = args->rank;
long localRowIndex = ln - startIndex;
getRowAt(&rows, localRowIndex, ¤tLocalRow);
processFuzzyRow(&rows, ¤tLocalRow, numOfColumns, numOfRows, numOfClasses, chunkSize, startIndex, ln, uApprox, lApprox, cvector, numOfThreads, rank);
}
printProgress(ln,numOfRows,&start_time,rank);
}
return 1;
}
/*
* This function processes a set of lines stored in "lines". It saves partial upper and lower approx values for each processed line.
* rank: the rank of the slave node calling the function
* startLine: This is the index of the first line in "lines" with respect to the dataset
* lines: this contains all lines. This is meant to be used with the "indices" parameter
* param: this is a set of arguments passed to the function.
* numOfLines: the number of lines in "lines"
* indices: this vector contains indices of each row in "lines" so that it is easy to access one line in "lines"
*/
static int processLines(int rank, long startLine, char* lines, void* param, int numOfLines, int* indices) {