k] = intercept / ((1 - E1hyp) * np.exp(-TE / T2star)) #M01=(Img_FA1[i,j,k]*(1-slope*np.cos(FAMap1[i,j,k])))/(np.sin(FAMap1[i,j,k])) #M02=(Img_FA2[i,j,k]*(1-slope*np.cos(FAMap2[i,j,k])))/(np.sin(FAMap2[i,j,k])) #M0[i,j,k]=(M01+M02)/(2*E2star*kval*(1-E1possib))#(1-slope)) #Sig2rev[i,j,k]=(M02*np.sin(FAMap1[i,j,k]))/(1-slope*np.cos(FAMap1[i,j,k])) #Sig1rev[i,j,k]=(M01*np.sin(FAMap2[i,j,k]))/(1-slope*np.cos(FAMap2[i,j,k])) #print(Img_FA1[i,j,k],Sig1rev[i,j,k],Img_FA2[i,j,k],Sig2rev[i,j,k]) #print('\n') else: T1[i, j, k] = 0 M0[i, j, k] = 0 from nifty_funclib import SaveArrayAsNIfTI Hpath, Fname = os.path.split(str(path)) Fname = Fname.split('.') specialname = "midang1lowang2" OutputPathT1 = os.path.join(Hpath + '\\SPGR\\' + "T1-3D" + specialname + ".nii") OutputPathM0 = os.path.join(Hpath + '\\' + "M0-3D.nii") OutputPathrho = os.path.join(Hpath + '\\SPGR\\' + "rho-3D" + specialname + ".nii") OutputPathrhohyp = os.path.join(Hpath + '\\' + "rhohyp-3D.nii") #OutputPathSig1rev = os.path.join( Hpath + '\\' + "Sig1theory.nii") #OutputPathSig2rev = os.path.join( Hpath + '\\' + "Sig2theory.nii") SaveArrayAsNIfTI(T1, res, res, res, OutputPathT1) #SaveArrayAsNIfTI(M0,res,res,res,OutputPathM0) SaveArrayAsNIfTI(rho, res, res, res, OutputPathrho) #SaveArrayAsNIfTI(rhohyp,res,res,res,OutputPathrhohyp) #SaveArrayAsNIfTI(Sig1rev,res,res,res,OutputPathSig1rev) #SaveArrayAsNIfTI(Sig2rev,res,res,res,OutputPathSig2rev)
def polynomialFitting(Image, mask, order,save): # Image, typically B1Maps : 3D image to be fitted with polynomial (can be complex, but only its magnitude is considered) # mask : 3D image of the region to be fitted (typically the brain) # order: order of the polynomial (between 6 and 8 is good for B1 maps) # Nch : number of channels # default parameters, if no mask provided == Over the whole image and default Interpolation order = 4 import numpy, os, sys import nibabel as nib Image = nib.load(Image) Image =Image.get_data() Image =numpy.squeeze(Image) # Image = Image[:,:,7] # Dims=Image.shape if mask == [] : mask = numpy.ones(shape=(Image.shape)) else: mask = nib.load(mask) mask = mask.get_data() mask = numpy.squeeze(mask) if order == [] : order = 4 if save == [] : save = False if len(Image.shape) ==2 : print("2D Mode") resx = 2./(Image.shape[0]+1); resy = 2./(Image.shape[1]+1); resz = 2; X=numpy.zeros(shape=Image.shape);Y=numpy.zeros(shape=Image.shape);Z = numpy.zeros(shape=(Image.shape)) X,Y = numpy.meshgrid(numpy.arange(-1.0+ resx/2,1.0- resx/2,resx,dtype=float),numpy.arange(-1.0+ resy/2,1.0- resy/2,resy,dtype=float)) if len(Image.shape) ==3 : print("3D Mode") resx = 2./Image.shape[0]; resy = 2./Image.shape[1]; resz = 2./Image.shape[2]; X=numpy.zeros(shape=Image.shape);Y=numpy.zeros(shape=Image.shape);Z = numpy.zeros(shape=(Image.shape)) X,Y,Z = numpy.meshgrid(numpy.arange(-1.0+ resx/2,1.0- resx/2,resx,dtype=float),numpy.arange(-1.0+ resy/2,1.0- resy/2,resy,dtype=float),numpy.arange(-1.0+ resz/2,1.0- resz/2,resz,dtype=float)) Index = numpy.isnan(mask) mask[Index]=0 I = numpy.where(mask[:]) Xvec=numpy.ravel(X); Yvec=numpy.ravel(Y); Zvec=numpy.ravel(Z); A=(numpy.power(Xvec,(1)))*(numpy.power(Yvec,(1)))*(numpy.power(Zvec,(1))) P=numpy.zeros(shape=(Xvec.size,order**3)) for k in range(order): for m in range(order): for n in range(order): P[:,(k)*(order)**2 + (m)*(order) + n] = (Xvec**k)*(Yvec**m)*(Zvec**n); Q= numpy.linalg.pinv(P, rcond=1e-12) Bvec=numpy.absolute(Image); D=Bvec[I] D=numpy.expand_dims(D,axis=1) print(Q.shape) print(D.shape) c = numpy.dot(Q,D); Bvecout=numpy.dot(P,c); if Image.ndim ==2 : InterpolatedImage=numpy.reshape(Bvecout,(Image.shape[0],Image.shape[1])) from visualization import PlotReconstructedImage PlotReconstructedImage(Image) PlotReconstructedImage(InterpolatedImage) if save: from nifty_funclib import SaveArrayAsNIfTI Hpath, Fname = os.path.split(str(OutputPath)) Fname = Fname[0].split('.') OutputPath = os.path.join( Hpath + '\\' + Fname[0] + 'Interpolated_Image_order_'+order+'.nii') SaveArrayAsNIfTI(InterpolatedImage,1,1,1,OutputPath) if Image.ndim ==3 : InterpolatedImage=numpy.reshape(Bvecout,(Image.shape[0],Image.shape[1],Image.shape[2])) PlotReconstructedImage(InterpolatedImage) if save: from nifty_funclib import SaveArrayAsNIfTI Hpath, Fname = os.path.split(str(OutputPath)) Fname = Fname[0].split('.') OutputPath = os.path.join( Hpath + '\\' + Fname[0] + 'Interpolated_Image_order_'+order+'.nii') SaveArrayAsNIfTI(InterpolatedImage,1,1,1,OutputPath) return InterpolatedImage
# for j in range(0,KX.shape[1],10): f.write(str(1)) f.write(',') f.write(str(1)) f.write(',') f.write(str(i)) f.write(',') f.write(str(float(Kx[i]))) f.write(',') f.write(str(float(Ky[i]))) f.write(',') f.write(str(float(Kz[i]))) f.write(',') f.write(str(numpy.real(CplxData[i % CplxData.shape[0], i % 48]))) f.write(',') f.write(str(numpy.imag(CplxData[i % CplxData.shape[0], i % 48]))) f.write("\n") f.close() if not HeaderOnly: ReconstructedImg, modulekspace, phasekspace = RegridBruker( parameters[0], parameters[1], parameters[2], 1, 1, parameters[3], CplxData, Kx, Ky, Kz, coefsR, coefsP, coefsS, parameters[10], verbose) from nifty_funclib import SaveArrayAsNIfTI, SaveArrayAsNIfTI_2 SaveArrayAsNIfTI(ReconstructedImg, float(parameters[7]), float(parameters[8]), float(parameters[9]), OutputPath) SaveArrayAsNIfTI(modulekspace, 1, 1, 1, "test_fantome_bruker_Kspace_Hsymetry2_test.nii") SaveArrayAsNIfTI(phasekspace, 1, 1, 1, "test_fantome_bruker_Kspace_Hsymetry2_test_phase.nii")
else : T1FA[i,j,k]=0 M0_T1FA[i,j,k]=0 from nifty_funclib import SaveArrayAsNIfTI Hpath, Fname = os.path.split(str(outputnii)) Fname = Fname.split('.') specialname="" #specialname="midang1midang2" OutputPathT1 = os.path.join( Hpath + '\\' + Fname[0]+"_T1-3D.nii") OutputPathE1FA = os.path.join( Hpath + '\\' + Fname[0]+ "_E1_3D.nii") OutputPathM0FA = os.path.join( Hpath + '\\' + Fname[0]+ "_M0_FA.nii") OutputPathM0spec = os.path.join( Hpath + '\\' + Fname[0]+ "_M0_spec.nii") OutputPathrho_T1FA = os.path.join( Hpath + '\\' + Fname[0]+ "_rho_FA.nii") OutputPathrho_T1spec = os.path.join( Hpath + '\\' + Fname[0]+ "_rho_spec.nii") OutputPathsumtest = os.path.join( Hpath + '\\' + Fname[0]+ "_sumtest.nii") #OutputPathrhohyp = os.path.join( Hpath + '\\' + "rhohyp-3D2.nii") if verbose: print((degval1,degval2,T1spec,E1spec)) print((OutputPathT1,OutputPathE1FA,OutputPathM0FA,OutputPathM0spec,OutputPathrho_T1FA,OutputPathrho_T1spec)) print(Fname) SaveArrayAsNIfTI(T1FA,res,res,res,OutputPathT1) #SaveArrayAsNIfTI(E1FA,res,res,res,OutputPathE1FA) SaveArrayAsNIfTI(M0_T1FA,res,res,res,OutputPathM0FA) #SaveArrayAsNIfTI(M0_T1spec,res,res,res,OutputPathM0spec) SaveArrayAsNIfTI(rho_T1FA,res,res,res,OutputPathrho_T1FA) SaveArrayAsNIfTI(rho_T1spec,res,res,res,OutputPathrho_T1spec) #SaveArrayAsNIfTI(sumtest,res,res,res,OutputPathsumtest)
new_affine[2,3]=new_affine[2,3]-new_affine[2,2] affine=new_affine #affine=np.array([[4., 0., 0., -95], [0., 4., 0., -126], [0., 0., 4., -95], [0., 0., 0., 1.]]) del new_affine if B0correct: freq=parameters[23] Timesampling=parameters[1]*parameters[26]*10**(-6) if field_interpol: fieldmap_data=Fieldmap_to_Source_space(source_shape,affine,fieldmap_file_orig) Hpath, Fname = os.path.split(str(OutputPath)) OutputPath = os.path.join( Hpath + '/' + Fname[0] + '_fieldmap.nii') #SaveArrayAsNIfTI(Reconstruct_multiplier*ReconstructedImg[0,:,:,:],pix_x,pix_y,pix_z,OutputPath) SaveArrayAsNIfTI(fieldmap_data,affine,OutputPath) fieldmap_file=OutputPath else: fieldmap_data=Fieldmap_get(fieldmap_file) Nucleus=parameters[6] GammaH = 42.576e6 if Nucleus.find("1H")>-1: Gamma = 42.576e6 ratio=1 elif Nucleus.find("23Na")>-1: Gamma=11.262e6 ratio=Gamma/GammaH elif Nucleus.find("31P")>-1: Gamma= 17.235e6 ratio=Gamma/GammaH elif Nucleus.find("7Li")>-1:
def KaiserBesselRegridding(): i = 0 Kpos = open( "C:\\Users\AC243636\Documents\Versioned_code\python\Data_Carole\samples.csv", 'r') Kdata = open( "C:\\Users\AC243636\Documents\Versioned_code\python\Data_Carole\datavalues_bab_1000NEX.csv", 'r') KPOS = numpy.zeros(shape=(129408, 2), dtype=numpy.float32) KVAL = numpy.zeros(shape=(129408, 1), dtype=numpy.complex64) for line in Kpos: values = line.split(',') KPOS[i, 0] = values[0] KPOS[i, 1] = values[1] i = i + 1 if i == 6066: break i = 0 for line in Kdata: if i % 4 == 0: values = line.split(',') Re = values[0] Imag = values[1] KVAL[i] = complex(float(Re), float(Imag)) i = i + 1 if i == 6066: break #Compute Kaiser Bessel NormalizedKernel, u, beta = CalculateKaiserBesselKernel(3, 2, 4) NormalizedKernelflip = numpy.flipud(NormalizedKernel) # print((NormalizedKernelflip)) NormalizedKernelflip = numpy.delete(NormalizedKernelflip, 2) NormalizedKernel = numpy.append(NormalizedKernelflip, NormalizedKernel) print((NormalizedKernel)) NormalizedKernel = numpy.mat(NormalizedKernel) NormalizedKernel2D = numpy.transpose(NormalizedKernel) * (NormalizedKernel) print(NormalizedKernel2D) print((NormalizedKernel2D.shape)) #Perform Gridding #1) Generate K space trajectory from scipy.spatial import Voronoi, voronoi_plot_2d import matplotlib.pyplot as plt # points = numpy.column_stack((a,b)) points = numpy.column_stack( (numpy.ravel(KPOS[:, 0]), numpy.ravel(KPOS[:, 1]))) # compute Voronoi tesselation vor = Voronoi(points) voronoi_plot_2d(vor) plt.show() ###########print (len(vor.regions)) area = numpy.zeros(len(vor.regions)) for node in range(len(vor.regions)): xv = vor.vertices[vor.regions[node], 0] yv = vor.vertices[vor.regions[node], 1] #############print (xv,yv) if ((xv != [] and yv != []) and (len(xv) == 4)): area[node] = simple_poly_area(xv, yv) #############print ("Aire ",node," == ",simple_poly_area(xv, yv)) # weightVoronoi=numpy.unique(numpy.round(area,9)) # weightVoronoi=numpy.sort(numpy.round(area,9)) # print weightVoronoi.shape weightVoronoi = numpy.round(area, 9) + (1 / (int(2022))) weightVoronoi = weightVoronoi / max(weightVoronoi) weightVoronoi = numpy.append(weightVoronoi, 1) print(weightVoronoi.shape) weightVoronoi[0] = 1e-7 f = open("VornoiCoefCarole.txt", "w") for j in range(0, 6065): f.write(str(weightVoronoi[j])) f.write("\n") f.close() del (points) del (vor) del (area) del (xv) del (yv) return # LinearWeigths=numpy.linspace(1/(2022), 1,2022) # LinearWeigths=numpy.delete(LinearWeigths,0) # LinearWeigths=numpy.append(LinearWeigths,1) # print LinearWeigths.shape imsize = 2048 size = 2048 * 1.5 # On utilise une grille 2 fois plus grande pour minimiser les erreurs de regridding et on crop apres # size = NbPoints*OverSamplingFactor*2*2 # Regridded_kspace = numpy.zeros(shape=(int(NbSlice),int(NbCoils),int(size)+2,int(size)+2), dtype=numpy.complex64) # Coil_Combined_Kspace = numpy.zeros(shape=(int(NbSlice),int(size)+2,int(size)+2)) Regridded_kspace = numpy.zeros(shape=(int(size), int(size)), dtype=numpy.complex64) ImageMag = numpy.zeros(shape=(int(size), int(size)), dtype=numpy.float32) # We generate a random value (Uniform Distribution (Gaussian ?)) and compare it with some threshold to remove the line Val = 0j for m in range(129408): x_current = numpy.round(KPOS[m][0] / numpy.amax(KPOS[:, 0]) * size / 2) y_current = numpy.round(KPOS[m][1] / numpy.amax(KPOS[:, 1]) * size / 2) # Val=DataAvg[j][i][l][m] # Val=DataAvg[m]*weightVoronoi[m] Val = KVAL[m, 0] * LinearWeigths[m % 64] # print(Val) for a in range(-1, 1, 1): for b in range(-1, 1, 1): # print a,b # print Val*NormalizedKernel2D[a+1,b+1] # print type(Val) # print type(KVAL[m,0]) # print type(Regridded_kspace[y_current+a][x_current+b]) Regridded_kspace[y_current + a][ x_current + b] = Regridded_kspace[y_current + a][ x_current + b] + Val * NormalizedKernel2D[a + 1, b + 1] # print Regridded_kspace[y_current+a][x_current+b] ImageMag[:][:] = (numpy.fft.fftshift( numpy.fft.ifftn(numpy.fft.fftshift((Regridded_kspace[:][:]))))) PlotReconstructedImage(ImageMag) # PlotReconstructedImage((Coil_Combined_Kspace_Module[j,imsize/2:imsize+imsize/2,imsize/2:imsize+imsize/2])/C) PlotImgMag(numpy.absolute((ImageMag))) print("[DONE]") from nifty_funclib import SaveArrayAsNIfTI SaveArrayAsNIfTI(ImageMag, 1, 1, 1, "Carole.nii") return ImageMag
) #(= FOV_y / (nbpts (*oversamplingFactor)*2) (On a deux radiales pour une dim de FOV) else: pix_x = float(2 * float(parameters[8]) / (float(parameters[1]) * float(parameters[5]))) pix_y = float( float(parameters[9]) / (float(parameters[0])) ) #(= FOV_y / nbLines (EN CARTESIEN) (NO oversampling in this direction)) if TPI: pix_x = float(parameters[21]) pix_y = float(parameters[21]) pix_z = float(parameters[21]) from nifty_funclib import SaveArrayAsNIfTI, SaveArrayAsNIfTI_2 if not TPI: SaveArrayAsNIfTI(ReconstructedImg, pix_x, pix_y, float(parameters[10]), OutputPath) # SaveArrayAsNIfTI_2(ReconstructedImg,pix_x,pix_y,float(parameters[10]),NbPoints,NbLines,NbSlices,rad,orientation,OutputPath) # SaveArrayAsNIfTI_2(ReconstructedImg,pix_x,pix_y,float(parameters[10]),int((parameters[1])*(parameters[5])*2),int(parameters[0]),int(parameters[4]),rad,str(parameters[12]),OutputPath) if TPI: if MIA: parameters[24] = 3 if int(parameters[24]) == 1: Hpath, Fname = os.path.split(str(OutputPath)) Fname = Fname[0].split('.') if SavePhase: OutputPath = os.path.join(Hpath + '/' + Fname[0] + '_KBgrid_MODULE.nii') SaveArrayAsNIfTI(ReconstructedImg[0, :, :, :], pix_x, pix_y, pix_z, OutputPath) OutputPath = os.path.join(Hpath + '/' + Fname[0] + '_KBgrid_PHASE.nii')
E1 * E2) / (kval * np.sqrt(E2) * (1 - E1) * np.sin(FAMap[i, j, k])) elif seq == 'TPI': rho_SSFP[i, j, k] = Img[i, j, k] / (kval * (np.tan(FAMap[i, j, k] / 2) * (1 - (E1 - np.cos(FAMap[i, j, k])) * rval(E1, FAMap[i, j, k], E2)))) else: print('error') #rho_SSFP[i,j,k]=Img[i,j,k]/(kval*(np.tan(FAMap[i,j,k]/2)*(1-(E1-np.cos(FAMap[i,j,k]))*rval(E1,FAMap[i,j,k],E2)))); # 1/(kvalSSFP*(np.tan(degval/2)*(1-(E1spec-np.cos(degval))*rval(E1spec,degval,E2)))) from nifty_funclib import SaveArrayAsNIfTI Hpath, Fname = os.path.split(str(outputnii)) Fname = Fname.split('.') #OutputPathrho_T1SPGR = os.path.join( Hpath + '/' + Fname[0]+ "_rhoSPGR.nii") #OutputPathrho_T1SSFP = os.path.join( Hpath + '/' + Fname[0]+ "_rhoSSFP.nii") if seq == 'trufi': OutputPathrho_SSFP_test = os.path.join(Hpath + '/' + Fname[0] + "_rho_bSSFP.nii") elif seq == 'TPI': OutputPathrho_SSFP_test = os.path.join(Hpath + '/' + Fname[0] + "_rho_SSFP.nii") if verbose: print((degval, T1, E1)) #SaveArrayAsNIfTI(rho_T1SSFP,affine,OutputPathrho_T1SSFP) SaveArrayAsNIfTI(rho_SSFP, affine, OutputPathrho_SSFP_test) #SaveArrayAsNIfTI(rho_T1SPGR,affine,OutputPathrho_T1SPGR)