def PlotWss(self, meshid, imagpath): ''' This method plots Wss signal and returns peak wss. ''' try: import matplotlib matplotlib.use('Agg') #switch to matplotlib.use('WXAgg') if you want to show and not save velocity profile. from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close, ylim except: sys.exit("PlotWss method requires matplotlib package (http://matplotlib.sourceforge.net.\n") tplot = linspace(0, self.tPeriod, len(self.Tauplot)) plot(tplot, self.Tauplot,'g-',linewidth = 3, label = 'WSS') minY = 0 for w in self.Tauplot: if w < minY: minY = w if minY != 0: plot(tplot, zeros(len(self.Tauplot)),':',linewidth = 1) ylim(ymin=minY) xlabel('Time ($s$)') ylabel('Wall shear stress ($dyne/cm^2$)') title ('Wss'+' peak:'+str(round(max(self.Tauplot),1))+' mean:'+str(round(mean(self.Tauplot),1))+' min:'+str(round(min(self.Tauplot),1))) legend() savefig(imagpath+str(meshid)+'_'+str(self.Name)+'_wss.png') print "Wss, MeshId", meshid, self.Name, "=", str(round(max(self.Tauplot),1)), "$dyne/cm^2$" close() return (round(max(self.Tauplot),1))
def test_smoothing_spline(): x = linspace(0, 2 * pi + pi / 4, 20) y = sin(x) # + np.random.randn(x.size) pp = SmoothSpline(x, y, p=1) x1 = linspace(-1, 2 * pi + pi / 4 + 1, 20) y1 = pp(x1) pp1 = pp.derivative() pp0 = pp1.integrate() dy1 = pp1(x1) y01 = pp0(x1) #dy = y-y1 import matplotlib.pyplot as plb plb.plot(x, y, x1, y1, '.', x1, dy1, 'ro', x1, y01, 'r-') plb.show() pass
def calculateTs_Kolmogorov_BVP(alpha, beta, tauchar = 1.0, xth= 1.0, xmin = -1.0): D = beta*beta /2. def dS(S,x): return -( (alpha-x/tauchar)/D ) * S -1.0/D; S_0 = .0; xs = linspace(xmin, xth, 1000); dx = (xs[1]-xs[0]) Ss = odeint(dS, S_0, xs); if max(Ss) > .0: raise RuntimeError('Ss should be negative') T1s = -cumsum(Ss[-1::-1]) * dx T1s = T1s[-1::-1] T1_interpolant = interp1d(xs, T1s, bounds_error=False, fill_value = T1s[-1]); def dS2(S,x): T1 = T1_interpolant(x) return -( (alpha-x/tauchar)/D ) * S -2.0*T1/D; Ss = odeint(dS2, S_0, xs); if max(Ss) > .0: raise RuntimeError('Ss should be negative') T2s = -cumsum(Ss[-1::-1]) * dx T2s = T2s[-1::-1] return xs, T1s, T2s
def GetTaoFromQ(self, el): ''' Computing wall shear stress in terms of the flow rate, using inverse womersley method of Cezeaux et al.1997 ''' self.radius = mean(el.Radius) self.Res = el.R self.length = el.Length self.Name = el.Name #WOMERSLEY NUMBER self.alpha = self.radius * sqrt( (2.0 * pi * self.density) / (self.tPeriod * self.viscosity)) #FOURIER SIGNAL k = len(self.signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k): An += self.signal[i] * cos( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) Bn += self.signal[i] * sin( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) An = An * (2.0 / k) Bn = Bn * (2.0 / k) self.fourierModes.append(complex(An, Bn)) n += 1 self.Steps = linspace(0, self.tPeriod, self.samples) self.WssSignal = [] self.Tauplot = [] for step in self.Steps: self.tao = -self.fourierModes[0].real * 2.0 k = 1 while k < self.nHarmonics: cI = complex(0., 1.) cA = (self.alpha * pow((1.0 * k), 0.5)) * pow(cI, 1.5) c1 = 2.0 * jn(1, cA) c0 = cA * jn(0, cA) cT = complex(0, -2.0 * pi * k * self.t / self.tPeriod) '''tao computation''' taoNum = self.alpha**2 * cI**3 * jn(1, cA) taoDen = c0 - c1 taoFract = taoNum / taoDen cTao = self.fourierModes[k] * exp(cT) * taoFract self.tao += cTao.real k += 1 self.tao *= -(self.viscosity / (self.radius**3 * pi)) self.Tauplot.append(self.tao * 10) #dynes/cm2 self.WssSignal.append(self.tao) self.t += self.dtPlot return self.WssSignal #Pascal
def GetTaoFromQ(self,el): ''' Computing wall shear stress in terms of the flow rate, using inverse womersley method of Cezeaux et al.1997 ''' self.radius = mean(el.Radius) self.Res = el.R self.length = el.Length self.Name = el.Name #WOMERSLEY NUMBER self.alpha = self.radius * sqrt((2.0 *pi*self.density)/(self.tPeriod*self.viscosity)) #FOURIER SIGNAL k = len(self.signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k): An += self.signal[i] * cos(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) Bn += self.signal[i] * sin(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) An = An * (2.0/k) Bn = Bn * (2.0/k) self.fourierModes.append(complex(An, Bn)) n+=1 self.Steps = linspace(0,self.tPeriod,self.samples) self.WssSignal = [] self.Tauplot = [] for step in self.Steps: self.tao = -self.fourierModes[0].real * 2.0 k=1 while k < self.nHarmonics: cI = complex(0.,1.) cA = (self.alpha * pow((1.0*k),0.5)) * pow(cI,1.5) c1 = 2.0 * jn(1, cA) c0 = cA * jn(0, cA) cT = complex(0, -2.0*pi*k*self.t/self.tPeriod) '''tao computation''' taoNum = self.alpha**2*cI**3*jn(1,cA) taoDen = c0-c1 taoFract = taoNum/taoDen cTao = self.fourierModes[k] * exp(cT) * taoFract self.tao += cTao.real k+=1 self.tao *= -(self.viscosity/(self.radius**3*pi)) self.Tauplot.append(self.tao*10) #dynes/cm2 self.WssSignal.append(self.tao) self.t += self.dtPlot return self.WssSignal #Pascal
def test_func(): from scipy import interpolate import matplotlib.pyplot as plt import matplotlib matplotlib.interactive(False) coef = np.array([[1, 1], [0, 1]]) # linear from 0 to 2 # coef = np.array([[1,1],[1,1],[0,2]]) # linear from 0 to 2 breaks = [0, 1, 2] pp = PPform(coef, breaks, a=-100, b=100) x = linspace(-1, 3, 20) y = pp(x) # @UnusedVariable x = linspace(0, 2 * pi + pi / 4, 20) y = sin(x) + np.random.randn(x.size) tck = interpolate.splrep(x, y, s=len(x)) # @UndefinedVariable xnew = linspace(0, 2 * pi, 100) ynew = interpolate.splev(xnew, tck, der=0) # @UndefinedVariable tck0 = interpolate.splmake( # @UndefinedVariable xnew, ynew, order=3, kind='smoothest', conds=None) pp = interpolate.ppform.fromspline(*tck0) # @UndefinedVariable plt.plot(x, y, "x", xnew, ynew, xnew, sin(xnew), x, y, "b", x, pp(x), 'g') plt.legend(['Linear', 'Cubic Spline', 'True']) plt.title('Cubic-spline interpolation') plt.show() t = np.arange(0, 1.1, .1) x = np.sin(2 * np.pi * t) y = np.cos(2 * np.pi * t) _tck1, _u = interpolate.splprep([t, y], s=0) # @UndefinedVariable tck2 = interpolate.splrep(t, y, s=len(t), task=0) # @UndefinedVariable # interpolate.spl tck = interpolate.splmake(t, y, order=3, kind='smoothest', conds=None) # @UndefinedVariable self = interpolate.ppform.fromspline(*tck2) # @UndefinedVariable plt.plot(t, self(t)) plt.show() pass
def __getitem__(self,key): if isinstance(key, str): raise MAError, "Unavailable for masked array." if type(key) is not tuple: key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if type(key[k]) is slice: step = key[k].step start = key[k].start stop = key[k].stop if start is None: start = 0 if step is None: step = 1 if type(step) is type(1j): size = int(abs(step)) newobj = function_base.linspace(start, stop, num=size) else: newobj = numeric.arange(start, stop, step) elif type(key[k]) is str: if (key[k] in 'rc'): self.matrix = True self.col = (key[k] == 'c') continue try: self.axis = int(key[k]) continue except (ValueError, TypeError): raise ValueError, "Unknown special directive" elif type(key[k]) in numeric.ScalarType: newobj = asarray([key[k]]) scalars.append(k) scalar = True else: newobj = key[k] objs.append(newobj) if isinstance(newobj, numeric.ndarray) and not scalar: if final_dtypedescr is None: final_dtypedescr = newobj.dtype elif newobj.dtype > final_dtypedescr: final_dtypedescr = newobj.dtype if final_dtypedescr is not None: for k in scalars: objs[k] = objs[k].astype(final_dtypedescr) res = concatenate(tuple(objs),axis=self.axis) return self._retval(res)
def generate_poisson_tex(params): seed = params.seed # TODO: select seed length = params.length cell_size = params.cell_size sigma = params.smoothing_sigma intensity = params.intensity buffer_len = int(ceil(length / cell_size)) cell_size = (1.0 * length) / buffer_len buffer = zeros(shape=(buffer_len,)) def generate_inverted_colors_sequence(length): colors = zeros(shape=(length,)) for i in range(length): colors[i] = i % 2 return colors def generate_random_colors_sequence(length): return numpy.random.rand(length) events = generate_poisson_events(intensity, length) colors = generate_random_colors_sequence(len(events)) current_event = 0 for i in xrange(buffer_len): current_time = i * cell_size if current_event < len(events) - 1 and current_time > events[current_event]: # XXX current_event += 1 buffer[i] = colors[current_event] tail = 4 * sigma gaussian_filter_len = int(ceil(tail / cell_size)) xcoord = linspace(-tail, tail, gaussian_filter_len) gaussian_filter = numpy.exp(-xcoord ** 2 / (2 * sigma ** 2)) gaussian_filter = gaussian_filter / gaussian_filter.sum() buffer = loop_convolve(buffer, gaussian_filter) return Texture(buffer=buffer, cell_size=cell_size)
def PlotWss(self, meshid, imagpath): ''' This method plots Wss signal and returns peak wss. ''' try: import matplotlib matplotlib.use( 'Agg' ) #switch to matplotlib.use('WXAgg') if you want to show and not save velocity profile. from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close, ylim except: sys.exit( "PlotWss method requires matplotlib package (http://matplotlib.sourceforge.net.\n" ) tplot = linspace(0, self.tPeriod, len(self.Tauplot)) plot(tplot, self.Tauplot, 'g-', linewidth=3, label='WSS') minY = 0 for w in self.Tauplot: if w < minY: minY = w if minY != 0: plot(tplot, zeros(len(self.Tauplot)), ':', linewidth=1) ylim(ymin=minY) xlabel('Time ($s$)') ylabel('Wall shear stress ($dyne/cm^2$)') title('Wss' + ' peak:' + str(round(max(self.Tauplot), 1)) + ' mean:' + str(round(mean(self.Tauplot), 1)) + ' min:' + str(round(min(self.Tauplot), 1))) legend() savefig(imagpath + str(meshid) + '_' + str(self.Name) + '_wss.png') print "Wss, MeshId", meshid, self.Name, "=", str( round(max(self.Tauplot), 1)), "$dyne/cm^2$" close() return (round(max(self.Tauplot), 1))
def Adapt(self, day): """This method will apply adaptation law for specified elements.""" if day>0: if day == 1: for el in self.solutions[day-1].NetworkMesh.Elements: if el.Type == "WavePropagation": kd1 = el.Radius[0] kd2 = el.Radius[len(el.Radius)-1] el.dayRadius[day-1]=[kd1,kd2] for el in self.solutions[day-1].NetworkMesh.Elements: el.Initialized = False preRun = False for elem in self.solutions[day-1].NetworkMesh.Elements: if elem.Type == "Anastomosis": proximalArtery = elem.Proximal distalArtery = elem.Distal proximalVein = elem.Vein #No adaptation in case of upper arm anastomosis and diabetic patient if self.simulationContext.Context["diab"] == 1 and self.simulationContext.Context["ftype"] > 2: print "Diabetic patient, no arterial adaptation" for ent, elList in self.solutions[day-1].NetworkMesh.Entities.iteritems(): if ent.Id == "axillarian" or ent.Id == "brachial" or ent.Id == "radial" or ent.Id == "ulnar" or ent.Id == "cephalic_vein" or ent.Id == "cubiti_vein" or ent.Id == "basilic_vein" or ent.Id == "subclavian_vein": for el in elList: kd1_n = el.Radius[0] kd2_n = el.Radius[len(el.Radius)-1] el.dayRadius[day]=[kd1_n,kd2_n] if ent.Id == "cephalic_vein" or ent.Id == "cubiti_vein" or ent.Id == "basilic_vein" or ent.Id == "subclavian_vein": for el in elList: taoRef = self.refValues[el.Name] taoPeaks = self.solutions[day-1].GetWssPeak(el) tao0 = taoPeaks[0] tao1 = taoPeaks[1] tao = linspace(tao0,tao1,len(el.Radius)) deltaTao = tao-taoRef k = (1.0+(deltaTao*self.Coeff)) if el == proximalVein: #linear adaptation on anastomosis of 20% k2 = 45./44. if day > 10: k2 = 1. x = linspace(0,len(el.Radius),len(el.Radius)) taoProxV = (tao0-tao1)*((x/len(el.Radius))**2-(2.0*(x/len(el.Radius))))+tao0 #y = (k1-k2)(x^2-2x)+k1 (quadratic decreasing wss) tao = taoProxV deltaTaoProxV = taoProxV-taoRef k = (1.0+(deltaTaoProxV*self.Coeff)) kProxV = (k-k2)*((x/len(el.Radius))**2)+k2 #y = (k2-k1)x^2+k1 (quadratic increasing radius) k=kProxV if min(tao) > taoRef: el.Radius*=k kd1_n = el.Radius[0] kd2_n = el.Radius[len(el.Radius)-1] el.dayRadius[day]=[kd1_n,kd2_n] else: for ent, elList in self.solutions[day-1].NetworkMesh.Entities.iteritems(): if ent.Id == "axillarian" or ent.Id == "brachial" or ent.Id == "radial" or ent.Id == "ulnar" or ent.Id == "cephalic_vein" or ent.Id == "cubiti_vein" or ent.Id == "basilic_vein" or ent.Id == "subclavian_vein": for el in elList: taoRef = self.refValues[el.Name] taoPeaks = self.solutions[day-1].GetWssPeak(el) tao0 = taoPeaks[0] tao1 = taoPeaks[1] tao = linspace(tao0,tao1,len(el.Radius)) deltaTao = tao-taoRef k = (1.0+(deltaTao*self.Coeff)) if el == proximalArtery: x = linspace(0,len(el.Radius),len(el.Radius)) taoProxA = (tao1-tao0)*((x/len(el.Radius))**2)+tao0 #y = (k2-k1)x^2+k1 (quadratic increasing wss) tao=taoProxA deltaTaoProxA = taoProxA-taoRef k = (1.0+(deltaTaoProxA*self.Coeff)) kProxA = (k-1.)*((x/len(el.Radius))**2-(2.0*(x/len(el.Radius))))+k #y = (k1-k2)(x^2-2x)+k1 (quadratic decreasing radius) k=kProxA if el == distalArtery: x = linspace(0,len(el.Radius),len(el.Radius)) taoDistA = (tao0-tao1)*((x/len(el.Radius))**2-(2.0*(x/len(el.Radius))))+tao0 #y = (k1-k2)(x^2-2x)+k1 (quadratic decreasing wss) tao = taoDistA deltaTaoDistA = taoDistA-taoRef k = (1.0+(deltaTaoDistA*self.Coeff)) kDistA = (k-1.)*((x/len(el.Radius))**2)+1. #y = (k2-k1)x^2+k1 (quadratic increasing radius) k=kDistA if el == proximalVein: #linear adaptation on anastomosis of 20% k2 = 1.02 #k2 = 45./44. if day > 10: k2 = 1. x = linspace(0,len(el.Radius),len(el.Radius)) taoProxV = (tao0-tao1)*((x/len(el.Radius))**2-(2.0*(x/len(el.Radius))))+tao0 #y = (k1-k2)(x^2-2x)+k1 (quadratic decreasing wss) tao = taoProxV deltaTaoProxV = taoProxV-taoRef k = (1.0+(deltaTaoProxV*self.Coeff)) kProxV = (k-k2)*((x/len(el.Radius))**2)+k2 #y = (k2-k1)x^2+k1 (quadratic increasing radius) print "PROXV K" , kProxV k=kProxV if min(tao) > taoRef: el.Radius*=k kd1_n = el.Radius[0] kd2_n = el.Radius[len(el.Radius)-1] el.dayRadius[day]=[kd1_n,kd2_n] if day == 0: preRun = True if day == -1: preRun = False return preRun
# tck = interpolate.splrep(x4, y4, s=smoothing) # x4_new = num_base.linspace(0.01, 100, 100) # y4_new = interpolate.splev(x4_new, tck, der=0) # obtain exponential function through lease square fit def erfc(p, x, y): return y-(p[0]*np.exp(p[1]*x)+p[2]) def f(x, p): return p[0]*np.exp(p[1]*x)+p[2] p0 = [1, -1, 1] plsq=optimize.leastsq(erfc, p0, args=(x1, y1)) x1_new = num_base.linspace(0.01, 100, 800) y1_new = f(x1_new, plsq[0]) plsq=optimize.leastsq(erfc, p0, args=(x2, y2)) x2_new = num_base.linspace(0.01, 100, 800) y2_new = f(x2_new, plsq[0]) plsq=optimize.leastsq(erfc, p0, args=(x3, y3)) x3_new = num_base.linspace(0.01, 100, 800) y3_new = f(x3_new, plsq[0]) plsq=optimize.leastsq(erfc, p0, args=(x4, y4)) x4_new = num_base.linspace(0.01, 100, 800) y4_new = f(x4_new, plsq[0]) # plot ECR with reduced range
def analyze_olfaction_covariance(covariance, receptors): ''' Covariance: n x n covariance matrix. Positions: list of n positions ''' positions = [pose.get_2d_position() for pose, sens in receptors] #@UnusedVariable positions = array(positions).transpose().squeeze() require_shape(square_shape(), covariance) n = covariance.shape[0] require_shape((2, n), positions) distances = create_distance_matrix(positions) correlation = cov2corr(covariance) flat_distances = distances.reshape(n * n) flat_correlation = correlation.reshape(n * n) # let's fit a polynomial deg = 4 poly = polyfit(flat_distances, flat_correlation, deg=deg) knots = linspace(min(flat_distances), max(flat_distances), 2000) poly_int = polyval(poly, knots) poly_fder = polyder(poly) fder = polyval(poly_fder, distances) Ttheta = create_olfaction_Ttheta(positions, fder) Tx, Ty = create_olfaction_Txy(positions, fder, distances) report = Node('olfaction-theory') report.data('flat_distances', flat_distances) report.data('flat_correlation', flat_correlation) with report.data_file('dist_vs_corr', 'image/png') as filename: pylab.figure() pylab.plot(flat_distances, flat_correlation, '.') pylab.plot(knots, poly_int, 'r-') pylab.xlabel('distance') pylab.ylabel('correlation') pylab.title('Correlation vs distance') pylab.legend(['data', 'interpolation deg = %s' % deg]) pylab.savefig(filename) pylab.close() with report.data('fder', fder).data_file('fder', 'image/png') as filename: pylab.figure() pylab.plot(knots, polyval(poly_fder, knots), 'r-') pylab.title('f der') pylab.savefig(filename) pylab.close() report.data('distances', distances) report.data('correlation', correlation) report.data('covariance', covariance) report.data('f', polyval(poly, distances)) f = report.figure(id='cor-vs-distnace', caption='Estimated kernels', shape=(3, 3)) f.sub('dist_vs_corr') f.sub('fder') f.sub('f', display='scale') f.sub('distances', display='scale') f.sub('correlation', display='posneg') f.sub('covariance', display='posneg') T = numpy.zeros(shape=(3, Tx.shape[0], Tx.shape[1])) T[0, :, :] = Tx T[1, :, :] = Ty T[2, :, :] = Ttheta T_report = create_report_figure_tensors(T, report_id='tensors', caption="Predicted learned tensors") report.add_child(T_report) return report
if (os.path.isfile(ecr_name)): # DEBUG #print ecr_name # DEBUG plt.clf() new_smoothing = 0 while new_smoothing >= 0: smoothing = new_smoothing x, y = io.loadtxt(ecr_name, usecols=[0,1], unpack=True) # DEBUG print "Current smoothing factor = %f" % (smoothing) tck = interpolate.splrep(x, y, s=smoothing) x_new = num_base.linspace(0.01, max(x), 100) y_new = interpolate.splev(x_new, tck, der=0) plt.plot(x, y, 'o', x_new, y_new, '-') plt.show() tmp = raw_input("Input new smoothing factor (press ENTER when done): ") if (tmp == ""): break else: new_smoothing = float(tmp) else: continue # obtain 1-d spline representation of data #tck = interpolate.splrep(x, y, s=smoothing)
def GetVelFromQ(self, el): ''' Computing velocity profile in terms of the flow rate, using inverse womersley method of Cezeaux et al.1997 ''' self.radius = mean(el.Radius) self.Res = el.R self.length = el.Length self.Name = el.Name Flow = mean(self.signal) #WOMERSLEY NUMBER self.alpha = self.radius * sqrt( (2.0 * pi * self.density) / (self.tPeriod * self.viscosity)) self.Wom = self.alpha self.Re = (2.0 * Flow * self.SimulationContext.Context['blood_density'] ) / (pi * self.radius * self.SimulationContext.Context['dynamic_viscosity']) #FOURIER SIGNAL k = len(self.signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k): An += self.signal[i] * cos( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) Bn += self.signal[i] * sin( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) An = An * (2.0 / k) Bn = Bn * (2.0 / k) self.fourierModes.append(complex(An, Bn)) n += 1 self.fourierModes[ 0] *= 0.5 #mean Flow, as expected. It's defined into xml input file. self.Steps = linspace(0, self.tPeriod, self.samples) self.VelRadius = {} self.VelRadiusSteps = {} self.VelocityPlot = {} for step in self.Steps: self.Velocity = {} y = -1 # raggio da -1 a 1, 200 punti. while y <= 1.: self.VelRadius[y] = 2 * (1.0**2 - y**2) * self.fourierModes[0] y += 0.01 k = 1 while k < self.nHarmonics: cI = complex(0., 1.) cA = (self.alpha * pow((1.0 * k), 0.5)) * pow(cI, 1.5) c1 = 2.0 * jn(1, cA) c0 = cA * jn(0, cA) cT = complex(0, -2.0 * pi * k * self.t / self.tPeriod) y = -1 #da -1 a 1 #y=0 #centerline while y <= 1.0: '''vel computation''' c0_y = cA * jn(0, (cA * y)) vNum = c0 - c0_y vDen = c0 - c1 vFract = vNum / vDen cV = self.fourierModes[k] * exp(cT) * vFract self.VelRadius[ y] += cV.real #valore di velocity riferito al raggio adimensionalizzato self.Velocity[y] = self.VelRadius[y].real y += 0.01 k += 1 unsortedRadii = [] for rad, vel in self.Velocity.iteritems(): unsortedRadii.append(rad) radii = sorted(unsortedRadii) self.VelPlot = [] for x in radii: for rad, vel in self.Velocity.iteritems(): if x == rad: self.VelPlot.append(vel * (100.0 / (self.radius**2 * pi))) self.VelocityPlot[step] = self.VelPlot self.t += self.dtPlot
def ShowVelocityProfile(self, meshid): ''' This method plots an animated representation of the velocity profile evolving in time using wx python library. ''' try: import matplotlib matplotlib.use('WXAgg') from matplotlib.pyplot import xlabel, ylabel, title, close, figure, ylim, show except: sys.exit("VelocityProfile methods require matplotlib package (http://matplotlib.sourceforge.net.\n") try: from wx import GetApp,EVT_CLOSE, EVT_IDLE except: sys.exit("ShowVelocityProfile method requires wxpython package (http://www.wxpython.org).\n") self.count = 0 orderingStep = [] for step, vel in self.VelocityPlot.iteritems(): orderingStep.append(step) lenVel = len(vel) if step == 0.0: firstVel = vel orderedStep = sorted(orderingStep) orderedVel = [] for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) orderedVel.reverse() maxY = 0 minY = 0 for vY in orderedVel: if max(vY) > maxY: maxY = max(vY) if min(vY) < minY: minY = min(vY) fig = figure() ax = fig.add_subplot(111) t = linspace(-1.0,1.0,lenVel) line, = ax.plot(t, firstVel,'r-',linewidth = 3) ylim(ymax=maxY) ylim(ymin=minY) xlabel('Fractional radius') ylabel('Velocity profile ($cm/s$)') title ('Mean radius($mm$)= '+str(round(self.radius*1e3,0))+' Reynolds N.= '+str(round(self.Re,0))+' Womersley N.= '+str(round(self.Wom,2))) '''WX ANIMATION''' def update_line(idleevent): if orderedVel == []: for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) orderedVel.reverse() self.count +=1 if self.count >=2: self.count = 0 EVT_CLOSE(GetApp(), update_line) close() line.set_ydata(orderedVel.pop()) fig.canvas.draw_idle() EVT_IDLE(GetApp(), update_line) show()
def SaveVelocityProfile(self, meshid, daystr): ''' This method plots velocity profile into png files and makes an avi file from png set. Mencoder is required. ''' try: import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import plot, xlabel, ylabel, title, savefig, ylim, axis, clf except: sys.exit("VelocityProfile methods require matplotlib package (http://matplotlib.sourceforge.net.\n") #Create temporary image and videos directories''' if not os.path.exists ('tmp/'): os.mkdir('tmp/') if not os.path.exists ('videos/'): os.mkdir('videos/') if not os.path.exists ('videos/%s' % daystr): os.mkdir('videos/%s' % daystr) not_found_msg = """ The mencoder command was not found; mencoder is used by this script to make an avi file from a set of pngs. It is typically not installed by default on linux distros because of legal restrictions, but it is widely available. """ try: subprocess.check_call(['mencoder']) except subprocess.CalledProcessError: print "mencoder command was found" pass # mencoder is found, but returns non-zero exit as expected # This is a quick and dirty check; it leaves some spurious output # for the user to puzzle over. except OSError: print not_found_msg sys.exit("quitting\n") self.count = 0 orderingStep = [] for step, vel in self.VelocityPlot.iteritems(): orderingStep.append(step) lenStep = len(self.VelocityPlot) lenVel = len(vel) orderedStep = sorted(orderingStep) orderedVel = [] for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) maxY = 0 minY = 0 for vY in orderedVel: if max(vY) > maxY: maxY = max(vY) if min(vY) < minY: minY = min(vY) x = linspace(-1.0,1.0,lenVel) # Values to be plotted on the x-axis. ylim(ymax=maxY) ylim(ymin=minY) i = 0 print 'Computing Images for velocity profile...' while i<lenStep: plot(x,orderedVel[i],'r-',linewidth = 3) axis((x[1],x[-1],minY,maxY)) xlabel('Fractional radius') ylabel('Velocity profile ($cm/s$)') title (str(self.Name)+' radius($mm$)= '+str(round(self.radius*1e3,1))+' Reynolds N.= '+str(round(self.Re,0))+' Womersley N.= '+str(round(self.Wom,2))) filename = str('%04d' % i) + '.png' savefig('tmp/'+filename, dpi=100) clf() i+=1 print 'Making movie from images..' command = ('mencoder', 'mf://tmp/*.png', '-mf', 'type=png:w=800:h=600:fps=25', '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4', '-oac', 'copy', '-o', 'videos/%s%s.avi' % (daystr,self.Name)) print "\n\nabout to execute:\n%s\n\n" % ' '.join(command) subprocess.check_call(command) print "\n\n The movie was written"
# obtain exponential function through lease square fit def erfc(p, x, y): return y - (p[0] * np.exp(p[1] * x) + p[2]) def f(x, p): return p[0] * np.exp(p[1] * x) + p[2] p0 = [1, -1, 1] plsq = optimize.leastsq(erfc, p0, args=(x1, y1)) x1_new = num_base.linspace(0.01, 100, 800) y1_new = f(x1_new, plsq[0]) plsq = optimize.leastsq(erfc, p0, args=(x2, y2)) x2_new = num_base.linspace(0.01, 100, 800) y2_new = f(x2_new, plsq[0]) plsq = optimize.leastsq(erfc, p0, args=(x3, y3)) x3_new = num_base.linspace(0.01, 100, 800) y3_new = f(x3_new, plsq[0]) plsq = optimize.leastsq(erfc, p0, args=(x4, y4)) x4_new = num_base.linspace(0.01, 100, 800) y4_new = f(x4_new, plsq[0]) # plot ECR with reduced range
def GetWssPeaks(self, el, flowsig): ''' This method returns Wss peak along the element. Wss in s=0 and s=1 is computed. ''' r0 = el.Radius[0] r1 = el.Radius[len(el.Radius) - 1] r01Signal = [] for sig in flowsig: r01Signal.append(sig) self.nSteps = arange(0, len(r01Signal), 1) self.dt = self.tPeriod / (len(self.nSteps) - 1) self.dtPlot = self.tPeriod / self.samples fourierModes = [] #Computing for s=0 r0WssSignal = [] #WOMERSLEY NUMBER r0Alpha = r0 * sqrt( (2.0 * pi * self.density) / (self.tPeriod * self.viscosity)) #Computing for s=1 r1WssSignal = [] #WOMERSLEY NUMBER r1Alpha = r1 * sqrt( (2.0 * pi * self.density) / (self.tPeriod * self.viscosity)) k01 = len(r01Signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k01): An += r01Signal[i] * cos( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) Bn += r01Signal[i] * sin( n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i]) An = An * (2.0 / k01) Bn = Bn * (2.0 / k01) fourierModes.append(complex(An, Bn)) n += 1 self.Steps = linspace(0, self.tPeriod, self.samples) for step in self.Steps: tao0 = -fourierModes[0].real * 2.0 tao1 = -fourierModes[0].real * 2.0 k = 1 while k < self.nHarmonics: cI = complex(0., 1.) cA_0 = (r0Alpha * pow((1.0 * k), 0.5)) * pow(cI, 1.5) c1_0 = 2.0 * jn(1, cA_0) c0_0 = cA_0 * jn(0, cA_0) cA_1 = (r1Alpha * pow((1.0 * k), 0.5)) * pow(cI, 1.5) c1_1 = 2.0 * jn(1, cA_1) c0_1 = cA_1 * jn(0, cA_1) cT = complex(0, -2.0 * pi * k * self.t / self.tPeriod) '''R0: Wall shear stress computation''' taoNum_0 = r0Alpha**2 * cI**3 * jn(1, cA_0) taoDen_0 = c0_0 - c1_0 taoFract_0 = taoNum_0 / taoDen_0 cTao_0 = fourierModes[k] * exp(cT) * taoFract_0 tao0 += cTao_0.real '''R1: Wall shear stress computation''' taoNum_1 = r1Alpha**2 * cI**3 * jn(1, cA_1) taoDen_1 = c0_1 - c1_1 taoFract_1 = taoNum_1 / taoDen_1 cTao_1 = fourierModes[k] * exp(cT) * taoFract_1 tao1 += cTao_1.real k += 1 tao0 *= -(self.viscosity / (r0**3 * pi)) r0WssSignal.append(tao0) tao1 *= -(self.viscosity / (r1**3 * pi)) r1WssSignal.append(tao1) self.t += self.dtPlot r0Peak = max(r0WssSignal) r1Peak = max(r1WssSignal) return r0Peak, r1Peak
def GetVelFromQ(self,el): ''' Computing velocity profile in terms of the flow rate, using inverse womersley method of Cezeaux et al.1997 ''' self.radius = mean(el.Radius) self.Res = el.R self.length = el.Length self.Name = el.Name Flow = mean(self.signal) #WOMERSLEY NUMBER self.alpha = self.radius * sqrt((2.0 *pi*self.density)/(self.tPeriod*self.viscosity)) self.Wom = self.alpha self.Re = (2.0*Flow*self.SimulationContext.Context['blood_density'])/(pi*self.radius*self.SimulationContext.Context['dynamic_viscosity']) #FOURIER SIGNAL k = len(self.signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k): An += self.signal[i] * cos(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) Bn += self.signal[i] * sin(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) An = An * (2.0/k) Bn = Bn * (2.0/k) self.fourierModes.append(complex(An, Bn)) n+=1 self.fourierModes[0] *= 0.5 #mean Flow, as expected. It's defined into xml input file. self.Steps = linspace(0,self.tPeriod,self.samples) self.VelRadius = {} self.VelRadiusSteps = {} self.VelocityPlot = {} for step in self.Steps: self.Velocity = {} y = -1 # raggio da -1 a 1, 200 punti. while y <=1.: self.VelRadius[y] = 2*(1.0**2 - y**2)*self.fourierModes[0] y+=0.01 k=1 while k < self.nHarmonics: cI = complex(0.,1.) cA = (self.alpha * pow((1.0*k),0.5)) * pow(cI,1.5) c1 = 2.0 * jn(1, cA) c0 = cA * jn(0, cA) cT = complex(0, -2.0*pi*k*self.t/self.tPeriod) y=-1 #da -1 a 1 #y=0 #centerline while y<=1.0: '''vel computation''' c0_y = cA * jn(0, (cA*y)) vNum = c0-c0_y vDen = c0-c1 vFract = vNum/vDen cV = self.fourierModes[k] * exp(cT) * vFract self.VelRadius[y] += cV.real #valore di velocity riferito al raggio adimensionalizzato self.Velocity[y] = self.VelRadius[y].real y+=0.01 k+=1 unsortedRadii = [] for rad, vel in self.Velocity.iteritems(): unsortedRadii.append(rad) radii = sorted(unsortedRadii) self.VelPlot = [] for x in radii: for rad, vel in self.Velocity.iteritems(): if x == rad: self.VelPlot.append(vel*(100.0/(self.radius**2*pi))) self.VelocityPlot[step] = self.VelPlot self.t += self.dtPlot
def ShowVelocityProfile(self, meshid): ''' This method plots an animated representation of the velocity profile evolving in time using wx python library. ''' try: import matplotlib matplotlib.use('WXAgg') from matplotlib.pyplot import xlabel, ylabel, title, close, figure, ylim, show except: sys.exit( "VelocityProfile methods require matplotlib package (http://matplotlib.sourceforge.net.\n" ) try: from wx import GetApp, EVT_CLOSE, EVT_IDLE except: sys.exit( "ShowVelocityProfile method requires wxpython package (http://www.wxpython.org).\n" ) self.count = 0 orderingStep = [] for step, vel in self.VelocityPlot.iteritems(): orderingStep.append(step) lenVel = len(vel) if step == 0.0: firstVel = vel orderedStep = sorted(orderingStep) orderedVel = [] for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) orderedVel.reverse() maxY = 0 minY = 0 for vY in orderedVel: if max(vY) > maxY: maxY = max(vY) if min(vY) < minY: minY = min(vY) fig = figure() ax = fig.add_subplot(111) t = linspace(-1.0, 1.0, lenVel) line, = ax.plot(t, firstVel, 'r-', linewidth=3) ylim(ymax=maxY) ylim(ymin=minY) xlabel('Fractional radius') ylabel('Velocity profile ($cm/s$)') title('Mean radius($mm$)= ' + str(round(self.radius * 1e3, 0)) + ' Reynolds N.= ' + str(round(self.Re, 0)) + ' Womersley N.= ' + str(round(self.Wom, 2))) '''WX ANIMATION''' def update_line(idleevent): if orderedVel == []: for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) orderedVel.reverse() self.count += 1 if self.count >= 2: self.count = 0 EVT_CLOSE(GetApp(), update_line) close() line.set_ydata(orderedVel.pop()) fig.canvas.draw_idle() EVT_IDLE(GetApp(), update_line) show()
def SaveVelocityProfile(self, meshid, daystr): ''' This method plots velocity profile into png files and makes an avi file from png set. Mencoder is required. ''' try: import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import plot, xlabel, ylabel, title, savefig, ylim, axis, clf except: sys.exit( "VelocityProfile methods require matplotlib package (http://matplotlib.sourceforge.net.\n" ) #Create temporary image and videos directories''' if not os.path.exists('tmp/'): os.mkdir('tmp/') if not os.path.exists('videos/'): os.mkdir('videos/') if not os.path.exists('videos/%s' % daystr): os.mkdir('videos/%s' % daystr) not_found_msg = """ The mencoder command was not found; mencoder is used by this script to make an avi file from a set of pngs. It is typically not installed by default on linux distros because of legal restrictions, but it is widely available. """ try: subprocess.check_call(['mencoder']) except subprocess.CalledProcessError: print "mencoder command was found" pass # mencoder is found, but returns non-zero exit as expected # This is a quick and dirty check; it leaves some spurious output # for the user to puzzle over. except OSError: print not_found_msg sys.exit("quitting\n") self.count = 0 orderingStep = [] for step, vel in self.VelocityPlot.iteritems(): orderingStep.append(step) lenStep = len(self.VelocityPlot) lenVel = len(vel) orderedStep = sorted(orderingStep) orderedVel = [] for timeStep in orderedStep: for step, vel in self.VelocityPlot.iteritems(): if timeStep == step: orderedVel.append(vel) maxY = 0 minY = 0 for vY in orderedVel: if max(vY) > maxY: maxY = max(vY) if min(vY) < minY: minY = min(vY) x = linspace(-1.0, 1.0, lenVel) # Values to be plotted on the x-axis. ylim(ymax=maxY) ylim(ymin=minY) i = 0 print 'Computing Images for velocity profile...' while i < lenStep: plot(x, orderedVel[i], 'r-', linewidth=3) axis((x[1], x[-1], minY, maxY)) xlabel('Fractional radius') ylabel('Velocity profile ($cm/s$)') title( str(self.Name) + ' radius($mm$)= ' + str(round(self.radius * 1e3, 1)) + ' Reynolds N.= ' + str(round(self.Re, 0)) + ' Womersley N.= ' + str(round(self.Wom, 2))) filename = str('%04d' % i) + '.png' savefig('tmp/' + filename, dpi=100) clf() i += 1 print 'Making movie from images..' command = ('mencoder', 'mf://tmp/*.png', '-mf', 'type=png:w=800:h=600:fps=25', '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4', '-oac', 'copy', '-o', 'videos/%s%s.avi' % (daystr, self.Name)) print "\n\nabout to execute:\n%s\n\n" % ' '.join(command) subprocess.check_call(command) print "\n\n The movie was written"
def GetWssPeaks(self,el, flowsig): ''' This method returns Wss peak along the element. Wss in s=0 and s=1 is computed. ''' r0 = el.Radius[0] r1 = el.Radius[len(el.Radius)-1] r01Signal = [] for sig in flowsig: r01Signal.append(sig) self.nSteps = arange(0,len(r01Signal),1) self.dt = self.tPeriod/(len(self.nSteps)-1) self.dtPlot = self.tPeriod/self.samples fourierModes = [] #Computing for s=0 r0WssSignal = [] #WOMERSLEY NUMBER r0Alpha = r0 * sqrt((2.0 *pi*self.density)/(self.tPeriod*self.viscosity)) #Computing for s=1 r1WssSignal = [] #WOMERSLEY NUMBER r1Alpha = r1 * sqrt((2.0 *pi*self.density)/(self.tPeriod*self.viscosity)) k01 = len(r01Signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k01): An += r01Signal[i] * cos(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) Bn += r01Signal[i] * sin(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) An = An * (2.0/k01) Bn = Bn * (2.0/k01) fourierModes.append(complex(An, Bn)) n+=1 self.Steps = linspace(0,self.tPeriod,self.samples) for step in self.Steps: tao0 = -fourierModes[0].real * 2.0 tao1 = -fourierModes[0].real * 2.0 k=1 while k < self.nHarmonics: cI = complex(0.,1.) cA_0 = (r0Alpha * pow((1.0*k),0.5)) * pow(cI,1.5) c1_0 = 2.0 * jn(1, cA_0) c0_0 = cA_0 * jn(0, cA_0) cA_1 = (r1Alpha * pow((1.0*k),0.5)) * pow(cI,1.5) c1_1 = 2.0 * jn(1, cA_1) c0_1 = cA_1 * jn(0, cA_1) cT = complex(0, -2.0*pi*k*self.t/self.tPeriod) '''R0: Wall shear stress computation''' taoNum_0 = r0Alpha**2*cI**3*jn(1,cA_0) taoDen_0 = c0_0-c1_0 taoFract_0 = taoNum_0/taoDen_0 cTao_0 = fourierModes[k] * exp(cT) * taoFract_0 tao0 += cTao_0.real '''R1: Wall shear stress computation''' taoNum_1 = r1Alpha**2*cI**3*jn(1,cA_1) taoDen_1 = c0_1-c1_1 taoFract_1 = taoNum_1/taoDen_1 cTao_1 = fourierModes[k] * exp(cT) * taoFract_1 tao1 += cTao_1.real k+=1 tao0 *= -(self.viscosity/(r0**3*pi)) r0WssSignal.append(tao0) tao1 *= -(self.viscosity/(r1**3*pi)) r1WssSignal.append(tao1) self.t += self.dtPlot r0Peak = max(r0WssSignal) r1Peak = max(r1WssSignal) return r0Peak,r1Peak
if (os.path.isfile(ecr_name)): # DEBUG #print ecr_name # DEBUG plt.clf() new_smoothing = 0 while new_smoothing >= 0: smoothing = new_smoothing x, y = io.loadtxt(ecr_name, usecols=[0, 1], unpack=True) # DEBUG print "Current smoothing factor = %f" % (smoothing) tck = interpolate.splrep(x, y, s=smoothing) x_new = num_base.linspace(0.01, max(x), 100) y_new = interpolate.splev(x_new, tck, der=0) plt.plot(x, y, 'o', x_new, y_new, '-') plt.show() tmp = raw_input( "Input new smoothing factor (press ENTER when done): ") if (tmp == ""): break else: new_smoothing = float(tmp) else: continue # obtain 1-d spline representation of data #tck = interpolate.splrep(x, y, s=smoothing)