diff --git a/.gitignore b/.gitignore index 6495fe11..e861c2d4 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ Python/.idea/ Python/devtest.py Python/dist/ Python/tigre/utilities/cuda_interface/*.cpp +Python/tigre/plugins/*/*.cpp .ipynb_checkpoints # Object files *.o diff --git a/Common/CUDA/TIGRE_common.cpp b/Common/CUDA/TIGRE_common.cpp index 55dd9c9c..9fbb21b8 100644 --- a/Common/CUDA/TIGRE_common.cpp +++ b/Common/CUDA/TIGRE_common.cpp @@ -5,8 +5,9 @@ #include #include #include "TIGRE_common.hpp" +// Prints like MATLAB's mexPrintf. It used to prefix every message with +// "Common/CUDA/TIGRE_common.cpp (9): ", the location of this line, not the caller. void mexPrintf(const char* format, ...) { - PRINT_HERE(""); va_list argpointer; va_start(argpointer, format); vprintf(format, argpointer); diff --git a/Common/CUDA/plugins/pCT/improvedForwardProjections.cu b/Common/CUDA/plugins/pCT/improvedForwardProjections.cu index e5374db5..044e1af8 100644 --- a/Common/CUDA/plugins/pCT/improvedForwardProjections.cu +++ b/Common/CUDA/plugins/pCT/improvedForwardProjections.cu @@ -22,6 +22,7 @@ #include #include "../../TIGRE_common.hpp" +#include "../../tigre_release_on_error.hpp" #include #include "improvedForwardProjections.hpp" #include @@ -497,8 +498,8 @@ __global__ void ParticleKernel(float* dhist1, float* dhist2, float* devicePosIn, int indX, indY, linInd; float tOld = 0.0; if (count==0){ - indX = int(pos1[0]/pix[0]+dimX/2.); // REPLACE: pos1 by pos0 - indY = int(pos1[1]/pix[1]+dimY/2.); + indX = (int)floorf(pos1[0]/pix[0]+dimX/2.); // REPLACE: pos1 by pos0 + indY = (int)floorf(pos1[1]/pix[1]+dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -511,8 +512,8 @@ __global__ void ParticleKernel(float* dhist1, float* dhist2, float* devicePosIn, for(int i= 0; i<=count; i++){ lk = (InterceptsVec[i]- tOld)*lenZ; if(tOld == 0){ - indX = int(d[0]/pix[0] +dimX/2); - indY = int(d[1]/pix[1] +dimY/2); + indX = (int)floorf(d[0]/pix[0] +dimX/2); + indY = (int)floorf(d[1]/pix[1] +dimY/2); linInd = indY + indX*(dSizeY); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ @@ -524,8 +525,8 @@ __global__ void ParticleKernel(float* dhist1, float* dhist2, float* devicePosIn, }else if(i == count){ lk = lenZ - InterceptsVec[i-1]*lenZ; - indX = int(pos1[0]/pix[0] +dimX/2); - indY = int(pos1[1]/pix[1] +dimY/2); + indX = (int)floorf(pos1[0]/pix[0] +dimX/2); + indY = (int)floorf(pos1[1]/pix[1] +dimY/2); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -534,8 +535,8 @@ __global__ void ParticleKernel(float* dhist1, float* dhist2, float* devicePosIn, } }else{ - indX = int(cspline(InterceptsVec[i] - eps, a[0], b[0], c[0], d[0])/pix[0] +dimX/2); - indY = int(cspline(InterceptsVec[i] - eps, a[1], b[1], c[1], d[1])/pix[1] +dimY/2); + indX = (int)floorf(cspline(InterceptsVec[i] - eps, a[0], b[0], c[0], d[0])/pix[0] +dimX/2); + indY = (int)floorf(cspline(InterceptsVec[i] - eps, a[1], b[1], c[1], d[1])/pix[1] +dimY/2); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -662,8 +663,8 @@ else{ // ---------------------------------------- Start with SL from detector to hull if (countIn == 0){ - indX = int(initpos[0]/pix[0] + dimX/2.); - indY = int(initpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(initpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(initpos[1]/pix[1] + dimY/2.); lk = HullIn[2] - initpos[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -676,8 +677,8 @@ else{ for(int i= 0; i<=countIn; i++){ lk = InterceptsVecIn[i] - tOld; if(i == 0){ - indX = int(initpos[0]/pix[0] + dimX/2.); - indY = int(initpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(initpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(initpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -687,8 +688,8 @@ else{ } else if(i == countIn){ lk = HullIn[2] - InterceptsVecIn[i-1]; - indX = int(HullIn[0]/pix[0] + dimX/2.); - indY = int(HullIn[1]/pix[1] + dimY/2.); + indX = (int)floorf(HullIn[0]/pix[0] + dimX/2.); + indY = (int)floorf(HullIn[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -697,8 +698,8 @@ else{ } else{ - indX = int(((initdir[0]*(InterceptsVecIn[i]-eps) + (initpos[0] - initdir[0] * initpos[2])))/pix[0] + dimX/2.); - indY = int(((initdir[1]*(InterceptsVecIn[i]-eps) + (initpos[1] - initdir[1] * initpos[2])))/pix[1] + dimY/2.); + indX = (int)floorf(((initdir[0]*(InterceptsVecIn[i]-eps) + (initpos[0] - initdir[0] * initpos[2])))/pix[0] + dimX/2.); + indY = (int)floorf(((initdir[1]*(InterceptsVecIn[i]-eps) + (initpos[1] - initdir[1] * initpos[2])))/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -712,8 +713,8 @@ else{ tOld = 0.0; if (countHull==0){ - indX = int(HullIn[0]/pix[0] + dimX/2.); - indY = int(HullIn[1]/pix[1] + dimY/2.); + indX = (int)floorf(HullIn[0]/pix[0] + dimX/2.); + indY = (int)floorf(HullIn[1]/pix[1] + dimY/2.); lk = HullOut[2] - HullIn[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -725,8 +726,8 @@ else{ for(int i= 0; i<=countHull; i++){ lk = (InterceptsVecHull[i] - tOld)*(HullOut[2] - HullIn[2]); if(tOld == 0){ - indX = int(d[0]/pix[0] + dimX/2.); - indY = int(d[1]/pix[1] + dimY/2.); + indX = (int)floorf(d[0]/pix[0] + dimX/2.); + indY = (int)floorf(d[1]/pix[1] + dimY/2.); linInd = indY + indX*(dSizeY); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ @@ -738,8 +739,8 @@ else{ }else if(i == countHull){ lk = (HullOut[2] - HullIn[2]) - InterceptsVecHull[i-1]*(HullOut[2] - HullIn[2]); - indX = int(pos1[0]/pix[0] + dimX/2.); - indY = int(pos1[1]/pix[1] + dimY/2.); + indX = (int)floorf(pos1[0]/pix[0] + dimX/2.); + indY = (int)floorf(pos1[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ linInd = indY + indX*(dSizeY); @@ -748,8 +749,8 @@ else{ } }else{ - indX = int(cspline(InterceptsVecHull[i] -eps, a[0], b[0], c[0], d[0])/pix[0] + dimX/2.); - indY = int(cspline(InterceptsVecHull[i] -eps, a[1], b[1], c[1], d[1])/pix[1] + dimY/2.); + indX = (int)floorf(cspline(InterceptsVecHull[i] -eps, a[0], b[0], c[0], d[0])/pix[0] + dimX/2.); + indY = (int)floorf(cspline(InterceptsVecHull[i] -eps, a[1], b[1], c[1], d[1])/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ linInd = indY + indX*(dSizeY); @@ -765,8 +766,8 @@ else{ // --------------------------- SL from hull to detector tOld = HullOut[2]; if (countOut == 0){ - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); lk = exitpos[2] - HullOut[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -779,8 +780,8 @@ else{ for(int i= 0; i<=countOut; i++){ lk = abs(InterceptsVecOut[i] - tOld); if(i == 0){ - indX = int(HullOut[0]/pix[0] + dimX/2.); - indY = int(HullOut[1]/pix[1] + dimY/2.); + indX = (int)floorf(HullOut[0]/pix[0] + dimX/2.); + indY = (int)floorf(HullOut[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -790,8 +791,8 @@ else{ } else if(i == countOut){ lk = exitpos[2] - InterceptsVecOut[i-1]; - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -800,8 +801,8 @@ else{ } else{ - indX = int(((exitdir[0]*(InterceptsVecOut[i]-eps) + (HullOut[0] - exitdir[0] * HullOut[2])))/pix[0] + dimX/2.); - indY = int(((exitdir[1]*(InterceptsVecOut[i]-eps) + (HullOut[1] - exitdir[1] * HullOut[2])))/pix[1] + dimY/2.); + indX = (int)floorf(((exitdir[0]*(InterceptsVecOut[i]-eps) + (HullOut[0] - exitdir[0] * HullOut[2])))/pix[0] + dimX/2.); + indY = (int)floorf(((exitdir[1]*(InterceptsVecOut[i]-eps) + (HullOut[1] - exitdir[1] * HullOut[2])))/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -847,8 +848,8 @@ else{ int indX, indY, linInd; float tOld = initpos[2]; if (count==0){ - indX = int(initpos[0]/pix[0] + dimX/2.); - indY = int(initpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(initpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(initpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -860,8 +861,8 @@ else{ for(int i= 0; i<=count; i++){ lk = InterceptsVec[i] - tOld; if(tOld == initpos[2]){ - indX = int(initpos[0]/pix[0] + dimX/2.); - indY = int(initpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(initpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(initpos[1]/pix[1] + dimY/2.); linInd = indY + indX*(dSizeY); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ @@ -873,8 +874,8 @@ else{ }else if(i == count){ lk = exitpos[2] - InterceptsVec[i-1]; - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ linInd = indY + indX*(dSizeY); @@ -883,8 +884,8 @@ else{ } }else{ - indX = int(((mydir[0]*(InterceptsVec[i]-eps) + (initpos[0] - mydir[0] * (initpos[2]))))/pix[0] + dimX/2.); - indY = int(((mydir[1]*(InterceptsVec[i]-eps) + (initpos[1] - mydir[1] * (initpos[2]))))/pix[1] + dimY/2.); + indX = (int)floorf(((mydir[0]*(InterceptsVec[i]-eps) + (initpos[0] - mydir[0] * (initpos[2]))))/pix[0] + dimX/2.); + indY = (int)floorf(((mydir[1]*(InterceptsVec[i]-eps) + (initpos[1] - mydir[1] * (initpos[2]))))/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ linInd = indY + indX*(dSizeY); @@ -920,18 +921,18 @@ __host__ void ParticleProjections(float * outProjection, float* posIn, float* po Detect Size = 400x400 Prepare Input for GPU*/ - const int sizeInputs = 2*numOfEntries*sizeof(float); - const int detectorMem = detectSizeX*detectSizeY*sizeof(float); + const size_t sizeInputs = 2*(size_t)numOfEntries*sizeof(float); + const size_t detectorMem = (size_t)detectSizeX*detectSizeY*sizeof(float); float reject = 0.0; - float *dPosIn, *dPosOut, *ddirIn, *ddirOut, *dhist1, *dhist2, *d_wepl, *dHull; - int *dnumEntries, *ddetectorX, *ddetectorY; - float *dpixelSize, *dDetectDistIn, *dDetectDistOut, *dEin, *dReject; + float *dPosIn = NULL, *dPosOut = NULL, *ddirIn = NULL, *ddirOut = NULL, *dhist1 = NULL, *dhist2 = NULL, *d_wepl = NULL, *dHull = NULL; + int *dnumEntries = NULL, *ddetectorX = NULL, *ddetectorY = NULL; + float *dpixelSize = NULL, *dDetectDistIn = NULL, *dDetectDistOut = NULL, *dEin = NULL, *dReject = NULL; float *hist1, *hist2; - hist1 = new float[detectSizeX*detectSizeY]; - hist2 = new float[detectSizeX*detectSizeY]; - for(int i = 0; i #ifndef improvedForwardProjections_H #define improvedForwardProjections_H -#define pi 3.14159265359 -#define eps 1e-8 -// Lengths of the per-proton intercept vectors. Compile('pCT', ...) in MATLAB -// passes them as -DvecSizeIn=... etc.; the defaults suit 0.25 mm pixels. +// Lengths of the per-proton intercept vectors. Compile('pCT', ...) in MATLAB and +// setup.py (TIGRE_PCT_PIXEL, TIGRE_PCT_INTERCEPTS) pass them as -DvecSizeIn=... +// etc.; the defaults suit 0.25 mm pixels. #ifndef vecSizeCS #define vecSizeCS 220 #endif @@ -42,9 +41,20 @@ //#include //#include +// Host entry points, called from the MATLAB MEX gateway and the Python (Cython) +// wrapper; the C++ compiler sees only these. void ParticleProjections(float* outProjection, float* posIn, float* posOut, float* dirIn, float* dirOut, float* p_wepl, \ int numOfEntries, int detectSizeX, int detectSizeY, float* pixelSize, float detectDistIn, float detectDistOut, float ein, float* ch_param); +void ParticleProjectionsCone(float* outProjection, float* posIn, float* posOut, float* dirIn, float* dirOut, float* p_wepl, \ + int numOfEntries, int detectSizeX, int detectSizeY, float* pixelSize, float detectDistIn, float detectDistOut, float sourcePos, \ + float ein, float* ch_param); + +// Device code, only for nvcc. +#ifdef __CUDACC__ +#define pi 3.14159265359 +#define eps 1e-8 + __device__ int calcIntercepts(float* InterceptsVec ,float* a, float* b, \ float* c, float* d, float* pos1, float pixelSize, bool* protFlag, int maxIntercep); @@ -63,9 +73,7 @@ __device__ int hullEntryExit(float* HullIntercept, float* position, float* direc __device__ int calcInterceptsLinear(float* LinInterceptsVec, float* start, float* stop, float* direction, float* pix, int maxIntercep, \ bool* protFlag); -void ParticleProjectionsCone(float* outProjection, float* posIn, float* posOut, float* dirIn, float* dirOut, float* p_wepl, \ - int numOfEntries, int detectSizeX, int detectSizeY, float* pixelSize, float detectDistIn, float detectDistOut, float sourcePos, \ - float ein, float* ch_param); + __device__ int calcInterceptsCone(float* InterceptsVec ,float* a, float* b, \ float* c, float* d, float* pos1, float pixelSize, bool* protFlag, int maxIntercep, \ @@ -86,186 +94,6 @@ __device__ int hullEntryExitCone(float* HullIntercept, float* position, float* d __device__ int calcInterceptsLinearCone(float* LinInterceptsVec, float* start, float* stop, float* direction, float* pix, int maxIntercep, \ bool* protFlag, float sourcePos); +#endif // __CUDACC__ #endif - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Common/CUDA/plugins/pCT/improvedForwardProjections_cone.cu b/Common/CUDA/plugins/pCT/improvedForwardProjections_cone.cu index a95e879b..7ebb4559 100644 --- a/Common/CUDA/plugins/pCT/improvedForwardProjections_cone.cu +++ b/Common/CUDA/plugins/pCT/improvedForwardProjections_cone.cu @@ -23,6 +23,7 @@ #include #include "../../TIGRE_common.hpp" +#include "../../tigre_release_on_error.hpp" #include #include "improvedForwardProjections.hpp" // #include @@ -627,8 +628,8 @@ __global__ void ParticleKernelCone(float* dhist1, float* dhist2, float* devicePo float tOld = 0.0; if (count==0){ - indX = int(pos1[0]/pix[0]+dimX/2.); // REPLACE: pos1 by pos0 - indY = int(pos1[1]/pix[1]+dimY/2.); + indX = (int)floorf(pos1[0]/pix[0]+dimX/2.); // REPLACE: pos1 by pos0 + indY = (int)floorf(pos1[1]/pix[1]+dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -642,8 +643,8 @@ __global__ void ParticleKernelCone(float* dhist1, float* dhist2, float* devicePo // lk = InterceptsLengths[i]; lk = (InterceptsVec[i]- tOld)*lenZ; if(i == 0){ - indX = int(d[0]/pix_start_x + dimX/2); - indY = int(d[1]/pix_start_y + dimY/2); + indX = (int)floorf(d[0]/pix_start_x + dimX/2); + indY = (int)floorf(d[1]/pix_start_y + dimY/2); linInd = indY + indX*(dSizeY); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ @@ -656,8 +657,8 @@ __global__ void ParticleKernelCone(float* dhist1, float* dhist2, float* devicePo }else if(i == count){ // lk = InterceptsLengths[i]; lk = lenZ - InterceptsVec[i-1]*lenZ; - indX = int(pos1[0]/pix[0] + dimX/2); - indY = int(pos1[1]/pix[1] + dimY/2); + indX = (int)floorf(pos1[0]/pix[0] + dimX/2); + indY = (int)floorf(pos1[1]/pix[1] + dimY/2); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -669,8 +670,8 @@ __global__ void ParticleKernelCone(float* dhist1, float* dhist2, float* devicePo if (i != 0 && i != count){ float curr_pix_x = ((InterceptsVec[i]-eps)*lenZ + *detectDistIn - *sourceDist) * (pix[0]/abs(*detectDistOut - *sourceDist)); float curr_pix_y = ((InterceptsVec[i]-eps)*lenZ + *detectDistIn - *sourceDist) * (pix[1]/abs(*detectDistOut - *sourceDist)); - indX = int(csplineCone(InterceptsVec[i] - eps, a[0], b[0], c[0], d[0])/curr_pix_x + dimX/2); - indY = int(csplineCone(InterceptsVec[i] - eps, a[1], b[1], c[1], d[1])/curr_pix_y + dimY/2); + indX = (int)floorf(csplineCone(InterceptsVec[i] - eps, a[0], b[0], c[0], d[0])/curr_pix_x + dimX/2); + indY = (int)floorf(csplineCone(InterceptsVec[i] - eps, a[1], b[1], c[1], d[1])/curr_pix_y + dimY/2); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -806,8 +807,8 @@ else{ float pix_end_x = abs(HullIn[2] - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); float pix_end_y = abs(HullIn[2] - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); if (countIn == 0){ - indX = int(initpos[0]/pix_start_x + dimX/2.); - indY = int(initpos[1]/pix_start_y + dimY/2.); + indX = (int)floorf(initpos[0]/pix_start_x + dimX/2.); + indY = (int)floorf(initpos[1]/pix_start_y + dimY/2.); lk = HullIn[2] - initpos[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -820,8 +821,8 @@ else{ for(int i= 0; i<=countIn; i++){ lk = InterceptsVecIn[i] - tOld; if(i == 0){ - indX = int(initpos[0]/pix_start_x + dimX/2.); - indY = int(initpos[1]/pix_start_y + dimY/2.); + indX = (int)floorf(initpos[0]/pix_start_x + dimX/2.); + indY = (int)floorf(initpos[1]/pix_start_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -831,8 +832,8 @@ else{ } else if(i == countIn){ lk = HullIn[2] - InterceptsVecIn[i-1]; - indX = int(HullIn[0]/pix_end_x + dimX/2.); - indY = int(HullIn[1]/pix_end_y + dimY/2.); + indX = (int)floorf(HullIn[0]/pix_end_x + dimX/2.); + indY = (int)floorf(HullIn[1]/pix_end_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -843,8 +844,8 @@ else{ else{ float curr_pix_x = abs((InterceptsVecIn[i]-eps) - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); float curr_pix_y = abs((InterceptsVecIn[i]-eps) - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); - indX = int(((initdir[0]*(InterceptsVecIn[i]-eps) + (initpos[0] - initdir[0] * initpos[2] )))/curr_pix_x + dimX/2.); - indY = int(((initdir[1]*(InterceptsVecIn[i]-eps) + (initpos[1] - initdir[1] * initpos[2] )))/curr_pix_y + dimY/2.); + indX = (int)floorf(((initdir[0]*(InterceptsVecIn[i]-eps) + (initpos[0] - initdir[0] * initpos[2] )))/curr_pix_x + dimX/2.); + indY = (int)floorf(((initdir[1]*(InterceptsVecIn[i]-eps) + (initpos[1] - initdir[1] * initpos[2] )))/curr_pix_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullIn[2]-initpos[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_in*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -863,8 +864,8 @@ else{ pix_end_x = abs(HullOut[2] - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); pix_end_y = abs(HullOut[2] - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); if (countHull==0){ - indX = int(HullIn[0]/pix_start_x + dimX/2.); - indY = int(HullIn[1]/pix_start_y + dimY/2.); + indX = (int)floorf(HullIn[0]/pix_start_x + dimX/2.); + indY = (int)floorf(HullIn[1]/pix_start_y + dimY/2.); lk = HullOut[2] - HullIn[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -876,8 +877,8 @@ else{ for(int i= 0; i<=countHull; i++){ lk = (InterceptsVecHull[i] - tOld)*(HullOut[2] - HullIn[2]); if(tOld == 0){ - indX = int(d[0]/pix_start_x + dimX/2.); - indY = int(d[1]/pix_start_y + dimY/2.); + indX = (int)floorf(d[0]/pix_start_x + dimX/2.); + indY = (int)floorf(d[1]/pix_start_y + dimY/2.); linInd = indY + indX*(dSizeY); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ @@ -889,8 +890,8 @@ else{ }else if(i == countHull){ lk = (HullOut[2] - HullIn[2]) - InterceptsVecHull[i-1]*(HullOut[2] - HullIn[2]); - indX = int(pos1[0]/pix_end_x + dimX/2.); - indY = int(pos1[1]/pix_end_y + dimY/2.); + indX = (int)floorf(pos1[0]/pix_end_x + dimX/2.); + indY = (int)floorf(pos1[1]/pix_end_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ linInd = indY + indX*(dSizeY); @@ -902,8 +903,8 @@ else{ float curr_len = (InterceptsVecHull[i]-eps)*(HullOut[2]-HullIn[2]) + (HullIn[2] - *sourceDist); // abs(((InterceptsVecHull[i]-eps)*lenZ + *detectDistIn) - *sourceDist) float curr_pix_x = curr_len * (pix[0]/abs(exitpos[2] - *sourceDist)); float curr_pix_y = curr_len * (pix[1]/abs(exitpos[2] - *sourceDist)); - indX = int(csplineCone(InterceptsVecHull[i] - eps, a[0], b[0], c[0], d[0])/curr_pix_x + dimX/2.); - indY = int(csplineCone(InterceptsVecHull[i] - eps, a[1], b[1], c[1], d[1])/curr_pix_y + dimY/2.); + indX = (int)floorf(csplineCone(InterceptsVecHull[i] - eps, a[0], b[0], c[0], d[0])/curr_pix_x + dimX/2.); + indY = (int)floorf(csplineCone(InterceptsVecHull[i] - eps, a[1], b[1], c[1], d[1])/curr_pix_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (HullOut[2]-HullIn[2]))){ linInd = indY + indX*(dSizeY); @@ -921,8 +922,8 @@ else{ pix_start_x = abs(HullOut[2] - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); pix_start_y = abs(HullOut[2] - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); if (countOut == 0){ - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); lk = exitpos[2] - HullOut[2]; if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -935,8 +936,8 @@ else{ for(int i= 0; i<=countOut; i++){ lk = abs(InterceptsVecOut[i] - tOld); if(i == 0){ - indX = int(HullOut[0]/pix_start_x + dimX/2.); - indY = int(HullOut[1]/pix_start_y + dimY/2.); + indX = (int)floorf(HullOut[0]/pix_start_x + dimX/2.); + indY = (int)floorf(HullOut[1]/pix_start_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -946,8 +947,8 @@ else{ } else if(i == countOut){ lk = exitpos[2] - InterceptsVecOut[i-1]; - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -958,8 +959,8 @@ else{ else{ float curr_pix_x = abs((InterceptsVecOut[i]-eps) - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); float curr_pix_y = abs((InterceptsVecOut[i]-eps) - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); - indX = int(((exitdir[0]*(InterceptsVecOut[i]-eps) + (HullOut[0] - exitdir[0] * HullOut[2])))/curr_pix_x + dimX/2.); - indY = int(((exitdir[1]*(InterceptsVecOut[i]-eps) + (HullOut[1] - exitdir[1] * HullOut[2])))/curr_pix_y + dimY/2.); + indX = (int)floorf(((exitdir[0]*(InterceptsVecOut[i]-eps) + (HullOut[0] - exitdir[0] * HullOut[2])))/curr_pix_x + dimX/2.); + indY = (int)floorf(((exitdir[1]*(InterceptsVecOut[i]-eps) + (HullOut[1] - exitdir[1] * HullOut[2])))/curr_pix_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < (exitpos[2]-HullOut[2]))){ linInd = indY + indX*(dSizeY); atomicAdd(&dhist1[linInd], weight_air_out*(lk/lenZ)*(lk/lenZ)*p_wepl[protonIndex]); @@ -1040,8 +1041,8 @@ else{ // exitpos[0] / (exitpos[2] - *sourceDir); float tOld = initpos[2]; if (count==0){ - indX = int(initpos[0]/pix_start_x + dimX/2.); - indY = int(initpos[1]/pix_start_y + dimY/2.); + indX = (int)floorf(initpos[0]/pix_start_x + dimX/2.); + indY = (int)floorf(initpos[1]/pix_start_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY)){ linInd = indY + indX*(dSizeY); @@ -1054,8 +1055,8 @@ else{ lk = InterceptsVec[i] - tOld; // lk = InterceptsLengths[i]; if(i == 0){ - indX = int(initpos[0]/pix_start_x + dimX/2.); - indY = int(initpos[1]/pix_start_y + dimY/2.); + indX = (int)floorf(initpos[0]/pix_start_x + dimX/2.); + indY = (int)floorf(initpos[1]/pix_start_y + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ linInd = indY + indX*(dSizeY); @@ -1066,8 +1067,8 @@ else{ }else if(i == count){ lk = exitpos[2] - InterceptsVec[i-1]; - indX = int(exitpos[0]/pix[0] + dimX/2.); - indY = int(exitpos[1]/pix[1] + dimY/2.); + indX = (int)floorf(exitpos[0]/pix[0] + dimX/2.); + indY = (int)floorf(exitpos[1]/pix[1] + dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ linInd = indY + indX*(dSizeY); @@ -1078,8 +1079,8 @@ else{ }else{ float curr_pix_x = abs((InterceptsVec[i]-eps) - *sourceDist) * (pix[0]/abs(exitpos[2] - *sourceDist)); float curr_pix_y = abs((InterceptsVec[i]-eps) - *sourceDist) * (pix[1]/abs(exitpos[2] - *sourceDist)); - indX = int(((mydir[0]*(InterceptsVec[i]-eps) + (initpos[0] - mydir[0] * (initpos[2]))))/curr_pix_x+dimX/2.); - indY = int(((mydir[1]*(InterceptsVec[i]-eps) + (initpos[1] - mydir[1] * (initpos[2]))))/curr_pix_y+dimY/2.); + indX = (int)floorf(((mydir[0]*(InterceptsVec[i]-eps) + (initpos[0] - mydir[0] * (initpos[2]))))/curr_pix_x+dimX/2.); + indY = (int)floorf(((mydir[1]*(InterceptsVec[i]-eps) + (initpos[1] - mydir[1] * (initpos[2]))))/curr_pix_y+dimY/2.); if ((0 <= indX) && (indX < dSizeX) && (0 <= indY) && (indY < dSizeY) && (0 < lk) && (lk < lenZ)){ linInd = indY + indX*(dSizeY); @@ -1116,18 +1117,18 @@ __host__ void ParticleProjectionsCone(float * outProjection, float* posIn, float Detect Size = 400x400 Prepare Input for GPU*/ - const int sizeInputs = 2*numOfEntries*sizeof(float); - const int detectorMem = detectSizeX*detectSizeY*sizeof(float); + const size_t sizeInputs = 2*(size_t)numOfEntries*sizeof(float); + const size_t detectorMem = (size_t)detectSizeX*detectSizeY*sizeof(float); float reject = 0.0; - float *dPosIn, *dPosOut, *ddirIn, *ddirOut, *dhist1, *dhist2, *d_wepl, *dHull; - int *dnumEntries, *ddetectorX, *ddetectorY; - float *dpixelSize, *dDetectDistIn, *dDetectDistOut, *dSourceDist, *dEin, *dReject; + float *dPosIn = NULL, *dPosOut = NULL, *ddirIn = NULL, *ddirOut = NULL, *dhist1 = NULL, *dhist2 = NULL, *d_wepl = NULL, *dHull = NULL; + int *dnumEntries = NULL, *ddetectorX = NULL, *ddetectorY = NULL; + float *dpixelSize = NULL, *dDetectDistIn = NULL, *dDetectDistOut = NULL, *dSourceDist = NULL, *dEin = NULL, *dReject = NULL; float *hist1, *hist2; - hist1 = new float[detectSizeX*detectSizeY]; - hist2 = new float[detectSizeX*detectSizeY]; - for(int i = 0; i= 9's importorskip + # skips only ModuleNotFoundError, and the plugin raises a plain ImportError. + pytest.skip(str(err), allow_module_level=True) + + +def test_straight_protons_give_mean_wepl_per_pixel(): + geo = types.SimpleNamespace( + dDetector=np.array([0.5, 0.5]), # (y, x) + sDetector=np.array([2.0, 2.0]), + DSID=245.0, + DSO=300.0, + DSD=355.0, + hull=np.zeros(4), + mode="parallel", + ) + k = np.arange(100) + ix = (k % 16) % 4 + iy = (k % 16) // 4 + pos = np.stack([(ix + 0.5 - 2) * 0.5, (iy + 0.5 - 2) * 0.5]) # row 0: x, row 1: y + direction = np.zeros((2, 100)) # straight along z + proj = pct.pCTCubicSpline(pos, pos, direction, direction, 10 + ix + 4 * iy, 100, geo) + + expected = 10 + np.arange(4)[None, :] + 4 * np.arange(4)[:, None] + assert proj.shape == (4, 4) + np.testing.assert_allclose(proj, expected, atol=1e-4) diff --git a/Python/tigre/plugins/__init__.py b/Python/tigre/plugins/__init__.py new file mode 100644 index 00000000..8795d217 --- /dev/null +++ b/Python/tigre/plugins/__init__.py @@ -0,0 +1,5 @@ +"""TIGRE plugins: optional parts of TIGRE, outside the core toolbox. + +Plugins with compiled code are not built by default; see each plugin's +documentation for how to build it (for example ``TIGRE_PLUGINS=pct``). +""" diff --git a/Python/tigre/plugins/pct/__init__.py b/Python/tigre/plugins/pct/__init__.py new file mode 100644 index 00000000..519d8960 --- /dev/null +++ b/Python/tigre/plugins/pct/__init__.py @@ -0,0 +1,21 @@ +"""Proton CT plugin: optimised proton radiographies (MATLAB/Plugins/pCT in MATLAB). + +Not built by default. Build TIGRE with it:: + + TIGRE_PLUGINS=pct pip install . + +(Windows cmd: ``set TIGRE_PLUGINS=pct`` and then ``pip install .``.) +""" + +try: + from ._pct import INTERCEPTS # noqa: F401 +except ImportError as err: # the compiled module is not there + raise ImportError( + "The TIGRE proton CT plugin is not compiled. Build TIGRE with it: set the environment " + "variable TIGRE_PLUGINS=pct and reinstall (TIGRE_PLUGINS=pct pip install . from the TIGRE " + "folder; in Windows cmd: set TIGRE_PLUGINS=pct, then pip install .)." + ) from err + +from .pCTCubicSpline import pCTCubicSpline # noqa: E402 + +__all__ = ["pCTCubicSpline", "INTERCEPTS"] diff --git a/Python/tigre/plugins/pct/_pct.pyx b/Python/tigre/plugins/pct/_pct.pyx new file mode 100644 index 00000000..ae544ff9 --- /dev/null +++ b/Python/tigre/plugins/pct/_pct.pyx @@ -0,0 +1,66 @@ +# This file is part of the TIGRE Toolbox + +# Copyright (c) 2015, University of Bath and +# CERN-European Organization for Nuclear Research +# All rights reserved. + +# License: Open Source under BSD. +# See the full license at +# https://github.com/CERN/TIGRE/license.txt + +# Contact: tigre.toolbox@gmail.com +# Codes: https://github.com/CERN/TIGRE/ +# -------------------------------------------------------------------------- +# Coded by: Stefanie Kaser, Benjamin Kirchmayer (CUDA code) + +# Cython binding for the proton CT plugin (Common/CUDA/plugins/pCT). The +# checks and argument handling are in pCTCubicSpline.py. + +cimport numpy as np +import numpy as np + +np.import_array() + +cdef extern from "improvedForwardProjections.hpp": + void ParticleProjections(float* outProjection, float* posIn, float* posOut, float* dirIn, float* dirOut, + float* p_wepl, int numOfEntries, int detectSizeX, int detectSizeY, float* pixelSize, + float detectDistIn, float detectDistOut, float ein, float* ch_param) except + + void ParticleProjectionsCone(float* outProjection, float* posIn, float* posOut, float* dirIn, float* dirOut, + float* p_wepl, int numOfEntries, int detectSizeX, int detectSizeY, float* pixelSize, + float detectDistIn, float detectDistOut, float sourcePos, float ein, + float* ch_param) except + + +# Intercept vector lengths this module was compiled with (TIGRE_PCT_PIXEL / +# TIGRE_PCT_INTERCEPTS at build time). +cdef extern from *: + int VEC_SIZE_IN "vecSizeIn" + int VEC_SIZE_CS "vecSizeCS" + int VEC_SIZE_OUT "vecSizeOut" + +INTERCEPTS = (VEC_SIZE_IN, VEC_SIZE_CS, VEC_SIZE_OUT) + + +def _particle_projections(np.ndarray[np.float32_t, ndim=1, mode="c"] pos_in not None, + np.ndarray[np.float32_t, ndim=1, mode="c"] pos_out not None, + np.ndarray[np.float32_t, ndim=1, mode="c"] dir_in not None, + np.ndarray[np.float32_t, ndim=1, mode="c"] dir_out not None, + np.ndarray[np.float32_t, ndim=1, mode="c"] wepl not None, + int size_x, int size_y, + np.ndarray[np.float32_t, ndim=1, mode="c"] pix not None, + float dist_in, float dist_out, float source_pos, float e_in, + np.ndarray[np.float32_t, ndim=1, mode="c"] hull not None, + bint cone): + """Return the radiography as a flat float32 array, pixel (iy, ix) at iy + ix*size_y. + + The CUDA code changes its direction inputs on the GPU only, so the arrays + passed here are not modified. + """ + cdef int n = wepl.shape[0] + cdef np.ndarray[np.float32_t, ndim=1, mode="c"] out = np.zeros(size_x * size_y, dtype=np.float32) + if cone: + ParticleProjectionsCone(&out[0], &pos_in[0], &pos_out[0], &dir_in[0], &dir_out[0], &wepl[0], n, + size_x, size_y, &pix[0], dist_in, dist_out, source_pos, e_in, &hull[0]) + else: + ParticleProjections(&out[0], &pos_in[0], &pos_out[0], &dir_in[0], &dir_out[0], &wepl[0], n, + size_x, size_y, &pix[0], dist_in, dist_out, e_in, &hull[0]) + return out diff --git a/Python/tigre/plugins/pct/pCTCubicSpline.py b/Python/tigre/plugins/pct/pCTCubicSpline.py new file mode 100644 index 00000000..a401f9c1 --- /dev/null +++ b/Python/tigre/plugins/pct/pCTCubicSpline.py @@ -0,0 +1,116 @@ +"""Optimised proton radiography: the TIGRE proton CT plugin.""" + +import numpy as np + +from ._pct import _particle_projections + + +def _protons(name, value, n): + """Return a C-contiguous float32 copy of a 2*N position/direction input.""" + arr = np.asarray(value) + if arr.ndim == 2 and arr.shape[0] == 2: + arr = arr.reshape(-1) # row 0: x of every proton, row 1: y + if arr.ndim != 1 or arr.size != 2 * n: + raise ValueError( + f"{name} must have shape (2, N) (x of every proton, then y) or be a vector of length 2*N, " + f"with N = {n} protons (the length of Wepl); got shape {np.shape(value)}" + ) + return np.ascontiguousarray(arr, dtype=np.float32) + + +def _geo_values(geo, name, n): + if not hasattr(geo, name): + raise ValueError(f"geo.{name} is missing") + arr = np.asarray(getattr(geo, name), dtype=np.float64).reshape(-1) + if arr.size != n: + raise ValueError(f"geo.{name} must have {n} value(s); got {arr.size}") + return arr + + +def pCTCubicSpline(posIn, posOut, dirIn, dirOut, Wepl, eIn, geo): + """Optimised proton radiography from single-proton data. + + Estimates each proton's path through the object with a cubic spline and bins its + water-equivalent path length (WEPL) along it (Collins-Fekete et al., Phys. Med. Biol. + 61 (2016) 8232). Same function and arguments as MATLAB ``pCTCubicSpline``. + + Parameters + ---------- + posIn, posOut : array_like, shape (2, N) or (2*N,) + Entry and exit positions in mm: x of every proton, then y. + dirIn, dirOut : array_like, shape (2, N) or (2*N,) + Entry and exit directions (x and y, with the z component equal to 1). + Wepl : array_like, shape (N,) + WEPL of each proton, in mm. + eIn : float + Initial beam energy, in MeV. + geo : object + With ``dDetector`` (pixel size) and ``sDetector`` (size of the radiography), both + in (y, x) order like other TIGRE detector fields in Python (MATLAB: [x; y]); + ``DSO``, ``DSID`` (source to entry detector), ``DSD`` (source to exit detector); + ``hull`` = [a, b, alpha, h] (h = 0: no hull); ``mode``, ``"parallel"`` or + ``"cone"``. Lengths in mm. + + Returns + ------- + numpy.ndarray, float32, shape (ny, nx) + The radiography, indexed [y, x] (MATLAB: proj(y, x)). Pixels no proton crossed + are NaN. + """ + wepl = np.ascontiguousarray(np.asarray(Wepl).reshape(-1), dtype=np.float32) + n = wepl.size + if n == 0 or n > 2**30 - 1: + raise ValueError("Wepl must have between 1 and 2^30-1 elements (one per proton)") + pos_in = _protons("posIn", posIn, n) + pos_out = _protons("posOut", posOut, n) + dir_in = _protons("dirIn", dirIn, n) + dir_out = _protons("dirOut", dirOut, n) + e_in = np.asarray(eIn, dtype=np.float32).reshape(-1) + if e_in.size != 1: + raise ValueError("eIn must be a single number (the initial beam energy in MeV)") + + # geo detector fields are (y, x) in Python; the CUDA code takes (x, y). + pix = _geo_values(geo, "dDetector", 2)[::-1].astype(np.float32) + det = _geo_values(geo, "sDetector", 2)[::-1].astype(np.float32) + hull = _geo_values(geo, "hull", 4).astype(np.float32) + dsd = np.float32(_geo_values(geo, "DSD", 1)[0]) + dsid = np.float32(_geo_values(geo, "DSID", 1)[0]) + dso = np.float32(_geo_values(geo, "DSO", 1)[0]) + mode = getattr(geo, "mode", None) + if mode not in ("parallel", "cone"): + raise ValueError("geo.mode must be 'parallel' or 'cone'") + with np.errstate(divide="ignore", invalid="ignore"): + size = det / pix + if np.any(pix <= 0) or not np.all(np.isfinite(size)) or np.any(size < 1): + raise ValueError( + "geo.sDetector and geo.dDetector must be positive, with sDetector >= dDetector" + ) + size_x, size_y = int(size[0]), int(size[1]) + + if hull[3] == 0: + print( + "Info: Calculation of optimized proton radiographies will be performed without object hull!" + ) + if hull[2] > 6.28318530717958648: + print( + "Info: Hull rotation angle exceeds 2 Pi. Please check the input! Continuing with calculation..." + ) + + out = _particle_projections( + pos_in, + pos_out, + dir_in, + dir_out, + wepl, + size_x, + size_y, + np.ascontiguousarray(pix), + float(dsid - dso), + float(dsd - dso), + float(-dso), + float(e_in[0]), + np.ascontiguousarray(hull), + mode == "cone", + ) + # Pixel (iy, ix) is at iy + ix*size_y: a (size_x, size_y) C array, transposed to [y, x]. + return np.ascontiguousarray(out.reshape(size_x, size_y).T) diff --git a/changelog.md b/changelog.md index 4ad1ba15..8c8ced4f 100644 --- a/changelog.md +++ b/changelog.md @@ -12,6 +12,7 @@ thank you. with `Compile pCT` (or `Compile all` for TIGRE and every plugin); plain `Compile` still builds core TIGRE only. The intercept vector lengths are set with `Compile('pCT','-pct_pixel',0.5)` or `-pct_intercepts`, instead of questions that rewrote a source file. `pRad_demo` and `pCTdata` moved with it and work from any folder. + `CompilePCT` is removed: use `Compile pCT`. - MATLAB: `ASD_POCS`, `OS_ASD_POCS`, `AwASD_POCS`, `OS_AwASD_POCS`, `B_ASD_POCS_beta`, `PICCS`, `PCSD` and `MLEM` return their data error as the second output, before `qualMeas`, like every other iterative algorithm (`[img,resL2,qualMeas] = ...`). Code that asked for `[img,qualMeas]` now gets the data error there and a warning @@ -38,6 +39,11 @@ thank you. them directly, e.g. `from _minTV import minTV`, now needs `from tigre.utilities.cuda_interface._minTV import minTV`. ### Added +- Python proton CT: `tigre.plugins.pct.pCTCubicSpline`, the optimised proton radiographies MATLAB already had. + Not built by default: install with `TIGRE_PLUGINS=pct pip install .` (or `TIGRE_PLUGINS=all`); intercept vector + lengths with `TIGRE_PCT_PIXEL` / `TIGRE_PCT_INTERCEPTS`. Demo: `Python/demos/pRad_demo.py`. +- MATLAB `pCTCubicSpline`, the same function as in Python: like `pCTCubicSpline_mex`, but takes any numeric type + and N-by-2 positions and directions. - `irn_piccs_cgls` (Python) / `IRN_PICCS_CGLS` (MATLAB): PICCS solved by iteratively reweighted norms and CGLS, from Hastings et al., Phys. Med. Biol. 71 (2026) 105019. The prior term can be `TV(x - prior)` (default), an L2 norm (PIPLE) or an L1 norm. It and `irn_tv_cgls`/`IRN_TV_CGLS` gain `outer_restart`/`'outerRestart'` (start each @@ -73,6 +79,11 @@ thank you. (off by default, as in MATLAB) (#201). ### Fixed +- Proton CT: protons that leave the radiography just below its first pixel are no longer counted in the first pixel + (pixel indices were truncated towards zero instead of rounded down). A CUDA error during `pCTCubicSpline` no longer + leaves its GPU memory allocated, and cone-beam radiographies no longer leak a little GPU memory on every call. +- Python: messages from TIGRE's C++/CUDA code (for example CUDA errors) no longer start with + `Common/CUDA/TIGRE_common.cpp (9):`, which gave the location of TIGRE's print function, not of the message. - MATLAB proton CT (`pCTCubicSpline_mex`): the last protons of every data set (up to 255, the remainder of a division by 256) were ignored, and fewer than 256 protons failed with "Kernel fail". The number of inputs was never checked, and non-`single` inputs gave wrong results silently; both now give clear errors, as do missing `geo` @@ -127,7 +138,6 @@ thank you. with a square detector and a size error otherwise. It is now the norm of `proj - Ax(img)`. ### Deprecated -- MATLAB: `CompilePCT`. It now calls `Compile('pCT')` with a deprecation warning, and no longer asks questions. - MATLAB: the `'lambda'` and `'lambda_red'` options of `OSEM`. They never changed the result, as the OSEM update has no step size. Passing them now gives a `TIGRE:deprecated` warning; they will be removed in TIGRE 4. diff --git a/docs/_ext/tigre_demos.py b/docs/_ext/tigre_demos.py index 7da56c54..b3e1f793 100644 --- a/docs/_ext/tigre_demos.py +++ b/docs/_ext/tigre_demos.py @@ -36,8 +36,9 @@ def _m_path(m: str) -> str: return f"MATLAB/{m}" if "/" in m else f"MATLAB/Demos/{m}" # Demos that need data, hardware or packages a website build does not have -# (d24 is a template: it needs your own curved-detector projections). -NOT_RUN = {"d21_ScannerDataLoader.py", "d24_CurvedDetector.py", "d25_Pytorch.py"} +# (d24 is a template: it needs your own curved-detector projections; pRad_demo +# needs the proton CT plugin, which is not built by default). +NOT_RUN = {"d21_ScannerDataLoader.py", "d24_CurvedDetector.py", "d25_Pytorch.py", "pRad_demo.py"} # (folder, heading, intro, [(python file or None, MATLAB file or None, title, description)]) CATALOGUE = [ @@ -133,7 +134,7 @@ def _m_path(m: str) -> str: "Material decomposition from two scans at different tube voltages."), (None, "SophiaBeads_demo.m", "Real micro-CT data: SophiaBeads", "Reconstruct the SophiaBeads dataset, a tube of glass beads."), - (None, "Plugins/pCT/Demos/pRad_demo.m", "Proton radiography", + ("pRad_demo.py", "Plugins/pCT/Demos/pRad_demo.m", "Proton radiography", "Compute an optimised proton radiography. See :doc:`/user-guide/proton-ct`."), ], ), diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index dbb3ffa4..e679a2a5 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -123,7 +123,7 @@ from loading to the final image. : Source-level changes for a little more speed. [](proton-ct.md) -: The MATLAB plugin for proton radiography. +: The proton CT plugin: optimised proton radiographies. ## Background diff --git a/docs/user-guide/proton-ct.md b/docs/user-guide/proton-ct.md index 3706a461..a9b4f623 100644 --- a/docs/user-guide/proton-ct.md +++ b/docs/user-guide/proton-ct.md @@ -1,28 +1,46 @@ --- -og:description: "Reconstruct proton CT data with TIGRE: the proton CT module, its geometry and the algorithms it supports." +og:description: "Reconstruct proton CT data with TIGRE: the proton CT plugin, its geometry and the algorithms it supports." myst: html_meta: - description: "Reconstruct proton CT data with TIGRE: the proton CT module, its geometry and the algorithms it supports." + description: "Reconstruct proton CT data with TIGRE: the proton CT plugin, its geometry and the algorithms it supports." --- # Proton CT -TIGRE includes a proton CT plugin for MATLAB, written in CUDA, that turns proton CT -measurements into optimised proton radiographies, following the method of +TIGRE includes a proton CT plugin, written in CUDA, for Python and MATLAB. It +turns proton CT measurements into optimised proton radiographies, following +the method of [Collins-Fekete et al. (2016)](https://doi.org/10.1088/0031-9155/61/23/8232). Protons scatter as they cross the object, so their paths are not straight lines. The plugin estimates each proton's path with a cubic spline and bins its water-equivalent path length (WEPL) along that path. The radiographies can then be reconstructed with TIGRE's usual algorithms to -give a full proton CT image, or used on their own. A Python version is not -available yet. +give a full proton CT image, or used on their own. -The plugin lives in `MATLAB/Plugins/pCT` (its CUDA code in -`Common/CUDA/plugins/pCT`). It is not compiled with the rest of TIGRE. +The plugin lives in `Python/tigre/plugins/pct` and `MATLAB/Plugins/pCT`, with +its CUDA code in `Common/CUDA/plugins/pCT`. It is not compiled with the rest of +TIGRE. ## Building the plugin +::::{tab-set} +:sync-group: lang + +:::{tab-item} Python +:sync: python +Set `TIGRE_PLUGINS` when installing TIGRE from its source folder: + +```bash +TIGRE_PLUGINS=pct pip install . +``` + +In Windows cmd: `set TIGRE_PLUGINS=pct`, then `pip install .`. +`TIGRE_PLUGINS=all` builds every plugin. +::: + +:::{tab-item} MATLAB +:sync: matlab Compile TIGRE first (`Compile`), then, from TIGRE's `MATLAB` folder: ```matlab @@ -30,32 +48,35 @@ Compile pCT ``` `Compile all` compiles TIGRE and every plugin in one go. +::: +:::: Each proton's path is stored in fixed-length intercept vectors, whose lengths are set when compiling. The defaults (10 before the hull, 220 inside it, 100 after it) suit 0.25 mm pixels. For another pixel size, give it in mm (if the -pixel lengths in x and y differ, give the smaller one): +pixel lengths in x and y differ, give the smaller one), or set the three +lengths yourself: -```matlab -Compile('pCT', '-pct_pixel', 0.5) -``` +| | Python (environment variable) | MATLAB | +|---|---|---| +| Pixel size | `TIGRE_PCT_PIXEL=0.5` | `Compile('pCT', '-pct_pixel', 0.5)` | +| Lengths | `TIGRE_PCT_INTERCEPTS=10,220,100` | `Compile('pCT', '-pct_intercepts', [10 220 100])` | -or set the three lengths yourself with -`Compile('pCT', '-pct_intercepts', [10 220 100])`. When the code runs, it -reports how many protons it rejected because the intercept vectors were too -short. +When the code runs, it reports how many protons it rejected because the +intercept vectors were too short. In Python, `tigre.plugins.pct.INTERCEPTS` +gives the lengths it was compiled with. -`CompilePCT`, used in earlier versions, still works but is deprecated: it now -calls `Compile('pCT')` and no longer asks questions. +`CompilePCT`, used in earlier versions of MATLAB TIGRE, has been replaced by +`Compile pCT`. ## Input data -Load the measured or simulated data in any format MATLAB reads (`.mat` or raw -binary files work well). All lengths must be in millimetres. +Load the measured or simulated data in any format you can read (`.mat` or +raw binary files work well). All lengths must be in millimetres. | Parameter | Name in the demo | Unit | |---|---|---| -| Water-equivalent path length | `WEPL` | mm | +| Water-equivalent path length | `Wepl` | mm | | Entry position, x and y | `posIn` | mm | | Exit position, x and y | `posOut` | mm | | Entry direction, x and y | `dirIn` | mm, with the z component equal to 1 | @@ -67,27 +88,47 @@ reliable. ## Computing a radiography -```matlab -proj = pCTCubicSpline_mex(posIn, posOut, dirIn, dirOut, Wepl, eIn, geo); +::::{tab-set} +:sync-group: lang + +:::{tab-item} Python +:sync: python +```python +from tigre.plugins.pct import pCTCubicSpline + +proj = pCTCubicSpline(posIn, posOut, dirIn, dirOut, Wepl, eIn, geo) ``` +::: -- `Wepl` is a vector of length N with the WEPL of each proton. -- `posIn`, `posOut`, `dirIn` and `dirOut` are vectors of length 2N: first the - x values of all protons, then the y values. +:::{tab-item} MATLAB +:sync: matlab +```matlab +proj = pCTCubicSpline(posIn, posOut, dirIn, dirOut, Wepl, eIn, geo); +``` +::: +:::: + +- `Wepl` holds the WEPL of each of the N protons. +- `posIn`, `posOut`, `dirIn` and `dirOut` hold x and y for each proton: a + vector of length 2N (the x values of all protons, then the y values), or in + Python an array of shape `(2, N)` (row 0 x, row 1 y), in MATLAB an N-by-2 + matrix (`[x y]`). - `eIn` is the initial beam energy, in MeV. -- All of them must be `single`. +- Any numeric type works; they are converted to single precision. +- `proj` is indexed `[y, x]` in Python and `(y, x)` in MATLAB. Pixels that no + proton crossed are NaN. -`geo` uses these fields: +`geo` can be any object (Python) or struct (MATLAB) with these fields: | Field | Meaning | Unit | |---|---|---| -| `geo.dDetector` | Pixel size of the radiography | mm | -| `geo.sDetector` | Size of the radiography in x and y (two values) | mm | -| `geo.DSO` | Distance from the source to the origin (positive) | mm | -| `geo.DSID` | Distance from the source to the entry detector (positive) | mm | -| `geo.DSD` | Distance from the source to the exit detector (positive) | mm | -| `geo.mode` | `'parallel'` or `'cone'` | | -| `geo.hull` | Convex hull parameters `[a, b, alpha, h]` | mm | +| `dDetector` | Pixel size of the radiography: (y, x) in Python, [x; y] in MATLAB, like other TIGRE detector fields | mm | +| `sDetector` | Size of the radiography, same order | mm | +| `DSO` | Distance from the source to the origin (positive) | mm | +| `DSID` | Distance from the source to the entry detector (positive) | mm | +| `DSD` | Distance from the source to the exit detector (positive) | mm | +| `mode` | `'parallel'` or `'cone'` | | +| `hull` | Convex hull parameters `[a, b, alpha, h]` | mm | The origin is at the centre of the object. Set `h = 0` to compute without a convex hull. Otherwise the hull is the elliptical cylinder @@ -101,10 +142,12 @@ that is, an ellipse rotated by $\alpha$ around the y axis. ## Testing -`MATLAB/Plugins/pCT/Demos/pRad_demo.m` computes one optimised radiography in -parallel geometry from a simulated test data set (loaded with `pCTdata`, from -`MATLAB/Plugins/pCT/data`). Run it to check that the plugin works on your -system. `MATLAB/Tests/test_pCT_plugin.m` is a quicker check with 100 synthetic +`Python/demos/pRad_demo.py` and `MATLAB/Plugins/pCT/Demos/pRad_demo.m` +compute one optimised radiography in parallel geometry from a simulated test +data set, `MATLAB/Plugins/pCT/data/pCT_data.mat` (the Python demo needs a +TIGRE source folder for it). Run one to check that the plugin works on your +system. `Python/tests/test_pct_plugin.py` and +`MATLAB/Tests/test_pCT_plugin.m` are quicker checks with 100 synthetic protons. ## Notes @@ -112,5 +155,6 @@ protons. - If `Compile pCT` fails with missing symbols, check that the `libstdc++` shipped with MATLAB is compatible with your CUDA version and your system's `gcc`. -- The plugin was first tested on Debian 10 with CUDA 11.2, an NVIDIA RTX 4000, - and MATLAB R2020b and R2021b. +- The plugin is CUDA only (NVIDIA GPUs). +- It was first tested on Debian 10 with CUDA 11.2, an NVIDIA RTX 4000, and + MATLAB R2020b and R2021b. diff --git a/pyproject.toml b/pyproject.toml index c19d455b..3e6728d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -59,6 +59,7 @@ include = ["tigre*"] [tool.setuptools.package-data] "tigre" = ["data/*.mat"] "tigre.utilities.cuda_interface" = ["*.pyx", "*.pxd", "*.pxi", "*.cpp"] +"tigre.plugins.pct" = ["*.pyx"] [tool.cibuildwheel] build-frontend = "build[uv]" diff --git a/setup.py b/setup.py index dfbdc454..e051c2d8 100644 --- a/setup.py +++ b/setup.py @@ -621,10 +621,86 @@ def include_headers(filename_list, sdist=False): include_dirs=[NUMPY_INCLUDE, CUDA["include"], "Common/CUDA/"], ) +# Plugins: optional parts of TIGRE (Python/tigre/plugins), not built by default. +# TIGRE_PLUGINS=pct (a comma-separated list) or TIGRE_PLUGINS=all builds them, +# like Compile pCT / Compile all in MATLAB. +PLUGINS = ("pct",) + + +def selected_plugins(): + requested = [p.strip().lower() for p in os.environ.get("TIGRE_PLUGINS", "").split(",") if p.strip()] + if "all" in requested: + return list(PLUGINS) + unknown = [p for p in requested if p not in PLUGINS] + if unknown: + raise RuntimeError( + "TIGRE_PLUGINS: unknown plugin(s) " + ", ".join(unknown) + ". Known: " + ", ".join(PLUGINS) + ", or all." + ) + return [p for p in PLUGINS if p in requested] + + +def pct_intercepts(): + """Intercept vector lengths for the proton CT plugin, as in MATLAB Compile('pCT', ...). + + Defaults (10, 220, 100) suit 0.25 mm pixels. TIGRE_PCT_PIXEL=0.5 scales the first two for + another pixel size in mm; TIGRE_PCT_INTERCEPTS=10,220,100 sets all three. + """ + sizes = [10, 220, 100] + pixel = os.environ.get("TIGRE_PCT_PIXEL", "").strip() + if pixel: + try: + scale = float(pixel) / 0.25 + if not scale > 0: + raise ValueError + except ValueError: + raise RuntimeError("TIGRE_PCT_PIXEL must be a positive pixel size in mm, e.g. 0.5") from None + # Rounded half up, like MATLAB's round (Python's round() rounds half to even). + sizes[0] = max(1, int(10 / scale + 0.5)) + sizes[1] = max(1, int(220 / scale + 0.5)) + intercepts = os.environ.get("TIGRE_PCT_INTERCEPTS", "").strip() + if intercepts: + try: + values = [int(v) for v in intercepts.split(",")] + except ValueError: + values = [] + if len(values) != 3 or min(values) < 1: + raise RuntimeError("TIGRE_PCT_INTERCEPTS must be 3 positive integers, e.g. 10,220,100") + sizes = values + return sizes + + +plugin_exts = [] +for plugin in selected_plugins(): + if plugin == "pct": + if BACKEND != "cuda": + print("TIGRE: the proton CT plugin is CUDA only; not building it for the " + BACKEND + " backend.") + continue + sizes = pct_intercepts() + print("TIGRE: building the proton CT plugin (intercept vectors: %d in, %d in hull, %d out)." % tuple(sizes)) + plugin_exts.append( + Extension( + "tigre.plugins.pct._pct", + sources=[ + "Common/CUDA/TIGRE_common.cpp", + "Common/CUDA/plugins/pCT/improvedForwardProjections.cu", + "Common/CUDA/plugins/pCT/improvedForwardProjections_cone.cu", + "Python/tigre/plugins/pct/_pct.pyx", + ], + define_macros=define_macros + + [("vecSizeIn", str(sizes[0])), ("vecSizeCS", str(sizes[1])), ("vecSizeOut", str(sizes[2]))], + library_dirs=[CUDA["lib64"]], + libraries=["cudart"], + language="c++", + runtime_library_dirs=[CUDA["lib64"]] if not IS_WINDOWS else None, + include_dirs=[NUMPY_INCLUDE, CUDA["include"], "Common/CUDA/", "Common/CUDA/plugins/pCT/"], + ) + ) + setup( # Packages and package data are listed in pyproject.toml. include_package_data=True, - ext_modules=[minPICCS_ext, Ax_ext, Atb_ext, tv_proximal_ext, minTV_ext, AwminTV_ext, gpuUtils_ext, RandomNumberGenerator_ext], + ext_modules=[minPICCS_ext, Ax_ext, Atb_ext, tv_proximal_ext, minTV_ext, AwminTV_ext, gpuUtils_ext, RandomNumberGenerator_ext] + + plugin_exts, cmdclass={"build_ext": BuildExtension}, # since the package has c code, the egg cannot be zipped zip_safe=False,