-
Notifications
You must be signed in to change notification settings - Fork 6
/
libcluster.hpp
9994 lines (9419 loc) · 367 KB
/
libcluster.hpp
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
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <sys/time.h>
#include "my_sort.h"
#include <sys/stat.h>
#ifdef GPU
#define MAX_ELEMENTS 8192*4096
#ifdef AMD
#define TM_MAX_SQ_BLOCK_SIZE 1280
#define TM_MAX_TR_BLOCK_SIZE 2560
#define RMSD_MAX_SQ_BLOCK_SIZE 1280
#define RMSD_MAX_TR_BLOCK_SIZE 2560
#endif
#ifdef NVIDIA
#define TM_MAX_SQ_BLOCK_SIZE 128
#define TM_MAX_TR_BLOCK_SIZE 128
#define RMSD_MAX_SQ_BLOCK_SIZE 512
#define RMSD_MAX_TR_BLOCK_SIZE 1024
#endif
extern char gtmscorecl_location[LINE_LENGTH], grmsdcl_location[LINE_LENGTH]; //path to tmscore.cl and rmsd.cl kernels
#endif
#define RMSD_MIN_VALUE 0.0
#define RMSD_STEP_SIZE_VALUE 0.06
#define TMSCORE_MIN_VALUE 0.17056
#define TMSCORE_STEP_SIZE_VALUE 0.00324
#define SQRT3 1.732050807568877
using namespace std;
enum _dmatrix_type {NO_DMATRIX,FLOAT,COMPACT};
enum _simd_type {SCALAR_,SSE2_,SSE3_,AVX_};
enum _metric_type {RMSD,TMSCORE};
enum _cluster_method{NO_CLUSTER,KMEANS,KCENTERS,HCOMPLETE,HSINGLE,HAVERAGE,DENSITY};
enum _compute_type{cCPU,cGPU};
enum _matrix_type{NO_MATRIX,BINARY,TEXT,CHAR};
enum _input_type{PDB_LIST,BINARY_COORDS};
//forward declaration of template classes - sometimes needed for friend class declarations
template <class T> class priority_heap_list;
template <class T> class triangular_matrix;
template <class T> class mapped_cluster_set;
template <class T> class parallel_cluster_set;
template <class T> class cluster_partition;
template <class T> class mapped_cluster_models_set;
template <class T> class cluster_models_set;
class cpu_properties;
//routines from tmscore/rmsd library
//scalar
void center_all_coords(int nstructs,int nat,float *coords);
float rmsd_cpu(int nat,float *coords1,float *coords2,float *rmatrix); //needed for final tmscore step
template <class T> float rmsd_cpu_par(int nthreads,int nat,int nmodels,float *coords,triangular_matrix<T> *matrix);
float rmsd_cpu_par(int nthreads,int nat,int nmodels,float *coords, float *density);
float tmscore_rmsd_cpu(int nat,float *coords1,float *coords2,float bR[3][3], float bt[3],float *rmsd);
//sse2
#ifdef SSE2
void shuffle_tmscore_coords_soa_sse(int nstructs, int nat, float *coords,float **x,float **y,float **z);
int shuffle_coords4_sse (int nstructs,int pdb_size, float *coords, float *shuffled_coords,float *ssqs);
template <class T> float rmsd_sse2_par(int nthreads,int nat,int nmodels,float *coords, triangular_matrix<T> *matrix);
float rmsd_sse2_par(int nthreads,int nat,int nmodels,float *coords, float *density);
float tmscore_cpu_soa_sse2(int nat, float *x1, float *y1,float *z1,float *x2,float *y2,float *z2,float bR[3][3], float bt[3], float *rmsd);
#endif
#ifdef SSE3
//sse3
template <class T> float rmsd_sse3_par(int nthreads,int nat,int nmodels,float *coords, triangular_matrix<T> *matrix);
float rmsd_sse3_par(int nthreads,int nat,int nmodels,float *coords,float *density);
float tmscore_cpu_soa_sse3(int nat, float *x1, float *y1,float *z1,float *x2,float *y2,float *z2,float bR[3][3], float bt[3], float *rmsd);
#endif
#ifdef AVX
//avx
template <class T> float rmsd_avx_par(int nthreads,int nat,int nmodels,float *coords,triangular_matrix<T> *matrix);
float rmsd_avx_par(int nthreads,int nat,int nmodels,float *coords, float *density);
void shuffle_tmscore_coords_soa_avx(int nstructs, int nat, float *coords,float **x,float **y,float **z);
float tmscore_cpu_soa_avx(int nat, float *x1, float *y1,float *z1,float *x2,float *y2,float *z2,float bR[3][3], float bt[3], float *rmsd);
int shuffle_coords8_avx (int nstructs,int pdb_size, float *coords, float *shuffled_coords,float *ssqs);
float shuffle_center_coords8_avx(int nat, float *coords, float *shuffled_coords,float centroid[3]);
float shuffle_center_coords8_unaligned_avx(int nat,float *coords, float *shuffled_coords,float centroid[3]);
#endif
int convert_coords_to_float4 (int nstructs,int pdb_size, float *coords, float4 *coords4);
int calculate_number_of_frames(int nat);
#ifdef GPU
int define_sizes_string (char **defines_string, int nthreads, int pdb4_size);
int read_source_file(char **array,const char *filename,char *defines_string);
int define_decoy_sizes_string (char **defines_string, int nthreads, int pdb4_size);
char *print_cl_errstring(cl_int err);
#endif
void shuffle_tmscore_coords_soa(int nstructs, int nat, float *coords,float **x,float **y,float **z);
float shuffle_center_coords4_sse(int nat, float *coords, float *shuffled_coords,float centroid[3]);
//misc common routines
double get_time();
void mean_stdev(int narray,float *array, float *mean, float *stdev);
void kshuffle(int k, int *arr, int narr, unsigned int *seed);
//sort routines
int sort_by_scores (int nstructs,float *scores, int *sorted,int min_first_flag);
void sedgesort (KEY_T *array, int len);
void partial_quickersort (KEY_T *array, int lower, int upper);
void insort (KEY_T *array, int len);
extern double gtimer1,gtimer2;
extern cpu_properties gcpu_info;
class cpu_properties{
public:
char vendor[12];
unsigned logical;
unsigned cores;
bool hyperthreads;
cpu_properties(){
//thanks to jcoffland for the code
unsigned regs[4];
// Get vendor
cpuID(0, regs);
((unsigned *)vendor)[0] = regs[1]; // EBX
((unsigned *)vendor)[1] = regs[3]; // EDX
((unsigned *)vendor)[2] = regs[2]; // ECX
string cpuVendor = string(vendor, 12);
// Get CPU features
cpuID(1, regs);
unsigned cpuFeatures = regs[3]; // EDX
// Logical core count per CPU
cpuID(1, regs);
logical = (regs[1] >> 16) & 0xff; // EBX[23:16]
// cout << " logical cpus: " << logical << endl;
cores = logical;
if (cpuVendor == "GenuineIntel") {
// Get DCP cache info
cpuID(4, regs);
cores = ((regs[0] >> 26) & 0x3f) + 1; // EAX[31:26] + 1
} else if (cpuVendor == "AuthenticAMD") {
// Get NC: Number of CPU cores - 1
cpuID(0x80000008, regs);
cores = ((unsigned)(regs[2] & 0xff)) + 1; // ECX[7:0] + 1
}
// cout << " cpu cores: " << cores << endl;
// Detect hyper-threads
hyperthreads = cpuFeatures & (1 << 28) && cores < logical;
// cout << "hyper-threads: " << (hyperthreads ? "true" : "false") << endl;
}
void cpuID(unsigned i, unsigned regs[4]) {
#ifdef _WIN32
__cpuid((int *)regs, (int)i);
#else
asm volatile
("cpuid" : "=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3])
: "a" (i), "c" (0));
// ECX is set to zero for CPUID function 4
#endif
}
};
class cluster_options{
public:
_metric_type score_type;
_matrix_type read_matrix_type,write_matrix_type;
_dmatrix_type distance_matrix_type;
_simd_type simd_type;
_compute_type compute;
_cluster_method method;
_input_type input_type;
int
all_atoms, //whether to calculate RMSD on all_atoms or the default CA's only -not yet implemented
//Cluster Variables
nclusters, //number of final clusters -used for kmeans and kcenters
//variables for kmeans
min_cluster_size, //minimum number of elements in cluster
nfixed_centers, //used for hybrid kcenters kmeans
//the first centers will be randomly determined and the last nfixed centers will be determined as the most distant from the random centers
total_iterations, //number of valid seeded solutions obtained for kmeans before stopping - if not set - will set to 10,000 or 2*nsolutions_after_best_score
maximum_iterations, //maximum number of iterations before convergence of a single solution
nsolutions_after_best_score, //number of kmeans partitions with no improvement in score before terminating
fine_parallel, //use fine_level parallelism for kmeans instead of task level for multiple kmeans
gpu_id; //optional gpu_id to specify different gpus in multigpu setups - default is -1 when NO_MATRIX is specified
float pvalue, //desired pvalue - used to calculate nsolutions_after_best_score
percentile; //desired estimated percentile where the best possible score is 1.00
char read_matrix_filename[FILENAME_LENGTH],
write_matrix_filename[FILENAME_LENGTH],
input_filename[FILENAME_LENGTH],
output_filename[FILENAME_LENGTH];
char *subset_filename;
public:
cluster_options(){
input_type=PDB_LIST;
score_type= RMSD;
read_matrix_type=NO_MATRIX;write_matrix_type=NO_MATRIX;
distance_matrix_type=FLOAT,simd_type =SCALAR_;
compute=cCPU;
method=KMEANS;
all_atoms=0;
nclusters=5;
fine_parallel=0;
gpu_id=-1;
//variables for kmeans
min_cluster_size=2;
nfixed_centers=0;
total_iterations=0;
maximum_iterations=10000;
nsolutions_after_best_score=-1;
pvalue=.01;
percentile=.99;
subset_filename=0;
strcpy(input_filename,"cluster_input");
strcpy(output_filename,"cluster_output");
}
~cluster_options(){
if(subset_filename) delete[] subset_filename;
}
};
class prune_options{
public:
_metric_type score_type;
_matrix_type read_matrix_type,write_matrix_type;
_dmatrix_type distance_matrix_type;
_simd_type simd_type;
_compute_type compute;
_cluster_method method;
_input_type input_type;
int
all_atoms, //whether to calculate RMSD on all_atoms or the default CA's only
nclusters,
prune_max_size, //indicates what the maximum size of the set should be after pruning
prune_min_size, //indicates what the minimum size of the set should be after pruning
prune_zmode, //determines whether outlier removal variables are calculated with zscores or using absolute values
keep_log, //keep track of which models are discarded - can be expensive for large sets
gpu_id; //optional gpu_id to specify different gpus in multigpu setups default is -1
float prune_min_zvalue, //the number of standard deviations from mean before being a outlier
prune_outlier_ratio, //controls the ratio outliers_removed/ensemble to limit the maximum number of outliers removed before the density is recalculated - if set to zero means that only the worst one is removed
prune_to, //prune until this density value is the worst remaining in ensemble
prune_stop; //stop pruning when the worst density is this value
char read_matrix_filename[FILENAME_LENGTH],
write_matrix_filename[FILENAME_LENGTH],
input_filename[FILENAME_LENGTH],
output_filename[FILENAME_LENGTH];
char *subset_filename;
//defaults
prune_options(){
input_type=PDB_LIST;
score_type= RMSD;
read_matrix_type=NO_MATRIX;write_matrix_type=NO_MATRIX;
distance_matrix_type=FLOAT,simd_type =SCALAR_;
compute=cCPU;
method=DENSITY;
all_atoms=0;
keep_log=0;
nclusters=3;
gpu_id=-1;
//variables for kmeans
subset_filename=0;
prune_max_size=0;
prune_min_size=0;
prune_zmode=0;
prune_min_zvalue=0;
prune_outlier_ratio=0;
prune_to=0;
prune_stop=0;
strcpy(input_filename,"prune_input");
strcpy(output_filename,"prune_output");
}
~prune_options(){;
if(subset_filename) delete[] subset_filename;
}
};
template <class T>
class priority_heap_list{ //used to find worst n scores
//This is used to keep track of the worst/best k scoring elements
//heap structure is used - first node is best scoring of bad elements
//if there are less than k in heap - element is added to heap
//if there are k in the heap - replace element at top of heap with nee element if the score of the element is worst than the best score and restore heap
//otherwise do not add to heap
//should be O(nlogk) - non destructive - read selection from heap map
//allow use of existing level of indirection through input *score_map allows for prefiltering - for example by a cutoff of the scores before the selection without much overhead
public:
int nscores,heap_size;
T *scores;
int *heap_map; //maps the linear array into the mini-heap structure used to find the k worst/best - max scores as defined by is_greater go on top - contains the k selected set
priority_heap_list (T *arr, int nworst,int mapped_arr_size,bool input_greater_is_better,int *score_map){
heap_size=nworst;nscores=mapped_arr_size;scores=arr;
heap_map=new int[nscores];
greater_is_better=input_greater_is_better;
if(score_map)
memmove(heap_map,score_map,nscores*sizeof(int));
else{
for(int i=0;i<nscores;i++)
heap_map[i]=i;
}
//heapify
for (int start =heap_size/2-1; start >=0; start--){
siftDown(start);
}
prioritize_rest_of_list();
}
~priority_heap_list(){
if(heap_map)delete [] heap_map;
}
int pop_heap(){
int retvalue=heap_map[0];
heap_map[0]=heap_map[heap_size-1];
heap_size--;
siftDown(0);
return(retvalue);
}
bool better (T a, T b){
return ((greater_is_better && a>b) || (!greater_is_better && a<b));
}
private:
bool greater_is_better;
T insert(int index){
heap_map[0]=heap_map[index];
siftDown(0);
return(scores[heap_map[0]]);
}
void siftDown(int start){
int root = start;
while (root*2+1 < heap_size ) {
int ir=heap_map[root];
T vr=scores[ir];
int child = 2*root+1;
int ic=heap_map[child];
T vc=scores[ic];
if (child +1 < heap_size && better(scores[heap_map[child+1]],vc)){
child++;
vc=scores[heap_map[child]];
}
if (better(vc,vr)) {
heap_map[root]=heap_map[child];
heap_map[child]=ir;
root=child;
}
else return;
}
}
void prioritize_rest_of_list(){ //feed the rest of the scores to the mini_heap
T best_score_of_bad_set=scores[heap_map[0]];
for(int i=heap_size;i<nscores;i++){
if(better(best_score_of_bad_set,scores[heap_map[i]])){
best_score_of_bad_set=insert(i);
}
}
}
};
class pruned_model{ //keeps track of pruned models
public:
char *name;
float score;
pruned_model(char *input_name,float input_score){
int len=strlen(input_name)+1;
name=new char[len];
strcpy(name,input_name);
score=input_score;
}
~pruned_model(){
if(name) delete [] name;
}
pruned_model(const pruned_model &A): score(A.score){
name=new char[strlen(A.name)+1];
strcpy(name,A.name);
}
pruned_model & operator = (const pruned_model &rhs){
if(this != &rhs){
score=rhs.score;
if(name) delete [] name;
name=new char[strlen(rhs.name)+1];
strcpy(name,rhs.name);
}
}
};
template <class T>
class triangular_matrix{
public:
int element_size;
int length;
float min_value,step_size,max_value,inv_step_size;
triangular_matrix(int input_length,float min_value,float step_size,bool greater_is_better){ //greater is better is only used in unsigned char case
length=input_length;
element_size=sizeof(T);
tmatrix=new T*[length];
for(int i=1;i<length;i++)
tmatrix[i]= new T[i];
fprintf(stderr,"allocate triangular matrix of %d length\n",length);
this->min_value= min_value;
this->step_size= step_size;
this ->max_value=min_value+255.5f*step_size;
inv_step_size=1.0f/step_size;
}
triangular_matrix(const triangular_matrix &A) : length(A.length), element_size(A.element_size), tmatrix (new T*[A.length]){
tmatrix=new T*[length];
for(int i=1;i<length;i++){
tmatrix[i]= new T[i];
memmove(tmatrix[i],A.tmatrix[i],i*sizeof(T));
}
this ->max_value=min_value+255.5f*step_size;
inv_step_size=1.0f/step_size;
}
triangular_matrix &operator=(const triangular_matrix &rhs ){
if(this != &rhs){
length=rhs.length;element_size=rhs.element_size;
T **new_matrix=new T*[length];
for(int i=1;i<length;i++){
new_matrix[i]= new T[i];
memmove(new_matrix[i],rhs.tmatrix[i],i*sizeof(T));
}
for(int i=1;i<length;i++)
if(tmatrix[i])delete [] tmatrix[i];
if(tmatrix)delete[] tmatrix;
tmatrix=new_matrix;
}
this ->max_value=min_value+255.5f*step_size;
inv_step_size=1.0f/step_size;
return *this;
}
void adjust_max_min(){
float max,min;
max=get_matrix(1,0);
min=get_matrix(1,0);
for(int i=1;i<length;i++){
for(int j=0;j<i;j++){
float value=get_matrix(i,j);
max=(value>max)? value :max;
min=(min>value)? value :min;
}
}
min_value=min;
step_size=(max-min)/256.0f;
inv_step_size=1.0/step_size;
max_value=min_value+255.5f*step_size;
}
void adjust_max_min(int *map, int nmap){
float max,min;
max=get_matrix(map[1],map[0]);
min=get_matrix(map[1],map[0]);
for(int i=1;i<nmap;i++){
int a=map[i];
for(int j=0;j<i;j++){
int b=map[j];
float value=get_matrix(a,b);
max=(value>max)? value :max;
min=(min>value)? value :min;
}
}
min_value=min;
step_size=(max-min)/256.0f;
inv_step_size=1.0/step_size;
max_value=min_value+255.5f*step_size;
}
int zero_matrix(){
for(int i=1;i<length;i++){
memset(tmatrix[i],0,i*sizeof(T));
}
}
~triangular_matrix(){//non-compact version
for(int i=1;i<length;i++)
if(tmatrix[i])delete [] tmatrix[i];
if(tmatrix)delete [] tmatrix;
}
T* get_address(int i, int j){
return((i>j)?&(tmatrix[i][j]) :&(tmatrix[j][i]));
}
T get_matrix(int i, int j){
return((i<j)?tmatrix[j][i] :tmatrix[i][j]);
}
T get_matrix_fast(int i, int j){
return (tmatrix[i][j]);
}
T get_native_matrix(int i, int j){
return((i<j)?tmatrix[j][i] :tmatrix[i][j]);
}
T get_native_matrix_fast(int i, int j){
return (tmatrix[i][j]);
}
void set_matrix_fast (int i, int j, T value){
tmatrix[i][j]=value;
}
T get_matrix_safe(int i, int j){
if(i<0 || i>= length || j<0 || j>=length){
fprintf(stderr,"subscripts %d %d out of range for size %d matrix\n",i,j,length);
exit(FALSE);
}
return((i<j)?tmatrix[j][i] :tmatrix[i][j]);
}
void set_matrix_safe (int i, int j, T value){
if(i<0 || i>= length || j<0 || j>=length){
fprintf(stderr,"subscripts %d %d out of range for size %d matrix\n",i,j,length);
exit(FALSE);
}
if(i<j)tmatrix[j][i]=value;
else tmatrix[i][j]=value;
}
void set_matrix(int i, int j, T value){
if(i<j)tmatrix[j][i]=value;
else tmatrix[i][j]=value;
}
int read_matrix_from_binary_file(FILE *fp,int *inverse_map,int ninverse_map){
int nread=0;
int nseek=0;
for(int i=1;i<ninverse_map;i++){
int a=inverse_map[i];
if(a >=0){
for(int j=0;j<i;j++){
int b=inverse_map[j];
if(b>=0){
T value;
fseek(fp,nseek*element_size,SEEK_CUR);
fread(&value,element_size,1,fp);
set_matrix(a,b,value);
nread++;
nseek=0;
}
else nseek++;
}
}
else{
nseek+=i;
}
}
return(nread);
}
int read_matrix_from_binary_file(FILE *fp){
int read,n=0,rvalue=1;
char dum;
for(int i=1;i<length;i++){
read=fread(tmatrix[i],element_size,i,fp);
if(!read){
fprintf(stderr,"file too short - read aborted at %d rows\n",i-1);
return(0);
}
}
if(fread(&dum,sizeof(char),1,fp)){
fprintf(stderr,"warning not at EOF after %d rows\n",length);
rvalue=-1;
}
return(rvalue);
}
int read_matrix_from_compact_file(FILE *fp,int *inverse_map,int ninverse_map){
//reads and converts binary matrix to normal distance matrix
int nread=0;
int nseek=0;
int my_length;
{
fread(&my_length,sizeof(int),1,fp);
fread(&min_value,sizeof(float),1,fp);//compact write is always float min
fread(&step_size,sizeof(float),1,fp);
}
for(int i=1;i<ninverse_map;i++){
int a=inverse_map[i];
if(a >=0){
for(int j=0;j<i;j++){
int b=inverse_map[j];
if(b>=0){
unsigned char ctemp;
fseek(fp,nseek,SEEK_CUR);
fread(&ctemp,1,1,fp);
set_matrix(a,b,min_value+step_size*(float)ctemp);
nread++;
nseek=0;
}
else nseek++;
}
}
else{
nseek+=i;
}
}
return(nread);
}
int read_matrix_from_compact_file(FILE *fp){
int nread=0;
//reads and converts binary matrix to normal distance matrix
int my_length;
{
fread(&my_length,sizeof(int),1,fp);
fread(&min_value,sizeof(float),1,fp);//compact write is always float min
fread(&step_size,sizeof(float),1,fp);
}
for(int i=1;i<length;i++){
for(int j=0;j<i;j++){
unsigned char ctemp;
fread(&ctemp,1,1,fp);
tmatrix[i][j]=min_value+step_size*(float)ctemp;
nread++;
}
}
return(nread);
}
int read_matrix_from_text_file(FILE *fp,int *inverse_map){
char line[LINE_LENGTH];
int nread=0;
while (fgets(line, LINE_LENGTH, fp)){
float value;
int m,n,i,j;;
sscanf (line, "%d %d %f",&m,&n,&value);
i=inverse_map[m];
j=inverse_map[n];
if(i>=0 && i<length && j>=0 && j <length){
tmatrix[i][j]=value;
nread++;
}
}
return(nread);
}
int read_matrix_from_text_file(FILE *fp){
char line[LINE_LENGTH];
int nread=0;
while (fgets(line, LINE_LENGTH, fp)){
float value;
int i,j;
sscanf (line, "%d %d %f",&i,&j,&value);
if(i<length && j <length){
tmatrix[i][j]=value;
nread++;
}
}
return(nread);
}
unsigned char convert_to_char(T value){
float findex=(value-min_value)/step_size;
int index=(int) (findex+.5);
if(index <0)index=0;
if(index >255)index=255;
return(unsigned char)index;
}
void write_matrix_to_compact_file(FILE *fp){
adjust_max_min();//find current max min
fwrite(&length,sizeof(int),1,fp);
fwrite(&min_value,sizeof(float),1,fp);
fwrite(&step_size,sizeof(float),1,fp);;
for(int i=1;i<length;i++)
for(int j=0;j<i;j++){
unsigned char cvalue=convert_to_char(tmatrix[i][j]);
fwrite(&cvalue,1,1,fp);
}
}
void write_matrix_to_compact_file(FILE *fp,int *map,int nmap){
adjust_max_min(map,nmap);//find current max min
fwrite(&length,sizeof(int),1,fp);
fwrite(&min_value,sizeof(float),1,fp);
fwrite(&step_size,sizeof(float),1,fp);
for(int i=1;i<nmap;i++){
int a=map[i];
for(int j=0;j<i;j++){
int b=map[j];
unsigned char cvalue=convert_to_char(get_matrix(a,b));
fwrite(&cvalue,1,1,fp);
}
}
}
void write_matrix_to_binary_file(FILE *fp){
for(int i=1;i<length;i++)
fwrite(tmatrix[i],element_size,i,fp);
}
void write_matrix_to_binary_file(FILE *fp,int *map,int nmap){
for(int i=1;i<nmap;i++)
for(int j=0;j<i;j++){
int a=map[i];
int b=map[j];
if(a>b)
fwrite(&(tmatrix[a][b]),element_size,1,fp);
else
fwrite(&(tmatrix[b][a]),element_size,1,fp);
}
}
void write_matrix_to_text_file (FILE *fp){
for (int i=1;i<length;i++)
for(int j=0;j<i;j++)
fprintf(fp,"%d %d %f\n",i,j,get_matrix(i,j));
}
void write_matrix_to_text_file (FILE *fp,int *map, int nmap){
for (int m=1;m<nmap;m++){
for(int n=0;n<m;n++){
int i=map[m];
int j=map[n];
fprintf(fp,"%d %d %f\n",m,n,get_matrix(m,n));
}
}
}
void generate_matrix(int nats,int pdb_size,float *coords,_compute_type compute,_metric_type score_type,_simd_type simd_type,int nthreads,int gpu_id){
if(compute==cCPU){
if(score_type==RMSD){
if(simd_type==SCALAR_){
//no SSE routine
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#else
nthreads=1;
#endif
rmsd_cpu_par(nthreads,nats,length,coords,this);
}
#ifdef SSE2
else if(simd_type ==SSE2_){//use SSE2 routine
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#endif
rmsd_sse2_par(nthreads,nats,length,coords,this);
}
#endif
#ifdef SSE3
else if(simd_type ==SSE3_){//use SSE2 routine
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#endif
rmsd_sse3_par(nthreads,nats,length,coords,this);
}
#endif
#ifdef AVX
else if(simd_type == AVX_){//use avx routine
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#endif
rmsd_avx_par(nthreads,nats,length,coords,this);
}
#endif
}//end rmsd
else if (score_type == TMSCORE){ //TMscore
float R[3][3],t[3];
if(simd_type == SCALAR_){
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#pragma omp parallel for num_threads (nthreads) schedule (dynamic)
#endif
for (int i=1;i<length;i++){
for (int j=0;j<i;j++){
this->set_matrix(i,j,tmscore_rmsd_cpu(nats,&(coords[i*pdb_size]),&(coords[j*pdb_size]),R,t,0));
}
}
}
#ifdef SSE2
else if (simd_type == SSE2_){
float *x=0,*y=0,*z=0;
shuffle_tmscore_coords_soa_sse(length,nats,coords,&x,&y,&z);
int anats=(nats%4)? (nats/4)*4+4 : nats;
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#pragma omp parallel for num_threads (nthreads) schedule (dynamic)
#endif
for (int i=1;i<length;i++){
for (int j=0;j<i;j++){
this->set_matrix(i,j,tmscore_cpu_soa_sse2(nats,&(x[i*anats]),&(y[i*anats]),&(z[i*anats]),&(x[j*anats]),&(y[j*anats]),&(z[j*anats]),0,0,0));
}
}
if(x) free (x);
if(y) free (y);
if(z) free (z);
}
#endif
#ifdef SSE3
else if (simd_type == SSE3_){
float *x=0,*y=0,*z=0;
shuffle_tmscore_coords_soa_sse(length,nats,coords,&x,&y,&z);
int anats=(nats%4)? (nats/4)*4+4 : nats;
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#pragma omp parallel for num_threads (nthreads) schedule (dynamic)
#endif
for (int i=1;i<length;i++){
for (int j=0;j<i;j++){
this->set_matrix(i,j,tmscore_cpu_soa_sse3(nats,&(x[i*anats]),&(y[i*anats]),&(z[i*anats]),&(x[j*anats]),&(y[j*anats]),&(z[j*anats]),0,0,0));
}
}
if(x) free (x);
if(y) free (y);
if(z) free (z);
}
#endif
#ifdef AVX
else if (simd_type == AVX_){
float *x=0,*y=0,*z=0;
int unat8=(nats%8)? (nats/8+1)*8 : nats;
shuffle_tmscore_coords_soa_avx(length,nats,coords,&x,&y,&z);
#ifdef OPENMP
int max_threads=omp_get_max_threads();
nthreads=(max_threads<nthreads)? max_threads : nthreads;
#pragma omp parallel for num_threads (nthreads) schedule (dynamic)
#endif
for (int i=1;i<length;i++){
for (int j=0;j<i;j++){
this->set_matrix(i,j,tmscore_cpu_soa_avx(nats,&(x[i*unat8]),&(y[i*unat8]),&(z[i*unat8]),&(x[j*unat8]),&(y[j*unat8]),&(z[j*unat8]),0,0,0));
}
}
if(x) free (x);
if(y) free (y);
if(z) free (z);
}
#endif
}//end TMSCORE
else{
fprintf(stderr,"unrecognized score type %d\n",score_type);
exit(FALSE);
}
}//end CPU
#ifdef GPU
else if(compute == cGPU){
if (score_type== RMSD)this->find_rmsd_matrix(0,64,0,grmsdcl_location,nats,coords,gpu_id,nthreads);
else if(score_type==TMSCORE)this->find_tmscore_matrix(0,64,0,gtmscorecl_location,nats,coords,gpu_id,nthreads);
else{
fprintf(stderr,"unrecognized score type %d\n",score_type);
exit(FALSE);
}
}
#endif
else{
fprintf(stderr,"unrecognized compute type %d\n",compute);
exit(FALSE);
}
}
#ifdef GPU
int find_tmscore_matrix(int cpu_flag,int nt, int nwg_per_cu,const char *source,int nats,float *coords,int gpu_id,int nthreads){
//this version outputs a lower triangle matrix
//the original code was written to calculate upper triangular matrix - change order of indices to get lower matrix
int nats4=(nats%4)?nats/4+1:nats/4;
int pdb_size=3*nats,pdb4_size=3*nats4;
char *defines_string=0,*kernel_source=0;
double start_program=0,start_rmsd=0,end=0;
float4 *coords4;
//add define string to source to specify maximum size
define_sizes_string (&defines_string,nt,pdb4_size);
read_source_file(&kernel_source,source,defines_string);
//openCL
cl_int4 sizes,start_points;
cl_platform_id platform;
cl_device_id device;
cl_context context;
cl_command_queue queue;
cl_program program;
cl_kernel tmscore_matrix,tmscore_matrix_rect;
cl_mem tmscores_buffer,coords41_buffer,coords42_buffer;
cl_float2 *tmscores;
cl_int err;
cl_uint ncu,num_of_devices,numPlatforms;
clGetPlatformIDs( 1, &platform, NULL );
//get all devices
cl_device_id cpus[10],gpus[10];
int ngpus=0;
if (clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 0,0, &num_of_devices) == CL_SUCCESS)
{
fprintf(stderr, "%d cpus found\n",num_of_devices);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, num_of_devices,cpus, 0);
}
if (clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0,0, &num_of_devices) == CL_SUCCESS)
{
fprintf(stderr, "%d gpus found\n",num_of_devices);
ngpus=num_of_devices;
clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, num_of_devices,gpus, 0);
}
// try to get a supported GPU device
//test with CPU
if(cpu_flag)
{
device=cpus[0];
clGetDeviceInfo(device,CL_DEVICE_MAX_COMPUTE_UNITS,sizeof(cl_uint),&ncu,NULL);
fprintf(stderr,"using cpu %d cores found\n",ncu);
}
else{
if (!ngpus)
{
fprintf(stderr, "no gpu found - running with cpu");
device=cpus[0];
clGetDeviceInfo(device,CL_DEVICE_MAX_COMPUTE_UNITS,sizeof(cl_uint),&ncu,NULL);
}
else
{
if(gpu_id > ngpus-1){
fprintf(stderr,"gpu_id error %d gpus found - highest allowed gpu_id is %d - gpu_id of %d given\n",ngpus,ngpus-1,gpu_id);
exit(FALSE);
}
if(gpu_id ==-1){
if(ngpus >1){
find_tmscore_matrix_multiple_gpus (nt,nwg_per_cu,source,nats,coords,nthreads);
return(1);
}
device=gpus[0];
}
else device=gpus[gpu_id];
clGetDeviceInfo(device,CL_DEVICE_MAX_COMPUTE_UNITS,sizeof(cl_uint),&ncu,NULL);
fprintf(stderr,"%d compute units found\n",ncu);
}
}
context = clCreateContext(NULL,1,&device,NULL,NULL,&err);
queue = clCreateCommandQueue(context, device, 0, &err);
//calculate maximum number of workgroups per compute unit
//for gpus this depends on the memory available
int lds=1024*32; //local cache size per cu - but at least 2 workgroups/cu are active at any one time so half of this is really available
if(cpu_flag)lds*=2;
//memory used is memory to cache coords plus memory for the alignment and reduction - this is different from the simple tmscore where the coords memory is used once
//there is a bug in OpenCL with local memory declared in a block that may or may not be freed...
int mem_per_wg=6*nats4*sizeof(float4)+nt*sizeof(float2);
#ifdef AMD
int max_wg_per_cu=lds/mem_per_wg/2;
#endif
#ifdef NVIDIA
int max_wg_per_cu=2*lds/mem_per_wg;
#endif
if( max_wg_per_cu <1) max_wg_per_cu =1;
if(nwg_per_cu)max_wg_per_cu=nwg_per_cu;
unsigned int max_nwg=(max_wg_per_cu)*ncu;
fprintf(stderr,"creating coord buffers\n");
//create hosts arrays and buffers
if (!(coords4 = (float4*) malloc(pdb4_size * length *sizeof(float4)))) exit(FALSE);
convert_coords_to_float4 (length,pdb_size,coords,coords4);
fprintf(stderr,"created buffers\n");
start_rmsd = get_time();
program = clCreateProgramWithSource(context,1,(const char**)&kernel_source, NULL,&err);
if ((err=clBuildProgram(program, 0, NULL, NULL, NULL, NULL) != CL_SUCCESS))
{
fprintf(stderr,"error %d %s\n",err,print_cl_errstring(err));
char buf[0x10000];
clGetProgramBuildInfo( program,device,CL_PROGRAM_BUILD_LOG,0x10000,buf,NULL);
fprintf(stderr,"\n%s\n", buf);
return 1;
}
end = get_time();
fprintf(stderr,"creating kernel\n");
tmscore_matrix = clCreateKernel(program, "tmscore_matrix", &err);
fprintf(stderr, "%8.3f seconds elapsed for program generation\n",end-start_rmsd);
start_rmsd = get_time();
start_rmsd = get_time();
int max_structs_for_coords=(int)(MAX_ELEMENTS/pdb4_size);
int max_structs_for_matrix=(int)sqrt((float) MAX_ELEMENTS/sizeof(float2));
int max_structs=(max_structs_for_coords < max_structs_for_matrix)? max_structs_for_coords : max_structs_for_matrix;
if(max_structs > TM_MAX_TR_BLOCK_SIZE) max_structs=TM_MAX_TR_BLOCK_SIZE;
if(!max_structs){fprintf(stderr,"insufficient memory to load structure\n");exit(FALSE);}
if(length<max_structs)max_structs=length;
//this version outputs a lower triangle matrix
//the original code was written to calculate upper triangular matrix - change order of indices to get lower matrix
int ngrid=(length%max_structs)?length/max_structs+1 : length/max_structs; //size of the grid of tiles - calculation is split into ngrid*(ngrid-1)/2 submatrices for large number of structures
if (ngrid > 1)
{
//recalculate with MAX_ELEMENTS/2
max_structs_for_coords=(int)((MAX_ELEMENTS/2)/pdb4_size);
max_structs_for_matrix=(int)sqrt((float) ((MAX_ELEMENTS/2)/sizeof(cl_float2)));
max_structs=(max_structs_for_coords < max_structs_for_matrix)? max_structs_for_coords : max_structs_for_matrix;
if (max_structs > TM_MAX_SQ_BLOCK_SIZE) max_structs=TM_MAX_SQ_BLOCK_SIZE;
if(!max_structs){fprintf(stderr,"insufficient memory to load structure\n");exit(FALSE);}
if(length<max_structs)max_structs=length;
ngrid=(length%max_structs)?length/max_structs+1 : length/max_structs;
}
int block_matrix_size_tr=max_structs*(max_structs-1)/2;
int block_matrix_size_sq=max_structs*max_structs;
fprintf(stderr,"creating openCL coords buff %d\n",max_structs*pdb4_size * sizeof(float4));
coords41_buffer = clCreateBuffer(context,CL_MEM_READ_ONLY, max_structs*pdb4_size * sizeof(float4),NULL, NULL );
if(ngrid >1)
{
fprintf(stderr,"creading square buffers\n");
// tmscore_matrix_rect = clCreateKernel(program, "tmscore_matrix_rect", &err);
// coords42_buffer = clCreateBuffer(context,CL_MEM_READ_ONLY, max_structs*pdb4_size * sizeof(float4),NULL, NULL );
tmscores_buffer = clCreateBuffer(context,CL_MEM_READ_WRITE, block_matrix_size_sq * sizeof(cl_float2),NULL, NULL);
if((!(tmscores=(cl_float2*)malloc(sizeof(cl_float2)*block_matrix_size_sq))))exit(FALSE);
}
else
{
tmscores_buffer = clCreateBuffer(context,CL_MEM_READ_WRITE, block_matrix_size_tr * sizeof(cl_float2),NULL, NULL);
if((!(tmscores=(cl_float2*)malloc(sizeof(cl_float2)*block_matrix_size_tr))))exit(FALSE);
}
fprintf(stderr,"calculating frames\n");
int nseeds=calculate_number_of_frames(nats);
sizes.x=nats;sizes.y=nats4;
//indices need to be worked out
for (int ni=0;ni<ngrid;ni++)