-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsitehound.c
1614 lines (1391 loc) · 48.9 KB
/
sitehound.c
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
/*****************************************************************************
*****************************************************************************
** sitehound.c by Dario Ghersi **
** Version: 20101214 **
** **
** Usage: please see manual for usage info **
** **
** The following code contains modified parts from the Open Source **
** Clustering Software in the functions create_distance_matrix, **
** sl_cluster and average_cluster **
** **
** Revisions: **
** 20101214 changed the atom type in the output (clusters.pdb) **
** 20101201 added the option for using compressed EasyMIFs maps **
** added the option to convert compressed maps back to dx files **
*****************************************************************************
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include "prototypes.h"
/*---------------------------------------------------------------------------*\
* GLOBAL VARIABLES *
\*---------------------------------------------------------------------------*/
unsigned int npoints[3]; /* number of points in the grid in x, y, z */
double resolution = 1.0; /* the resolution of the grid */
double energy_cutoff = -0.4; /* the energy cutoff to filter out points */
double spatial_cutoff = 7.8; /* the spatial cutoff needed to cut
the partition */
unsigned int cl_num_contacts = 10; /* the number of clusters whose contact
residues will be computed */
double lower_corner[3]; /* coordinates of the lower corner of the box */
char filename[MAX_STR_LEN] = "-1"; /* the name of the map */
char maptype[MAX_STR_LEN] = ""; /* the type of the map (easymifs, autogrid) */
char linkage[MAX_STR_LEN] = "average" ; /* clustering parameter
('average' or 'single') */
unsigned int cluster_atom_num = 0; /* to append clusters in PDB */
char clusters_chain_id; /* the chain identifier for the clusters in PDB */
char used_chains[TOTAL_CHAIN_IDS] = {'\0'}; /* array for storing the chains in the PDB */
unsigned int decompress = 0; /* flag to decompress a .cmp map back to .dx */
long seed = 1; /* the initial seed for the random jiggling of the points */
/*---------------------------------------------------------------------------*\
* FUNCTIONS DEFINITIONS *
\*---------------------------------------------------------------------------*/
char *basename(char *s)
{
/* return */
char *b;
char p[1000];
char *temp;
b = malloc(sizeof(char) * MAX_STR_LEN);
temp = strtok(s, ".");
strncpy(b, temp, MAX_STR_LEN);
p[0] = '\0';
while(temp = strtok(NULL, ".")) {
strcat(b, p);
strcpy(p, ".");
strcat(p, temp);
}
return b;
}
/* -------------------------------------------------------------------------- */
double ran(long *seed)
{
long k;
double ans;
*seed ^= MASK;
k = (*seed) / IQ;
*seed = IA * (*seed -k * IQ) - IR * k;
if (*seed < 0)
*seed += IM;
ans = AM * (*seed);
*seed ^= MASK;
return ans;
}
/* -------------------------------------------------------------------------- */
double euclidean_distance(const Data *p, const Atom *a)
{
/* returned the squared euclidean distance between a point and an atom */
double ed = 0.0; /* the squared euclidean distance */
ed = (p->x - a->x) * (p->x - a->x) + (p->y - a->y) * (p->y - a->y) +
(p->z - a->z) * (p->z - a->z);
return(ed);
}
/* -------------------------------------------------------------------------- */
void free_memory_restable(Restable *residue_list)
{
Restable *next_residue;
while (residue_list != NULL) {
next_residue = residue_list->next;
free(residue_list);
residue_list = next_residue;
}
free(residue_list);
}
/* -------------------------------------------------------------------------- */
void set_parameters(int argc, char **argv)
{
/* get the command line parameters and set them in the global variables */
char *program_name;
int return_value;
program_name = argv[0];
while ((argc > 1) && (argv[1][0] == '-')) {
switch (argv[1][1]) {
case 't': /* type of map */
strtok(argv[1], "=");
strncpy(maptype, strtok(NULL, " "), MAX_STR_LEN);
break;
case 'f': /* filename */
strtok(argv[1], "=");
strncpy(filename, strtok(NULL, " "), MAX_STR_LEN);
break;
case 'l': /* linkage option */
if (argv[1][3] == 's') {
strcpy(linkage, "single");
}
else if (argv[1][3] == 'a') {
strcpy(linkage, "average");
}
else {
fprintf(stderr, "Linkage option not recognized\nAborting...\n");
exit(1);
}
break;
case 'r': /* resolution */
strtok(argv[1], "=");
return_value = sscanf(strtok(NULL, " "), "%lf", &resolution);
if (return_value == 0) {
fprintf(stderr, "Resolution option not recognized\nAborting...\n");
exit(1);
}
break;
case 'e': /* energy cutoff */
strtok(argv[1], "=");
return_value = sscanf(strtok(NULL, " "), "%lf", &energy_cutoff);
if (return_value == 0) {
fprintf(stderr, "Energy option not recognized\nAborting...\n");
exit(1);
}
if (energy_cutoff > 0.0) {
fprintf(stderr, "Energy should be a negative number\nAborting...\n");
exit(1);
}
break;
case 's': /* spatial cutoff */
strtok(argv[1], "=");
return_value = sscanf(strtok(NULL, " "), "%lf", &spatial_cutoff);
if (return_value == 0) {
fprintf(stderr, "Spatial option not recognized\nAborting...\n");
exit(1);
}
break;
case 'p': /* number of clusters for contact residues */
strtok(argv[1], "=");
return_value = sscanf(strtok(NULL, " "), "%d", &cl_num_contacts);
if (return_value == 0) {
fprintf(stderr, "Contact residues option not recognized\nAborting...\n");
exit(1);
}
break;
case 'z': /* decompress a .cmp map back to .dx file and exit */
decompress = 1;
break;
default:
fprintf(stderr, "Option not recognized\nAborting...\n");
exit(1);
}
++argv;
--argc;
}
}
/*---------------------------------------------------------------------------*/
void filter_autogrid_map(const char *filename, const double energy_cutoff)
{
/* read in an autogrid map and writes a new file with only the filtered
points (whose energy is below the user-defined threshold */
FILE *infile, *outfile;
char *cp, outfilename[MAX_STR_LEN];
char line[MAX_STR_LEN];
char *temp = NULL;
bool end_of_header = FALSE;
double center[3]; /* coordinates of the center */
double coords[3]; /* coordinates of a point */
double energy;
unsigned int cx, cy, cz; /* counter variables for computing the coordinates */
unsigned int index_point = 1; /* keep track of the points */
/* open/check the file to be filtered */
if (!(infile = fopen(filename, "r"))) {
fprintf(stderr, "Cannot open %s\nAborting...\n", filename);
exit(1);
}
/* read the header of the autogrid file */
while ( (!end_of_header) && fgets(line, MAX_STR_LEN, infile)) {
if (strstr(line, "SPACING")) { /* grab the resolution of the grid */
strtok(line, " ");
temp = strtok(NULL, " "); sscanf(temp, "%lf", &resolution);
}
if (strstr(line, "NELEMENTS")) { /* grab the number of points in x, y, z */
strtok(line, " ");
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[X]);
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[Y]);
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[Z]);
}
if (strstr(line, "CENTER")) { /* grab the coordinates of the center */
strtok(line, " ");
temp = strtok(NULL, " "); sscanf(temp, "%lf", ¢er[X]);
temp = strtok(NULL, " "); sscanf(temp, "%lf", ¢er[Y]);
temp = strtok(NULL, " "); sscanf(temp, "%lf", ¢er[Z]);
end_of_header = TRUE;
}
}
if (! end_of_header) {
fprintf(stderr, "Problem with autogrid file\nAborting...\n");
exit(1);
}
/* compute the coordinates of the lower corner of the box */
lower_corner[X] = center[X] - resolution * npoints[X] / 2;
lower_corner[Y] = center[Y] - resolution * npoints[Y] / 2;
lower_corner[Z] = center[Z] - resolution * npoints[Z] / 2;
/* open the output file */
cp = strdup(filename);
strcpy(outfilename, basename(cp));
strcat(outfilename, ".tmp");
if (!(outfile = fopen(outfilename, "w"))) {
fprintf(stderr, "Cannot open %s for writing\nAborting...\n", outfilename);
}
/* read the data from the autogrid file and write the filtered points to
the output file */
for (cz = 0; cz < npoints[Z] + 1; cz++) {
coords[Z] = lower_corner[Z] + resolution * cz;
for (cy = 0; cy < npoints[Y] + 1; cy++) {
coords[Y] = lower_corner[Y] + resolution * cy;
for (cx = 0; cx < npoints[X] + 1; cx++) {
coords[X] = lower_corner[X] + resolution * cx;
if (fgets(line, MAX_STR_LEN, infile) == NULL) {
fprintf(stderr, "Problems with autogrid file\n...Aborting\n");
exit(1);
}
sscanf(line, "%lf", &energy); /* read the energy value */
if (energy <= energy_cutoff) { /* if energy < cutoff write point */
fprintf(outfile, "%d %.3f %.3f %.3f %.3f\n", index_point,
coords[X], coords[Y], coords[Z], energy);
}
index_point++;
}
}
}
/* set npoints to the actual number of points */
npoints[X]++; npoints[Y]++; npoints[Z]++;
/* close input and output files */
fclose(infile);
fclose(outfile);
}
/*---------------------------------------------------------------------------*/
double *expand(unsigned int *bytes, unsigned int num_lines, unsigned int num_values)
{
/* expansion part of the LZW compression algorithm *
Consult http://warp.povusers.org/EfficientLZW/index.html for an *
excellent discussion of the efficiency issues */
FILE *temp_file;
double *energy_values;
unsigned int *bytes_ptr, index, old;
unsigned int i, current_num_value = 0, string_length;
const char dictionary[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', ' '};
const unsigned int length_dictionary = 13;
const unsigned int size_dict = 1 << BITS;
const unsigned int last_position = 57; /* the last occupied position in the
hash table */
unsigned int dict_pos = last_position;
char *dict[size_dict];
char B;
/* memory allocation */
bytes_ptr = bytes;
energy_values = malloc(sizeof(double) * num_values);
/* initialize the hash table (with characters from 0 to 9, point and space) */
for (i = 0; i < size_dict; i++) {
dict[i] = malloc(2 * sizeof(char));
dict[i][0] = '\0';
dict[i][1] = '\0';
}
for (i = 0; i < length_dictionary; i++) {
dict[(int) dictionary[i]] = malloc(2 * sizeof(char));
dict[(int) dictionary[i]][0] = dictionary[i];
dict[(int) dictionary[i]][1] = '\0';
}
/* expand the compressed data */
if ((temp_file = tmpfile()) == NULL) { /* open a temporary file */
fprintf(stderr, "Problem opening temporary file...Aborting\n");
exit(1);
}
index = *bytes_ptr;
bytes_ptr++;
current_num_value++;
fprintf(temp_file, "%s", dict[index]);
old = index;
while (current_num_value < num_lines) { /* main loop */
index = *bytes_ptr;
bytes_ptr++;
if (dict[index][0] != '\0') { /* index is in the dictionary */
fprintf(temp_file, "%s", dict[index]);
B = dict[index][0];
dict_pos++;
/* add the string to the dictionary if there is room */
if (dict_pos < size_dict) {
free(dict[dict_pos]);
string_length = strlen(dict[old]);
dict[dict_pos] = malloc(sizeof(char) * (string_length + 2));
strcpy(dict[dict_pos], dict[old]);
dict[dict_pos][string_length] = B;
dict[dict_pos][string_length + 1] = '\0';
}
}
else { /* index is not in the dictionary */
B = dict[old][0];
dict_pos++;
free(dict[dict_pos]);
string_length = strlen(dict[old]);
dict[dict_pos] = malloc(sizeof(char) * (string_length + 2));
strcpy(dict[dict_pos], dict[old]);
dict[dict_pos][string_length] = B;
dict[dict_pos][string_length + 1] = '\0';
fprintf(temp_file, "%s", dict[dict_pos]);
}
/* prepare to read the next index */
current_num_value++;
old = index;
}
/* fill in the energy values array */
i = 0;
rewind(temp_file);
while (!feof(temp_file)) {
fscanf(temp_file, "%lf\n", &energy_values[i]);
i++;
if (i == num_values - 1)
break;
}
/* clean up the memory */
for (i = 0; i < size_dict; i++)
free(dict[i]);
fclose(temp_file);
return energy_values;
}
/*---------------------------------------------------------------------------*/
void filter_easymifs_map(const char *filename, const double energy_cutoff)
{
/* read in an easymifs map and writes a new file with only the filtered
points (whose energy is below the user-defined threshold */
FILE *infile, *outfile;
char *cp, outfilename[MAX_STR_LEN];
char line[MAX_STR_LEN];
char *temp = NULL;
char open_mode[MAX_STR_LEN];
bool end_of_header = FALSE;
bool compressed = FALSE; /* whether we are using compressed maps */
double coords[3]; /* coordinates of a point */
double energy;
double *energy_values = NULL;
unsigned int cx, cy, cz; /* counter variables for computing the coordinates */
unsigned int index_point = 1; /* keep track of the points */
unsigned int counter = 0;
unsigned int total_num_points;
unsigned int *bytes = NULL; /* to store the compressed map */
unsigned int *bytes_ptr;
int size = 0;
int byte = 0;
const unsigned int num_bytes = BITS / 8;
resolution = -1.000;
/* if the extension of the file is .cmp then assume it is compressed */
temp = strrchr(filename, '.');
if (temp != NULL) {
if (strcmp(temp, ".cmp") == 0) {
compressed = TRUE;
strncpy(open_mode, "rb", MAX_STR_LEN); /* set the open mode to binary */
}
else {
strncpy(open_mode, "r", MAX_STR_LEN);
}
}
/* open/check the file to be filtered */
if (!(infile = fopen(filename, open_mode))) {
fprintf(stderr, "Cannot open %s\nAborting...\n", filename);
exit(1);
}
/* open the output file */
cp = strdup(filename);
strcpy(outfilename, basename(cp));
if (decompress)
strcat(outfilename, ".dx");
else
strcat(outfilename, ".tmp");
if (!(outfile = fopen(outfilename, "w"))) {
fprintf(stderr, "Cannot open %s for writing\nAborting...\n", outfilename);
}
/* make sure the map is compressed before attempting the decompression */
if (decompress && !compressed) {
fprintf(stderr, "The map does not seem to be compressed\nAborting...\n");
exit(1);
}
/* read the header of the easymifs file */
while ( (!end_of_header) && fgets(line, MAX_STR_LEN, infile)) {
if (decompress) { /* print the line and go on */
fprintf(outfile, "%s", line);
if (strstr(line, "data follows")) /* end of the header */
end_of_header = TRUE;
}
if (strstr(line, "counts")) { /* grab the number of points in x, y, z */
strtok(line, " ");
strtok(NULL, " "); strtok(NULL, " "); strtok(NULL, " ");
temp = strtok(NULL, " ");
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[X]);
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[Y]);
temp = strtok(NULL, " "); sscanf(temp, "%d", &npoints[Z]);
}
if (strstr(line, "origin")) { /* grab the coordinates of the origin */
strtok(line, " ");
temp = strtok(NULL, " "); sscanf(temp, "%lf", &lower_corner[X]);
temp = strtok(NULL, " "); sscanf(temp, "%lf", &lower_corner[Y]);
temp = strtok(NULL, " "); sscanf(temp, "%lf", &lower_corner[Z]);
}
if (strstr(line, "delta") && (resolution < 0.0)) {
/* grab the resolution of the grid */
strtok(line, " ");
temp = strtok(NULL, " "); sscanf(temp, "%lf", &resolution);
}
if (strstr(line, "data follows")) /* end of the header */
end_of_header = TRUE;
}
if (! end_of_header) {
fprintf(stderr, "Problem with easymifs file\nAborting...\n");
exit(1);
}
/* calculate the total number of points */
total_num_points = npoints[X] * npoints[Y] * npoints[Z];
counter = 0;
if (compressed) { /* read the bytes and expand the map */
bytes = malloc(sizeof(unsigned int) * total_num_points * 2);
bytes_ptr = bytes;
while (!feof(infile)) {
size = fread(&byte, num_bytes, 1, infile);
if (size > 0) {
counter++;
*bytes_ptr = byte;
bytes_ptr++;
}
}
energy_values = expand(bytes, counter, total_num_points);
}
/* read the data from the file (or use the values stored in energy_values)
and write the filtered points to the output file */
counter = 0;
for (cx = 0; cx < npoints[X]; cx++) {
coords[X] = lower_corner[X] + resolution * cx;
for (cy = 0; cy < npoints[Y]; cy++) {
coords[Y] = lower_corner[Y] + resolution * cy;
for (cz = 0; cz < npoints[Z]; cz++) {
coords[Z] = lower_corner[Z] + resolution * cz;
if (compressed) {
energy = energy_values[counter];
counter++;
}
else {
if (fgets(line, MAX_STR_LEN, infile) == NULL) {
fprintf(stderr, "Problems with EasyMIFs file\n...Aborting\n");
exit(1);
}
sscanf(line, "%lf", &energy); /* read the energy value */
}
if (decompress) { /* write the energy value */
fprintf(outfile, "%.3f\n", energy);
}
else if (energy <= energy_cutoff) { /* if energy < cutoff write point */
fprintf(outfile, "%d %.3f %.3f %.3f %.3f\n", index_point,
coords[X], coords[Y], coords[Z], energy);
}
index_point++;
}
}
}
/* clean up the memory */
if (compressed) {
free(bytes);
free(energy_values);
}
/* close input and output files */
fclose(infile);
fclose(outfile);
}
/*---------------------------------------------------------------------------*/
void cluster_grid(const char *filename, const double cutoff,
const char *linkage)
{
/* pilot function that performs the clustering of the grid points */
Data *data;
double **distance_matrix;
int *clusters;
Node *results = NULL;
Summary *summary;
char *cp, infilename[MAX_STR_LEN];
int n = 0; /* number of grid points */
int nc; /* number of clusters */
int i;
/* get the filename */
cp = strdup(filename);
strcpy(infilename, basename(cp));
strcat(infilename, ".tmp");
/* load the data matrix */
data = create_data_matrix((const char *) infilename, &n);
/* compute the distance matrix */
distance_matrix = create_distance_matrix(data, n);
/* perform the clustering */
fprintf(stdout, " Performing clustering with %s linkage...\n", linkage);
fprintf(stdout, " Energy cutoff: %.3f\n", energy_cutoff);
fprintf(stdout, " Spatial cutoff: %.3f\n", cutoff);
if (strcmp(linkage, "single") == 0)
results = sl_cluster(distance_matrix, n);
else if(strcmp(linkage, "average") == 0)
results = average_cluster(distance_matrix, n);
/* free the allocated memory for the distance matrix */
for (i = 0; i < n; i++)
free(distance_matrix[i]);
free(distance_matrix);
/* cut the tree at the specified cutoff level */
clusters = cuttree(results, n, cutoff, &nc);
free(results);
/* rank the points according to total cluster interaction energy */
rank_data(data, clusters, nc, n);
free(clusters);
/* print the results */
print_clusters(data, n, filename);
/* create and print the cluster summary */
summary = create_summary(data, n, nc);
print_summary(summary, nc, filename);
free(data);
free(summary);
fprintf(stdout, " ...done\n");
}
/*---------------------------------------------------------------------------*/
Data *create_data_matrix(const char *filename, int *n)
{
/* create a data matrix suitable for computing the distance matrix */
FILE *infile;
int i;
char s[MAX_STR_LEN], *temp;
Data *data;
double sign; /* sign for the random jiggling */
double random;
if (!(infile = fopen(filename, "r"))) {
fprintf(stderr, "Cannot open %s\nAborting...\n", filename);
exit(1);
}
/* count how many points the file contains */
while (fgets(s, MAX_STR_LEN - 1, infile))
(*n)++;
/* allocate memory */
data = (Data *) malloc(sizeof(Data) * (*n));
/* fill in the data */
rewind(infile);
for (i = 0; i < *n; i++) {
fgets(s, MAX_STR_LEN - 1, infile);
temp = strtok(s, " ");
sscanf(temp, "%lu", &data[i].index);
data[i].x = strtod(strtok(NULL, " "), NULL);
data[i].y = strtod(strtok(NULL, " "), NULL);
data[i].z = strtod(strtok(NULL, " "), NULL);
if (strcmp(linkage, "average") == 0) { /* jiggle the points to break ties */
random = ran(&seed);
sign = (random > 0.5) ? 1.0: -1.0;
data[i].x += sign * ran(&seed) * 1.0E-6;
data[i].y += sign * ran(&seed) * 1.0E-6;
data[i].z += sign * ran(&seed) * 1.0E-6;
}
data[i].energy = strtod(strtok(NULL, " "), NULL);
}
fclose(infile);
return data;
}
/*---------------------------------------------------------------------------*/
double **create_distance_matrix(Data * data, int n)
{
/* create the distance matrix */
int i, j;
double **matrix;
matrix = malloc(sizeof(double *) * n);
matrix[0] = NULL;
/* The zeroth row has zero columns.
We allocate it anyway for convenience. */
for (i = 1; i < n; i++) {
matrix[i] = malloc(sizeof(double) * i);
if (matrix[i] == NULL)
break; /* Not enough memory available */
}
if (i < n) { /* break condition encountered */
j = i;
for (i = 1; i < j; i++)
free(matrix[i]);
return NULL;
}
/* Calculate the distances and save them in the matrix */
for (i = 0; i < n; i++)
for (j = 0; j < i; j++)
matrix[i][j] = sqrt(pow(data[i].x - data[j].x, 2) +
pow(data[i].y - data[j].y, 2) +
pow(data[i].z - data[j].z, 2));
return matrix;
}
/*---------------------------------------------------------------------------*/
double find_closest_pair(int n, double **distmatrix, int *ip, int *jp)
{
int i, j;
double distance = distmatrix[1][0];
for (i = 0; i < n; i++)
{ for (j = 0; j < i; j++)
{ if (distmatrix[i][j]<distance)
{ distance = distmatrix[i][j];
*ip = i;
*jp = j;
}
}
}
return distance;
}
/*---------------------------------------------------------------------------*/
Node *sl_cluster(double **distmatrix, int n)
{
/* perform single-linkage clustering using the SLINK algorithm */
int i, j, k;
const int nnodes = n - 1;
int *vector;
double *temp;
int *index;
Node *result;
/* memory allocation */
temp = malloc(sizeof(double) * nnodes);
if (!temp)
return NULL;
index = malloc(sizeof(int) * n);
if (!index) {
free(temp);
return NULL;
}
vector = malloc(sizeof(int) * nnodes);
if (!vector) {
free(index);
free(temp);
return NULL;
}
result = malloc(sizeof(Node) * nnodes);
if (!result) {
free(vector);
free(index);
free(temp);
return NULL;
}
for (i = 0; i < nnodes; i++) {
vector[i] = i;
result[i].distance = DBL_MAX;
}
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++)
temp[j] = distmatrix[i][j];
for (j = 0; j < i; j++) {
k = vector[j];
if (result[j].distance >= temp[j]) {
if (result[j].distance < temp[k])
temp[k] = result[j].distance;
result[j].distance = temp[j];
vector[j] = i;
}
else if (temp[j] < temp[k])
temp[k] = temp[j];
}
for (j = 0; j < i; j++)
if (result[j].distance >= result[vector[j]].distance)
vector[j] = i;
}
free(temp);
for (i = 0; i < nnodes; i++)
result[i].left = i;
qsort(result, nnodes, sizeof(Node), compare_nodes);
for (i = 0; i < n; i++)
index[i] = i;
for (i = 0; i < nnodes; i++) {
j = result[i].left;
k = vector[j];
result[i].left = index[j];
result[i].right = index[k];
index[k] = -i - 1;
}
free(vector);
free(index);
return result;
}
/*---------------------------------------------------------------------------*/
Node *average_cluster(double **distmatrix, int nelements)
{
/* perform average-linkage clustering */
int j;
int n;
int* clusterid;
int* number;
Node* result;
clusterid = malloc(nelements*sizeof(int));
if(!clusterid) return NULL;
number = malloc(nelements*sizeof(int));
if(!number)
{ free(clusterid);
return NULL;
}
result = malloc((nelements-1)*sizeof(Node));
if (!result)
{ free(clusterid);
free(number);
return NULL;
}
/* Setup a list specifying to which cluster a gene belongs, and keep track
* of the number of elements in each cluster (needed to calculate the
* average). */
for (j = 0; j < nelements; j++) {
number[j] = 1;
clusterid[j] = j;
}
for (n = nelements; n > 1; n--) {
int sum;
int is = 1;
int js = 0;
result[nelements-n].distance = find_closest_pair(n, distmatrix, &is, &js);
/* Save result */
result[nelements-n].left = clusterid[is];
result[nelements-n].right = clusterid[js];
/* Fix the distances */
sum = number[is] + number[js];
for (j = 0; j < js; j++) {
distmatrix[js][j] = distmatrix[is][j]*number[is]
+ distmatrix[js][j]*number[js];
distmatrix[js][j] /= sum;
}
for (j = js+1; j < is; j++) {
distmatrix[j][js] = distmatrix[is][j]*number[is]
+ distmatrix[j][js]*number[js];
distmatrix[j][js] /= sum;
}
for (j = is+1; j < n; j++) {
distmatrix[j][js] = distmatrix[j][is]*number[is]
+ distmatrix[j][js]*number[js];
distmatrix[j][js] /= sum;
}
for (j = 0; j < is; j++) distmatrix[is][j] = distmatrix[n-1][j];
for (j = is+1; j < n-1; j++) distmatrix[j][is] = distmatrix[n-1][j];
/* Update number of elements in the clusters */
number[js] = sum;
number[is] = number[n-1];
/* Update clusterids */
clusterid[js] = n-nelements-1;
clusterid[is] = clusterid[n-1];
}
free(clusterid);
free(number);
return result;
}
/*---------------------------------------------------------------------------*/
int *cuttree(Node * tree, int nelements, double cutoff, int *nclusters)
{
int i, j, k;
int icluster = 0;
int n; /* number of nodes to join */
int *nodeid;
int *clusterid;
*nclusters = 1;
/* calculate how many clusters there will be */
for (i = nelements - 2; i >= 0; i--)
if (tree[i].distance > cutoff)
(*nclusters)++;
else
break;
n = nelements - *nclusters;
clusterid = (int *) malloc(sizeof(int) * nelements);
for (i = nelements - 2; i >= n; i--) {
k = tree[i].left;
if (k >= 0) {
clusterid[k] = icluster;
icluster++;
}
k = tree[i].right;
if (k >= 0) {
clusterid[k] = icluster;
icluster++;
}
}
nodeid = malloc(n * sizeof(int));
if (!nodeid) {
for (i = 0; i < nelements; i++)
clusterid[i] = -1;
return clusterid;
}
for (i = 0; i < n; i++)
nodeid[i] = -1;
for (i = n - 1; i >= 0; i--) {
if (nodeid[i] < 0) {
j = icluster;
nodeid[i] = j;
icluster++;
}
else
j = nodeid[i];
k = tree[i].left;
if (k < 0)
nodeid[-k - 1] = j;
else
clusterid[k] = j;
k = tree[i].right;
if (k < 0)
nodeid[-k - 1] = j;
else
clusterid[k] = j;
}
free(nodeid);
return clusterid;
}
/*---------------------------------------------------------------------------*/
void rank_data(Data * data, const int *clusters, const int nc, const int n)
{
double total_energies[nc];
int i;
for (i = 0; i < nc; i++)
total_energies[i] = 0.0;
/* compute the total clusters interaction energy */
for (i = 0; i < n; i++)
total_energies[clusters[i]] += data[i].energy;
/* attach to each data point the total interaction energy of its cluster */
for (i = 0; i < n; i++) {
data[i].cl_energy = total_energies[clusters[i]];
data[i].cl_number = clusters[i];
}
/* sort the data points */
qsort(data, n, sizeof(Data), compare_data);
}
/*---------------------------------------------------------------------------*/
Summary *create_summary(Data * data, const int n, const int nc)
{
Summary *summary;
int i, s = 0, cn;
double weight; /* weighting factor for the coordinates */
summary = (Summary *) malloc(sizeof(Summary) * nc);
/* first data point */
summary[s].cl_energy = data[0].cl_energy;
weight = data[0].energy / data[0].cl_energy;
summary[s].x = data[0].x * weight;
summary[s].y = data[0].y * weight;
summary[s].z = data[0].z * weight;
summary[s].nmembers = 1;
cn = data[0].cl_number;
for (i = 1; i < n; i++) { /* all data points but the first */
if (cn != data[i].cl_number) { /* new cluster info */
s++;
cn = data[i].cl_number;
summary[s].cl_energy = data[i].cl_energy;
weight = data[i].energy / data[i].cl_energy;
summary[s].x = data[i].x * weight;
summary[s].y = data[i].y * weight;
summary[s].z = data[i].z * weight;