1413 lines
55 KiB
Python
1413 lines
55 KiB
Python
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 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
|
|
cstar = [0,0]
|
|
if '9' in masterpath and 'Rest' in masterpath:
|
|
if '/mnt/D/jeremias' in masterpath:
|
|
c_path = '/mnt/D/jeremias/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
|
|
Dt = 0.03072
|
|
cstar = [8,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]],'white',linewidth=linesize,linestyle='--',label='$catheter$')
|
|
|
|
tm = np.linspace(0,Dt*tend,tend)
|
|
ax.set_xlim([-0.05,0.81])
|
|
|
|
else:
|
|
ax.set_xlabel(r'$time \ \ (s)$',fontsize=22)
|
|
ax.set_ylabel(r'$ \delta p \ \ (mmHg) $',fontsize=22)
|
|
#ax.set_ylim([-13,16])
|
|
tend = ref.size-3
|
|
tvec = np.linspace(0,Tf,ref.size)
|
|
|
|
|
|
#ax.plot(tm,ref,'white',linewidth=3,linestyle='--',label='$catheter$')
|
|
ax.plot(tm[0:tend],ref[0:tend],'white',linewidth=linesize,linestyle='-',label='$R=1$')
|
|
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 = pickle.load(ppe_raw)['pdrop']*(barye2mmHg)
|
|
ste = pickle.load(ste_raw)['pdrop']*(barye2mmHg)
|
|
|
|
if options['estim']=='PPE':
|
|
ax.plot(tm[0:tend],ppe[0:tend],linewidth=linesize,linestyle='-',marker='o',markersize=dotsize , label='$R='+str(r)+'$')
|
|
elif options['estim']=='STE':
|
|
ax.plot(tm[0:tend],ste[0:tend],linewidth=linesize,linestyle='-',marker='o',markersize=dotsize,label='$R='+str(r)+'$')
|
|
|
|
if 'all' not in mode:
|
|
plt.xlabel('$time \ (s)$',fontsize=18)
|
|
plt.ylabel('$\delta p \ (mmHg)$',fontsize=18)
|
|
ax.legend(fontsize=12,loc=1)
|
|
if options['save_ppe']:
|
|
if options['estim']=='PPE':
|
|
fig.savefig(options['save_path']+options['name'], bbox_inches='tight',dpi=500)
|
|
if options['save_ste']:
|
|
if options['estim']=='STE':
|
|
fig.savefig(options['save_path']+options['name'], bbox_inches='tight',dpi=500)
|
|
|
|
|
|
|
|
|
|
plt.show()
|
|
|
|
def CLOCK(t1, t2):
|
|
tot_time = np.round(t2 - t1, 2)
|
|
if tot_time < 60:
|
|
print('Total time: ' + str(tot_time) + ' s')
|
|
elif tot_time < 3600:
|
|
time_min = tot_time//60
|
|
time_sec = tot_time - time_min*60
|
|
print('Total time: ' + str(time_min) +
|
|
' min, ' + str(time_sec) + ' s')
|
|
else:
|
|
time_hour = tot_time//3600
|
|
time_tot2 = tot_time - time_hour*3600
|
|
time_min = time_tot2//60
|
|
time_sec = time_tot2 - time_min*60
|
|
print('Total time: ' + str(time_hour) + ' hrs, ' +
|
|
str(time_min) + ' min, ' + str(time_sec) + ' s')
|
|
|
|
|
|
|
|
def ROUTINE(options):
|
|
|
|
if 'Histograms' in options:
|
|
if options['Histograms']['apply']:
|
|
print('--- Histograms ---')
|
|
meshnames = options['Histograms']['meshnames']
|
|
paths = options['Histograms']['paths']
|
|
colors = options['Histograms']['colors']
|
|
outpath = options['Histograms']['outpath']
|
|
Plot_Histogram(meshnames,paths,colors,outpath)
|
|
|
|
if 'dP' in options:
|
|
if options['dP']['apply']:
|
|
print('--- dP ---')
|
|
Plot_dP(options['dP']['data'],options,'pdrop',options['dP']['R'])
|
|
|
|
if 'HistCorrector' in options:
|
|
if options['HistCorrector']['apply']:
|
|
print('--- Histogram for Corrector ---')
|
|
|
|
import pickle
|
|
errors = open(options['HistCorrector']['errors'],'rb')
|
|
errors = pickle.load(errors)
|
|
Hi = np.zeros(errors[0].size)
|
|
for i in range(len(errors.keys())):
|
|
Hi += errors[i]
|
|
Hi = Hi/(i+1)
|
|
plt.hist(Hi, bins=100, density=True,range=[0.01,4],edgecolor='black',
|
|
color='orangered', alpha=0.75)
|
|
|
|
plt.ylim([0,14])
|
|
plt.xlabel('$|w/u|$',fontsize=18)
|
|
plt.ylabel('$density$',fontsize=18)
|
|
#plt.legend(fontsize=16)
|
|
plt.savefig(options['HistCorrector']['outpath'],dpi=500)
|
|
plt.show()
|
|
|
|
if 'Error-curves' in options:
|
|
if options['Error-curves']['apply']:
|
|
print('--- Error-curves analysis ---')
|
|
ratio = False
|
|
fac=1
|
|
if '11mm' in options['Error-curves']['subfolders']:
|
|
fac=100
|
|
for types in options['Error-curves']['type']:
|
|
if types=='mean_ratio':
|
|
types = 'mean'
|
|
ratio = True
|
|
if types=='max_ratio':
|
|
types = 'max'
|
|
ratio = True
|
|
if types=='norm2_m':
|
|
types='norm2'
|
|
meas=True
|
|
nc = 0
|
|
if len(options['Error-curves']['subfolders'])==0:
|
|
ucomp = []
|
|
wcomp = []
|
|
colorset = options['Error-curves']['colors']
|
|
path = options['Error-curves']['folder']
|
|
try:
|
|
ucomp = np.loadtxt(path + '/u'+types+'.txt')
|
|
wcomp = np.loadtxt(path + '/w'+types+'.txt')
|
|
times = np.loadtxt(path + '/times.txt')
|
|
except IOError:
|
|
print('no Error-curves for ' + subf)
|
|
if not ratio:
|
|
plt.plot(
|
|
times, ucomp, color=colorset[nc], linestyle='-', label= '$u$' )
|
|
plt.plot(
|
|
times, wcomp, color=colorset[nc], linestyle='--', label='$w$')
|
|
else:
|
|
plt.plot(
|
|
times, ucomp, color=colorset[nc], linestyle='-', label= '$u$' )
|
|
plt.plot(
|
|
times, wcomp, color=colorset[nc], linestyle='--', label='$w$')
|
|
nc +=1
|
|
else:
|
|
for subf in options['Error-curves']['subfolders']:
|
|
ucomp = []
|
|
wcomp = []
|
|
if 'colors' in options['Error-curves']:
|
|
print('colors setted...')
|
|
colorset = options['Error-curves']['colors']
|
|
colorsetted = True
|
|
else:
|
|
colorsetted = False
|
|
styles = options['Error-curves']['styles']
|
|
labelset = options['Error-curves']['labels']
|
|
path = options['Error-curves']['folder'] + subf + '/'
|
|
wcomp = np.loadtxt(path + 'w'+types+'.txt')
|
|
times = np.loadtxt(path + 'times.txt')
|
|
if types != 'grad':
|
|
ucomp = np.loadtxt(path + 'u'+types+'.txt')
|
|
|
|
|
|
if colorsetted:
|
|
if not ratio:
|
|
if types not in ['grad']:
|
|
if meas:
|
|
plt.plot(times, fac*ucomp, color=colorset[nc], linestyle='--', label= '$ u \ '+ labelset[nc] +'$',linewidth=2.5 )
|
|
plt.plot(times, fac*wcomp, color=colorset[nc], linestyle=styles[nc], label= '$ w \ '+ labelset[nc] +'$',linewidth=2.5)
|
|
else:
|
|
wu = wcomp/ucomp
|
|
plt.plot(
|
|
times, wu, color=colorset[nc], linestyle=styles[nc], label= '$'+ labelset[nc] +'$' )
|
|
nc +=1
|
|
else:
|
|
if not ratio:
|
|
if types not in ['grad']:
|
|
if meas:
|
|
plt.plot(times, fac*ucomp, linestyle='--', label= '$'+ labelset[nc] +'$' )
|
|
else:
|
|
plt.plot(times, fac*ucomp, linestyle='--', label= '$'+ labelset[nc] +'$' )
|
|
plt.plot(
|
|
times, fac*wcomp, linestyle=styles[nc], label= '$'+ labelset[nc] +'$')
|
|
else:
|
|
wu = wcomp/ucomp
|
|
plt.plot(
|
|
times, wu, linestyle=styles[nc], label= '$'+ labelset[nc] +'$' )
|
|
nc +=1
|
|
|
|
|
|
|
|
plt.xlabel('$time \ \ (s)$', fontsize=18)
|
|
plt.legend(fontsize=14)
|
|
if options['Error-curves']['title']:
|
|
plt.title(options['Error-curves']['title'], fontsize=18)
|
|
|
|
if not ratio:
|
|
if types == 'grad':
|
|
plt.ylim([0, 230])
|
|
plt.ylabel('$ |grad(w)|_2 \ \ (1/s)$', fontsize=18)
|
|
elif types == 'norm2':
|
|
plt.ylim([0, 52])
|
|
plt.ylabel('$ |w|_2 \ \ (cm/s)$', fontsize=18)
|
|
else:
|
|
plt.ylabel('$velocity \ \ (cm/s)$', fontsize=18)
|
|
plt.savefig(options['Error-curves']['outpath'] + types + '.png', dpi=500, bbox_inches='tight')
|
|
else:
|
|
plt.ylabel('$|w/u|$', fontsize=18)
|
|
#if 'max' in types:
|
|
#plt.ylim([0, 1.8])
|
|
plt.savefig(options['Error-curves']['outpath'] + types + '_ratio.png', dpi=500, bbox_inches='tight')
|
|
plt.show()
|
|
|
|
if 'Histograms_checkpoint' in options:
|
|
if options['Histograms_checkpoint']['apply']:
|
|
print('--- Histograms ---')
|
|
path = options['Histograms_checkpoint']['path']
|
|
freq = np.loadtxt(path + 'hist_freq.txt')
|
|
edges = np.loadtxt(path + 'hist_edges.txt')
|
|
fig, ax = plt.subplots()
|
|
#ax.bar(edges[:-1], freq, width=np.diff(edges), edgecolor="black", align="edge")
|
|
ax.bar(edges[:-1], freq, width=np.diff(edges), align="edge")
|
|
plt.title(options['Histograms_checkpoint']['title'], fontsize=18)
|
|
plt.xlim([0 , 50])
|
|
plt.ylim([0 , 1.8])
|
|
plt.savefig(path + 'hist.png', dpi=500, bbox_inches='tight')
|
|
plt.show()
|
|
|
|
if 'Pressure_drops' in options:
|
|
if options['Pressure_drops']['apply']:
|
|
print('--- Pressure_drops ---')
|
|
import pickle
|
|
nc = 0
|
|
tommhg = options['Pressure_drops']['convertor']
|
|
|
|
for subf in options['Pressure_drops']['subfolders']:
|
|
ucomp = []
|
|
wcomp = []
|
|
if 'colors' in options['Pressure_drops']:
|
|
colorset = options['Pressure_drops']['colors']
|
|
colorsetted = True
|
|
else:
|
|
colorsetted = False
|
|
styles = options['Pressure_drops']['styles']
|
|
labelset = options['Pressure_drops']['labels']
|
|
path = options['Pressure_drops']['folder'] + subf + '/'
|
|
dataname = 'pdrop_COR_impl_stan.dat'
|
|
if 'STE' in path:
|
|
dataname = 'pdrop_STE_impl_stan.dat'
|
|
if labelset[nc]=='ref':
|
|
dataname = 'pdrop.dat'
|
|
data = open(path+dataname, 'rb')
|
|
p_drop = pickle.load(data)['pdrop']/tommhg
|
|
data = open(path+dataname, 'rb')
|
|
times = pickle.load(data)['time']
|
|
|
|
if labelset[nc] == 'ref':
|
|
plt.plot(times, p_drop,color='black', linestyle='-', label= '$ref$' )
|
|
else:
|
|
|
|
if colorsetted:
|
|
plt.plot(
|
|
times, p_drop, color=colorset[nc], linestyle=styles[nc], label= '$'+ labelset[nc] +'$' )
|
|
else:
|
|
plt.plot(times, p_drop, linestyle=styles[nc], label= '$'+ labelset[nc] +'$' )
|
|
|
|
if options['Pressure_drops']['catheter']:
|
|
|
|
c_path = '/home/yeye/Desktop/PhD/MEDICAL_DATA/Study_David/catheter_data/catheter_'+ labelset[nc]+'_rest_stats.csv'
|
|
|
|
|
|
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])
|
|
|
|
|
|
if '11mm' in subf:
|
|
tdelay = 0.015
|
|
elif '9mm' in subf:
|
|
tdelay = -0.12
|
|
elif '13mm' in subf:
|
|
tdelay = 0.1
|
|
elif 'Normal' in subf:
|
|
tdelay = -0.01
|
|
|
|
plt.plot(tcat+tdelay,catheter,color=colorset[nc],linestyle='--')# ,label='$cat' + subf + '$')
|
|
|
|
nc +=1
|
|
|
|
|
|
#plt.ylim([0, 170])
|
|
plt.xlabel('$time \ \ (s)$', fontsize=18)
|
|
plt.legend(fontsize=14)
|
|
if options['Pressure_drops']['title']:
|
|
plt.title(options['Pressure_drops']['title'], fontsize=18)
|
|
plt.ylabel('$ \delta P \ \ (mmHg)$', fontsize=18)
|
|
plt.savefig(options['Pressure_drops']['outpath'] + 'pressure_drops.png', dpi=500, bbox_inches='tight')
|
|
plt.show()
|
|
|
|
if 'l2_comp' in options:
|
|
if options['l2_comp']['apply']:
|
|
print('--- L2 component analysis ---')
|
|
fig, ax = plt.subplots()
|
|
for subf in options['l2_comp']['subfolder']:
|
|
path = options['l2_comp']['folder'] + subf + '/'
|
|
colors = options['l2_comp']['colors']
|
|
mode = options['l2_comp']['mode']['type']
|
|
|
|
if mode in ['gain','gain_compressed']:
|
|
gain = True
|
|
path_to_comp = options['l2_comp']['mode']['comp']
|
|
wx = np.loadtxt(path_to_comp + '/wx.txt')
|
|
wy = np.loadtxt(path_to_comp + '/wy.txt')
|
|
wz = np.loadtxt(path_to_comp + '/wz.txt')
|
|
else:
|
|
gain = False
|
|
wx = np.loadtxt(path + '/wx.txt')
|
|
wy = np.loadtxt(path + '/wy.txt')
|
|
wz = np.loadtxt(path + '/wz.txt')
|
|
|
|
times = np.loadtxt(path + '/times.txt')
|
|
if subf != 'SNRinfV120' and gain:
|
|
varux = np.loadtxt(path + '/varux.txt')
|
|
varuy = np.loadtxt(path + '/varuy.txt')
|
|
varuz = np.loadtxt(path + '/varuz.txt')
|
|
if 'SNRinfV120' in subf:
|
|
lsty = '--'
|
|
labels = ['','','','','']
|
|
else:
|
|
lsty = '-'
|
|
lsty2 = '--'
|
|
labels = ['$wx$','$wy$','$wz$','$div$']
|
|
labels2 = ['$\delta u_x$','$\delta u_y$','$\delta u_z$']
|
|
labels3 = ['$x$','$y$','$z$']
|
|
|
|
if mode == 'gain':
|
|
plt.plot(times, varux, color = colors[0], linestyle=lsty2 , label= labels2[0] )
|
|
plt.plot(times, varuy, color = colors[1], linestyle=lsty2 , label= labels2[1] )
|
|
plt.plot(times, varuz, color = colors[2], linestyle=lsty2 , label= labels2[2] )
|
|
plt.plot(times, wx, color = colors[0], linestyle=lsty, label= labels[0] )
|
|
plt.plot(times, wy, color = colors[1], linestyle=lsty, label= labels[1] )
|
|
plt.plot(times, wz, color = colors[2], linestyle=lsty, label= labels[2] )
|
|
elif mode == 'gain_compressed':
|
|
plt.plot(times, varux-wx, color = colors[0], linestyle=lsty, label= labels3[0] )
|
|
plt.plot(times, varuy-wy, color = colors[1], linestyle=lsty, label= labels3[1] )
|
|
plt.plot(times, varuz-wz, color = colors[2], linestyle=lsty, label= labels3[2] )
|
|
else:
|
|
plt.plot(times, wx, color = colors[0], linestyle=lsty, label= labels[0] )
|
|
plt.plot(times, wy, color = colors[1], linestyle=lsty, label= labels[1] )
|
|
plt.plot(times, wz, color = colors[2], linestyle=lsty, label= labels[2] )
|
|
|
|
plt.xlabel('$time \ \ (s)$', fontsize=18)
|
|
|
|
if options['l2_comp']['div']:
|
|
div = np.loadtxt(path + 'div.txt')
|
|
div_rescaled = div*0.01
|
|
div_rescaled = div_rescaled + 0.1
|
|
plt.plot(times, div_rescaled, color = 'indigo', linestyle=lsty, label= labels[3] )
|
|
|
|
if 'title' in options['l2_comp']:
|
|
if options['l2_comp']['title']:
|
|
plt.title(options['l2_comp']['title'], fontsize=18)
|
|
|
|
|
|
|
|
if options['l2_comp']['aliasing']:
|
|
if 'Poiseuille' in options['l2_comp']['folder']:
|
|
print('adding alaising color in Poiseuille')
|
|
import matplotlib.transforms as mtransforms
|
|
trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
|
|
if 'SNR10' in subf:
|
|
time_al = [0.15,0.78]
|
|
elif 'SNRinf' in subf:
|
|
time_al = [0.21,0.78]
|
|
pm_al = 0.5*(time_al[1] + time_al[0])
|
|
r_al = 0.5*(time_al[1] - time_al[0])
|
|
ax.fill_between(times, 0, 1, where=np.abs(times -pm_al)<= r_al ,facecolor='gold', alpha=0.4, transform=trans)
|
|
if mode == 'gain_compressed':
|
|
ax.text(pm_al/times[-1], 0.55, '$aliasing$', horizontalalignment='center',verticalalignment='center', transform=ax.transAxes,fontsize=17)
|
|
else:
|
|
ax.text(pm_al/times[-1], 0.82, '$aliasing$', horizontalalignment='center',verticalalignment='center', transform=ax.transAxes,fontsize=17)
|
|
|
|
leg = plt.legend(fancybox=True,fontsize=16)
|
|
leg.get_frame().set_linewidth(0.0)
|
|
ax.tick_params(axis='both', which='major', labelsize=14)
|
|
#plt.ylim([-0.005 , 0.235])
|
|
|
|
if mode == 'gain_compressed':
|
|
plt.ylim([-0.25 , 1.75])
|
|
plt.ylabel('$|| \delta u ||_{L2} - || w ||_{L2}$', fontsize=18)
|
|
if not gain:
|
|
plt.ylim([-0.005 , 0.5])
|
|
plt.ylabel('$ \sqrt{\int w^2 dx /| \Omega|}/ venc$', fontsize=18)
|
|
|
|
plt.savefig(options['l2_comp']['folder'] + options['l2_comp']['name'] + '.png', dpi=500, bbox_inches='tight')
|
|
plt.show()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__=='__main__':
|
|
|
|
if 'Zion' in os.popen('hostname').read():
|
|
user = 'yeye'
|
|
np.set_printoptions(threshold=5)
|
|
if 'fwn-bborg-5-166' in os.popen('hostname').read():
|
|
user = 'p283370'
|
|
|
|
|
|
if len(sys.argv) > 1:
|
|
if os.path.exists(sys.argv[1]):
|
|
inputfile = sys.argv[1]
|
|
print('Found input file ' + inputfile)
|
|
else:
|
|
raise Exception('Command line arg given but input file does not exist:'
|
|
' {}'.format(sys.argv[1]))
|
|
else:
|
|
raise Exception('An input file is required as argument!')
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
options = inout.read_parameters(inputfile)
|
|
ROUTINE(options)
|
|
end_time = time.time()
|
|
CLOCK(start_time,end_time)
|
|
|
|
|
|
|
|
# END
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|