NuMRI/codes/Graphics.py

1582 lines
61 KiB
Python
Raw Normal View History

2020-01-17 16:24:10 +01:00
import h5py
from dolfin import *
import numpy as np
from matplotlib import pyplot as plt
import scipy as sc
import scipy.io as sio
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
import os, sys
import csv
from common import inout
import time
from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def MATmedical(path):
datatype = None
if 'ODV' in path:
datatype = 'odv'
print('The DATA file has the next structure: [x,y,z,coil,CardiacPhase,gradient,NSA] where x \
and y are the spatial dimensions for the image. z is one because is only one slice. Coil is \
the number of coils (5), CardiacPhase is the time dimension. Gradient is the number of gradients used in the \
adquisition (2). NSA is the number of signal average.')
if 'Phantom' in path:
datatype = 'cib_phantom'
#print('CIB phantom data which contains magnitude and velocity measurements.')
if not datatype=='cib_phantom':
STRUC = sio.loadmat(path)
DAT0 = STRUC['data']
if datatype=='odv':
KDAT0 = STRUC['kdata']
[row,col,coil,numt2,p4,p5] = DAT0.shape
else:
KDAT0 = STRUC['k_data']
[row,col,slicesel,coil,numt2,p4,p5] = DAT0.shape
z0 = 0
NSA = 0
coilnum = 3
DAT1 = np.zeros([row,col,numt2],dtype=complex)
DAT2 = np.zeros([row,col,numt2],dtype=complex)
KDAT1 = np.zeros([row,col,numt2],dtype=complex)
KDAT2 = np.zeros([row,col,numt2],dtype=complex)
if datatype=='odv':
for k in range(numt2):
DAT1[:,:,k] = DAT0[:,:,coilnum,k,0,NSA]
DAT2[:,:,k] = DAT0[:,:,coilnum,k,1,NSA]
KDAT1[:,:,k] = KDAT0[:,:,coilnum,k,0,NSA]
KDAT2[:,:,k] = KDAT0[:,:,coilnum,k,1,NSA]
return [DAT1,DAT2,KDAT1,KDAT2]
else:
UK1 = np.zeros([row,col,numt2],dtype=complex)
UK2 = np.zeros([row,col,numt2],dtype=complex)
for k in range(numt2):
DAT1[:,:,k] = DAT0[:,:,z0,coilnum,k,0,NSA]
DAT2[:,:,k] = DAT0[:,:,z0,coilnum,k,1,NSA]
KDAT1[:,:,k] = KDAT0[:,:,z0,coilnum,k,0,NSA]
KDAT2[:,:,k] = KDAT0[:,:,z0,coilnum,k,1,NSA]
UK1[:,:,k] = np.fft.fftshift(np.fft.fft2(DAT1[:,:,k]))
UK2[:,:,k] = np.fft.fftshift(np.fft.fft2(DAT2[:,:,k]))
return [DAT1,DAT2,KDAT1,KDAT2]
elif datatype=='cib_phantom':
lp = len(path)
for k in range(lp):
if path[lp-1-k]=='/':
name_var = path[lp-k:lp]
break
name_var = name_var.replace('.mat','')
if name_var in ['VENC','Segmented_Aorta','voxel_MR']:
STRUC = sio.loadmat(path)
return STRUC[name_var]
else:
#import h5py
arrays = {}
f = h5py.File(path)
for k, v in f.items():
arrays[k] = np.array(v)
return arrays[name_var].transpose((1,2,3,0))
def Plot_Inlet():
''' To Show the flow given at the inlet in the FEM simulation '''
Tf = 0.9
dt = 0.0005
t = np.linspace(0,Tf,Tf/dt)
U = 60
Th = 0.37
DOLFIN_PI = 3.1416
y = U*np.sin(DOLFIN_PI*t/Th)*(t<=Th) + (Th<t)*(3.67949466208*U*np.sin(9*DOLFIN_PI*t/Th)*np.exp(-t*10))
Delta = 5
ts = 0.33
beta = DOLFIN_PI/Th*(Delta/np.tan(Delta*DOLFIN_PI*ts/Th) - 1/np.tan(DOLFIN_PI*ts/Th))
alpha = np.exp(ts*beta)*np.sin(DOLFIN_PI*ts/Th)/np.sin(Delta*DOLFIN_PI*ts/Th)
y2 = U*np.sin(DOLFIN_PI*t/Th)*(t<=ts) + (ts<t)*(alpha*U*np.sin(Delta*DOLFIN_PI*t/Th)*np.exp(-t*beta) )
print('alpha',alpha)
print('beta',beta)
plt.plot(t,y2)
plt.show()
def Plot_Histogram(meshnames,paths,colors,outpath):
alphas = [0.72, 1]
plt.figure(figsize=(8, 6), dpi=100)
ind = 0
for nm in range(len(meshnames)):
if 'box' in meshnames[nm]:
# VOXEL SEQUENCE SIZE
Lx = 64
Ly = 64
Lz = 90
# The BOX where undersampling take place
x0 = 10
y0 = 12
z0 = 0
x1 = 21
y1 = 20
z1 = 12
ddx = (x1-x0)/(Lx-1)
ddy = (y1-y0)/(Ly-1)
ddz = (z1-z0)/(Lz-1)
# LAGRANGE
plt.axvline(x=10*np.sqrt(ddx**2+ddy**2+ddz**2),
linewidth=2, color=colors[nm])
break
mesh = Mesh()
hdf = HDF5File(mesh.mpi_comm(), paths[nm] + meshnames[nm] + '.h5', 'r')
hdf.read(mesh, '/mesh', False)
hdf.close()
Cells = mesh.cells()
Points = mesh.coordinates()
Hi = np.zeros([mesh.num_cells()])
inradius_method = False
circumradius_method = True
heights_method = False
for k in range(mesh.num_cells()):
# Coordinates of each cell (A,B,C,D)
A = Points[Cells[k]][0]
B = Points[Cells[k]][1]
C = Points[Cells[k]][2]
D = Points[Cells[k]][3]
if heights_method:
hs = np.zeros([4])
for l in range(4):
if l == 0:
[P1, P2, P3, P4] = [A, B, C, D]
if l == 1:
[P1, P2, P3, P4] = [D, A, B, C]
if l == 2:
[P1, P2, P3, P4] = [C, D, A, B]
if l == 3:
[P1, P2, P3, P4] = [B, C, D, A]
n = np.cross(P2-P1, P3-P1)
n = n/np.linalg.norm(n)
d = -np.inner(n, P1)
hs[l] = np.abs(np.inner(n, P4) + d)
h_meas = np.max(hs)
if inradius_method:
Vi = 1/6*np.abs(np.inner(A-D, np.cross(B-D, C-D))) # Volume
a1 = 0.5*np.linalg.norm(np.cross(B-A, C-A))
a2 = 0.5*np.linalg.norm(np.cross(B-A, D-A))
a3 = 0.5*np.linalg.norm(np.cross(C-B, D-B))
a4 = 0.5*np.linalg.norm(np.cross(C-A, D-A))
inradius = 3*Vi/(a1+a2+a3+a4)
h_meas = inradius
if circumradius_method:
# From: 'http://mathworld.wolfram.com/Circumsphere.html'
Ma = np.zeros([4, 4])
Mc = np.zeros([4, 4])
Mx = np.zeros([4, 4])
My = np.zeros([4, 4])
Mz = np.zeros([4, 4])
sa2 = A[0]**2 + A[1]**2 + A[2]**2
sb2 = B[0]**2 + B[1]**2 + B[2]**2
sc2 = C[0]**2 + C[1]**2 + C[2]**2
sd2 = D[0]**2 + D[1]**2 + D[2]**2
e1 = np.concatenate((A, [1]), axis=0)
e2 = np.concatenate((B, [1]), axis=0)
e3 = np.concatenate((C, [1]), axis=0)
e4 = np.concatenate((D, [1]), axis=0)
c1 = np.concatenate(([sa2], A), axis=0)
c2 = np.concatenate(([sb2], B), axis=0)
c3 = np.concatenate(([sc2], C), axis=0)
c4 = np.concatenate(([sd2], D), axis=0)
mx1 = np.concatenate(([sa2], [A[1]], [A[2]], [1]), axis=0)
mx2 = np.concatenate(([sb2], [B[1]], [B[2]], [1]), axis=0)
mx3 = np.concatenate(([sc2], [C[1]], [C[2]], [1]), axis=0)
mx4 = np.concatenate(([sd2], [D[1]], [D[2]], [1]), axis=0)
my1 = np.concatenate(([sa2], [A[0]], [A[2]], [1]), axis=0)
my2 = np.concatenate(([sb2], [B[0]], [B[2]], [1]), axis=0)
my3 = np.concatenate(([sc2], [C[0]], [C[2]], [1]), axis=0)
my4 = np.concatenate(([sd2], [D[0]], [D[2]], [1]), axis=0)
mz1 = np.concatenate(([sa2], [A[0]], [A[1]], [1]), axis=0)
mz2 = np.concatenate(([sb2], [B[0]], [B[1]], [1]), axis=0)
mz3 = np.concatenate(([sc2], [C[0]], [C[1]], [1]), axis=0)
mz4 = np.concatenate(([sd2], [D[0]], [D[1]], [1]), axis=0)
Ma[0, :] = e1
Ma[1, :] = e2
Ma[2, :] = e3
Ma[3, :] = e4
Mc[0, :] = c1
Mc[1, :] = c2
Mc[2, :] = c3
Mc[3, :] = c4
Mx[0, :] = mx1
Mx[1, :] = mx2
Mx[2, :] = mx3
Mx[3, :] = mx4
My[0, :] = my1
My[1, :] = my2
My[2, :] = my3
My[3, :] = my4
Mz[0, :] = mz1
Mz[1, :] = mz2
Mz[2, :] = mz3
Mz[3, :] = mz4
a = np.linalg.det(Ma)
c = np.linalg.det(Mc)
Dx = np.linalg.det(Mx)
Dy = -np.linalg.det(My)
Dz = np.linalg.det(Mz)
circumradius = np.sqrt(
Dx**2 + Dy**2 + Dz**2-4*a*c)/(2*np.abs(a))
h_meas = 2*circumradius
# mean of Inradius and Circumraidius in milimiters
Hi[k] = 10*(h_meas)
print('Size of ' + meshnames[nm] + ' :', np.min(Hi), np.max(Hi))
plt.hist(Hi, bins=60, range=[0, 10], density=True, edgecolor='black',
color=colors[nm], alpha=alphas[0], label= '$' + meshnames[nm] + '$')
ind = ind+1
plt.ylim([0,1.3])
plt.xlabel('$h \ (mm)$',fontsize=18)
plt.ylabel('$n^o \ of \ elements$',fontsize=18)
plt.legend(fontsize=16)
plt.savefig(outpath + 'Histograms.png',dpi=500)
plt.show()
def PlotTest(D0,D1,D2,D3):
fig = plt.figure(figsize=(10, 6), dpi=100)
vvmin = 0
vvmax = 60
title1 = 'Reference'
title2 = 'Aliased'
title3 = 'Dealiased'
title4 = 'Full sampled'
ax0 = fig.add_subplot(1,4,1)
plt.imshow(D0, cmap='magma', interpolation='nearest')
#plt.imshow(D0, cmap='magma', interpolation='nearest',vmin=vvmin,vmax=vvmax)
plt.title(title1)
ax0.set_aspect('auto')
plt.xticks([])
plt.yticks([])
ax1 = fig.add_subplot(1,4,2)
plt.imshow(D1, cmap='magma', interpolation='nearest')
#plt.imshow(D1, cmap='magma', interpolation='nearest',vmin=vvmin,vmax=vvmax)
plt.title(title2)
ax1.set_aspect('auto')
plt.xticks([])
plt.yticks([])
ax2 = fig.add_subplot(1,4,3)
plt.imshow(D2, cmap='magma', interpolation='nearest')
#plt.imshow(D2, cmap='magma', interpolation='nearest',vmin=vvmin,vmax=vvmax)
plt.title(title3)
ax2.set_aspect('auto')
plt.xticks([])
plt.yticks([])
ax3 = fig.add_subplot(1,4,4)
plt.imshow(D3, cmap='magma', interpolation='nearest')
#plt.imshow(D3, cmap='magma', interpolation='nearest',vmin=vvmin,vmax=vvmax)
plt.title(title4)
ax3.set_aspect('auto')
plt.xticks([])
plt.yticks([])
plt.show()
def TakePhoto(M1,scale_mode='auto'):
fig = plt.figure(figsize=(10, 6), dpi=100)
title1 = '$M(x_0,y,f)$'
if scale_mode=='auto':
plt.imshow(M1, cmap='viridis', interpolation='nearest')
else:
plt.imshow(M1, cmap='viridis', interpolation='nearest',vmin=scale_mode[0],vmax=scale_mode[1])
#plt.axes().set_aspect('auto')
#plt.tight_layout()
#plt.title(title1,fontsize=20)
plt.xticks([])
plt.yticks([])
#plt.xlabel('$f$',fontsize=20)
#plt.ylabel('$y$',fontsize=20)
plt.show()
def PrintSequence(A,scale_mode='auto',window=0,repeat=0,recorder=False):
plt.ion()
fig = plt.figure(figsize=(8, 6), dpi=100)
ax = fig.add_subplot(1,1,1)
[row,col,numt2] = A.shape
maxA = np.max(A)
minA = np.min(A)
from matplotlib.colors import LinearSegmentedColormap
basic_cols = ['#ff4e2b', '#000000', '#1893db']
my_cmap = LinearSegmentedColormap.from_list('mycmap', basic_cols)
if window==1:
ywin = [row*0.50+10,row*0.50-12]
xwin = [col*0.5-12,col*0.5+11]
if window==4:
ywin = [190,140]
xwin = [35,90]
for rp in range(-1,repeat):
for k in range(numt2):
if scale_mode=='auto':
plt.imshow(A[:,:,k],cmap='magma', interpolation='nearest',vmin=minA,vmax=maxA*1.1)
if scale_mode=='none':
plt.imshow(A[:,:,k],cmap='magma', interpolation='nearest')
#elif scale_mode.shape==1:
# plt.imshow(A[:,:,k],cmap=my_cmap, interpolation='nearest',vmin=scale_mode[0],vmax=scale_mode[1])
if window>0:
plt.ylim(ywin)
plt.xlim(xwin)
ax.set_aspect('auto')
plt.xticks([])
plt.yticks([])
#plt.xlabel('$x$',Fontsize=20)
#plt.ylabel('$y$',Fontsize=20)
plt.title('phase ' + str(k))
plt.show()
if recorder:
plt.savefig('results/pictures/frame'+str(k),bbox_inches='tight')
plt.pause(0.101)
plt.clf()
def PrintSequence2(A,X,Y,Z,x,y,z):
plt.ion()
fig = plt.figure(figsize=(7, 7), dpi=100)
ax = fig.add_subplot(1,1,1)
[row,col,dep] = A.shape
xi = np.linspace(np.min(x),np.max(x),row)
yi = np.linspace(np.min(y),np.max(y),col)
yi2 = np.min(yi) + np.max(yi) - yi
from matplotlib.colors import LinearSegmentedColormap
basic_cols = ['#ff4e2b', '#000000', '#1893db']
my_cmap = LinearSegmentedColormap.from_list('mycmap', basic_cols)
ccmap = mpl.cm.Spectral
xt = x
yt = y
zt = z
yt2 = (np.min(y) + np.max(y)) - y
Dz = (np.max(z) - np.min(z))/dep
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shifted'):
'''
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero.
Input
-----
cmap : The matplotlib colormap to be altered
start : Offset from lowest point in the colormap's range.
Defaults to 0.0 (no lower offset). Should be between
0.0 and `midpoint`.
midpoint : The new center of the colormap. Defaults to
0.5 (no shift). Should be between 0.0 and 1.0. In
general, this should be 1 - vmax / (vmax + abs(vmin))
For example if your data range from -15.0 to +5.0 and
you want the center of the colormap at 0.0, `midpoint`
should be set to 1 - 5/(5 + 15)) or 0.75
stop : Offset from highest point in the colormap's range.
Defaults to 1.0 (no upper offset). Should be between
`midpoint` and 1.0.
'''
cdict = {
'red': [],
'green': [],
'blue': [],
'alpha': []
}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack([
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True)
])
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict['red'].append((si, r, r))
cdict['green'].append((si, g, g))
cdict['blue'].append((si, b, b))
cdict['alpha'].append((si, a, a))
newcmap = mpl.colors.LinearSegmentedColormap(name, cdict)
plt.register_cmap(cmap=newcmap)
return newcmap
ccmap = mpl.cm.Spectral
shifted_ccmap = shiftedColorMap(ccmap, midpoint=0.75, name='shifted')
for k in range(dep):
zmin = np.min(z) + k*Dz
zmax = zmin + Dz
xs = np.array([])
ys = np.array([])
zs = np.array([])
for j in range(z.size):
if z[j]>= zmin and z[j]<zmax:
xs = np.concatenate((xs,[xt[j]]))
ys = np.concatenate((ys,[yt[j]]))
zs = np.concatenate((zs,[zt[j]]))
[xs2,ys2] = ToolsF.getpixel(xs,ys,xi,yi)
Afil = ToolsF.FilterWithPoints(A[:,:,k],X,Y,Z,xs,ys,xi,yi,k,0.1)
plt.plot(xi[xs2],yi2[ys2],'.w')
plt.imshow(Afil,cmap=my_cmap, extent=(np.min(xt),np.max(xt),np.min(yt),np.max(yt)),interpolation='nearest',vmin=-80,vmax=80)
plt.xticks([])
plt.yticks([])
plt.title('phase ' + str(k))
plt.show()
plt.pause(0.101)
plt.clf()
def ComparePoint(A,B,norma,center):
Anorm = A
Bnorm = B
if norma==1:
Anorm = np.abs(A)*100/np.amax(A)
Bnorm = np.abs(B)*100/np.amax(B)
fig = plt.figure()
[row,col,numt2] = A.shape
tvec = np.linspace(0,numt2,numt2)
CA = np.zeros(tvec.shape)
CB = np.zeros(tvec.shape)
if center==2:
yc = int(col*0.5)
xc = int(row*0.5)
if center==1:
yc = int((col-1)*0.5)
xc = int((row-1)*0.4)
if center==0:
yc = 76
xc = 162
for k in range(numt2):
CA[k] = Anorm[xc,yc,k]
CB[k] = Bnorm[xc,yc,k]
plt.plot(tvec,CA,'-r',label='$Rec$')
plt.plot(tvec,CB,'-b',label='$Orig$')
plt.xlabel('$time \ \ frame$',fontsize=20)
plt.ylabel('$ velocity $',fontsize=20)
plt.legend(fontsize=15)
plt.show()
def CenterComparison(A,B,C,R,center):
title1 = '$Orig$'
title2 = '$KTB-$'+ str(R)
title3 = '$CS-$' + str(R)
fig = plt.figure()
[row,col,numt2] = A.shape
tvec = np.linspace(0,numt2,numt2)
CA = np.zeros(tvec.shape)
CB = np.zeros(tvec.shape)
CC = np.zeros(tvec.shape)
if center==2:
yc = int(col*0.5)
xc = int(row*0.5)
if center==1:
yc = int((col-1)*0.5)
xc = int((row-1)*0.4)
if center==0:
yc = 76
xc = 162
for k in range(numt2):
CA[k] = A[xc,yc,k]
CB[k] = B[xc,yc,k]
CC[k] = C[xc,yc,k]
plt.plot(tvec,CA,'-k',label=title1)
plt.plot(tvec,CB,'-b',label=title2)
plt.plot(tvec,CC,'-r',label=title3)
plt.xlabel('$time \ \ frame$',fontsize=20)
plt.ylabel('$ velocity $',fontsize=20)
plt.legend(fontsize=12)
plt.show()
def VelocityChannel(M,repeat,recorder):
[row,col,numt2] = M.shape
[X,Y] = np.meshgrid(np.linspace(0,col,col),np.linspace(0,row,row))
plt.ion()
rown = row*6/row
coln = col*6/row
fig = plt.figure()#figsize=(4, 6) , dpi=200)
ax = fig.add_subplot(111, projection='3d')
for rr in range(-1,repeat):
for t in range(numt2):
V = M[:,:,t]
#ax.plot_surface(X, Y, V, cmap=plt.cm.magma, vmin=-30, vmax=50, linewidth=0, antialiased=False)
#ax.plot_wireframe(X, Y, V,rcount=20,ccount=20,linewidth=0.5)
ax.plot_surface(X, Y, V,cmap='magma',vmin=-30, vmax=100, linewidth=0, antialiased=False)
ax.set_zlim(-120, 150)
#ax.set_xlim( 40, 80)
#ax.set_ylim( 100, 180)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$v(r)$')
ax.set_title('phase ' + str(t))
plt.pause(0.001)
plt.draw()
if recorder==1:
plt.savefig('Pictures/frame'+str(t))
if t<numt2-1:
plt.cla()
def PlotTri(tri,pos,p):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
#ax.plot_trisurf(pos[:,0], pos[:,1], pos[:,2], triangles=tri.simplices, cmap=plt.cm.Spectral,linewidth=0.1,edgecolors='k')
#ax.tripcolor(pos[:,0], pos[:,1], pos[:,2], triangles=tri.simplices, facecolors=p2.T, edgecolor='black')
plt.show()
def PlotPressureDrop(mode):
barye2mmHg = 1/1333.22387415
CT = np.loadtxt('Pressure/DROPS/pd_NS_coarse.txt')
CT2 = np.loadtxt('Pressure/DROPS/pd_NS_coarse2.txt')
ref_ao = np.loadtxt('Pressure/DROPS2/refPPE1_coarse.txt')
ref = np.loadtxt('Pressure/DROPS2/refPPE1_coarse_leo1.txt')
CS2 = np.loadtxt('Pressure/DROPS2/CSPPE2_coarse_leo1.txt')
PPE_CT = np.loadtxt('Pressure/DROPS/pd_PPE_NS_coarse.txt')
PPE_CT_leo = np.loadtxt('Pressure/DROPS/pd_PPE_NS_coarse_leo1.txt')
STE_CT = np.loadtxt('Pressure/DROPS/test_STE_R1_coarse.txt')
test_STE_CT = np.loadtxt('Pressure/DROPS/test2_STE_R1_coarse_leo1.txt')
STEint_CT = np.loadtxt('Pressure/DROPS/test_STEint_R1_coarse.txt')
test_STEint_CT = np.loadtxt('Pressure/DROPS/test2_STEint_R1_coarse_leo1.txt')
# UNDERSAMPLING
PPE_R1_leo1 = np.loadtxt('Pressure/DROPS/test_PPE_R1_coarse_leo1.txt')
PPE_KT_R2_leo1 = np.loadtxt('Pressure/DROPS/KT_PPE_R2_coarse_leo1.txt')
PPE_KT_R4_leo1 = np.loadtxt('Pressure/DROPS/KT_PPE_R4_coarse_leo1.txt')
PPE_KT_R8_leo1 = np.loadtxt('Pressure/DROPS/KT_PPE_R8_coarse_leo1.txt')
PPE_KT_R12_leo1 = np.loadtxt('Pressure/DROPS/KT_PPE_R12_coarse_leo1.txt')
PPE_KT_R20_leo1 = np.loadtxt('Pressure/DROPS/KT_PPE_R20_coarse_leo1.txt')
PPE_CS_R2_leo1 = np.loadtxt('Pressure/DROPS/CS_PPE_R2_coarse_leo1.txt')
PPE_CS_R4_leo1 = np.loadtxt('Pressure/DROPS/CS_PPE_R4_coarse_leo1.txt')
PPE_CS_R8_leo1 = np.loadtxt('Pressure/DROPS/CS_PPE_R8_coarse_leo1.txt')
PPE_CS_R12_leo1 = np.loadtxt('Pressure/DROPS/CS_PPE_R12_coarse_leo1.txt')
PPE_CS_R20_leo1 = np.loadtxt('Pressure/DROPS/CS_PPE_R20_coarse_leo1.txt')
#CT_fine = np.loadtxt('Pressure/DROPS/pd_NS_fine.txt')
#CT_fine_T = np.loadtxt('Pressure/DROPS/pd_NS_fine_T.txt')
#PPE_CT_fine = np.loadtxt('Pressure/DROPS/pd_PPE_NS_fine.txt')
#PPE_CT_fine_leo3 = np.loadtxt('Pressure/DROPS/pd_PPE_NS_fine_leo3.txt')
tvec2 = np.linspace(0, 2.5 ,PPE_CT_leo.size)
tvec = np.linspace(tvec2[1]*0.5 ,2.5+tvec2[1]*0.5 , CT.size)
#tvec_T = np.linspace(0,2.5,CT_fine_T.size)
fig = plt.figure()
if mode=='KT':
plt.plot(tvec,CT,'-k',linewidth=2,label='$ref$')
plt.plot(tvec2,PPE_R1_leo1,'xkcd:red',linewidth=2,linestyle='-' , label='$R = 1$')
plt.plot(tvec2,PPE_KT_R2_leo1,'xkcd:blue',linewidth=2,linestyle='-' ,label='$R = 2$')
plt.plot(tvec2,PPE_KT_R4_leo1,'xkcd:green',linewidth=2,linestyle='-',label='$R = 4$')
plt.plot(tvec2,PPE_KT_R8_leo1,'xkcd:orange',linewidth=2,linestyle='-',label='$R = 8$')
plt.plot(tvec2,PPE_KT_R20_leo1,'xkcd:magenta',linewidth=2,linestyle='-', label='$R = 20$')
plt.title('$kt-BLAST$',fontsize=20)
if mode=='CS':
plt.plot(tvec,CT,'-k',linewidth=2,label='$ref$')
plt.plot(tvec2,ref_ao,'xkcd:red',linewidth=2,linestyle='--' , label='$aorta$')
plt.plot(tvec2,ref,'xkcd:red',linewidth=2,linestyle='-' , label='$leo$')
plt.plot(tvec2,CS2,'xkcd:blue',linewidth=2,linestyle='-' ,label='$R = 2$')
#plt.plot(tvec2,PPE_R1_leo1,'xkcd:red',linewidth=2,linestyle='-' , label='$R = 1$')
#plt.plot(tvec2,PPE_CS_R2_leo1,'xkcd:blue',linewidth=2,linestyle='-' ,label='$R = 2$')
#plt.plot(tvec2,PPE_CS_R4_leo1,'xkcd:green',linewidth=2,linestyle='-',label='$R = 4$')
#plt.plot(tvec2,PPE_CS_R8_leo1,'xkcd:orange',linewidth=2,linestyle='-',label='$R = 8$')
#plt.plot(tvec2,PPE_CS_R20_leo1,'xkcd:magenta',linewidth=2,linestyle='-', label='$R = 20$')
plt.title('$Compressed \ \ Sensing$',fontsize=20)
if mode=='STE':
plt.plot(tvec,CT,'-k',linewidth=2,label='$ref$')
plt.plot(tvec2,STE_CT , 'xkcd:purple' , label='STE-CT aorta')
plt.plot(tvec2,test_STE_CT , 'xkcd:purple' , linestyle='--', marker='o', label='STE-CT leo')
if mode=='STEint':
plt.plot(tvec,CT,'-k',linewidth=2,label='$ref$')
plt.plot(tvec2,STEint_CT, 'xkcd:aquamarine', label='STEint-CT aorta')
plt.plot(tvec2,test_STEint_CT, 'xkcd:aquamarine', linestyle='--', marker='o',label='STEint-CT aorta')
plt.ylim([-2,7])
plt.xlabel(r'$time \ \ \ (s)$',fontsize=20)
plt.ylabel(r'$\delta p \ \ \ (mmHg) $',fontsize=20)
plt.legend(fontsize=16)
##############################################################################################################################
#fig = plt.figure()
#plt.plot(tvec2,CT_fine,'-ok',label='CT')
##plt.plot(tvec_T,CT_fine_T,'--k',label='CT T')
#plt.plot(tvec2 ,PPE_CT_fine ,'-om',label='PPE-CT aorta')
#plt.plot(tvec2 ,PPE_CT_fine_leo3,'-oc',label='PPE-CT leo3')
#plt.title('aorta fine')
#plt.xlabel(r'$time \ \ (s) $',fontsize=20)
#plt.ylabel(r'$\delta p \ \ \ (mmHg) $',fontsize=20)
#plt.legend(fontsize=14)
plt.show()
def Plot_flux(masterpath,meshpath,options,mode,R):
mesh = Mesh()
hdf1 = HDF5File(mesh.mpi_comm(), meshpath , 'r')
hdf1.read(mesh, '/mesh', False)
boundaries = MeshFunction('size_t', mesh , mesh.topology().dim() - 1)
hdf1.read(boundaries, '/boundaries')
Evel = VectorElement('Lagrange',mesh.ufl_cell(),1)
V = FunctionSpace(mesh,Evel)
n = FacetNormal(mesh)
MESH = {}
MESH['mesh'] = mesh
MESH['FEM'] = V
t = float(dt)
ds = Measure("ds", subdomain_data=boundaries)
QQ = {}
veli = {}
machine = __import__('4Dflow')
checkpoint_path = masterpath + 'R1/checkpoint/'
veli[1] = machine.READcheckpoint(MESH,'v',1,checkpoint_path,'u')
for r in R:
check_path = masterpath + 'R'+str(r)+'/checkpoint/'
veli[r] = machine.READcheckpoint(MESH,'v',1,check_path,'u')
print('velocities imported')
NT = len(veli[1])
QQ[1] = np.zeros([NT])
for k in R:
QQ[k] = np.zeros([NT])
u = Function(V)
ind = 0
while ind<NT:
u.assign(veli[1][ind])
QQ[1][ind] = assemble(dot(u,n)*ds(2))
ind = ind + 1
for r in R:
ind = 0
while ind<NT:
u.assign(veli[r][ind])
QQ[r][ind] = assemble(dot(u,n)*ds(2))
ind = ind + 1
if mode=='pdrop_black2':
linesize = 4
dotsize = 5
plt.style.use('dark_background')
fig, ax = plt.subplots( figsize=(8, 5), dpi=100)
ax.axis('off')
ref = -QQ[1]
tvec = np.linspace(1,NT,NT)
#ax.set_ylim([-np.max(ref)*0.4,np.max(ref)*1.2])
tend = NT
ax.plot(tvec[0:tend],ref[0:tend],'white',linewidth=linesize,linestyle='-',label='$ref$')
for r in R:
ax.plot(tvec[0:tend],-QQ[r][0:tend],linewidth=linesize,linestyle='-',marker='o',markersize=dotsize)
if options['save_flux']:
fig.savefig(options['save_path']+options['name'], bbox_inches='tight',dpi=500)
plt.show()
def Plot_dP(masterpath,options,mode,R):
import pickle
######################################################################
barye2mmHg = 1/1333.22387415
Dt = 0.03072
if options['dP']['mode'] == 'cib':
barye2mmHg = -0.00750062
elif options['dP']['mode'] == 'ct':
ref = np.loadtxt(masterpath + 'ref.txt')
t = np.linspace(0, Tf, ref.size)
tm = np.linspace(0.5*t[0]+0.5*t[1], 0.5 *
t[t.size-2]+0.5*t[t.size-1], ref.size)
tm = t
tend = ref.size
for estim in options['dP']['estim']:
if estim == 'PPE':
ppe_ref = open(masterpath+'pdrop_PPE_impl_stan.dat', 'rb')
ppe_ref = pickle.load(ppe_ref)['pdrop']*(barye2mmHg)
tend = ppe_ref.size
t = np.linspace(0, tend*Dt, ppe_ref.size)
tm = np.linspace(0.5*t[0]+0.5*t[1], 0.5 *
t[t.size-2]+0.5*t[t.size-1], ppe_ref.size)
tm_ppe = t
if estim == 'STE':
ste_ref = open(masterpath+'pdrop_STE_impl_stan.dat', 'rb')
ste_ref = pickle.load(ste_ref)['pdrop']*(barye2mmHg)
tm_ste = np.linspace(0, ste_ref.size*Dt, ste_ref.size)
if estim == 'DAE':
dae_ref = open(masterpath+'pdrop_DAE_impl_stan.dat', 'rb')
dae_ref = pickle.load(dae_ref)['pdrop']*(barye2mmHg)
if estim == 'COR':
cor_ref = open(masterpath+'pdrop_COR_impl_stan.dat', 'rb')
cor_ref = pickle.load(cor_ref)['pdrop']*(barye2mmHg)
tm_cor = np.linspace(0, cor_ref.size*Dt, cor_ref.size)
######################################################################
if mode=='pdrop':
#plt.style.use('dark_background')
fig, ax = plt.subplots( figsize=(8, 5), dpi=100)
linesize = 3
dotsize = 6
if options['dP']['mode']=='cib':
if not options['dP']['catheter']=='None':
tend = ppe_ref.size
Dt = 0.019
if 'GM' in masterpath:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/Patients/Study_14_GM/catheter/catheter_stats.csv'
shift_t = 0
Dt = 0.03831417624521074
cstar = [0,0]
if 'RT' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/Study_David/Patients/Study_12_RT/catheter/catheter_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/Patients/Study_12_RT/catheter/catheter_stats.csv'
shift_t = 0.037
Dt = 0.025817555938037858
cstar = [0,0]
if '9' in masterpath and 'Rest' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/MEDICAL_DATA/Study_David/catheter_data/catheter_9mm_rest_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/catheter_data/catheter_9mm_rest_stats.csv'
shift_t = -0.10
cstar = [8,0]
if '11' in masterpath and 'Rest' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/MEDICAL_DATA/Study_David/catheter_data/catheter_11mm_rest_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/catheter_data/catheter_11mm_rest_stats.csv'
shift_t = 0.05
cstar = [0,0]
if '13' in masterpath and 'Rest' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/MEDICAL_DATA/Study_David/catheter_data/catheter_13mm_rest_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/catheter_data/catheter_13mm_rest_stats.csv'
shift_t = 0.09
cstar = [0,0]
if 'Normal' in masterpath and 'Rest' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/MEDICAL_DATA/Study_David/catheter_data/catheter_normal_rest_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/catheter_data/catheter_normal_rest_stats.csv'
shift_t = 0
cstar = [0,0]
with open(c_path, 'r') as csvfile:
mylist = [row[0] for row in csv.reader(csvfile, delimiter=';')]
Values = np.array(mylist)
catheter = np.zeros([len(Values)-2])
tcat = np.zeros([len(Values)-2])
for l in range(2,len(Values)):
row = Values[l].split(',')
catheter[l-2] = float(row[5])
tcat[l-2] = float(row[0])
tcat = tcat+shift_t
ax.plot(tcat[cstar[0]:tcat.size-cstar[1]],catheter[cstar[0]:tcat.size-cstar[1]],'black',linewidth=linesize,linestyle='--',label='$catheter$')
ax.set_xlim([-0.05,0.81])
ax.set_ylim([np.min(catheter)-np.mean(catheter) ,np.max(catheter)*1.2])
elif options['dP']['mode']=='ct':
ax.plot(tm[0:tend],ref[0:tend],options['REFcol'],linewidth=linesize,linestyle='-',marker='o',label='$ref$')
else:
if 'catheter' in options['dP']:
if not options['dP']['catheter']=='None':
CAT = np.load(options['dP']['catheter'])
[x0,x1,a,b,alpha] = options['dP']['factors']
t_cat = CAT['t']
dp_cat = CAT['dp']
ind1 = x0
ind2 = dp_cat.size-x1
t_cat = t_cat[ind1:ind2]
dp_cat = dp_cat[ind1:ind2]
t_cat2 = t_cat*a
t_cat2 = t_cat2*np.cos(alpha*np.pi/180) + dp_cat*np.sin(alpha*np.pi/180)
dp_cat2 = dp_cat*np.cos(alpha*np.pi/180) - t_cat2*np.sin(alpha*np.pi/180)
t_cat2 = t_cat2 - t_cat2[0]+ b
ax.plot(t_cat2,dp_cat2,'black',linewidth=linesize,linestyle='-',marker='o',label='$cat$')
for r in R:
for estim in options['dP']['estim']:
if r==1:
if estim=='PPE':
ax.plot(tm_ppe[0:tend],ppe_ref[0:tend],options['ppecol'],linewidth=linesize,linestyle='-',marker='o',label='$ppe: R=1$')
if estim=='STE':
ax.plot(tm_ste[0:tend],ste_ref[0:tend],options['stecol'],linewidth=linesize,linestyle='-',marker='o',label='$ste: R=1$')
if estim=='COR':
ax.plot(tm_cor[0:tend],cor_ref[0:tend],options['corcol'],linewidth=linesize,linestyle='-',marker='o',label='$cor: R=1$')
else:
press_raw = open(masterpath+'R'+str(r)+'/pdrop_'+estim+'_impl_stan.dat','rb')
press = pickle.load(press_raw)['pdrop']*(-barye2mmHg)
tvec = np.linspace(0,Tf,press.size)
ax.plot(tvec[1:-1],press[1:-1],options[estim+'col'],linewidth=2,linestyle='-',marker='o',label='$ppe$')
plt.xlabel(r'$time \ \ \ (s)$',fontsize=20)
plt.ylabel(r'$ \Delta p \ \ \ (mmHg) $',fontsize=20)
plt.legend(fontsize=14)
if options['dP']['save']:
fig.savefig(options['dP']['name'], bbox_inches='tight',dpi=500)
if mode=='error':
plt.figure(figsize=(10, 6), dpi=100)
ppe = {}
ste = {}
tvec = {}
eps_ppe = np.zeros([len(R)])
eps_ste = np.zeros([len(R)])
std_ppe = np.zeros([len(R)])
std_ste = np.zeros([len(R)])
k = 0
ref2 = ref[1:ref.size]
for r in R:
ppe_raw = open(masterpath+'/R'+str(r)+'/pdrop_PPE_impl_stan.dat','rb')
ste_raw = open(masterpath+'/R'+str(r)+'/pdrop_STE_impl_stan.dat','rb')
ppe[r] = pickle.load(ppe_raw)['pdrop']*(-barye2mmHg)
ste[r] = pickle.load(ste_raw)['pdrop']*(-barye2mmHg)
tvec[r] = np.linspace(0,Tf,ppe[r].size)
if r==0 and mesh_size=='coarse':
dif_ppe = np.abs(ref2-ppe[r])
dif_ste = np.abs(ref2-ste[r])
else:
dif_ppe = np.abs(ref-ppe[r])
dif_ste = np.abs(ref-ste[r])
#eps_ppe[k] = np.sqrt(1/ref.size)*np.sqrt( np.sum(dif_ppe**2) )
#eps_ste[k] = np.sqrt(1/ref.size)*np.sqrt( np.sum(dif_ste**2) )
eps_ppe[k] = np.mean(dif_ppe)
eps_ste[k] = np.mean(dif_ste)
std_ppe[k] = np.std(dif_ppe)
std_ste[k] = np.std(dif_ste)
k += 1
plt.errorbar(R,eps_ppe, yerr=std_ppe, ecolor=options['ppecol'] ,color=options['ppecol'] , uplims=True, lolims=True,marker='o',label='$PPE$')
plt.errorbar(R,eps_ste, yerr=std_ste, ecolor=options['stecol'] ,color=options['stecol'] ,uplims=True, lolims=True, marker='o',label='$STE$')
plt.xlabel(r'$R$',fontsize=20)
plt.ylabel(r'$ \overline{\delta P(R)- \delta P_{ref}} \ \ mmHg$',fontsize=18)
plt.legend(fontsize=14)
plt.title( '$ size : ' + mesh_size + ' \ \ dt = ' + str(1000*dt) + ' \ ms $',fontsize=16)
plt.xlim([-2,25])
plt.ylim([-3,7])
if 'pdrop_black' in mode:
plt.style.use('dark_background')
fig, ax = plt.subplots( figsize=(8, 5), dpi=100)
linesize = 3
dotsize = 6
if 'all' in mode:
ax.axis('off')
if options['dP']['mode']=='cib':
#ax.set_ylim([np.min(ref),np.max(ref)])
#ax.set_ylim([111,112])
tend = ref.size
Dt = 0.019
if 'GM' in masterpath:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/Patients/Study_14_GM/catheter/catheter_stats.csv'
shift_t = 0
Dt = 0.03831417624521074
cstar = [0,0]
if 'RT' in masterpath:
if '/mnt/D/jeremias' in masterpath:
c_path = '/mnt/D/jeremias/Study_David/Patients/Study_12_RT/catheter/catheter_stats.csv'
else:
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/Patients/Study_12_RT/catheter/catheter_stats.csv'
shift_t = 0.037
Dt = 0.025817555938037858