-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1813 lines (1406 loc) · 68.9 KB
/
main.cpp
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
/**********************************************
File : main.cpp
Author : Mingcheng Chen
Last Update : October 30th, 2013
***********************************************/
#include "lcs.h"
#include "lcsUtility.h"
#include "lcsUnitTest.h"
#include "lcsGeometry.h"
#include <ctime>
#include <cmath>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cuda_runtime.h>
#define MAX_THREADS_PER_SM 512
#define MAX_THREADS_PER_BLOCK 256
#define MAX_SHARED_MEMORY_PER_SM 49000//49152
#define WARP_SIZE 32
#define MAX_MULTIPLE 16
//#define TET_WALK_STAT
//#define GET_PATH
//#define GET_VEL
//#define BLOCK_STAT
extern "C" void TetrahedronBlockIntersection(double *vertexPositions, int *tetrahedralConnectivities, int *queryTetrahedron, int *queryBlock, bool *queryResult,
int numOfBlocksInY, int numOfBlocksInZ, double globalMinX, double globalMinY, double globalMinZ, double blockSize,
double epsilon, int numOfQueries, double marginRatio);
extern "C" void InitialCellLocation(double *vertexPositions, int *tetrahedralConnectivities, int *cellLocations, int xRes, int yRes, int zRes,
double minX, double minY, double minZ, double dx, double dy, double dz, double epsilon, int numOfCells);
extern "C" void InitializeConstantsForBlockedTracingKernelOfRK4(double *globalVertexPositions, int *globalTetrahedralConnectivities,
int *globalTetrahedralLinks, int *startOffsetInCell, int *startOffsetInPoint, double *vertexPositionsForBig,
double *startVelocitiesForBig, double *endVelocitiesForBig, int *blockedLocalConnectivities, int *blockedLocalLinks,
int *blockedGlobalCellIDs, int *activeBlockList, // Map active block ID to interesting block ID
int *blockOfGroups, int *offsetInBlocks, int *stage, double *lastPosition,
double *k, double *nx,
double *pastTimes, double *placesOfInterest, int *startOffsetInParticle, int *blockedActiveParticleIDList,
int *cellLocations, int *exitCells, double hostTimeStep, double hostEpsilon
#ifdef TET_WALK_STAT
, int *numOfTetWalks
#endif
);
extern "C" void BlockedTracingOfRK4(double startTime, double endTime, double timeStep, double epsilon, int numOfActiveBlocks, int blockSize, int sharedMemorySize, int multiple);
extern "C" void GetNumOfGroupsForBlocks(int *startOffsetInParticles, int *numOfGroupsForBlocks, int numOfActiveBlocks, int groupSize);
extern "C" void AssignGroups(int *numOfGroupsForBlocks, // It should be the prefix sum now.
int *blockOfGroups, int *offsetInBlocks, int numOfActiveBlocks);
extern "C" void CollectActiveBlocks(int *activeParticles, int *exitCells, double *placesOfInterest, int *localTetIDs, int *blockLocations, int *interestingBlockMap,
int *startOffsetsInLocalIDMap, int *blocksOfTets, int *localIDsOfTets, int *interestingBlockMarks, int *activeBlocks,
int *activeBlockIndices, int *numOfActiveBlocks, // Initially 0
int mark, int numOfActiveParticles, //int numOfStages,
int numOfBlocksInX, int numOfBlocksInY, int numOfBlocksInZ, double globalMinX, double globalMinY, double globalMinZ,
double blockSize, double epsilon);
extern "C" void GetNumOfParticlesByStageInBlocks(int *numOfParticlesByStageInBlocks, int *particleOrders, int *stages, int *activeParticles,
int *blockLocations, int *activeBlockIndices, int numOfStages, int numOfActiveParticles);
extern "C" void CollectParticlesToBlocks(int *numOfParticlesByStageInBlocks, // Now it is a prefix sum array.
int *particleOrders,
int *stages,
int *activeParticles,
int *blockLocations,
int *activeBlockIndices,
int *blockedParticleList,
int numOfStages, int numOfActiveParticles);
extern "C" void CollectEveryKElement(int *input, int *output, int k, int length);
extern "C" int ExclusiveScanForInt(int *d_arr, int length);
extern "C" void InitializeScanArray(int *exitCells, int *scanArray, int length);
extern "C" void CollectActiveParticles(int *exitCells, int *scanArray, int *activeParticles, int length);
extern "C" void InitializeScanArray2(int *exitCells, int *oldActiveParticles, int *scanArray, int length);
extern "C" void CollectActiveParticles2(int *exitCells, int *oldActiveParticles, int *scanArray, int *newActiveParticles, int length);
extern "C" void BigBlockInitializationForPositions(double *globalVertexPositions, int *blockedGlobalPointIDs, int *startOffsetInPoint,
double *vertexPositionsForBig, int numOfInterestingBlocks);
extern "C" void BigBlockInitializationForVelocities(double *globalStartVelocities, double *globalEndVelocities, int *blockedGlobalPointIDs, int *startOffsetInPoint,
double *startVelocitiesForBig, double *endVelocitiesForBig, int numOfInterestingBlocks);
//const char *configurationFile = "RungeKutta4.conf";
//const char *configurationFile = "RungeKutta4ForTCPC.conf";
//const char *configurationFile = "RungeKutta4ForUpperVasc.conf";
//const char *configurationFile = "RungeKutta4ForAR2.conf";
//const char *configurationFile = "RungeKutta4ForDoubleGyre3D.conf";
const char *configurationFile = "RungeKutta4ForPatient96.conf";
const char *lastPositionFile = "lcsLastPositions.txt";
const char *FTLEFile = "lcsFTLEValues.vtk";
lcs::Configure *configure;
lcs::Frame **frames;
int numOfFrames;
int numOfTimePoints;
int *tetrahedralConnectivities, *tetrahedralLinks;
double *vertexPositions;
int globalNumOfCells, globalNumOfPoints;
double globalMinX, globalMaxX, globalMinY, globalMaxY, globalMinZ, globalMaxZ;
double blockSize;
int numOfBlocksInX, numOfBlocksInY, numOfBlocksInZ;
// For FTLE calculation
double *finalPositions;
// For tetrahedron-block intersection
int *xLeftBound, *xRightBound, *yLeftBound, *yRightBound, *zLeftBound, *zRightBound;
int numOfQueries;
int *queryTetrahedron, *queryBlock;
char *queryResults; // Whether certain tetrahedron intersects with certain block
// For blocks
int numOfBlocks, numOfInterestingBlocks;
lcs::BlockRecord **blocks;
int *startOffsetInCell, *startOffsetInPoint;
// For initial cell location
int *initialCellLocations;
// For tracing
lcs::ParticleRecord **particleRecords;
int *exitCells;
int numOfInitialActiveParticles;
// For shared memory
int maxSharedMemoryRequired;
// CUDA C variables
// error
cudaError_t err;
#ifdef TET_WALK_STAT
// Device memory for tetrahedron walk statistics
int *d_numOfTetWalks;
#endif
// Device memory for exclusive scan for int
int *d_exclusiveScanArrayForInt;
// Device memory for interesting block map
int *d_interestingBlockMap;
// Device memory for (tet, blk) to local tet ID map
int *d_startOffsetsInLocalIDMap;
int *d_blocksOfTets;
int *d_localIDsOfTets;
// Device memory for particle redistribution
int *d_numOfParticlesByStageInBlocks; // It depends on the maximum stage number of the integration method.
int *d_interestingBlockMarks;
int *d_particleOrders; // The local order number in (block, stage) group
int *d_blockLocations;
// Device memory for global geometry
int *d_tetrahedralConnectivities, *d_tetrahedralLinks;
double *d_vertexPositions;
int *d_queryTetrahedron, *d_queryBlock;
bool *d_queryResults;
// Device memory for cell locations of particles
int *d_cellLocations;
// Device memory for local geometry in blocks
int *d_localConnectivities, *d_localLinks;
int *d_globalCellIDs, *d_globalPointIDs;
int *d_startOffsetInCell, *d_startOffsetInPoint;
// Device memory for particle
int *d_activeBlockOfParticles;
int *d_localTetIDs;
int *d_exitCells;
int *d_activeParticles[2];
int currActiveParticleArray;
int *d_stages;
double *d_lastPositionForRK4;
double *d_kForRK4, *d_nxForRK4;
double *d_pastTimes;
double *d_placesOfInterest;
// Device memory for velocities
double *d_velocities[2];
// Device memory for big blocks
double *d_vertexPositionsForBig, *d_startVelocitiesForBig, *d_endVelocitiesForBig;
// Device memory for canFitInSharedMemory flags
//bool *d_canFitInSharedMemory;
// Device memory for active block list
int *d_activeBlocks;
int *d_activeBlockIndices;
int *d_numOfActiveBlocks;
// Device memory for tracing work groups distribution
int *d_numOfGroupsForBlocks;
int *d_blockOfGroups;
int *d_offsetInBlocks;
// Device memory for start offsets of particles in active blocks
int *d_startOffsetInParticles;
// Device memory for particles grouped in blocks
int *d_blockedActiveParticles;
int GetBlockID(int x, int y, int z) {
return (x * numOfBlocksInY + y) * numOfBlocksInZ + z;
}
void GetXYZFromBlockID(int blockID, int &x, int &y, int &z) {
z = blockID % numOfBlocksInZ;
blockID /= numOfBlocksInZ;
y = blockID % numOfBlocksInY;
x = blockID / numOfBlocksInY;
}
void GetXYZFromPosition(const lcs::Vector &position, int &x, int &y, int &z) {
x = (int)((position.GetX() - globalMinX) / blockSize);
y = (int)((position.GetY() - globalMinY) / blockSize);
z = (int)((position.GetZ() - globalMinZ) / blockSize);
}
void SystemTest() {
printf("sizeof(double) = %d\n", (int)sizeof(double));
printf("sizeof(float) = %d\n", (int)sizeof(float));
printf("sizeof(int) = %d\n", (int)sizeof(int));
printf("sizeof(int *) = %d\n", (int)sizeof(int *));
printf("sizeof(char) = %d\n", (int)sizeof(char));
printf("\n");
}
void ReadConfFile() {
configure = new lcs::Configure(configurationFile);
if (configure->GetIntegration() == "FE") lcs::ParticleRecord::SetDataType(lcs::ParticleRecord::FE);
if (configure->GetIntegration() == "RK4") lcs::ParticleRecord::SetDataType(lcs::ParticleRecord::RK4);
if (configure->GetIntegration() == "RK45") lcs::ParticleRecord::SetDataType(lcs::ParticleRecord::RK45);
printf("\n");
}
void LoadFrames() {
numOfFrames = configure->GetNumOfFrames();
frames = new lcs::Frame *[numOfFrames];
for (int i = 0; i < numOfFrames; i++) {
double timePoint = configure->GetTimePoints()[i];
std::string veloFileName = configure->GetDataFilePrefix() + "." + configure->GetDataFileIndices()[i] + "." + configure->GetDataFileSuffix();
printf("Loading frame %d (file = %s) ... ", i, veloFileName.c_str());
frames[i] = new lcs::Frame(timePoint, veloFileName.c_str());
//frames[i] = new lcs::Frame(timePoint, "patient2/geometry.txt", veloFileName.c_str());
if (i) frames[i]->GetTetrahedralGrid()->CleanAllButVelocities();
printf("Done.\n");
}
printf("\n");
frames[0]->GetTetrahedralGrid()->TetrahedronSize();
printf("\n");
}
void GetTopologyAndGeometry() {
globalNumOfCells = frames[0]->GetTetrahedralGrid()->GetNumOfCells();
globalNumOfPoints = frames[0]->GetTetrahedralGrid()->GetNumOfVertices();
printf("globalNumOfCells = %d, globalNumOfPoints = %d\n", globalNumOfCells, globalNumOfPoints);
tetrahedralConnectivities = new int [globalNumOfCells * 4];
tetrahedralLinks = new int [globalNumOfCells * 4];
vertexPositions = new double [globalNumOfPoints * 3];
frames[0]->GetTetrahedralGrid()->ReadConnectivities(tetrahedralConnectivities);
frames[0]->GetTetrahedralGrid()->ReadLinks(tetrahedralLinks);
frames[0]->GetTetrahedralGrid()->ReadPositions(vertexPositions);
}
void GetGlobalBoundingBox() {
lcs::Vector firstPoint = frames[0]->GetTetrahedralGrid()->GetVertex(0);
globalMaxX = globalMinX = firstPoint.GetX();
globalMaxY = globalMinY = firstPoint.GetY();
globalMaxZ = globalMinZ = firstPoint.GetZ();
for (int i = 1; i < globalNumOfPoints; i++) {
lcs::Vector point = frames[0]->GetTetrahedralGrid()->GetVertex(i);
globalMaxX = std::max(globalMaxX, point.GetX());
globalMinX = std::min(globalMinX, point.GetX());
globalMaxY = std::max(globalMaxY, point.GetY());
globalMinY = std::min(globalMinY, point.GetY());
globalMaxZ = std::max(globalMaxZ, point.GetZ());
globalMinZ = std::min(globalMinZ, point.GetZ());
}
printf("Global Bounding Box\n");
printf("X: [%lf, %lf], length = %lf\n", globalMinX, globalMaxX, globalMaxX - globalMinX);
printf("Y: [%lf, %lf], length = %lf\n", globalMinY, globalMaxY, globalMaxY - globalMinY);
printf("Z: [%lf, %lf], length = %lf\n", globalMinZ, globalMaxZ, globalMaxZ - globalMinZ);
printf("\n");
}
void CalculateNumOfBlocksInXYZ() {
blockSize = configure->GetBlockSize();
numOfBlocksInX = (int)((globalMaxX - globalMinX) / blockSize) + 1;
numOfBlocksInY = (int)((globalMaxY - globalMinY) / blockSize) + 1;
numOfBlocksInZ = (int)((globalMaxZ - globalMinZ) / blockSize) + 1;
}
void PrepareTetrahedronBlockIntersectionQueries() {
// Get the bounding box for every tetrahedral cell
xLeftBound = new int [globalNumOfCells];
xRightBound = new int [globalNumOfCells];
yLeftBound = new int [globalNumOfCells];
yRightBound = new int [globalNumOfCells];
zLeftBound = new int [globalNumOfCells];
zRightBound = new int [globalNumOfCells];
numOfQueries = 0;
for (int i = 0; i < globalNumOfCells; i++) {
lcs::Tetrahedron tetrahedron = frames[0]->GetTetrahedralGrid()->GetTetrahedron(i);
lcs::Vector firstPoint = tetrahedron.GetVertex(0);
double localMinX, localMaxX, localMinY, localMaxY, localMinZ, localMaxZ;
localMaxX = localMinX = firstPoint.GetX();
localMaxY = localMinY = firstPoint.GetY();
localMaxZ = localMinZ = firstPoint.GetZ();
for (int j = 1; j < 4; j++) {
lcs::Vector point = tetrahedron.GetVertex(j);
localMaxX = std::max(localMaxX, point.GetX());
localMinX = std::min(localMinX, point.GetX());
localMaxY = std::max(localMaxY, point.GetY());
localMinY = std::min(localMinY, point.GetY());
localMaxZ = std::max(localMaxZ, point.GetZ());
localMinZ = std::min(localMinZ, point.GetZ());
}
// Consider the margin
localMaxX += configure->GetMarginRatio() * blockSize;
localMaxY += configure->GetMarginRatio() * blockSize;
localMaxZ += configure->GetMarginRatio() * blockSize;
localMinX -= configure->GetMarginRatio() * blockSize;
localMinY -= configure->GetMarginRatio() * blockSize;
localMinZ -= configure->GetMarginRatio() * blockSize;
if (localMinX < globalMinX) localMinX = globalMinX;
if (localMinY < globalMinY) localMinY = globalMinY;
if (localMinZ < globalMinZ) localMinZ = globalMinZ;
if (localMaxX > globalMaxX) localMaxX = globalMaxX;
if (localMaxY > globalMaxY) localMaxY = globalMaxY;
if (localMaxZ > globalMaxZ) localMaxZ = globalMaxZ;
xLeftBound[i] = (int)((localMinX - globalMinX) / blockSize);
xRightBound[i] = (int)((localMaxX - globalMinX) / blockSize);
yLeftBound[i] = (int)((localMinY - globalMinY) / blockSize);
yRightBound[i] = (int)((localMaxY - globalMinY) / blockSize);
zLeftBound[i] = (int)((localMinZ - globalMinZ) / blockSize);
zRightBound[i] = (int)((localMaxZ - globalMinZ) / blockSize);
numOfQueries += (xRightBound[i] - xLeftBound[i] + 1) *
(yRightBound[i] - yLeftBound[i] + 1) *
(zRightBound[i] - zLeftBound[i] + 1);
}
// Prepare host input and output arrays
queryTetrahedron = new int [numOfQueries];
queryBlock = new int [numOfQueries];
queryResults = new char [numOfQueries];
int currQuery = 0;
for (int i = 0; i < globalNumOfCells; i++)
for (int xItr = xLeftBound[i]; xItr <= xRightBound[i]; xItr++)
for (int yItr = yLeftBound[i]; yItr <= yRightBound[i]; yItr++)
for (int zItr = zLeftBound[i]; zItr <= zRightBound[i]; zItr++) {
queryTetrahedron[currQuery] = i;
queryBlock[currQuery] = GetBlockID(xItr, yItr, zItr);
/// DEBUG ///
if (queryBlock[currQuery] < 0 || queryBlock[currQuery] >= numOfBlocksInX * numOfBlocksInY * numOfBlocksInZ) {
printf("incorrect block = %d\n", queryBlock[currQuery]);
printf("%d\n", numOfBlocksInX * numOfBlocksInY * numOfBlocksInZ);
lcs::Error("incorrect block");
}
currQuery++;
}
// Release bounding box arrays
delete [] xLeftBound;
delete [] xRightBound;
delete [] yLeftBound;
delete [] yRightBound;
delete [] zLeftBound;
delete [] zRightBound;
}
void LaunchGPUforIntersectionQueries() {
// Create CUDA C buffer pointing to the device tetrahedralConnectivities
err = cudaMalloc(&d_tetrahedralConnectivities, sizeof(int) * globalNumOfCells * 4);
if (err) lcs::Error("Fail to create a buffer for device tetrahedralConnectivities");
// Create CUDA C buffer pointing to the device vertexPositions
err = cudaMalloc(&d_vertexPositions, sizeof(double) * globalNumOfPoints * 3);
if (err) lcs::Error("Fail to create a buffer for device vertexPositions");
// Create CUDA C buffer pointing to the device queryTetrahedron
err = cudaMalloc(&d_queryTetrahedron, sizeof(int) * numOfQueries);
if (err) lcs::Error("Fail to create a buffer for device queryTetrahedron");
// Create CUDA C buffer pointing to the device queryBlock
err = cudaMalloc(&d_queryBlock, sizeof(int) * numOfQueries);
if (err) lcs::Error("Fail to create a buffer for device queryBlock");
// Create CUDA C buffer pointing to the device queryResults (output)
err = cudaMalloc(&d_queryResults, sizeof(bool) * numOfQueries);
if (err) lcs::Error("Fail to create a buffer for device queryResults");
// Copy from host to device
err = cudaMemcpy(d_tetrahedralConnectivities, tetrahedralConnectivities, sizeof(int) * globalNumOfCells * 4, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to copy tetrahedralConnectivities");
err = cudaMemcpy(d_vertexPositions, vertexPositions, sizeof(double) * globalNumOfPoints * 3, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to copy vertexPositions");
err = cudaMemcpy(d_queryTetrahedron, queryTetrahedron, sizeof(int) * numOfQueries, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to copy queryTetrahedron");
err = cudaMemcpy(d_queryBlock, queryBlock, sizeof(int) * numOfQueries, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to copy queryBlock");
printf("Start to use GPU to process tetrahedron-block intersection queries ...\n");
printf("\n");
int startTime = clock();
TetrahedronBlockIntersection(d_vertexPositions, d_tetrahedralConnectivities, d_queryTetrahedron,
d_queryBlock, d_queryResults, numOfBlocksInY, numOfBlocksInZ, globalMinX, globalMinY, globalMinZ,
blockSize, configure->GetEpsilonForTetBlkIntersection(), numOfQueries, configure->GetMarginRatio());
int endTime = clock();
// Copy from device to host
err = cudaMemcpy(queryResults, d_queryResults, sizeof(bool) * numOfQueries, cudaMemcpyDeviceToHost);
if (err) lcs::Error("Fail to copy queryResults from device");
// Free d_queryResults
cudaFree(d_queryTetrahedron);
cudaFree(d_queryBlock);
cudaFree(d_queryResults);
printf("First 10 results: ");
for (int i = 0; i < 10; i++)
printf("%d", queryResults[i]);
printf("\n\n");
int sum = 0;
for (int i = 0; i < numOfQueries; i++)
sum += queryResults[i];
printf("sum of queryResults[i] = %d\n", sum);
printf("The GPU Kernel for tetrahedron-block intersection queries cost %lf sec.\n",
(endTime - startTime) * 1.0 / CLOCKS_PER_SEC);
printf("\n");
// Unit Test for Tetrahedron-Block Intersection Kernel
startTime = clock();
/// DEBUG ///
/*
int specialTet = 6083453, specialBlk = 66;
char specialRes = 1;
UnitTestForTetBlkIntersection(frames[0]->GetTetrahedralGrid(),
blockSize, globalMinX, globalMinY, globalMinZ,
numOfBlocksInY, numOfBlocksInZ,
&specialTet, &specialBlk, &specialRes,
1, configure->GetEpsilonForTetBlkIntersection());
*/
if (configure->UseUnitTestForTetBlkIntersection()) {
UnitTestForTetBlkIntersection(frames[0]->GetTetrahedralGrid(),
blockSize, globalMinX, globalMinY, globalMinZ,
numOfBlocksInY, numOfBlocksInZ,
queryTetrahedron, queryBlock, queryResults,
numOfQueries, configure->GetEpsilonForTetBlkIntersection());
printf("\n");
}
endTime = clock();
printf("The unit test cost %lf sec.\n", (endTime - startTime) * 1.0 / CLOCKS_PER_SEC);
printf("\n");
}
void DivisionProcess() {
// Filter out empty blocks and build interestingBlockMap
numOfBlocks = numOfBlocksInX * numOfBlocksInY * numOfBlocksInZ;
int *interestingBlockMap = new int [numOfBlocks];
memset(interestingBlockMap, 255, sizeof(int) * numOfBlocks);
err = cudaMalloc(&d_interestingBlockMap, sizeof(int) * numOfBlocks);
if (err) lcs::Error("Fail to create device interestingBlockMap");
numOfInterestingBlocks = 0;
/// DEBUG ///
/*
for (int i = 0; i < numOfQueries; i++)
if (queryTetrahedron[i] == 6083453 || queryTetrahedron[i] == 6083454) {
printf("tet: %d, blk: %d, res: %d\n", queryTetrahedron[i], queryBlock[i], queryResults[i]);
}
*/
for (int i = 0; i < numOfQueries; i++)
if (queryResults[i]) {
int blockID = queryBlock[i];
if (interestingBlockMap[blockID] != -1) continue;
interestingBlockMap[blockID] = numOfInterestingBlocks++;
}
err = cudaMemcpy(d_interestingBlockMap, interestingBlockMap, sizeof(int) * numOfBlocks, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write to device interestingBlockMap");
// Count the numbers of tetrahedrons in non-empty blocks and the numbers of blocks of tetrahedrons
int sizeOfHashMap = 0;
int *numOfTetrahedronsInBlock, *numOfBlocksOfTetrahedron;
int **cellsInBlock;
numOfTetrahedronsInBlock = new int [numOfInterestingBlocks];
memset(numOfTetrahedronsInBlock, 0, sizeof(int) * numOfInterestingBlocks);
numOfBlocksOfTetrahedron = new int [globalNumOfCells];
memset(numOfBlocksOfTetrahedron, 0, sizeof(int) * globalNumOfCells);
for (int i = 0; i < numOfQueries; i++)
if (queryResults[i]) {
numOfTetrahedronsInBlock[interestingBlockMap[queryBlock[i]]]++;
numOfBlocksOfTetrahedron[queryTetrahedron[i]]++;
sizeOfHashMap++;
}
// Initialize device arrays
err = cudaMalloc(&d_startOffsetsInLocalIDMap, sizeof(int) * (globalNumOfCells + 1));
if (err) lcs::Error("Fail to create device startOffsetsInLocalMap");
err = cudaMalloc(&d_blocksOfTets, sizeof(int) * sizeOfHashMap);
if (err) lcs::Error("Fail to create device blocksOfTets");
err = cudaMalloc(&d_localIDsOfTets, sizeof(int) * sizeOfHashMap);
if (err) lcs::Error("Fail to create device localIDsOfTets");
// Initialize some work arrays
int *startOffsetsInLocalIDMap = new int [globalNumOfCells + 1];
startOffsetsInLocalIDMap[0] = 0;
for (int i = 1; i <= globalNumOfCells; i++) {
/// DEBUG ///
if (numOfBlocksOfTetrahedron[i - 1] == 0) {
printf("zero: i = %d\n", i);
break;
}
startOffsetsInLocalIDMap[i] = startOffsetsInLocalIDMap[i - 1] + numOfBlocksOfTetrahedron[i - 1];
}
int *topOfCells = new int [globalNumOfCells];
memset(topOfCells, 0, sizeof(int) * globalNumOfCells);
int *blocksOfTets = new int [sizeOfHashMap];
int *localIDsOfTets = new int [sizeOfHashMap];
// Fill cellsInblock and build local cell ID map
cellsInBlock = new int * [numOfInterestingBlocks];
for (int i = 0; i < numOfInterestingBlocks; i++)
cellsInBlock[i] = new int [numOfTetrahedronsInBlock[i]];
int *heads = new int [numOfInterestingBlocks];
memset(heads, 0, sizeof(int) * numOfInterestingBlocks);
for (int i = 0; i < numOfQueries; i++)
if (queryResults[i]) {
int tetrahedronID = queryTetrahedron[i];
int blockID = interestingBlockMap[queryBlock[i]];
/// DEBUG ///
if (blockID < 0 || blockID >= numOfInterestingBlocks) {
printf("blockID = %d\n", blockID);
lcs::Error("incorrect blockID");
}
int positionInHashMap = startOffsetsInLocalIDMap[tetrahedronID] + topOfCells[tetrahedronID];
blocksOfTets[positionInHashMap] = queryBlock[i];
localIDsOfTets[positionInHashMap] = heads[blockID];
topOfCells[tetrahedronID]++;
cellsInBlock[blockID][heads[blockID]++] = tetrahedronID;
}
delete [] heads;
/// DEBUG ///
for (int i = 0; i < globalNumOfCells; i++)
if (startOffsetsInLocalIDMap[i] >= startOffsetsInLocalIDMap[i + 1]) {
printf("%d %d\n", i, startOffsetsInLocalIDMap[i]);
lcs::Error("local ID Map error");
}
printf("hash size = %d\n", startOffsetsInLocalIDMap[globalNumOfCells]);
printf("sizeOfHashMap = %d\n", sizeOfHashMap);
printf("globalNumOfCells = %d\n", globalNumOfCells);
// Fill some device arrays
err = cudaMemcpy(d_startOffsetsInLocalIDMap, startOffsetsInLocalIDMap, sizeof(int) * (globalNumOfCells + 1), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write to device startOffsetsInLocalIDMap");
err = cudaMemcpy(d_blocksOfTets, blocksOfTets, sizeof(int) * sizeOfHashMap, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write to device blocksOfTets");
err = cudaMemcpy(d_localIDsOfTets, localIDsOfTets, sizeof(int) * sizeOfHashMap, cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write to device localIDsOfTets");
// Delete some work arrays
delete [] startOffsetsInLocalIDMap;
delete [] topOfCells;
delete [] blocksOfTets;
delete [] localIDsOfTets;
delete [] interestingBlockMap;
// Initialize blocks and release cellsInBlock and numOfTetrahedronsInBlock
blocks = new lcs::BlockRecord * [numOfInterestingBlocks];
for (int i = 0; i < numOfInterestingBlocks; i++) {
blocks[i] = new lcs::BlockRecord();
blocks[i]->SetLocalNumOfCells(numOfTetrahedronsInBlock[i]);
blocks[i]->CreateGlobalCellIDs(cellsInBlock[i]);
delete [] cellsInBlock[i];
}
delete [] cellsInBlock;
delete [] numOfTetrahedronsInBlock;
// Initialize work arrays
int *cellMarks = new int [globalNumOfCells];
int *pointMarks = new int [globalNumOfPoints];
int *localPointIDs = new int [globalNumOfPoints];
int *localCellIDs = new int [globalNumOfCells];
int *pointList = new int [globalNumOfPoints];
int *tempConnectivities = new int [globalNumOfCells * 4];
int *tempLinks = new int [globalNumOfCells * 4];
int markCount = 0;
memset(cellMarks, 0, sizeof(int) * globalNumOfCells);
memset(pointMarks, 0, sizeof(int) * globalNumOfPoints);
// Process blocks
int smallEnoughBlocks = 0;
maxSharedMemoryRequired = 0;
//canFitInSharedMemory = new bool [numOfInterestingBlocks];
for (int i = 0; i < numOfInterestingBlocks; i++) {
markCount++;
int population = 0;
// Get local points
for (int j = 0; j < blocks[i]->GetLocalNumOfCells(); j++) {
int globalCellID = blocks[i]->GetGlobalCellID(j);
cellMarks[globalCellID] = markCount;
localCellIDs[globalCellID] = j;
for (int k = 0; k < 4; k++) {
int globalPointID = tetrahedralConnectivities[(globalCellID << 2) + k];
if (globalPointID == -1 || pointMarks[globalPointID] == markCount) continue;
pointMarks[globalPointID] = markCount;
localPointIDs[globalPointID] = population;
pointList[population++] = globalPointID;
}
}
blocks[i]->SetLocalNumOfPoints(population);
blocks[i]->CreateGlobalPointIDs(pointList);
// Mark whether the block can fit into the shared memory
int currentBlockMemoryCost = blocks[i]->EvaluateNumOfBytes();
//if (currentBlockMemoryCost <= configure->GetSharedMemoryKilobytes() * 1024) smallEnoughBlocks++;
if (currentBlockMemoryCost <= MAX_SHARED_MEMORY_PER_SM) smallEnoughBlocks++;
if (currentBlockMemoryCost <= MAX_SHARED_MEMORY_PER_SM && currentBlockMemoryCost > maxSharedMemoryRequired) maxSharedMemoryRequired = currentBlockMemoryCost;
//if (currentBlockMemoryCost <= configure->GetSharedMemoryKilobytes() * 1024) {
// smallEnoughBlocks++;
// canFitInSharedMemory[i] = true;
//} else
// canFitInSharedMemory[i] = false;
// Calculate the local connectivity and link
for (int j = 0; j < blocks[i]->GetLocalNumOfCells(); j++) {
int globalCellID = blocks[i]->GetGlobalCellID(j);
// Fill tempConnectivities
for (int k = 0; k < 4; k++) {
int globalPointID = tetrahedralConnectivities[(globalCellID << 2) + k];
int localPointID;
if (globalPointID != -1 && pointMarks[globalPointID] == markCount)
localPointID = localPointIDs[globalPointID];
else localPointID = -1;
tempConnectivities[(j << 2) + k] = localPointID;
}
// Fill tempLinks
for (int k = 0; k < 4; k++) {
int globalNeighborID = tetrahedralLinks[(globalCellID << 2) + k];
int localNeighborID;
if (globalNeighborID != -1 && cellMarks[globalNeighborID] == markCount)
localNeighborID = localCellIDs[globalNeighborID];
else localNeighborID = -1;
tempLinks[(j << 2) + k] = localNeighborID;
}
}
blocks[i]->CreateLocalConnectivities(tempConnectivities);
blocks[i]->CreateLocalLinks(tempLinks);
}
printf("Division is done. smallEnoughBlocks = %d\n", smallEnoughBlocks);
printf("maxSharedMemoryRequired = %d\n", maxSharedMemoryRequired);
printf("\n");
// Select big blocks
//int *bigBlocks = new int [numOfInterestingBlocks];
//numOfBigBlocks = 0;
//for (int i = 0; i < numOfInterestingBlocks; i++)
// if (!canFitInSharedMemory[i])
// bigBlocks[numOfBigBlocks++] = i;
//err = cudaMalloc(&d_bigBlocks, sizeof(int) * numOfBigBlocks);
//if (err) lcs::Error("Fail to create device bigBlocks");
//err = cudaMemcpy(d_bigBlocks, bigBlocks, sizeof(int) * numOfBigBlocks, cudaMemcpyHostToDevice);
//if (err) lcs::Error("Fail to write to d_bigBlockFail to write to d_bigBlocks");
//delete [] bigBlocks;
// Release work arrays
delete [] cellMarks;
delete [] pointMarks;
delete [] localPointIDs;
delete [] localCellIDs;
delete [] pointList;
delete [] tempConnectivities;
delete [] tempLinks;
// Some statistics
int minPos = globalNumOfCells, maxPos = 0;
int numOfUnder100 = 0, numOfUnder200 = 0;
for (int i = 0; i < numOfInterestingBlocks; i++) {
maxPos = std::max(maxPos, blocks[i]->GetLocalNumOfCells());
minPos = std::min(minPos, blocks[i]->GetLocalNumOfCells());
numOfUnder100 += blocks[i]->GetLocalNumOfCells() < 100;
numOfUnder200 += blocks[i]->GetLocalNumOfCells() < 200;
}
printf("Statistics\n");
printf("The number of blocks is %d.\n", numOfBlocks);
printf("The number of non-zero blocks is %d.\n", numOfInterestingBlocks);
printf("The number of under-100 blocks is %d.\n", numOfUnder100);
printf("The number of under-200 blocks is %d.\n", numOfUnder200);
printf("The maximum number of tetrahedrons in a block is %d.\n", maxPos);
printf("The minimum non-zero number of tetrahedrons in a block is %d.\n", minPos);
printf("\n");
}
void StoreBlocksInDevice() {
// Initialize start offsets in cells and points
startOffsetInCell = new int [numOfInterestingBlocks + 1];
startOffsetInPoint = new int [numOfInterestingBlocks + 1];
startOffsetInCell[0] = 0;
startOffsetInPoint[0] = 0;
// Calculate start offsets
int maxNumOfCells = 0, maxNumOfPoints = 0;
for (int i = 0; i < numOfInterestingBlocks; i++) {
startOffsetInCell[i + 1] = startOffsetInCell[i] + blocks[i]->GetLocalNumOfCells();
startOffsetInPoint[i + 1] = startOffsetInPoint[i] + blocks[i]->GetLocalNumOfPoints();
maxNumOfCells += blocks[i]->GetLocalNumOfCells();
maxNumOfPoints += blocks[i]->GetLocalNumOfPoints();
}
printf("Total number of cells in all the blocks is %d.\n", startOffsetInCell[numOfInterestingBlocks]);
printf("Total number of points in all the blocks is %d.\n", startOffsetInPoint[numOfInterestingBlocks]);
printf("\n");
//Create d_canFitInSharedMemory
//err = cudaMalloc(&d_canFitInSharedMemory, sizeof(bool) * numOfInterestingBlocks);
//if (err) lcs::Error("Fail to create a buffer for device canFitInSharedMemory");
// Create d_vertexPositionsForBig
err = cudaMalloc(&d_vertexPositionsForBig, sizeof(double) * 3 * maxNumOfPoints);
if (err) lcs::Error("Fail to create a buffer for device vertexPositionsForBig");
// Create d_startVelocitiesForBig
err = cudaMalloc(&d_startVelocitiesForBig, sizeof(double) * 3 * maxNumOfPoints);
if (err) lcs::Error("Fail to create a buffer for device startVelocitiesForBig");
// Create d_endVelocitiesForBig
err = cudaMalloc(&d_endVelocitiesForBig, sizeof(double) * 3 * maxNumOfPoints);
if (err) lcs::Error("Fail to create a buffer for device endVelocitiesForBig");
// Create d_startOffsetInCell
err = cudaMalloc(&d_startOffsetInCell, sizeof(int) * (numOfInterestingBlocks + 1));
if (err) lcs::Error("Fail to create a buffer for device startOffsetInCell");
// Create d_startOffsetInCellForBig
//err = cudaMalloc(&d_startOffsetInCellForBig, sizeof(int) * (numOfInterestingBlocks + 1));
//if (err) lcs::Error("Fail to create a buffer for device startOffsetInCellForBig");
// Create d_startOffsetInPoint
err = cudaMalloc(&d_startOffsetInPoint, sizeof(int) * (numOfInterestingBlocks + 1));
if (err) lcs::Error("Fail to create a buffer for device startOffsetInPoint");
// Create d_startOffsetInPointForBig
//err = cudaMalloc(&d_startOffsetInPointForBig, sizeof(int) * (numOfInterestingBlocks + 1));
//if (err) lcs::Error("Fail to create a buffer for device startOffsetInPointForBig");
// Create d_localConnectivities
err = cudaMalloc(&d_localConnectivities, sizeof(int) * startOffsetInCell[numOfInterestingBlocks] * 4);
if (err) lcs::Error("Fail to create a buffer for device localConnectivities");
// Create d_localLinks
err = cudaMalloc(&d_localLinks, sizeof(int) * startOffsetInCell[numOfInterestingBlocks] * 4);
if (err) lcs::Error("Fail to create a buffer for device localLinks");
// Create d_globalCellIDs
err = cudaMalloc(&d_globalCellIDs, sizeof(int) * startOffsetInCell[numOfInterestingBlocks]);
if (err) lcs::Error("Fail to create a buffer for device globalCellIDs");
// Create d_globalPointIDs
err = cudaMalloc(&d_globalPointIDs, sizeof(int) * startOffsetInPoint[numOfInterestingBlocks]);
if (err) lcs::Error("Fail to create a buffer for device globalPointIDs");
// Fill d_canFitInSharedMemory
//err = cudaMemcpy(d_canFitInSharedMemory, canFitInSharedMemory, sizeof(bool) * numOfInterestingBlocks, cudaMemcpyHostToDevice);
//if (err) lcs::Error("Fail to write-to-device for d_canFitInSharedMemory");
// Fill d_startOffsetInCell
err = cudaMemcpy(d_startOffsetInCell, startOffsetInCell, sizeof(int) * (numOfInterestingBlocks + 1), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_startOffsetInCell");
// Fill d_startOffsetInCellForBig
//err = cudaMemcpy(d_startOffsetInCellForBig, startOffsetInCellForBig, sizeof(int) * (numOfInterestingBlocks + 1), cudaMemcpyHostToDevice);
//if (err) lcs::Error("Fail to write-to-device for d_startOffsetInCellForBig");
// Fill d_startOffsetInPoint
err = cudaMemcpy(d_startOffsetInPoint, startOffsetInPoint, sizeof(int) * (numOfInterestingBlocks + 1), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_startOffsetInPoint");
// Fill d_startOffsetInPointForBig
//err = cudaMemcpy(d_startOffsetInPointForBig, startOffsetInPointForBig, sizeof(int) * (numOfInterestingBlocks + 1), cudaMemcpyHostToDevice);
//if (err) lcs::Error("Fail to write-to-device for d_startOffsetInPointForBig");
// Fill d_localConnectivities
for (int i = 0; i < numOfInterestingBlocks; i++) {
int length = startOffsetInCell[i + 1] - startOffsetInCell[i];
if (!length) continue;
int *currLocalConnectivities = blocks[i]->GetLocalConnectivities();
// Enqueue write-to-device
err = cudaMemcpy(d_localConnectivities + startOffsetInCell[i] * 4, currLocalConnectivities, length * 4 * sizeof(int), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_localConnectivities");
}
// Fill d_localLinks
for (int i = 0; i < numOfInterestingBlocks; i++) {
int length = startOffsetInCell[i + 1] - startOffsetInCell[i];
if (!length) continue;
int *currLocalLinks = blocks[i]->GetLocalLinks();
// Enqueue write-to-device
err = cudaMemcpy(d_localLinks + startOffsetInCell[i] * 4, currLocalLinks, length * 4 * sizeof(int), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_localLinks");
}
// Fill d_globalCellIDs
for (int i = 0; i < numOfInterestingBlocks; i++) {
int length = startOffsetInCell[i + 1] - startOffsetInCell[i];
if (!length) continue;
int *currGlobalCellIDs = blocks[i]->GetGlobalCellIDs();
// Enqueue write-to-device
err = cudaMemcpy(d_globalCellIDs + startOffsetInCell[i], currGlobalCellIDs, length * sizeof(int), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_globalCellIDs");
}
// Fill d_globalPointIDs
for (int i = 0; i < numOfInterestingBlocks; i++) {
int length = startOffsetInPoint[i + 1] - startOffsetInPoint[i];
if (!length) continue;
int *currGlobalPointIDs = blocks[i]->GetGlobalPointIDs();
// Enqueue write-to-device
err = cudaMemcpy(d_globalPointIDs + startOffsetInPoint[i], currGlobalPointIDs, length * sizeof(int), cudaMemcpyHostToDevice);
if (err) lcs::Error("Fail to write-to-device for d_globalPointIDs");
}
}
void Division() {
// Prepare queries
PrepareTetrahedronBlockIntersectionQueries();
// Launch GPU to solve queries
LaunchGPUforIntersectionQueries();
// Main process of division
DivisionProcess();
// Store blocks in the global memory of device
StoreBlocksInDevice();
}
void InitialCellLocation() {
printf("Start to use GPU to process initial cell location ...\n");
printf("\n");
double minX = configure->GetBoundingBoxMinX();
double maxX = configure->GetBoundingBoxMaxX();
double minY = configure->GetBoundingBoxMinY();
double maxY = configure->GetBoundingBoxMaxY();
double minZ = configure->GetBoundingBoxMinZ();
double maxZ = configure->GetBoundingBoxMaxZ();
int xRes = configure->GetBoundingBoxXRes();
int yRes = configure->GetBoundingBoxYRes();
int zRes = configure->GetBoundingBoxZRes();
double dx = (maxX - minX) / xRes;
double dy = (maxY - minY) / yRes;
double dz = (maxZ - minZ) / zRes;
int numOfGridPoints = (xRes + 1) * (yRes + 1) * (zRes + 1);
initialCellLocations = new int [numOfGridPoints];
// Create OpenCL buffer pointing to the device cellLocations (output)
err = cudaMalloc(&d_cellLocations, sizeof(int) * numOfGridPoints);
if (err) lcs::Error("Fail to create a buffer for device cellLocations");
// Initialize d_cellLocations to -1 arrays
err = cudaMemset(d_cellLocations, 255, sizeof(int) * numOfGridPoints);
if (err) lcs::Error("Fail to initialize d_cellLocations");
int startTime = clock();
InitialCellLocation(d_vertexPositions, d_tetrahedralConnectivities, d_cellLocations, xRes, yRes, zRes,
minX, minY, minZ, dx, dy, dz, configure->GetEpsilon(), globalNumOfCells);
int endTime = clock();
// Copy from device to host
err = cudaMemcpy(initialCellLocations, d_cellLocations, sizeof(int) * numOfGridPoints, cudaMemcpyDeviceToHost);
if (err) lcs::Error("Fail to get initialCellLocations");
// Delete d_cellLocations
cudaFree(d_cellLocations);
/// DEBUG ///
FILE *locationFile = fopen("lcsInitialLocations.txt", "w");
for (int i = 0; i < numOfGridPoints; i++)
if (initialCellLocations[i] != -1)