def drawall(self, **kwargs): if not self.n == self.drawax.shape: self.drawax = np.ones(self.n, dtype='bool') if not self.n[1] == self.hrel.shape[0]: self.hrel = np.ones(self.n[1], dtype='float32') if not self.n[0] == self.vrel.shape[0]: self.vrel = np.ones(self.n[0], dtype='float32') if kwargs.has_key('lw'): kwargs['linewidth'] = kwargs.pop('lw') if not kwargs.has_key('linewidth'): kwargs['linewidth'] = self.linewidth else: self.linewidth = kwargs['linewidth'] forcesharex = False forcesharey = False if kwargs.has_key('sharex'): forcesharex = True if kwargs.has_key('sharey'): forcesharey = True inter = pylab.isinteractive() pylab.interactive( False) # wait to draw the axes, until they've all been created. axg = self.axgrid() for iv in range(self.n[0]): for ih in range(self.n[1]): if forcesharex: # I should put this functionality into a func. pass elif self.sharex[iv, ih] and self._sharex_ax[self.sharex[iv, ih]]: kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]] elif kwargs.has_key('sharex'): kwargs.pop('sharex') if forcesharey: pass elif self.sharey[iv, ih] and self._sharey_ax[self.sharey[iv, ih]]: kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]] elif kwargs.has_key('sharey'): kwargs.pop('sharey') if self.drawax[iv, ih]: #self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs) self.ax[iv, ih] = axes(axg[iv, ih, :], **kwargs) self.ax[iv, ih].hold(True) if self.sharex[ iv, ih] and not self._sharex_ax[self.sharex[iv, ih]]: self._sharex_ax[self.sharex[iv, ih]] = self.ax[iv, ih] if self.sharey[ iv, ih] and not self._sharey_ax[self.sharey[iv, ih]]: self._sharey_ax[self.sharey[iv, ih]] = self.ax[iv, ih] flag = True self._xlabel_ax = self.ax[-1, 0] self._ylabel_ax = self._xlabel_ax pylab.interactive(inter) pylab.draw_if_interactive() return self.ax
def __call__(self, **params): p = ParamOverrides(self, params) fig = plt.figure(figsize=(5, 5)) # This one-liner works in Octave, but in matplotlib it # results in lines that are all connected across rows and columns, # so here we plot each line separately: # plt.plot(x,y,"k-",transpose(x),transpose(y),"k-") # Here, the "k-" means plot in black using solid lines; # see matplotlib for more info. isint = plt.isinteractive() # Temporarily make non-interactive for # plotting plt.ioff() for r, c in zip(p.y[::p.skip], p.x[::p.skip]): plt.plot(c, r, "k-") for r, c in zip(np.transpose(p.y)[::p.skip],np.transpose(p.x)[::p.skip]): plt.plot(c, r, "k-") # Force last line avoid leaving cells open if p.skip != 1: plt.plot(p.x[-1], p.y[-1], "k-") plt.plot(np.transpose(p.x)[-1], np.transpose(p.y)[-1], "k-") plt.xlabel('x') plt.ylabel('y') # Currently sets the input range arbitrarily; should presumably figure out # what the actual possible range is for this simulation (which would presumably # be the maximum size of any GeneratorSheet?). plt.axis(p.axis) if isint: plt.ion() self._generate_figure(p) return fig
def __call__(self, t, text=''): """ Updates the hill_plot at time t. You can provide a title for the figure. If bool(title)==False, t is shown. """ layer_f = self.layers.get_fluxes3d(t) surf_f = self.surfacewater.get_fluxes3d(t) self.q_sub.set_UVC(numpy.asarray(layer_f.X), numpy.asarray(layer_f.Z)) self.q_surf.set_UVC(numpy.asarray(surf_f.X), numpy.asarray(surf_f.Z)) for l in self.layers: self.polys[l.node_id].set_fc(self.cmap(self.evalfunction(l))) x, z = self.__get_layer_shape(l, *self.__cells_of_layer[l.node_id]) self.polys[l.node_id].set_xy(numpy.column_stack((x, z))) self.topline.set_ydata(self.__get_snow_height()) if not text: text = str(t) self.title.set_text(text) if pylab.isinteractive(): pylab.draw() # Collect all matplotlib artist to use the HillPlot in animations artists = [self.title] artists += list(self.polys.values()) artists.append(self.topline) artists.append(self.q_sub) artists.append(self.q_surf) return artists
def drawall(self, **kwargs): if not self.n == self.drawax.shape: self.drawax = np.ones(self.n, dtype='bool') if 'lw' in kwargs.keys(): kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) if 'linewidth' not in kwargs.keys(): kwargs['linewidth'] = self.linewidth else: self.linewidth = kwargs['linewidth'] inter = pylab.isinteractive() pylab.interactive(False) # wait to draw the axes, until they've all been # created. for iv, ih in self._iter_axinds(): if self.drawax[iv, ih]: self.ax[iv, ih] = axes(self.axPlacer(iv, ih), sharex=self.sharex(iv, ih), sharey=self.sharey(iv, ih), **kwargs) self._xlabel_ax = self.ax[-1, 0] self._ylabel_ax = self._xlabel_ax pylab.interactive(inter) pylab.draw_if_interactive() return self.ax
def matrix_plot(self, matrix, figure_name='matrix_plot.pdf'): import numpy from matplotlib import pylab def _blob(x,y,area,colour): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) pylab.fill(xcorners, ycorners, colour, edgecolor=colour) reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(matrix)))/numpy.log(2)) height, width = matrix.shape pylab.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'white') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = matrix[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#0099CC') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#660000') if reenable: pylab.ion() pylab.savefig(figure_name)
def matrix_plot(self, matrix, figure_name='matrix_plot.pdf'): import numpy from matplotlib import pylab def _blob(x, y, area, colour): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) pylab.fill(xcorners, ycorners, colour, edgecolor=colour) reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() maxWeight = 2**numpy.ceil( numpy.log(numpy.max(numpy.abs(matrix))) / numpy.log(2)) height, width = matrix.shape pylab.fill(numpy.array([0, width, width, 0]), numpy.array([0, 0, height, height]), 'white') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = matrix[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, 0.2, '#0099CC') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, 0.2, '#660000') if reenable: pylab.ion() pylab.savefig(figure_name)
def drawall(self, **kwargs): if not self.n == self.drawax.shape: self.drawax = np.ones(self.n, dtype='bool') if not self.n[1] == self.hrel.shape[0]: self.hrel = np.ones(self.n[1], dtype='float32') if not self.n[0] == self.vrel.shape[0]: self.vrel = np.ones(self.n[0], dtype='float32') if 'lw' in kwargs.keys(): kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) if 'linewidth' not in kwargs.keys(): kwargs['linewidth'] = self.linewidth else: self.linewidth = kwargs['linewidth'] forcesharex = False forcesharey = False if 'sharex' in kwargs.keys(): forcesharex = True if 'sharey' in kwargs.keys(): forcesharey = True inter = pylab.isinteractive() pylab.interactive(False) # wait to draw the axes, until they've all been # created. axg = self.axgrid() for iv in range(self.n[0]): for ih in range(self.n[1]): if forcesharex: # I should put this functionality into a func. pass elif (self.sharex[iv, ih] and self._sharex_ax[self.sharex[iv, ih]]): kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]] elif 'sharex' in kwargs.keys(): kwargs.pop('sharex') if forcesharey: pass elif (self.sharey[iv, ih] and self._sharey_ax[self.sharey[iv, ih]]): kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]] elif 'sharey' in kwargs.keys(): kwargs.pop('sharey') if self.drawax[iv, ih]: # self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs) self.ax[iv, ih] = axes(axg[iv, ih,:], **kwargs) self.ax[iv, ih].hold(True) if self.sharex[iv, ih] and not\ self._sharex_ax[self.sharex[iv, ih]]: self._sharex_ax[self.sharex[iv, ih]] = self.ax[iv, ih] if self.sharey[iv, ih] and not\ self._sharey_ax[self.sharey[iv, ih]]: self._sharey_ax[self.sharey[iv, ih]] = self.ax[iv, ih] self._xlabel_ax = self.ax[-1, 0] self._ylabel_ax = self._xlabel_ax pylab.interactive(inter) pylab.draw_if_interactive() return self.ax
def __call__(self, t=None): a = numpy.array if t: self.t = t f = cmf.cell_flux_directions(self.cells, self.t) self.quiver.set_UVC(a(f.X), a(f.Y)) if plt.isinteractive(): plt.draw()
def __init__(self, cells, value_function, cmap=default_colormap, hold=True, vmin=None, vmax=None, **kwargs): """ Creates a new map from cells :param cells: :param value_function: :param cmap: :param hold: :param vmin: :param vmax: :param kwargs: """ if not hasattr(cmf.Cell, 'geometry'): raise NotImplementedError('The geometry of the cells can not be used, shapely is not installed') self.cmap = cmap self.cells = [c for c in cells if c.geometry] self.__f = value_function was_interactive = plt.isinteractive() if was_interactive: plt.ioff() self.polygons = {} def flatten_multipolygons(shape): if hasattr(shape, "geoms"): return shape.geoms else: return [shape] geos = [flatten_multipolygons(c.geometry) for c in self.cells] values = [self.f(c) for c in self.cells] self.maxvalue = vmax or max(values) self.minvalue = vmin or min(values) if self.minvalue >= self.maxvalue: self.minvalue = self.maxvalue - 1 if not hold: plt.cla() for cell, shapes, v in zip(self.cells, geos, values): c = self.cmap(float(v - self.minvalue) / float(self.maxvalue - self.minvalue)) self.polygons[cell] = [self.draw_shapes(s, c, **kwargs) for s in shapes] plt.axis('equal') norm = Normalize(self.minvalue, self.maxvalue) plt.matplotlib.cm.ScalarMappable.__init__(self, norm, cmap) if was_interactive: plt.draw() plt.ion()
def __call__(self, recalc_range=False): if recalc_range: self.maxvalue = max((self.f(c) for c in self.cells)) self.minvalue = min((self.f(c) for c in self.cells)) for cell, polys in self.polygons.items(): v = self.f(cell) c = self.cmap((v - self.minvalue) / (self.maxvalue - self.minvalue)) for poly in polys: poly.set_fc(c) if plt.isinteractive(): plt.draw()
def __call__(self, **params): p = ParamOverrides(self, params) name = p.plot_template.keys().pop(0) plot = make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity, p.sheet.bounds, p.normalize, name=p.plot_template[name]) fig = plt.figure(figsize=(5, 5)) if plot: bitmap = plot.bitmap isint = plt.isinteractive( ) # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image, origin='lower', interpolation='nearest') plt.axis('off') for (t, pref, sel, c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t == 'contours'): plt.contour(v, [sel, sel], colors=c, linewidths=2) if (t == 'arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v) / scale)]) v_sc = np.zeros((len(v) / scale, len(v) / scale)) s_sc = np.zeros((len(v) / scale, len(v) / scale)) for i in X: for j in X: v_sc[i][j] = v[scale * i][scale * j] s_sc[i][j] = s[scale * i][scale * j] plt.quiver(scale * X, scale * X, -np.cos(2 * np.pi * v_sc) * s_sc, -np.sin(2 * np.pi * v_sc) * s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title = '%s overlaid with %s at time %s' % (plot.name, pref, topo.sim.timestr()) if isint: plt.ion() p.filename_suffix = "_" + p.sheet.name self._generate_figure(p) return fig
def __call__(self, **params): p=ParamOverrides(self,params) name=p.plot_template.keys().pop(0) plot=make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity,p.sheet.bounds, p.normalize,name=p.plot_template[name]) fig = plt.figure(figsize=(5,5)) if plot: bitmap=plot.bitmap isint=plt.isinteractive() # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image,origin='lower',interpolation='nearest') plt.axis('off') for (t,pref,sel,c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t=='contours'): plt.contour(v,[sel,sel],colors=c,linewidths=2) if (t=='arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v)/scale)]) v_sc = np.zeros((len(v)/scale,len(v)/scale)) s_sc = np.zeros((len(v)/scale,len(v)/scale)) for i in X: for j in X: v_sc[i][j] = v[scale*i][scale*j] s_sc[i][j] = s[scale*i][scale*j] plt.quiver(scale*X, scale*X, -np.cos(2*np.pi*v_sc)*s_sc, -np.sin(2*np.pi*v_sc)*s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr()) if isint: plt.ion() p.filename_suffix="_"+p.sheet.name self._generate_figure(p) return fig
def hinton(W, maxWeight=None): reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(W)))/numpy.log(2)) P.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'gray') P.axis('off') P.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > maxWeight/2: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w <= maxWeight/2: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'black') if reenable: P.ion() P.show()
import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf import matplotlib.pylab as pd d1=sys.argv[1];d2=sys.argv[2] path=os.path.join(d1,d2) img_ml=nd.imread(path) pd.ion() print pd.isinteractive() fig1, ax1 = plt.subplots(num=1,figsize=(6,1.0*img_ml.shape[0]/img_ml.shape[1]*6)) fig1.subplots_adjust(0,0,1,1);ax1.grid('off') ax1.axis('off') fig1.canvas.set_window_title(d2) im1 = ax1.imshow(img_ml) fig1.canvas.draw() fig2, ax2 = plt.subplots(3,1,num=2,figsize=[14,10]) ax2[0].hist(img_ml[:,:,0].reshape(img_ml.shape[0]*img_ml.shape[1]),bins=256,color='r') ax2[0].set_xlim([0,256]) ax2[1].hist(img_ml[:,:,1].reshape(img_ml.shape[0]*img_ml.shape[1]),bins=256,color='g') ax2[1].set_xlim([0,256]) ax2[2].hist(img_ml[:,:,2].reshape(img_ml.shape[0]*img_ml.shape[1]),bins=256,color='b') ax2[2].set_xlim([0,256]) plt.show(block=False) print 'yes Im running'
def particle_size_distribution(struct,t_index,z_index): """plot particle size distribution""" ptv,particle_parameters = get_data_at_index(struct,t_index,z_index) alpha_water = particle_parameters['alpha_water'] alpha_ice = particle_parameters['alpha_ice'] g_ice = particle_parameters['g_ice'] g_water = particle_parameters['g_water'] Dr = particle_parameters['Dr'] print 'Default processing' print 'effective_diameter_prime = %4i (microns)' %(ptv.eff_diameter_prime[0,0]*1e6) print 'effective_diameter = %4i (microns)' %(ptv.effective_diameter[0,0]*1e6) print 'mode diameter = %4i (microns)' %(ptv.dmode[0,0]*1e6) print 'mean diameter = %4i (microns)' %(ptv.mean_diameter[0,0]*1e6) print 'Doppler velocity = %4.2f (m/s)' %ptv.MeanDopplerVelocity[0,0] print 'rw_fall_vel = %4.2f (m/s)' %ptv.rw_fall_velocity[0,0] print 'mw_fall_vel = %4.2f (m/s)' %ptv.mw_fall_velocity[0,0] print 'model_spectral_width = %4.2f (m/s)' %ptv.model_spectral_width[0,0] print 'radar_spectral_width = %4.2f (m/s)' %ptv.radar_spectral_width[0,0] print 'alpha_water = ' ,alpha_water print 'alpha_ice = ',alpha_ice print 'gamma_water = ',g_water print 'gamma_ice = ',g_ice print 'zeta = ',ptv.zeta[0,0] rho_ice = 0.91 *1000.0 # kg/m^3 gas_constant = 287 #J/(kg K) #vector of diameters in m from 1 micron to 1 cm D = np.logspace(0.0,4.0,200)/1e6 dD = np.zeros_like(D) dD[1:] = D[1:]-D[:-1] if ptv.phase[0,0]: alpha = alpha_ice gam = g_ice else: alpha = alpha_water gam = g_water colors = ['b','g','r','c'] lwidth = 1.0 while 1: #recalculate size distribution with new alpha? alpha_gamma_str = raw_input('new params: alpha,gamma,zeta = ? or map ') #strip all blanks #alpha_gamma_str.lstrip() alpha_gamma_str.replace(" ","") n_alpha = 1 n_gam = 1 print alpha_gamma_str if not alpha_gamma_str == 'map': n_times=[2,2] if len(alpha_gamma_str) == 0: break elif alpha_gamma_str.find(',')>= 0: index = alpha_gamma_str.find(',') index2 = alpha_gamma_str[(index+1):].find(',') index2 = index +index2+1 alpha = np.float(alpha_gamma_str[:index]) gam = np.float(alpha_gamma_str[index +1:index2]) ptv.zeta[0,0] = np.float(alpha_gamma_str[index2+1:len(alpha_gamma_str)]) else: n_alpha = 20 n_gam = 40 n_times = [n_alpha,n_gam] cost_func = np.zeros((n_alpha,n_gam)) print n_times, n_times[0] print n_alpha,n_gam,ptv.zeta[0,0] if alpha_gamma_str == 'map': for i in range(1,n_times[0]): for k in range(1,n_times[1]): alpha = np.float(i)/2.0 gam = .05 * np.float(k) print print 'alpha = ',alpha,' gamma= ',gam particle_parameters['alpha_water'] = alpha particle_parameters['alpha_ice'] = alpha particle_parameters['g_water'] = gam particle_parameters['g_ice'] = gam beta_ext_radar = np.NaN * np.zeros((1,1)) beta_ext_lidar = np.NaN * np.zeros((1,1)) zeta =np.NaN * np.zeros((1,1)) beta_ext_lidar = rs_inv['beta_a_backscat'][t_index,z_index]/0.05 beta_ext_radar = rs_mmcr['Backscatter'][t_index,z_index] * 8 * np.pi/3.0 zeta = rs_spheroid_particle['zeta'][t_index,z_index] print beta_ext_lidar.shape dmode = spu.dmode_from_lidar_radar(beta_ext_lidar,beta_ext_radar,particle_parameters ,ptv.zeta,ptv.phase,8.6e-3) print dmode mode_dia,effective_dia,size_dist,mw_size_dist,aw_size_dist,rw_size_dist\ ,mw_fall_vel,rw_fall_vel,LWC_ext,LWC_p180 = precip_computation(\ alpha ,gam ,D ,extinction ,beta_a_backscat ,eff_dia_prime ,phase ,temperature ,pressure) else: #single value not mapping cost function particle_parameters['alpha_water'] = alpha particle_parameters['alpha_ice'] = alpha particle_parameters['g_water'] = gam particle_parameters['g_ice'] = gam #eff dia prime from radar and lidar #ptv.eff_diameter_prime[0,0] = edp.lidar_radar_eff_diameter_prime( # ptv.beta_ext_lidar # ,ptv.beta_ext_radar # ,ptv.phase # ,8.6e-3) print 'source',particle_parameters['ext_source'] print ptv.beta_a_backscat print particle_parameters['p180_ice'] print ptv.beta_ext_radar print ptv.zeta print ptv.phase if ptv.phase[0,0] == 1: p180 = particle_parameters['p180_ice'] else: p180 = 0.05 print 'beta_ext' , ptv.beta_a_backscat/p180 if particle_parameters['ext_source'] == 'bs/p180': ptv.dmode = spu.dmode_from_lidar_radar( ptv.beta_a_backscat/p180 ,ptv.beta_ext_radar ,particle_parameters ,ptv.zeta ,ptv.phase ,8.6e-3) else: ptv.dmode = spu.dmode_from_lidar_radar( ptv.beta_ext_lidar ,ptv.beta_ext_radar ,particle_parameters ,ptv.zeta ,ptv.phase ,8.6e-3) #compute effective diameter from mode_diameter ptv.effective_diameter[0,0],ptv.mean_diameter[0,0],ptv.mean_mass_diameter[0,0]\ = spu.effective_diameter( ptv.dmode ,particle_parameters ,ptv.zeta ,ptv.phase) #compute liquid water content (kg/m^3) LWC_ext = spu.liquid_water_content( ptv.effective_diameter ,ptv.beta_ext_lidar,ptv.phase) if ptv.phase[0,0] == 1: ptv.LWC_p180 = spu.liquid_water_content( ptv.effective_diameter ,ptv.beta_a_backscat/particle_parameters['p180_ice'] ,ptv.phase) elif ptv.phase[0,0] == 0 : ptv.LWC_p180 = spu.liquid_water_content( ptv.effective_diameter ,ptv.beta_a_backscat/0.05 ,ptv.phase) else: ptv.LWC_p180 = np.NaN #compute precip rate (m/s) #precip_rate = 1/density (m^3/kg) * LWC (kg/m^3) * fall_velocity (m/s) ptv.hsrl_radar_precip_rate[0,0] = 0.001 * ptv.LWC_p180[0,0] * ptv.MeanDopplerVelocity[0,0] #LR_precip_rate[0,0]= 0.001 * LWC_p180[0,0] * MeanDopplerVelocity[0,0 ptv.rw_fall_velocity[0,0],ptv.mw_fall_velocity[0,0],ptv.model_spectral_width[0,0]\ = spu.weighted_fall_velocity( ptv.dmode ,particle_parameters ,ptv.zeta ,ptv.temps ,ptv.pressures ,ptv.phase) size_dist = D**alpha * np.exp(-(alpha/gam) * (D/ptv.dmode[0,0])**gam) norm = np.sum(size_dist * dD) size_dist /=norm print 'norm',norm #area weighted distribution aw_size_dist = D**(alpha+2.0) * np.exp(-(alpha/gam) * (D/ptv.dmode[0,0])**gam) norm = np.sum(aw_size_dist * dD) aw_size_dist /= norm print norm #mass weighted distribution mw_size_dist = D**(alpha+ ptv.zeta + 2.0) * np.exp(-(alpha/gam) * (D/ptv.dmode[0,0])**gam) norm = np.sum(mw_size_dist * dD) mw_size_dist /= norm print norm #radar weighted distribution rw_size_dist = D**(alpha+ 2.0 * ptv.zeta + 4.0) * np.exp(-(alpha/gam) * (D/ptv.dmode[0,0])**gam) norm = np.sum(rw_size_dist * dD) rw_size_dist /= norm #compute model fall velocity at this point #constants, program works in mks rho_ice=0.91 * 1000.0 #kg/m^3 rho_water = 1000.0 #kg/m^3 gas_constant = 287 #J/(kg K) rho_air = 100.0 *ptv.pressures/(gas_constant * ptv.temps) #in kg/m^3 eta = spu.dynamic_viscosity(ptv.temps) #X = spu.best_number(D,Dr,ptv.zeta,rho_ice,rho_air,eta) X_const = spu.best_constant(rho_air,eta) if ptv.phase == 1: X = spu.best_number(D,Dr,X_const,ptv.zeta,rho_ice) else: X = spu.best_number(D,Dr,X_const,1.0,rho_water) Vf = spu.spheroid_fall_velocity(D,X,ptv.zeta,rho_air,eta,ptv.phase) #cost_func[i,k] = (doppler_vel-rw_fall_vel)**2 + (spectral_width-model_spectral_width)**2 #print 'cost function = ',cost_func[i,k] if alpha_gamma_str == 'map': plt.figure(999) imgplot = plt.imshow(np.log(cost_func)) plt.figure(1000) #plt.ioff() lines=plt.plot(D*1e6 ,np.transpose(size_dist), colors[0] ,D*1e6,np.transpose(aw_size_dist),colors[1] ,D*1e6,np.transpose(mw_size_dist),colors[2] ,D*1e6,np.transpose(rw_size_dist),colors[3]) plt.grid(True) ax=plt.gca() plt.setp(lines,linewidth=lwidth) plt.legend(['number','area','mass','radar']) ax.set_xlim(0,4500) plt.ylabel('weighted size distributions') plt.xlabel('Diameter (microns)') #plt.ion() plt.figure(1001) #plt.ioff() lines1=plt.plot(D*1e6 ,np.transpose(size_dist), colors[0] ,D*1e6,np.transpose(aw_size_dist),colors[1] ,D*1e6,np.transpose(mw_size_dist),colors[2] ,D*1e6,np.transpose(rw_size_dist),colors[3]) plt.grid(True) ax=plt.gca() plt.setp(lines1,linewidth=lwidth) plt.legend(['number','area','mass','radar']) plt.xlabel('Diameter (microns)') ax.set_xscale('log') #plt.show(False) plt.figure(1002) #plt.ioff() lines2=plt.plot(D*1e6,np.transpose(Vf),'r') plt.grid(True) ax=plt.gca() plt.setp(lines2,linewidth=lwidth) plt.xlabel('diameter (microns)') plt.ylabel('fall velocity (m/s)') ax.set_xscale('log') print print 'effective_diameter_prime = %4.0f (microns)' %(1e6 * ptv.eff_diameter_prime) print 'effective diameter = %4.0f (micons)' %(ptv.effective_diameter * 1e6) print 'mode diameter = %4.0f (microns)' %(ptv.dmode * 1e6) print 'mean diameter = %4.0f (microns)' %(ptv.mean_diameter *1e6) print 'LWC , extinction = %6.4f (gr/m^3)' %(ptv.LWC_ext * 1e3) print 'LWC ,p(180)/4pi = %4.2f = %6.4f (gr/m^3)' \ %(particle_parameters['p180_ice'],ptv.LWC_p180 * 1e3) if ptv.phase[0,0] == 1: print 'phase = ice' elif ptv.phase[0,0] == 0: print 'phase = water' else: print 'phase = NaN' print 'Doppler velocity = %4.2f (m/s)' %ptv.MeanDopplerVelocity print 'rw_fall_vel = %4.2f (m/s)' %ptv.rw_fall_velocity print 'mw_fall_vel = %4.2f (m/s)' %ptv.mw_fall_velocity print 'model_spectral_width = %4.2f (m/s)' %ptv.model_spectral_width print 'radar_spectral_width = %4.2f (m/s)' %ptv.radar_spectral_width print 'alpha = ' ,alpha print 'gamma = ',gam print 'zeta = ',ptv.zeta[0,0] lwidth = lwidth + 1.0 if not plt.isinteractive(): plt.show(False) #plt.ion() return
def _start_report(self): self.was_interactive = plt.isinteractive() plt.ioff() self.f = plt.figure(figsize=(self.figwidth, self.figheight)) self.pageno = 1
def __init__(self, cells, t, solute=None, cmap=default_color_map): """ Creates a new HillPlot on the active figure, showing the state of each layer - cells: The a sequence of cmf cells to use in this hill_plot. You can use the whole project if you like - t: Current time step. Needed to retrieve the fluxes - solute:The solute concentration to show. If None, the wetness of the layer will be shown - cmap: a matplotlib colormap (see module cm) for coloring """ was_interactive = pylab.isinteractive() if was_interactive: pylab.ioff() self.cells = cells self.layers = cmf.node_list(chain(*[c.layers for c in cells])) self.surfacewater = cmf.node_list(c.surfacewater for c in cells) x_pos = [self.__x(c.x, c.y) for c in cells] self.topline = pylab.plot(x_pos, self.__get_snow_height(), 'k-', lw=2)[0] self.__cells_of_layer = {} self.polys = {} # Get standard evaluation functions if isinstance(solute, cmf.solute): self.evalfunction = lambda layer: layer.conc(solute) else: self.evalfunction = lambda layer: layer.wetness self.cmap = cmap self.figure = pylab.gcf() for i, c in enumerate(cells): c_left = cells[i - 1] if i else c c_right = cells[i + 1] if i < len(cells) - 1 else c for l in c.layers: x, z = self.__get_layer_shape(l, c, c_left, c_right) self.polys[l.node_id], = pylab.fill(x, z, fc=self.cmap( self.evalfunction(l)), ec='none', zorder=0) self.__cells_of_layer[l.node_id] = (c, c_left, c_right) layer_pos = self.layers.get_positions() surf_pos = self.surfacewater.get_positions() layer_f = self.layers.get_fluxes3d(t) surf_f = self.surfacewater.get_fluxes3d(t) scale = max(numpy.linalg.norm(surf_f.X), numpy.linalg.norm( layer_f.X)) * 10 layer_x = self.__x(numpy.asarray(layer_pos.X), numpy.asarray(layer_pos.Y)) surf_x = self.__x(numpy.asarray(surf_pos.X), numpy.asarray(surf_pos.Y)) self.q_sub = pylab.quiver(layer_x, layer_pos.Z, layer_f.X + layer_f.Y, layer_f.Z, scale=scale, minlength=0.1, pivot='middle', zorder=1) self.q_surf = pylab.quiver(surf_x, surf_pos.Z, surf_f.X + surf_f.Y, surf_f.Z, color='b', scale=scale, minlength=0.1, pivot='middle', zorder=1) self.title = pylab.title(t) if was_interactive: pylab.draw() pylab.ion()
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy']) # call the function to fit to the data (training the network) history = model.fit(x_train, y_train, epochs=1000, batch_size=20, validation_data=(x_test, y_test)) scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100)) plt.figure() plt.isinteractive() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='best') plt.figure() plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('acc') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='best')
def f(self, funct): self.__f = funct if plt.isinteractive(): self(True)