calcMergedEneGra.cl 64.2 KB
Newer Older
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
/*

OCLADock, an OpenCL implementation of AutoDock 4.2 running a Lamarckian Genetic Algorithm
Copyright (C) 2017 TU Darmstadt, Embedded Systems and Applications Group, Germany. All rights reserved.

AutoDock is a Trade Mark of the Scripps Research Institute.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/

// IMPORTANT: The following block contains definitions
// already made either in energy or gradient calculation files.
// For that reason, these are commented here.

#if 0
//#define DEBUG_ENERGY_KERNEL

#include "calcenergy_basic.h"

typedef struct
{
       float atom_charges_const[MAX_NUM_OF_ATOMS];
       char  atom_types_const  [MAX_NUM_OF_ATOMS];
} kernelconstant_interintra;

typedef struct
{
       char  intraE_contributors_const[3*MAX_INTRAE_CONTRIBUTORS];
} kernelconstant_intracontrib;

typedef struct
{
       float reqm_const [ATYPE_NUM];
       float reqm_hbond_const [ATYPE_NUM];
       unsigned int  atom1_types_reqm_const [ATYPE_NUM];
       unsigned int  atom2_types_reqm_const [ATYPE_NUM];
       float VWpars_AC_const   [MAX_NUM_OF_ATYPES*MAX_NUM_OF_ATYPES];
       float VWpars_BD_const   [MAX_NUM_OF_ATYPES*MAX_NUM_OF_ATYPES];
       float dspars_S_const    [MAX_NUM_OF_ATYPES];
       float dspars_V_const    [MAX_NUM_OF_ATYPES];
} kernelconstant_intra;

typedef struct
{
       int   rotlist_const     [MAX_NUM_OF_ROTATIONS];
} kernelconstant_rotlist;

typedef struct
{
       float ref_coords_x_const[MAX_NUM_OF_ATOMS];
       float ref_coords_y_const[MAX_NUM_OF_ATOMS];
       float ref_coords_z_const[MAX_NUM_OF_ATOMS];
       float rotbonds_moving_vectors_const[3*MAX_NUM_OF_ROTBONDS];
       float rotbonds_unit_vectors_const  [3*MAX_NUM_OF_ROTBONDS];
       float ref_orientation_quats_const  [4*MAX_NUM_OF_RUNS];
} kernelconstant_conform;

// All related pragmas are in defines.h (accesible by host and device code)

// The GPU device function calculates the energy's gradient (forces or derivatives) 
// of the entity described by genotype, dockpars and the ligand-data
// arrays in constant memory and returns it in the "gradient_genotype" parameter. 
// The parameter "run_id" has to be equal to the ID of the run 
// whose population includes the current entity (which can be determined with get_group_id(0)), 
// since this determines which reference orientation should be used.

//#define PRINT_GRAD_TRANSLATION_GENES
//#define PRINT_GRAD_ROTATION_GENES
//#define PRINT_GRAD_TORSION_GENES

#define ENABLE_PARALLEL_GRAD_TORSION

// The following is a scaling of gradients.
// Initially all genotypes and gradients
// were expressed in grid-units (translations)
// and sexagesimal degrees (rotation and torsion angles).
// Expressing them using angstroms / radians
// might help gradient-based minimizers.
// This conversion is applied to final gradients.
#define CONVERT_INTO_ANGSTROM_RADIAN

// Scaling factor to multiply the gradients of 
// the genes expressed in degrees (all genes except the first three) 
// (GRID-SPACING * GRID-SPACING) / (DEG_TO_RAD * DEG_TO_RAD) = 461.644
#define SCFACTOR_ANGSTROM_RADIAN ((0.375 * 0.375)/(DEG_TO_RAD * DEG_TO_RAD))

void map_priv_angle(float* angle)
// The GPU device function maps
// the input parameter to the interval 0...360
// (supposing that it is an angle).
{
	while (*angle >= 360.0f) {
		*angle -= 360.0f;
	}

	while (*angle < 0.0f) {
		*angle += 360.0f;
	}
}

#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable

// Atomic operations used in gradients of intra contributors.
// Only atomic_cmpxchg() works on floats. 
// So for atomic add on floats, this link was used:
// https://streamhpc.com/blog/2016-02-09/atomic-operations-for-floats-in-opencl-improved/
void atomicAdd_g_f(volatile __local float *addr, float val)
{
	union{
		unsigned int u32;
		float f32;
	} next, expected, current;

	current.f32 = *addr;

	do{
		expected.f32 = current.f32;
		next.f32 = expected.f32 + val;
		current.u32 = atomic_cmpxchg( (volatile __local unsigned int *)addr, expected.u32, next.u32);
	} while( current.u32 != expected.u32 );
}

void atomicSub_g_f(volatile __local float *addr, float val)
{
	union{
		unsigned int u32;
		float f32;
	} next, expected, current;

	current.f32 = *addr;

	do{
		expected.f32 = current.f32;
		next.f32 = expected.f32 - val;
		current.u32 = atomic_cmpxchg( (volatile __local unsigned int *)addr, expected.u32, next.u32);
	} while( current.u32 != expected.u32 );
}
#endif


// IMPORTANT: the code of gradient calculation was the initial template.
// Then, statements corresponding to enery calculations were added gradually.
// The latter can be distinguised this way: they are place within lines without indentation.

void gpu_calc_energrad(	    
				int    dockpars_rotbondlist_length,
				char   dockpars_num_of_atoms,
			    	char   dockpars_gridsize_x,
			    	char   dockpars_gridsize_y,
			    	char   dockpars_gridsize_z,
								    		// g1 = gridsize_x
				uint   dockpars_gridsize_x_times_y, 		// g2 = gridsize_x * gridsize_y
				uint   dockpars_gridsize_x_times_y_times_z,	// g3 = gridsize_x * gridsize_y * gridsize_z
		 __global const float* restrict dockpars_fgrids, // This is too large to be allocated in __constant 
		            	char   dockpars_num_of_atypes,
		            	int    dockpars_num_of_intraE_contributors,
			    	float  dockpars_grid_spacing,
			    	float  dockpars_coeff_elec,
			    	float  dockpars_qasp,
			    	float  dockpars_coeff_desolv,
				float  dockpars_smooth,

				// Some OpenCL compilers don't allow declaring 
				// local variables within non-kernel functions.
				// These local variables must be declared in a kernel, 
				// and then passed to non-kernel functions.
		    	__local float* genotype,
			__local float* energy,
		    	__local int*   run_id,

		    	__local float* calc_coords_x,
		    	__local float* calc_coords_y,
		    	__local float* calc_coords_z,
__local float* partial_energies,

#if defined (DEBUG_ENERGY_KERNEL)
__local float* partial_interE,
__local float* partial_intraE,
#endif

		     __constant        kernelconstant_interintra* 	kerconst_interintra,
		     __global const    kernelconstant_intracontrib*  	kerconst_intracontrib,
		     __constant        kernelconstant_intra*		kerconst_intra,
		     __constant        kernelconstant_rotlist*   	kerconst_rotlist,
		     __constant        kernelconstant_conform*		kerconst_conform
			,
		     __constant int*   	     rotbonds_const,
		     __global   const int*   rotbonds_atoms_const,
		     __constant int*         num_rotating_atoms_per_rotbond_const
			,
		     __global   const float* angle_const,
		     __constant       float* dependence_on_theta_const,
		     __constant       float* dependence_on_rotangle_const

		    // Gradient-related arguments
		    // Calculate gradients (forces) for intermolecular energy
		    // Derived from autodockdev/maps.py
		    // "is_enabled_gradient_calc": enables gradient calculation.
		    // In Genetic-Generation: no need for gradients
		    // In Gradient-Minimizer: must calculate gradients
			,
			    int    dockpars_num_of_genes,
	    	    __local float* gradient_inter_x,
	            __local float* gradient_inter_y,
	            __local float* gradient_inter_z,
		    __local float* gradient_intra_x,
		    __local float* gradient_intra_y,
		    __local float* gradient_intra_z,
		    __local float* gradient_genotype			
)
{
partial_energies[get_local_id(0)] = 0.0f;

#if defined (DEBUG_ENERGY_KERNEL)
partial_interE[get_local_id(0)] = 0.0f;
partial_intraE[get_local_id(0)] = 0.0f;
#endif

	// Initializing gradients (forces) 
	// Derived from autodockdev/maps.py
	for (uint atom_id = get_local_id(0);
		  atom_id < dockpars_num_of_atoms;
		  atom_id+= NUM_OF_THREADS_PER_BLOCK) {
		// Intermolecular gradients
		gradient_inter_x[atom_id] = 0.0f;
		gradient_inter_y[atom_id] = 0.0f;
		gradient_inter_z[atom_id] = 0.0f;
		// Intramolecular gradients
		gradient_intra_x[atom_id] = 0.0f;
		gradient_intra_y[atom_id] = 0.0f;
		gradient_intra_z[atom_id] = 0.0f;
	}

	// Initializing gradient genotypes
	for (uint gene_cnt = get_local_id(0);
		  gene_cnt < dockpars_num_of_genes;
		  gene_cnt+= NUM_OF_THREADS_PER_BLOCK) {
		gradient_genotype[gene_cnt] = 0.0f;
	}
	barrier(CLK_LOCAL_MEM_FENCE);

	// Convert orientation genes from sex. to radians
	float phi         = genotype[3] * DEG_TO_RAD;
	float theta       = genotype[4] * DEG_TO_RAD;
	float genrotangle = genotype[5] * DEG_TO_RAD;

	float genrot_unitvec [3];
	float sin_angle = native_sin(theta);
	genrot_unitvec [0] = sin_angle*native_cos(phi);
	genrot_unitvec [1] = sin_angle*native_sin(phi);
	genrot_unitvec [2] = native_cos(theta);

	uchar g1 = dockpars_gridsize_x;
	uint  g2 = dockpars_gridsize_x_times_y;
  	uint  g3 = dockpars_gridsize_x_times_y_times_z;

	// ================================================
	// CALCULATING ATOMIC POSITIONS AFTER ROTATIONS
	// ================================================
	for (uint rotation_counter = get_local_id(0);
	          rotation_counter < dockpars_rotbondlist_length;
	          rotation_counter+=NUM_OF_THREADS_PER_BLOCK)
	{
		int rotation_list_element = kerconst_rotlist->rotlist_const[rotation_counter];

		if ((rotation_list_element & RLIST_DUMMY_MASK) == 0)	// If not dummy rotation
		{
			uint atom_id = rotation_list_element & RLIST_ATOMID_MASK;

			// Capturing atom coordinates
			float atom_to_rotate[3];

			if ((rotation_list_element & RLIST_FIRSTROT_MASK) != 0)	// If first rotation of this atom
			{
				atom_to_rotate[0] = kerconst_conform->ref_coords_x_const[atom_id];
				atom_to_rotate[1] = kerconst_conform->ref_coords_y_const[atom_id];
				atom_to_rotate[2] = kerconst_conform->ref_coords_z_const[atom_id];
			}
			else
			{
				atom_to_rotate[0] = calc_coords_x[atom_id];
				atom_to_rotate[1] = calc_coords_y[atom_id];
				atom_to_rotate[2] = calc_coords_z[atom_id];
			}

			// Capturing rotation vectors and angle
			float rotation_unitvec[3];
			float rotation_movingvec[3];
			float rotation_angle;

			float quatrot_left_x, quatrot_left_y, quatrot_left_z, quatrot_left_q;
			float quatrot_temp_x, quatrot_temp_y, quatrot_temp_z, quatrot_temp_q;

			if ((rotation_list_element & RLIST_GENROT_MASK) != 0)	// If general rotation
			{
				rotation_unitvec[0] = genrot_unitvec[0];
				rotation_unitvec[1] = genrot_unitvec[1];
				rotation_unitvec[2] = genrot_unitvec[2];

				rotation_movingvec[0] = genotype[0];
				rotation_movingvec[1] = genotype[1];
				rotation_movingvec[2] = genotype[2];

				rotation_angle = genrotangle;
			}
			else	// If rotating around rotatable bond
			{
				uint rotbond_id = (rotation_list_element & RLIST_RBONDID_MASK) >> RLIST_RBONDID_SHIFT;

				rotation_unitvec[0] = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id];
				rotation_unitvec[1] = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id+1];
				rotation_unitvec[2] = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id+2];

				rotation_movingvec[0] = kerconst_conform->rotbonds_moving_vectors_const[3*rotbond_id];
				rotation_movingvec[1] = kerconst_conform->rotbonds_moving_vectors_const[3*rotbond_id+1];
				rotation_movingvec[2] = kerconst_conform->rotbonds_moving_vectors_const[3*rotbond_id+2];

				rotation_angle = genotype[6+rotbond_id]*DEG_TO_RAD;

				// Performing additionally the first movement which 
				// is needed only if rotating around rotatable bond
				atom_to_rotate[0] -= rotation_movingvec[0];
				atom_to_rotate[1] -= rotation_movingvec[1];
				atom_to_rotate[2] -= rotation_movingvec[2];
			}

			// Transforming orientation and torsion angles into quaternions
			rotation_angle  = rotation_angle * 0.5f;
			float sin_angle = native_sin(rotation_angle);
			quatrot_left_q  = native_cos(rotation_angle);
			quatrot_left_x  = sin_angle*rotation_unitvec[0];
			quatrot_left_y  = sin_angle*rotation_unitvec[1];
			quatrot_left_z  = sin_angle*rotation_unitvec[2];

			// Performing rotation
			if ((rotation_list_element & RLIST_GENROT_MASK) != 0)	// If general rotation,
										// two rotations should be performed
										// (multiplying the quaternions)
			{
				// Calculating quatrot_left*ref_orientation_quats_const,
				// which means that reference orientation rotation is the first
				quatrot_temp_q = quatrot_left_q;
				quatrot_temp_x = quatrot_left_x;
				quatrot_temp_y = quatrot_left_y;
				quatrot_temp_z = quatrot_left_z;

				quatrot_left_q = quatrot_temp_q*kerconst_conform->ref_orientation_quats_const[4*(*run_id)]-
						 quatrot_temp_x*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+1]-
						 quatrot_temp_y*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+2]-
						 quatrot_temp_z*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+3];
				quatrot_left_x = quatrot_temp_q*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+1]+
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)]*quatrot_temp_x+
						 quatrot_temp_y*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+3]-
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)+2]*quatrot_temp_z;
				quatrot_left_y = quatrot_temp_q*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+2]+
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)]*quatrot_temp_y+
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)+1]*quatrot_temp_z-
						 quatrot_temp_x*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+3];
				quatrot_left_z = quatrot_temp_q*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+3]+
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)]*quatrot_temp_z+
						 quatrot_temp_x*kerconst_conform->ref_orientation_quats_const[4*(*run_id)+2]-
						 kerconst_conform->ref_orientation_quats_const[4*(*run_id)+1]*quatrot_temp_y;
			}

			quatrot_temp_q = 0 -
					 quatrot_left_x*atom_to_rotate [0] -
					 quatrot_left_y*atom_to_rotate [1] -
					 quatrot_left_z*atom_to_rotate [2];
			quatrot_temp_x = quatrot_left_q*atom_to_rotate [0] +
					 quatrot_left_y*atom_to_rotate [2] -
					 quatrot_left_z*atom_to_rotate [1];
			quatrot_temp_y = quatrot_left_q*atom_to_rotate [1] -
					 quatrot_left_x*atom_to_rotate [2] +
					 quatrot_left_z*atom_to_rotate [0];
			quatrot_temp_z = quatrot_left_q*atom_to_rotate [2] +
					 quatrot_left_x*atom_to_rotate [1] -
					 quatrot_left_y*atom_to_rotate [0];

			atom_to_rotate [0] = 0 -
					  quatrot_temp_q*quatrot_left_x +
					  quatrot_temp_x*quatrot_left_q -
					  quatrot_temp_y*quatrot_left_z +
					  quatrot_temp_z*quatrot_left_y;
			atom_to_rotate [1] = 0 -
					  quatrot_temp_q*quatrot_left_y +
					  quatrot_temp_x*quatrot_left_z +
					  quatrot_temp_y*quatrot_left_q -
					  quatrot_temp_z*quatrot_left_x;
			atom_to_rotate [2] = 0 -
					  quatrot_temp_q*quatrot_left_z -
					  quatrot_temp_x*quatrot_left_y +
					  quatrot_temp_y*quatrot_left_x +
					  quatrot_temp_z*quatrot_left_q;

			// Performing final movement and storing values
			calc_coords_x[atom_id] = atom_to_rotate [0] + rotation_movingvec[0];
			calc_coords_y[atom_id] = atom_to_rotate [1] + rotation_movingvec[1];
			calc_coords_z[atom_id] = atom_to_rotate [2] + rotation_movingvec[2];

		} // End if-statement not dummy rotation

		barrier(CLK_LOCAL_MEM_FENCE);

	} // End rotation_counter for-loop

	// ================================================
	// CALCULATING INTERMOLECULAR GRADIENTS
	// ================================================
	for (uint atom_id = get_local_id(0);
	          atom_id < dockpars_num_of_atoms;
	          atom_id+= NUM_OF_THREADS_PER_BLOCK)
	{
		uint atom_typeid = kerconst_interintra->atom_types_const[atom_id];
		float x = calc_coords_x[atom_id];
		float y = calc_coords_y[atom_id];
		float z = calc_coords_z[atom_id];
		float q = kerconst_interintra->atom_charges_const[atom_id];

		if ((x < 0) || (y < 0) || (z < 0) || (x >= dockpars_gridsize_x-1)
				                  || (y >= dockpars_gridsize_y-1)
						  || (z >= dockpars_gridsize_z-1)){
partial_energies[get_local_id(0)] += 16777216.0f; //100000.0f;
	
#if defined (DEBUG_ENERGY_KERNEL)
partial_interE[get_local_id(0)] += 16777216.0f;
#endif
			
			// Setting gradients (forces) penalties.
			// These are valid as long as they are high
			gradient_inter_x[atom_id] += 16777216.0f;
			gradient_inter_y[atom_id] += 16777216.0f;
			gradient_inter_z[atom_id] += 16777216.0f;
		}
		else
		{
			// Getting coordinates
			int x_low  = (int)floor(x); 
			int y_low  = (int)floor(y); 
			int z_low  = (int)floor(z);
			int x_high = (int)ceil(x); 
			int y_high = (int)ceil(y); 
			int z_high = (int)ceil(z);
			float dx = x - x_low; 
			float dy = y - y_low; 
			float dz = z - z_low;

			//printf("%-15s %-5u %-10.8f %-10.8f %-10.8f\n", "dx,dy,dz", atom_id, dx, dy, dz);

			// Calculating interpolation weights
			float weights[2][2][2];
			weights [0][0][0] = (1-dx)*(1-dy)*(1-dz);
			weights [1][0][0] = dx*(1-dy)*(1-dz);
			weights [0][1][0] = (1-dx)*dy*(1-dz);
			weights [1][1][0] = dx*dy*(1-dz);
			weights [0][0][1] = (1-dx)*(1-dy)*dz;
			weights [1][0][1] = dx*(1-dy)*dz;
			weights [0][1][1] = (1-dx)*dy*dz;
			weights [1][1][1] = dx*dy*dz;

			// Capturing affinity values
			uint ylow_times_g1  = y_low*g1;
			uint yhigh_times_g1 = y_high*g1;
		  	uint zlow_times_g2  = z_low*g2;
			uint zhigh_times_g2 = z_high*g2;

			// Grid offset
			uint offset_cube_000 = x_low  + ylow_times_g1  + zlow_times_g2;
			uint offset_cube_100 = x_high + ylow_times_g1  + zlow_times_g2;
			uint offset_cube_010 = x_low  + yhigh_times_g1 + zlow_times_g2;
			uint offset_cube_110 = x_high + yhigh_times_g1 + zlow_times_g2;
			uint offset_cube_001 = x_low  + ylow_times_g1  + zhigh_times_g2;
			uint offset_cube_101 = x_high + ylow_times_g1  + zhigh_times_g2;
			uint offset_cube_011 = x_low  + yhigh_times_g1 + zhigh_times_g2;
			uint offset_cube_111 = x_high + yhigh_times_g1 + zhigh_times_g2;

			uint mul_tmp = atom_typeid*g3;

			float cube[2][2][2];
			cube [0][0][0] = *(dockpars_fgrids + offset_cube_000 + mul_tmp);
			cube [1][0][0] = *(dockpars_fgrids + offset_cube_100 + mul_tmp);
			cube [0][1][0] = *(dockpars_fgrids + offset_cube_010 + mul_tmp);
		        cube [1][1][0] = *(dockpars_fgrids + offset_cube_110 + mul_tmp);
		        cube [0][0][1] = *(dockpars_fgrids + offset_cube_001 + mul_tmp);
			cube [1][0][1] = *(dockpars_fgrids + offset_cube_101 + mul_tmp);
                        cube [0][1][1] = *(dockpars_fgrids + offset_cube_011 + mul_tmp);
                        cube [1][1][1] = *(dockpars_fgrids + offset_cube_111 + mul_tmp);

// Calculating affinity energy
partial_energies[get_local_id(0)] += TRILININTERPOL(cube, weights);

#if defined (DEBUG_ENERGY_KERNEL)
partial_interE[get_local_id(0)] += TRILININTERPOL(cube, weights);
#endif

			// -------------------------------------------------------------------
			// Deltas dx, dy, dz are already normalized 
			// (by host/src/getparameters.cpp) in OCLaDock.
			// The correspondance between vertices in xyz axes is:
			// 0, 1, 2, 3, 4, 5, 6, 7  and  000, 100, 010, 001, 101, 110, 011, 111
			// -------------------------------------------------------------------
			/*
			    deltas: (x-x0)/(x1-x0), (y-y0...
			    vertices: (000, 100, 010, 001, 101, 110, 011, 111)        

				  Z
				  '
				  3 - - - - 6
				 /.        /|
				4 - - - - 7 |
				| '       | |
				| 0 - - - + 2 -- Y
				'/        |/
				1 - - - - 5
			       /
			      X
			*/

			// Intermediate values for vectors in x-direction
			float x10, x52, x43, x76;
			float vx_z0, vx_z1;

			// Intermediate values for vectors in y-direction
			float y20, y51, y63, y74;
			float vy_z0, vy_z1;

			// Intermediate values for vectors in z-direction
			float z30, z41, z62, z75;
			float vz_y0, vz_y1;

			// -------------------------------------------------------------------
			// Calculating gradients (forces) corresponding to 
			// "atype" intermolecular energy
			// Derived from autodockdev/maps.py
			// -------------------------------------------------------------------

			// Vector in x-direction
			x10 = cube [1][0][0] - cube [0][0][0]; // z = 0
			x52 = cube [1][1][0] - cube [0][1][0]; // z = 0
			x43 = cube [1][0][1] - cube [0][0][1]; // z = 1
			x76 = cube [1][1][1] - cube [0][1][1]; // z = 1
			vx_z0 = (1 - dy) * x10 + dy * x52;     // z = 0
			vx_z1 = (1 - dy) * x43 + dy * x76;     // z = 1
			gradient_inter_x[atom_id] += (1 - dz) * vx_z0 + dz * vx_z1;

			// Vector in y-direction
			y20 = cube[0][1][0] - cube [0][0][0];	// z = 0
			y51 = cube[1][1][0] - cube [1][0][0];	// z = 0
			y63 = cube[0][1][1] - cube [0][0][1];	// z = 1
			y74 = cube[1][1][1] - cube [1][0][1];	// z = 1
			vy_z0 = (1 - dx) * y20 + dx * y51;	// z = 0
			vy_z1 = (1 - dx) * y63 + dx * y74;	// z = 1
			gradient_inter_y[atom_id] += (1 - dz) * vy_z0 + dz * vy_z1;

			// Vectors in z-direction
			z30 = cube [0][0][1] - cube [0][0][0];	// y = 0
			z41 = cube [1][0][1] - cube [1][0][0];	// y = 0
			z62 = cube [0][1][1] - cube [0][1][0];	// y = 1 
			z75 = cube [1][1][1] - cube [1][1][0];	// y = 1
			vz_y0 = (1 - dx) * z30 + dx * z41;	// y = 0
			vz_y1 = (1 - dx) * z62 + dx * z75;	// y = 1
			gradient_inter_z[atom_id] += (1 - dy) * vz_y0 + dy * vz_y1;

			//printf("%-15s %-3u %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f\n", "atom aff", atom_id, vx_z0, vx_z1, vy_z0, vy_z1, vz_y0, vz_y1);

			// -------------------------------------------------------------------
			// Calculating gradients (forces) corresponding to 
			// "elec" intermolecular energy
			// Derived from autodockdev/maps.py
			// -------------------------------------------------------------------

			// Capturing electrostatic values
			atom_typeid = dockpars_num_of_atypes;

			mul_tmp = atom_typeid*g3;
			cube [0][0][0] = *(dockpars_fgrids + offset_cube_000 + mul_tmp);
			cube [1][0][0] = *(dockpars_fgrids + offset_cube_100 + mul_tmp);
      			cube [0][1][0] = *(dockpars_fgrids + offset_cube_010 + mul_tmp);
      			cube [1][1][0] = *(dockpars_fgrids + offset_cube_110 + mul_tmp);
		       	cube [0][0][1] = *(dockpars_fgrids + offset_cube_001 + mul_tmp);
		        cube [1][0][1] = *(dockpars_fgrids + offset_cube_101 + mul_tmp);
		        cube [0][1][1] = *(dockpars_fgrids + offset_cube_011 + mul_tmp);
		        cube [1][1][1] = *(dockpars_fgrids + offset_cube_111 + mul_tmp);

// Calculating electrostatic energy
partial_energies[get_local_id(0)] += q * TRILININTERPOL(cube, weights);

#if defined (DEBUG_ENERGY_KERNEL)
partial_interE[get_local_id(0)] += q * TRILININTERPOL(cube, weights);
#endif

			// Vector in x-direction
			x10 = cube [1][0][0] - cube [0][0][0]; // z = 0
			x52 = cube [1][1][0] - cube [0][1][0]; // z = 0
			x43 = cube [1][0][1] - cube [0][0][1]; // z = 1
			x76 = cube [1][1][1] - cube [0][1][1]; // z = 1
			vx_z0 = (1 - dy) * x10 + dy * x52;     // z = 0
			vx_z1 = (1 - dy) * x43 + dy * x76;     // z = 1
			gradient_inter_x[atom_id] += q * ((1 - dz) * vx_z0 + dz * vx_z1);

			// Vector in y-direction
			y20 = cube[0][1][0] - cube [0][0][0];	// z = 0
			y51 = cube[1][1][0] - cube [1][0][0];	// z = 0
			y63 = cube[0][1][1] - cube [0][0][1];	// z = 1
			y74 = cube[1][1][1] - cube [1][0][1];	// z = 1
			vy_z0 = (1 - dx) * y20 + dx * y51;	// z = 0
			vy_z1 = (1 - dx) * y63 + dx * y74;	// z = 1
			gradient_inter_y[atom_id] += q *((1 - dz) * vy_z0 + dz * vy_z1);

			// Vectors in z-direction
			z30 = cube [0][0][1] - cube [0][0][0];	// y = 0
			z41 = cube [1][0][1] - cube [1][0][0];	// y = 0
			z62 = cube [0][1][1] - cube [0][1][0];	// y = 1 
			z75 = cube [1][1][1] - cube [1][1][0];	// y = 1
			vz_y0 = (1 - dx) * z30 + dx * z41;	// y = 0
			vz_y1 = (1 - dx) * z62 + dx * z75;	// y = 1
			gradient_inter_z[atom_id] += q *((1 - dy) * vz_y0 + dy * vz_y1);

			//printf("%-15s %-3u %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f\n", "elec", atom_id, vx_z0, vx_z1, vy_z0, vy_z1, vz_y0, vz_y1);

			// -------------------------------------------------------------------
			// Calculating gradients (forces) corresponding to 
			// "dsol" intermolecular energy
			// Derived from autodockdev/maps.py
			// -------------------------------------------------------------------

			// Capturing desolvation values
			atom_typeid = dockpars_num_of_atypes+1;

			mul_tmp = atom_typeid*g3;
			cube [0][0][0] = *(dockpars_fgrids + offset_cube_000 + mul_tmp);
			cube [1][0][0] = *(dockpars_fgrids + offset_cube_100 + mul_tmp);
      			cube [0][1][0] = *(dockpars_fgrids + offset_cube_010 + mul_tmp);
      			cube [1][1][0] = *(dockpars_fgrids + offset_cube_110 + mul_tmp);
      			cube [0][0][1] = *(dockpars_fgrids + offset_cube_001 + mul_tmp);
      			cube [1][0][1] = *(dockpars_fgrids + offset_cube_101 + mul_tmp);
      			cube [0][1][1] = *(dockpars_fgrids + offset_cube_011 + mul_tmp);
      			cube [1][1][1] = *(dockpars_fgrids + offset_cube_111 + mul_tmp);

// Calculating desolvation energy
partial_energies[get_local_id(0)] += fabs(q) * TRILININTERPOL(cube, weights);

#if defined (DEBUG_ENERGY_KERNEL)
partial_interE[get_local_id(0)] += fabs(q) * TRILININTERPOL(cube, weights);
#endif

			// Vector in x-direction
			x10 = cube [1][0][0] - cube [0][0][0]; // z = 0
			x52 = cube [1][1][0] - cube [0][1][0]; // z = 0
			x43 = cube [1][0][1] - cube [0][0][1]; // z = 1
			x76 = cube [1][1][1] - cube [0][1][1]; // z = 1
			vx_z0 = (1 - dy) * x10 + dy * x52;     // z = 0
			vx_z1 = (1 - dy) * x43 + dy * x76;     // z = 1
			gradient_inter_x[atom_id] += fabs(q) * ((1 - dz) * vx_z0 + dz * vx_z1);

			// Vector in y-direction
			y20 = cube[0][1][0] - cube [0][0][0];	// z = 0
			y51 = cube[1][1][0] - cube [1][0][0];	// z = 0
			y63 = cube[0][1][1] - cube [0][0][1];	// z = 1
			y74 = cube[1][1][1] - cube [1][0][1];	// z = 1
			vy_z0 = (1 - dx) * y20 + dx * y51;	// z = 0
			vy_z1 = (1 - dx) * y63 + dx * y74;	// z = 1
			gradient_inter_y[atom_id] += fabs(q) *((1 - dz) * vy_z0 + dz * vy_z1);

			// Vectors in z-direction
			z30 = cube [0][0][1] - cube [0][0][0];	// y = 0
			z41 = cube [1][0][1] - cube [1][0][0];	// y = 0
			z62 = cube [0][1][1] - cube [0][1][0];	// y = 1 
			z75 = cube [1][1][1] - cube [1][1][0];	// y = 1
			vz_y0 = (1 - dx) * z30 + dx * z41;	// y = 0
			vz_y1 = (1 - dx) * z62 + dx * z75;	// y = 1
			gradient_inter_z[atom_id] += fabs(q) *((1 - dy) * vz_y0 + dy * vz_y1);

			//printf("%-15s %-3u %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f %-10.8f\n", "desol", atom_id, vx_z0, vx_z1, vy_z0, vy_z1, vz_y0, vz_y1);
			// -------------------------------------------------------------------
		}

	} // End atom_id for-loop (INTERMOLECULAR ENERGY)


#if defined (DEBUG_ENERGY_KERNEL)
barrier(CLK_LOCAL_MEM_FENCE);

if (get_local_id(0) == 0)
{
	float energy_interE = partial_interE[0];

	for (uint contributor_counter=1;
	          contributor_counter<NUM_OF_THREADS_PER_BLOCK;
	          contributor_counter++)
	{
		energy_interE += partial_interE[contributor_counter];
	}
	partial_interE[0] = energy_interE;
	//printf("%-20s %-10.8f\n", "energy_interE: ", energy_interE);
}

barrier(CLK_LOCAL_MEM_FENCE);
#endif


	// Inter- and intra-molecular energy calculation
	// are independent from each other, so NO barrier is needed here.
  	// As these two require different operations,
	// they can be executed only sequentially on the GPU.

	// ================================================
	// CALCULATING INTRAMOLECULAR GRADIENTS
	// ================================================
	for (uint contributor_counter = get_local_id(0);
	          contributor_counter < dockpars_num_of_intraE_contributors;
	          contributor_counter+= NUM_OF_THREADS_PER_BLOCK)
	{
		// Storing in a private variable 
		// the gradient contribution of each contributing atomic pair
		float priv_gradient_per_intracontributor= 0.0f;

		// Getting atom IDs
		uint atom1_id = kerconst_intracontrib->intraE_contributors_const[3*contributor_counter];
		uint atom2_id = kerconst_intracontrib->intraE_contributors_const[3*contributor_counter+1];
	
		/*
		printf ("%-5u %-5u %-5u\n", contributor_counter, atom1_id, atom2_id);
		*/
		
		// Calculating vector components of vector going
		// from first atom's to second atom's coordinates
		float subx = calc_coords_x[atom1_id] - calc_coords_x[atom2_id];
		float suby = calc_coords_y[atom1_id] - calc_coords_y[atom2_id];
		float subz = calc_coords_z[atom1_id] - calc_coords_z[atom2_id];

		// Calculating atomic distance
		float dist = native_sqrt(subx*subx + suby*suby + subz*subz);
		float atomic_distance = dist*dockpars_grid_spacing;

		// Getting type IDs
		uint atom1_typeid = kerconst_interintra->atom_types_const[atom1_id];
		uint atom2_typeid = kerconst_interintra->atom_types_const[atom2_id];

		uint atom1_type_vdw_hb = kerconst_intra->atom1_types_reqm_const [atom1_typeid];
	     	uint atom2_type_vdw_hb = kerconst_intra->atom2_types_reqm_const [atom2_typeid];
		//printf ("%-5u %-5u %-5u\n", contributor_counter, atom1_id, atom2_id);

		// Getting optimum pair distance (opt_distance) from reqm and reqm_hbond
		// reqm: equilibrium internuclear separation 
		//       (sum of the vdW radii of two like atoms (A)) in the case of vdW
		// reqm_hbond: equilibrium internuclear separation
		//  	 (sum of the vdW radii of two like atoms (A)) in the case of hbond 
		float opt_distance;

		if (kerconst_intracontrib->intraE_contributors_const[3*contributor_counter+2] == 1)	//H-bond
		{
			opt_distance = kerconst_intra->reqm_hbond_const [atom1_type_vdw_hb] + kerconst_intra->reqm_hbond_const [atom2_type_vdw_hb];
		}
		else	//van der Waals
		{
			opt_distance = 0.5f*(kerconst_intra->reqm_const [atom1_type_vdw_hb] + kerconst_intra->reqm_const [atom2_type_vdw_hb]);
		}

		// Getting smoothed distance
		// smoothed_distance = function(atomic_distance, opt_distance)
		float smoothed_distance;
		float delta_distance = 0.5f*dockpars_smooth;

		if (atomic_distance <= (opt_distance - delta_distance)) {
			smoothed_distance = atomic_distance + delta_distance;
		}
		else if (atomic_distance < (opt_distance + delta_distance)) {
			smoothed_distance = opt_distance;
		}
		else { // else if (atomic_distance >= (opt_distance + delta_distance))
			smoothed_distance = atomic_distance - delta_distance;
		}

		// Calculating gradient contributions
		// Cuttoff1: internuclear-distance at 8A only for vdw and hbond.
		if (atomic_distance < 8.0f)
		{
			// Calculating van der Waals / hydrogen bond term
partial_energies[get_local_id(0)] += native_divide(kerconst_intra->VWpars_AC_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,12));

#if defined (DEBUG_ENERGY_KERNEL)
partial_intraE[get_local_id(0)] += native_divide(kerconst_intra->VWpars_AC_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,12));
#endif

			priv_gradient_per_intracontributor += native_divide (-12*kerconst_intra->VWpars_AC_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],
									     native_powr(smoothed_distance/*atomic_distance*/, 13)
									    );

			if (kerconst_intracontrib->intraE_contributors_const[3*contributor_counter+2] == 1) {	//H-bond
partial_energies[get_local_id(0)] -= native_divide(kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,10));

#if defined (DEBUG_ENERGY_KERNEL)
partial_intraE[get_local_id(0)] -= native_divide(kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,10));
#endif

				priv_gradient_per_intracontributor += native_divide (10*kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],
										     native_powr(smoothed_distance/*atomic_distance*/, 11)
										    );
			}
			else {	//van der Waals
partial_energies[get_local_id(0)] -= native_divide(kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,6));

#if defined (DEBUG_ENERGY_KERNEL)
partial_intraE[get_local_id(0)] -= native_divide(kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],native_powr(smoothed_distance/*atomic_distance*/,6));
#endif

				priv_gradient_per_intracontributor += native_divide (6*kerconst_intra->VWpars_BD_const[atom1_typeid * dockpars_num_of_atypes+atom2_typeid],
										     native_powr(smoothed_distance/*atomic_distance*/, 7)
										    );
			}
		} // if cuttoff1 - internuclear-distance at 8A	

		// Calculating energy contributions
		// Cuttoff2: internuclear-distance at 20.48A only for el and sol.
		if (atomic_distance < 20.48f)
		{
			// Calculating electrostatic term
partial_energies[get_local_id(0)] += native_divide (
	                                     dockpars_coeff_elec * kerconst_interintra->atom_charges_const[atom1_id] * kerconst_interintra->atom_charges_const[atom2_id],
	                                     atomic_distance * (DIEL_A + native_divide(DIEL_B,(1.0f + DIEL_K*native_exp(-DIEL_B_TIMES_H*atomic_distance))))
	                                           );

#if defined (DEBUG_ENERGY_KERNEL)
partial_intraE[get_local_id(0)] += native_divide (
                                             dockpars_coeff_elec * kerconst_interintra->atom_charges_const[atom1_id] * kerconst_interintra->atom_charges_const[atom2_id],
                                             atomic_distance * (DIEL_A + native_divide(DIEL_B,(1.0f + DIEL_K*native_exp(-DIEL_B_TIMES_H*atomic_distance))))
                                                 );
#endif


			// http://www.wolframalpha.com/input/?i=1%2F(x*(A%2B(B%2F(1%2BK*exp(-h*B*x)))))
			float upper = DIEL_A*native_powr(native_exp(DIEL_B_TIMES_H*atomic_distance) + DIEL_K, 2) + (DIEL_B)*native_exp(DIEL_B_TIMES_H*atomic_distance)*(DIEL_B_TIMES_H_TIMES_K*atomic_distance + native_exp(DIEL_B_TIMES_H*atomic_distance) + DIEL_K);
		
			float lower = native_powr(atomic_distance, 2) * native_powr(DIEL_A * (native_exp(DIEL_B_TIMES_H*atomic_distance) + DIEL_K) + DIEL_B * native_exp(DIEL_B_TIMES_H*atomic_distance), 2);

	       		priv_gradient_per_intracontributor +=  -dockpars_coeff_elec * kerconst_interintra->atom_charges_const[atom1_id] * kerconst_interintra->atom_charges_const[atom2_id] * native_divide (upper, lower);

			// Calculating desolvation term
// 1/25.92 = 0.038580246913580245
partial_energies[get_local_id(0)] += ((kerconst_intra->dspars_S_const[atom1_typeid] +
				       dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom1_id]))*kerconst_intra->dspars_V_const[atom2_typeid] +
			               (kerconst_intra->dspars_S_const[atom2_typeid] +
				       dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom2_id]))*kerconst_intra->dspars_V_const[atom1_typeid]) *
			               dockpars_coeff_desolv*native_exp(-0.03858025f*native_powr(atomic_distance, 2));

#if defined (DEBUG_ENERGY_KERNEL)
partial_intraE[get_local_id(0)] += ((kerconst_intra->dspars_S_const[atom1_typeid] +
				       dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom1_id]))*kerconst_intra->dspars_V_const[atom2_typeid] +
			               (kerconst_intra->dspars_S_const[atom2_typeid] +
				       dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom2_id]))*kerconst_intra->dspars_V_const[atom1_typeid]) *
			               dockpars_coeff_desolv*native_exp(-0.03858025f*native_powr(atomic_distance, 2));
#endif

			priv_gradient_per_intracontributor += (
									       (kerconst_intra->dspars_S_const[atom1_typeid] + dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom1_id])) * kerconst_intra->dspars_V_const[atom2_typeid] +
								               (kerconst_intra->dspars_S_const[atom2_typeid] + dockpars_qasp*fabs(kerconst_interintra->atom_charges_const[atom2_id])) * kerconst_intra->dspars_V_const[atom1_typeid]
									      ) *
						               			dockpars_coeff_desolv * /*-0.07716049382716049*/ -0.077160f * atomic_distance * native_exp(/*-0.038580246913580245*/ -0.038580f *native_powr(atomic_distance, 2));
		} // if cuttoff2 - internuclear-distance at 20.48A

		// Decomposing "priv_gradient_per_intracontributor" 
		// into the contribution of each atom of the pair.
		// Distances in Angstroms of vector that goes from 
		// "atom1_id"-to-"atom2_id", therefore - subx, - suby, and - subz are used
		float subx_div_dist = native_divide(-subx, dist);
		float suby_div_dist = native_divide(-suby, dist);
		float subz_div_dist = native_divide(-subz, dist);

		float priv_intra_gradient_x = priv_gradient_per_intracontributor * subx_div_dist;
		float priv_intra_gradient_y = priv_gradient_per_intracontributor * suby_div_dist;
		float priv_intra_gradient_z = priv_gradient_per_intracontributor * subz_div_dist;
		
		// Calculating gradients in xyz components.
		// Gradients for both atoms in a single contributor pair
		// have the same magnitude, but opposite directions
		atomicSub_g_f(&gradient_intra_x[atom1_id], priv_intra_gradient_x);
		atomicSub_g_f(&gradient_intra_y[atom1_id], priv_intra_gradient_y);
		atomicSub_g_f(&gradient_intra_z[atom1_id], priv_intra_gradient_z);

		atomicAdd_g_f(&gradient_intra_x[atom2_id], priv_intra_gradient_x);
		atomicAdd_g_f(&gradient_intra_y[atom2_id], priv_intra_gradient_y);
		atomicAdd_g_f(&gradient_intra_z[atom2_id], priv_intra_gradient_z);
	} // End contributor_counter for-loop (INTRAMOLECULAR ENERGY)

barrier(CLK_LOCAL_MEM_FENCE);

if (get_local_id(0) == 0)
{
	*energy = partial_energies[0];

	for (uint contributor_counter=1;
	          contributor_counter<NUM_OF_THREADS_PER_BLOCK;
	          contributor_counter++)
	{
		*energy += partial_energies[contributor_counter];
	}
}

barrier(CLK_LOCAL_MEM_FENCE);

#if defined (DEBUG_ENERGY_KERNEL)
if (get_local_id(0) == 0)
{
	float energy_intraE = partial_intraE[0];
	
	for (uint contributor_counter=1;
	          contributor_counter<NUM_OF_THREADS_PER_BLOCK;
	          contributor_counter++)
	{
		energy_intraE += partial_intraE[contributor_counter];
	}
	partial_intraE[0] = energy_intraE;
	//printf("%-20s %-10.8f\n", "energy_intraE: ", energy_intraE);
}
barrier(CLK_LOCAL_MEM_FENCE);
#endif
	
	// Commented to remove unnecessary local storage which was
	// required by gradient_per_intracontributor[MAX_INTRAE_CONTRIBUTORS]
	/*
	barrier(CLK_LOCAL_MEM_FENCE);

	// Accumulating gradients from "gradient_per_intracontributor" for each each
	if (get_local_id(0) == 0) {
		for (uint contributor_counter = 0;
			  contributor_counter < dockpars_num_of_intraE_contributors;
			  contributor_counter ++) {

			// Getting atom IDs
			uint atom1_id = kerconst_intracontrib->intraE_contributors_const[3*contributor_counter];
			uint atom2_id = kerconst_intracontrib->intraE_contributors_const[3*contributor_counter+1];

			// Calculating xyz distances in Angstroms of vector
			// that goes from "atom1_id"-to-"atom2_id"
			float subx = (calc_coords_x[atom2_id] - calc_coords_x[atom1_id]);
			float suby = (calc_coords_y[atom2_id] - calc_coords_y[atom1_id]);
			float subz = (calc_coords_z[atom2_id] - calc_coords_z[atom1_id]);
			float dist = native_sqrt(subx*subx + suby*suby + subz*subz);

			float subx_div_dist = native_divide(subx, dist);
			float suby_div_dist = native_divide(suby, dist);
			float subz_div_dist = native_divide(subz, dist);

			// Calculating gradients in xyz components.
			// Gradients for both atoms in a single contributor pair
			// have the same magnitude, but opposite directions
			gradient_intra_x[atom1_id] -= gradient_per_intracontributor[contributor_counter] * subx_div_dist;
			gradient_intra_y[atom1_id] -= gradient_per_intracontributor[contributor_counter] * suby_div_dist;
			gradient_intra_z[atom1_id] -= gradient_per_intracontributor[contributor_counter] * subz_div_dist;

			gradient_intra_x[atom2_id] += gradient_per_intracontributor[contributor_counter] * subx_div_dist;
			gradient_intra_y[atom2_id] += gradient_per_intracontributor[contributor_counter] * suby_div_dist;
			gradient_intra_z[atom2_id] += gradient_per_intracontributor[contributor_counter] * subz_div_dist;

			//printf("%-20s %-10u %-5u %-5u %-10.8f\n", "grad_intracontrib", contributor_counter, atom1_id, atom2_id, gradient_per_intracontributor[contributor_counter]);
		}
	}
	*/	

	barrier(CLK_LOCAL_MEM_FENCE);




	// Accumulating inter- and intramolecular gradients
	for (uint atom_cnt = get_local_id(0);
		  atom_cnt < dockpars_num_of_atoms;
		  atom_cnt+= NUM_OF_THREADS_PER_BLOCK) {

		// Grid gradients were calculated in the grid space,
		// so they have to be put back in Angstrom.

		// Intramolecular gradients were already in Angstrom,
		// so no scaling for them is required.
		gradient_inter_x[atom_cnt] = native_divide(gradient_inter_x[atom_cnt], dockpars_grid_spacing);
		gradient_inter_y[atom_cnt] = native_divide(gradient_inter_y[atom_cnt], dockpars_grid_spacing);
		gradient_inter_z[atom_cnt] = native_divide(gradient_inter_z[atom_cnt], dockpars_grid_spacing);

		#if defined (PRINT_GRAD_ROTATION_GENES)
		if (atom_cnt == 0) {
			printf("\n%s\n", "----------------------------------------------------------");
			printf("%s\n", "Gradients: inter and intra");
			printf("%10s %13s %13s %13s %5s %13s %13s %13s\n", "atom_id", "grad_intER.x", "grad_intER.y", "grad_intER.z", "|", "grad_intRA.x", "grad_intRA.y", "grad_intRA.z");
		}
		printf("%10u %13.6f %13.6f %13.6f %5s %13.6f %13.6f %13.6f\n", atom_cnt, gradient_inter_x[atom_cnt], gradient_inter_y[atom_cnt], gradient_inter_z[atom_cnt], "|", gradient_intra_x[atom_cnt], gradient_intra_y[atom_cnt], gradient_intra_z[atom_cnt]);
		#endif

		// Re-using "gradient_inter_*" for total gradient (inter+intra)
		gradient_inter_x[atom_cnt] += gradient_intra_x[atom_cnt];
		gradient_inter_y[atom_cnt] += gradient_intra_y[atom_cnt];
		gradient_inter_z[atom_cnt] += gradient_intra_z[atom_cnt];

		//printf("%-15s %-5u %-10.8f %-10.8f %-10.8f\n", "grad_grid", atom_cnt, gradient_inter_x[atom_cnt], gradient_inter_y[atom_cnt], gradient_inter_z[atom_cnt]);
		//printf("%-15s %-5u %-10.8f %-10.8f %-10.8f\n", "grad_intra", atom_cnt, gradient_intra_x[atom_cnt], gradient_intra_y[atom_cnt], gradient_intra_z[atom_cnt]);
		//printf("%-15s %-5u %-10.8f %-10.8f %-10.8f\n", "calc_coords", atom_cnt, calc_coords_x[atom_cnt], calc_coords_y[atom_cnt], calc_coords_z[atom_cnt]);

		#if defined (PRINT_GRAD_ROTATION_GENES)
		if (atom_cnt == 0) {
			printf("\n%s\n", "----------------------------------------------------------");
			printf("%s\n", "Gradients: total = inter + intra");
			printf("%10s %13s %13s %13s\n", "atom_id", "grad.x", "grad.y", "grad.z");
		}
		printf("%10u %13.6f %13.6f %13.6f \n", atom_cnt, gradient_inter_x[atom_cnt], gradient_inter_y[atom_cnt], gradient_inter_z[atom_cnt]);
		#endif
	}

	barrier(CLK_LOCAL_MEM_FENCE);



	// ------------------------------------------
	// Obtaining translation-related gradients
	// ------------------------------------------
	if (get_local_id(0) == 0) {
		for (uint lig_atom_id = 0;
			  lig_atom_id<dockpars_num_of_atoms;
			  lig_atom_id++) {

			// Re-using "gradient_inter_*" for total gradient (inter+intra)
			gradient_genotype[0] += gradient_inter_x[lig_atom_id]; // gradient for gene 0: gene x
			gradient_genotype[1] += gradient_inter_y[lig_atom_id]; // gradient for gene 1: gene y
			gradient_genotype[2] += gradient_inter_z[lig_atom_id]; // gradient for gene 2: gene z
		}

		// Scaling gradient for translational genes as 
		// their corresponding gradients were calculated in the space 
		// where these genes are in Angstrom,
		// but OCLaDock translational genes are within in grids
		gradient_genotype[0] *= dockpars_grid_spacing;
		gradient_genotype[1] *= dockpars_grid_spacing;
		gradient_genotype[2] *= dockpars_grid_spacing;

		#if defined (PRINT_GRAD_TRANSLATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("gradient_x:%f\n", gradient_genotype [0]);
		printf("gradient_y:%f\n", gradient_genotype [1]);
		printf("gradient_z:%f\n", gradient_genotype [2]);
		#endif
	}

	// ------------------------------------------
	// Obtaining rotation-related gradients
	// ------------------------------------------ 
				
	// Transform gradients_inter_{x|y|z} 
	// into local_gradients[i] (with four quaternion genes)
	// Derived from autodockdev/motions.py/forces_to_delta_genes()

	// Transform local_gradients[i] (with four quaternion genes)
	// into local_gradients[i] (with three Shoemake genes)
	// Derived from autodockdev/motions.py/_get_cube3_gradient()
	// ------------------------------------------
	if (get_local_id(0) == 1) {

		float3 torque_rot;
		torque_rot.x = 0.0f;
		torque_rot.y = 0.0f;
		torque_rot.z = 0.0f;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-20s %-10.6f %-10.6f %-10.6f\n", "initial torque: ", torque_rot.x, torque_rot.y, torque_rot.z);
		#endif

		// Declaring a variable to hold the center of rotation 
		// In getparameters.cpp, it indicates 
		// translation genes are in grid spacing (instead of Angstroms)
		float3 about;
		about.x = genotype[0];
		about.y = genotype[1];
		about.z = genotype[2];
	
		// Temporal variable to calculate translation differences.
		// They are converted back to Angstroms here
		float3 r;
			
		for (uint lig_atom_id = 0;
			  lig_atom_id<dockpars_num_of_atoms;
			  lig_atom_id++) {
			r.x = (calc_coords_x[lig_atom_id] - about.x) * dockpars_grid_spacing; 
			r.y = (calc_coords_y[lig_atom_id] - about.y) * dockpars_grid_spacing;  
			r.z = (calc_coords_z[lig_atom_id] - about.z) * dockpars_grid_spacing; 

			// Re-using "gradient_inter_*" for total gradient (inter+intra)
			float3 force;
			force.x	= gradient_inter_x[lig_atom_id];
			force.y	= gradient_inter_y[lig_atom_id]; 
			force.z	= gradient_inter_z[lig_atom_id];

			torque_rot += cross(r, force);

			#if defined (PRINT_GRAD_ROTATION_GENES)
#if 0
			printf("%-20s %-10u\n", "contrib. of atom-id: ", lig_atom_id);
			printf("%-20s %-10.5f %-10.5f %-10.5f\n", "r             : ", r.x, r.y, r.z);
			printf("%-20s %-10.5f %-10.5f %-10.5f\n", "force         : ", force.x, force.y, force.z);
			printf("%-20s %-10.5f %-10.5f %-10.5f\n", "partial torque: ", torque_rot.x, torque_rot.y, torque_rot.z);
			printf("\n");
#endif
			// This printing is similar to autodockdevpy
			if (lig_atom_id == 0) {
				printf("\n%s\n", "----------------------------------------------------------");
				printf("%s\n", "Torque: atom-based accumulation of torque");
				printf("%10s %10s %10s %10s %5s %12s %12s %12s %5s %11s %11s %11s\n", "atom_id", "r.x", "r.y", "r.z", "|", "force.x", "force.y", "force.z", "|", "torque.x", "torque.y", "torque.z");
			}
			printf("%10u %10.6f %10.6f %10.6f %5s %12.6f %12.6f %12.6f %5s %12.6f %12.6f %12.6f\n", lig_atom_id, r.x, r.y, r.z, "|", force.x, force.y, force.z, "|", torque_rot.x, torque_rot.y, torque_rot.z);
			//printf("%-10u %-10.6f %-10.6f %-10.6f %-10.6f %-10.6f %-10.6f\n", lig_atom_id, r.x, r.y, r.z, force.x, force.y, force.z);
			#endif

		}





		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-20s %-10.6f %-10.6f %-10.6f\n", "final torque: ", torque_rot.x, torque_rot.y, torque_rot.z);
		#endif

		// Derived from rotation.py/axisangle_to_q()
		// genes[3:7] = rotation.axisangle_to_q(torque, rad)
		float torque_length = fast_length(torque_rot);
		
		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-20s %-10.6f\n", "torque length: ", torque_length);
		#endif

		/*
		// Infinitesimal rotation in radians
		const float infinitesimal_radian = 1E-5;
		*/

		// Finding the quaternion that performs
		// the infinitesimal rotation around torque axis
		float4 quat_torque;
		#if 0
		quat_torque.w = native_cos(HALF_INFINITESIMAL_RADIAN/*infinitesimal_radian*0.5f*/);
		quat_torque.x = fast_normalize(torque_rot).x * native_sin(HALF_INFINITESIMAL_RADIAN/*infinitesimal_radian*0.5f*/);
		quat_torque.y = fast_normalize(torque_rot).y * native_sin(HALF_INFINITESIMAL_RADIAN/*infinitesimal_radian*0.5f*/);
		quat_torque.z = fast_normalize(torque_rot).z * native_sin(HALF_INFINITESIMAL_RADIAN/*infinitesimal_radian*0.5f*/);
		#endif

		quat_torque.w = COS_HALF_INFINITESIMAL_RADIAN;
		quat_torque.x = fast_normalize(torque_rot).x * SIN_HALF_INFINITESIMAL_RADIAN; 
		quat_torque.y = fast_normalize(torque_rot).y * SIN_HALF_INFINITESIMAL_RADIAN;
		quat_torque.z = fast_normalize(torque_rot).z * SIN_HALF_INFINITESIMAL_RADIAN;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		#if 0		
		printf("fast_normalize(torque_rot).x:%-.6f\n", fast_normalize(torque_rot).x);
		printf("fast_normalize(torque_rot).y:%-.6f\n", fast_normalize(torque_rot).y);
		printf("fast_normalize(torque_rot).z:%-.6f\n", fast_normalize(torque_rot).z);
		#endif

		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-20s %-10.6f\n", "INFINITESIMAL_RADIAN: ", INFINITESIMAL_RADIAN);

		printf("%-20s %-10.6f %-10.6f %-10.6f %-10.6f\n", "quat_torque (w,x,y,z): ", quat_torque.w, quat_torque.x, quat_torque.y, quat_torque.z);
		#endif

		// Converting quaternion gradients into orientation gradients 
		// Derived from autodockdev/motion.py/_get_cube3_gradient

		// This is where we are in the orientation axis-angle space
		// Equivalent to "current_oclacube" in autodockdev/motions.py
		// TODO: Check very initial input orientation genes
		float current_phi, current_theta, current_rotangle;
		current_phi      = genotype[3]; // phi      (in sexagesimal (DEG) unbounded)
		current_theta    = genotype[4]; // theta    (in sexagesimal (DEG) unbounded)
		current_rotangle = genotype[5]; // rotangle (in sexagesimal (DEG) unbounded)

		map_priv_angle(&current_phi);	   // phi      (in DEG bounded within [0, 360])
		map_priv_angle(&current_theta);	   // theta    (in DEG bounded within [0, 360])
		map_priv_angle(&current_rotangle); // rotangle (in DEG bounded within [0, 360])

		current_phi      = current_phi      * DEG_TO_RAD; // phi      (in RAD)
		current_theta    = current_theta    * DEG_TO_RAD; // theta    (in RAD)
 		current_rotangle = current_rotangle * DEG_TO_RAD; // rotangle (in RAD)

		bool is_theta_gt_pi = (current_theta > PI_FLOAT) ? true: false;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f %-10.6f %-10.6f\n", "current_axisangle (1,2,3): ", current_phi, current_theta, current_rotangle);
		#endif		

		// This is where we are in quaternion space
		// current_q = oclacube_to_quaternion(angles)
		float4 current_q;

		// Axis of rotation
		float rotaxis_x = native_sin(current_theta) * native_cos(current_phi);
		float rotaxis_y = native_sin(current_theta) * native_sin(current_phi);
		float rotaxis_z = native_cos(current_theta);
		
		float ang;
		ang = current_rotangle * 0.5f;
		current_q.w = native_cos(ang); 
		current_q.x = rotaxis_x * native_sin(ang);
		current_q.y = rotaxis_y * native_sin(ang);
		current_q.z = rotaxis_z * native_sin(ang);

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f %-10.6f %-10.6f %-10.6f\n", "current_q (w,x,y,z): ", current_q.w, current_q.x, current_q.y, current_q.z);
		#endif

		// This is where we want to be in quaternion space
		float4 target_q;

		// target_q = rotation.q_mult(q, current_q)
		// Derived from autodockdev/rotation.py/q_mult()
		// In our terms means q_mult(quat_{w|x|y|z}, current_q{w|x|y|z})
		target_q.w = quat_torque.w*current_q.w - quat_torque.x*current_q.x - quat_torque.y*current_q.y - quat_torque.z*current_q.z;// w
		target_q.x = quat_torque.w*current_q.x + quat_torque.x*current_q.w + quat_torque.y*current_q.z - quat_torque.z*current_q.y;// x
		target_q.y = quat_torque.w*current_q.y + quat_torque.y*current_q.w + quat_torque.z*current_q.x - quat_torque.x*current_q.z;// y
		target_q.z = quat_torque.w*current_q.z + quat_torque.z*current_q.w + quat_torque.x*current_q.y - quat_torque.y*current_q.x;// z
		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f %-10.6f %-10.6f %-10.6f\n", "target_q (w,x,y,z): ", target_q.w, target_q.x, target_q.y, target_q.z);
		#endif

		// This is where we want to be in the orientation axis-angle space
		float target_phi, target_theta, target_rotangle;

		// target_oclacube = quaternion_to_oclacube(target_q, theta_larger_than_pi)
		// Derived from autodockdev/motions.py/quaternion_to_oclacube()
		// In our terms means quaternion_to_oclacube(target_q{w|x|y|z}, theta_larger_than_pi)

		ang = acos(target_q.w);
		target_rotangle = 2.0f * ang;

		float inv_sin_ang = native_recip(native_sin(ang));
		rotaxis_x = target_q.x * inv_sin_ang;
		rotaxis_y = target_q.y * inv_sin_ang;
		rotaxis_z = target_q.z * inv_sin_ang;

		target_theta = acos(rotaxis_z);

    		if (is_theta_gt_pi == false) {
		        target_phi   = fmod((atan2( rotaxis_y,  rotaxis_x) + PI_TIMES_2), PI_TIMES_2);
		}
		else {
		        target_phi   = fmod((atan2(-rotaxis_y, -rotaxis_x) + PI_TIMES_2), PI_TIMES_2);
		        target_theta = PI_TIMES_2 - target_theta;
		}

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f %-10.6f %-10.6f\n", "target_axisangle (1,2,3): ", target_phi, target_theta, target_rotangle);
		#endif
		
   		// The infinitesimal rotation will produce an infinitesimal displacement
    		// in shoemake space. This is to guarantee that the direction of
    		// the displacement in shoemake space is not distorted.
    		// The correct amount of displacement in shoemake space is obtained
		// by multiplying the infinitesimal displacement by shoemake_scaling:
		//float shoemake_scaling = native_divide(torque_length, INFINITESIMAL_RADIAN/*infinitesimal_radian*/);
		float orientation_scaling = torque_length * INV_INFINITESIMAL_RADIAN;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f\n", "orientation_scaling: ", orientation_scaling);
		#endif

		// Derivates in cube3
		float grad_phi, grad_theta, grad_rotangle;
		/*
		grad_phi      = orientation_scaling * (target_phi      - current_phi);
		grad_theta    = orientation_scaling * (target_theta    - current_theta);
		grad_rotangle = orientation_scaling * (target_rotangle - current_rotangle);
		*/
		grad_phi      = orientation_scaling * (fmod(target_phi 	 - current_phi 	    + PI_FLOAT, PI_TIMES_2) - PI_FLOAT);
		grad_theta    = orientation_scaling * (fmod(target_theta    - current_theta    + PI_FLOAT, PI_TIMES_2) - PI_FLOAT);
		grad_rotangle = orientation_scaling * (fmod(target_rotangle - current_rotangle + PI_FLOAT, PI_TIMES_2) - PI_FLOAT);

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s \n", "grad_axisangle (1,2,3) - before empirical scaling: ");
		printf("%-13s %-13s %-13s \n", "grad_phi", "grad_theta", "grad_rotangle");
		printf("%-13.6f %-13.6f %-13.6f\n", grad_phi, grad_theta, grad_rotangle);
		#endif
			
		// Corrections of derivatives
		// Constant arrays have 1000 elements.
		// Each array spans approximatedly from 0.0 to 2*PI.
		// The distance between each x-point (angle-delta) is 2*PI/1000.
		const float angle_delta = 0.00628353f;
		const float inv_angle_delta = 159.154943;
				
		// Correcting theta gradients interpolating 
		// values from correction look-up-tables
		// (X0,Y0) and (X1,Y1) are known points
		// How to find the Y value in the straight line between Y0 and Y1,
		// corresponding to a certain X?
		/*
			| dependence_on_theta_const
			| dependence_on_rotangle_const
			|
			|
			|                        Y1
			|
			|             Y=?
			|    Y0   
			|_________________________________ angle_const
			     X0  	X	 X1
		*/

		// Finding the index-position of "grad_delta" in the "angle_const" array
		//uint index_theta    = floor(native_divide(current_theta    - angle_const[0], angle_delta));
		//uint index_rotangle = floor(native_divide(current_rotangle - angle_const[0], angle_delta));
		uint index_theta    = floor((current_theta    - angle_const[0]) * inv_angle_delta);
		uint index_rotangle = floor((current_rotangle - angle_const[0]) * inv_angle_delta);

		// Interpolating theta values
		// X0 -> index - 1
		// X1 -> index + 1
		// Expresed as weighted average:
		// Y = [Y0 * ((X1 - X) / (X1-X0))] +  [Y1 * ((X - X0) / (X1-X0))]
		// Simplified for GPU (less terms):
		// Y = [Y0 * (X1 - X) + Y1 * (X - X0)] / (X1 - X0)
		// Taking advantage of constant:
		// Y = [Y0 * (X1 - X) + Y1 * (X - X0)] * inv_angle_delta

		float X0_theta, Y0_theta;
		float X1_theta, Y1_theta;
		float X_theta;
		float dependence_on_theta;  	//Y = dependence_on_theta
		X_theta = current_theta;

		// Using interpolation on out-of-bounds elements results in hang
		if (index_theta <= 0) {
			//printf("WARNING: index_theta: %u\n", index_theta);
			dependence_on_theta = dependence_on_theta_const[0];	//printf("%f\n",dependence_on_theta_const[0]);
		}
		else if (index_theta >= 999){
			//printf("WARNING: index_theta: %u\n", index_theta);
			dependence_on_theta = dependence_on_theta_const[999];	//printf("%f\n",dependence_on_theta_const[999]);
		}
		else {
			X0_theta = angle_const[index_theta];
			Y0_theta = dependence_on_theta_const[index_theta];
			X1_theta = angle_const[index_theta+1];
			Y1_theta = dependence_on_theta_const[index_theta+1];
		}
		dependence_on_theta = (Y0_theta * (X1_theta-X_theta) + Y1_theta * (X_theta-X0_theta)) * inv_angle_delta;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f\n", "dependence_on_theta: ", dependence_on_theta);
		#endif

		// Interpolating rotangle values
		float X0_rotangle, Y0_rotangle;
		float X1_rotangle, Y1_rotangle;
		float X_rotangle;
		float dependence_on_rotangle; 	//Y = dependence_on_rotangle
		X_rotangle = current_rotangle;

		// Using interpolation on previous and/or next elements results in hang
		if (index_rotangle <= 0) {
			//printf("WARNING: index_rotangle: %u\n", index_rotangle);
			dependence_on_rotangle = dependence_on_rotangle_const[0]; 	//printf("%f\n",dependence_on_rotangle_const[0]);
		}
		else if (index_rotangle >= 999){
			//printf("WARNING: index_rotangle: %u\n", index_rotangle);
			dependence_on_rotangle = dependence_on_rotangle_const[999];	//printf("%f\n",dependence_on_rotangle_const[999]);
		}
		else {
			X0_rotangle = angle_const[index_rotangle];
			Y0_rotangle = dependence_on_rotangle_const[index_rotangle];
			X1_rotangle = angle_const[index_rotangle+1];
			Y1_rotangle = dependence_on_rotangle_const[index_rotangle+1];
		}
		dependence_on_rotangle = (Y0_rotangle * (X1_rotangle-X_rotangle) + Y1_rotangle * (X_rotangle-X0_rotangle)) * inv_angle_delta;

		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s %-10.6f\n", "dependence_on_rotangle: ", dependence_on_rotangle);
		#endif

		// Setting gradient rotation-related genotypes in cube
		// Multiplicating by DEG_TO_RAD is to make it uniform to DEG (see torsion gradients)
		gradient_genotype[3] = native_divide(grad_phi, (dependence_on_theta * dependence_on_rotangle))  * DEG_TO_RAD;
		gradient_genotype[4] = native_divide(grad_theta, dependence_on_rotangle)			* DEG_TO_RAD; 
		gradient_genotype[5] = grad_rotangle                                                            * DEG_TO_RAD;
		#if defined (PRINT_GRAD_ROTATION_GENES)
		printf("\n%s\n", "----------------------------------------------------------");
		printf("%-30s \n", "grad_axisangle (1,2,3) - after empirical scaling: ");
		printf("%-13s %-13s %-13s \n", "grad_phi", "grad_theta", "grad_rotangle");
		printf("%-13.6f %-13.6f %-13.6f\n", gradient_genotype[3], gradient_genotype[4], gradient_genotype[5]);
		#endif
	}

	// ------------------------------------------
	// Obtaining torsion-related gradients
	// ------------------------------------------

	#if defined (ENABLE_PARALLEL_GRAD_TORSION)
	for (uint rotbond_id = get_local_id(0);
		  rotbond_id < dockpars_num_of_genes-6;
		  rotbond_id +=NUM_OF_THREADS_PER_BLOCK) {

		#if defined (PRINT_GRAD_TORSION_GENES)
		if (rotbond_id == 0) {
			printf("\n%s\n", "NOTE: torsion gradients are calculated by many work-items");
		}
		#endif
	#else
	if (get_local_id(0) == 2) {

		for (uint rotbond_id = 0;
			  rotbond_id < dockpars_num_of_genes-6;
			  rotbond_id ++) {
	#endif

			// Querying ids of atoms belonging to the rotatable bond in question
			int atom1_id = rotbonds_const[2*rotbond_id];
			int atom2_id = rotbonds_const[2*rotbond_id+1];

			float3 atomRef_coords;
			atomRef_coords.x = calc_coords_x[atom1_id];
			atomRef_coords.y = calc_coords_y[atom1_id];
			atomRef_coords.z = calc_coords_z[atom1_id];

			#if defined (PRINT_GRAD_TORSION_GENES)
			printf("\n%s\n", "----------------------------------------------------------");
			printf("%-5s %3u \n\t %-5s %3i \n\t %-5s %3i\n", "gene: ", (rotbond_id+6), "atom1: ", atom1_id, "atom2: ", atom2_id);
			#endif		

			float3 rotation_unitvec;
			/*
			rotation_unitvec.x = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id];
			rotation_unitvec.y = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id+1];
			rotation_unitvec.z = kerconst_conform->rotbonds_unit_vectors_const[3*rotbond_id+2];
			*/
			rotation_unitvec.x = calc_coords_x[atom2_id] - calc_coords_x[atom1_id];
			rotation_unitvec.y = calc_coords_y[atom2_id] - calc_coords_y[atom1_id];
			rotation_unitvec.z = calc_coords_z[atom2_id] - calc_coords_z[atom1_id];
			rotation_unitvec = fast_normalize(rotation_unitvec);

			#if defined (PRINT_GRAD_TORSION_GENES)
			printf("\n");
			printf("%-15s \n\t %-10.6f %-10.6f %-10.6f\n", "unitvec: ", rotation_unitvec.x, rotation_unitvec.y, rotation_unitvec.z);
			#endif	

			// Torque of torsions
			float3 torque_tor;
			torque_tor.x = 0.0f;
			torque_tor.y = 0.0f;
			torque_tor.z = 0.0f;

			// Iterating over each ligand atom that rotates 
			// if the bond in question rotates
			for (uint rotable_atom_cnt = 0;
				  rotable_atom_cnt<num_rotating_atoms_per_rotbond_const[rotbond_id];
				  rotable_atom_cnt++) {

				uint lig_atom_id = rotbonds_atoms_const[MAX_NUM_OF_ATOMS*rotbond_id + rotable_atom_cnt];

				// Calculating torque on point "A" 
				// (could be any other point "B" along the rotation axis)
				float3 atom_coords;
				atom_coords.x = calc_coords_x[lig_atom_id];
				atom_coords.y = calc_coords_y[lig_atom_id];
				atom_coords.z = calc_coords_z[lig_atom_id];

				// Temporal variable to calculate translation differences.
				// They are converted back to Angstroms here
				float3 r;
				r.x = (atom_coords.x - atomRef_coords.x) * dockpars_grid_spacing;
				r.y = (atom_coords.y - atomRef_coords.y) * dockpars_grid_spacing;
				r.z = (atom_coords.z - atomRef_coords.z) * dockpars_grid_spacing;

				// Re-using "gradient_inter_*" for total gradient (inter+intra)
				float3 atom_force;
				atom_force.x = gradient_inter_x[lig_atom_id]; 
				atom_force.y = gradient_inter_y[lig_atom_id];
				atom_force.z = gradient_inter_z[lig_atom_id];

				torque_tor += cross(r, atom_force);

				#if defined (PRINT_GRAD_TORSION_GENES)
				if (rotable_atom_cnt == 0) {
					printf("\n %-30s %3i\n", "contributor for gene : ", (rotbond_id+6));
				}
				//printf("%-15s %-10u\n", "rotable_atom_cnt: ", rotable_atom_cnt);
				//printf("%-15s %-10u\n", "atom_id: ", lig_atom_id);
				printf("\t %-15s %-10.6f %-10.6f %-10.6f \t %-15s %-10.6f %-10.6f %-10.6f\n", "atom_coords: ", atom_coords.x, atom_coords.y, atom_coords.z, "atom_force: ", atom_force.x, atom_force.y, atom_force.z);
				//printf("%-15s %-10.6f %-10.6f %-10.6f\n", "r: ", r.x, r.y, r.z);

				//printf("%-15s %-10.6f %-10.6f %-10.6f\n", "atom_force: ", atom_force.x, atom_force.y, atom_force.z);
				//printf("%-15s %-10.6f %-10.6f %-10.6f\n", "torque_tor: ", torque_tor.x, torque_tor.y, torque_tor.z);
				#endif

			}
			#if defined (PRINT_GRAD_TORSION_GENES)
			printf("\n");
			#endif

			// Projecting torque on rotation axis
			float torque_on_axis = dot(rotation_unitvec, torque_tor);

			// Assignment of gene-based gradient
			gradient_genotype[rotbond_id+6] = torque_on_axis * DEG_TO_RAD /*(M_PI / 180.0f)*/;

			#if defined (PRINT_GRAD_TORSION_GENES)
			printf("gradient_torsion [%u] :%f\n", rotbond_id+6, gradient_genotype [rotbond_id+6]);
			#endif
			
		} // End of iterations over rotatable bonds

	#if defined (ENABLE_PARALLEL_GRAD_TORSION)
	
	#else
	}
	#endif
	//----------------------------------

	barrier(CLK_LOCAL_MEM_FENCE);

	#if defined (CONVERT_INTO_ANGSTROM_RADIAN)
	for (uint gene_cnt = get_local_id(0);
		  gene_cnt < dockpars_num_of_genes;
		  gene_cnt+= NUM_OF_THREADS_PER_BLOCK) {

		if (gene_cnt > 2) {
			gradient_genotype[gene_cnt] *= SCFACTOR_ANGSTROM_RADIAN;
		}
	}
	barrier(CLK_LOCAL_MEM_FENCE);
	#endif
}