def make_histogram(self, data, show_axis=None, distance=True): color = colors.Category.CAT20C[0] matplotlib.rcParams.update({'font.size': 9.5}) figure = Figure(frameon=False, figsize=(4, 2), dpi=72, edgecolor=color) specs = matplotlib.gridspec.GridSpec(ncols=8, nrows=1, figure=figure) plot = figure.add_subplot(specs[0, 1:7]) plot.patch.set_alpha(1.0) adjust_spines(plot, ['left'], color) formatter = FormatStrFormatter('%g') plot.yaxis.set_major_formatter(formatter) plot.yaxis.set_major_locator(MaxNLocator(5)) if distance: plot.plot(data[:, 0], data[:, 1], lw=0.75) else: plot.vlines(data[:, 0], 0, data[:, 1]) plot.set_xlim(min(data[:, 0]), max(data[:, 0])) # Ask matplotlib to render the figure to a bitmap using the Agg backend canvas = FigureCanvasCairo(figure) width, height = canvas.get_width_height() renderer = RendererCairo(canvas.figure.dpi) renderer.set_width_height(width, height) self.plot_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) renderer.set_ctx_from_surface(self.plot_surface) canvas.figure.draw(renderer) self.show_histogram = True
def figureToImage(fig): canvas = FigureCanvas(fig) buffer = StringIO() canvas.print_figure(buffer, dpi=fig.get_dpi(), facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) buffer.reset() im = Image.open(buffer) return im
def jpg(self): """ Returns a StringIO JPG plot for the sensor """ fig = self.matplot() canvas = FigureCanvas(fig) try: jpg_output = StringIO() except NameError: jpg_output = BytesIO() canvas.print_jpg(jpg_output) return jpg_output.getvalue()
def png(self): """ Returns a StringIO PNG plot for the sensor """ fig = self.matplot() canvas = FigureCanvas(fig) try: png_output = StringIO() except NameError: png_output = BytesIO() canvas.print_png(png_output) return png_output.getvalue()
def plot_data_split(request, id, split_nr): split_nr = int(split_nr) task = get_object_or_404(Task, pk=id) img = [task.get_split_image(split_nr)] #import pdb #pdb.set_trace() if (img == None): return None # why it does not work ? from pylab import axis axis('off') from StringIO import StringIO dpi = 60 bgcol = '#ffffff' fig = Figure(figsize=(7, 0.3), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) bx = fig.add_subplot(111) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) #import pdb #pdb.set_trace() bx.imshow(img, aspect='auto', interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) # bx = fig.add_subplot(212) # bx.set_yticklabels([]) # bx.set_xticklabels([]) # bx.imshow(img,aspect='auto',interpolation='nearest',cmap=cm.jet,extent=[0,len(img[0])-1,0,1]) canvas.draw() imdata = StringIO() fig.savefig(imdata, format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(), mimetype='image/png')
def plot_data_split(request,id,split_nr): split_nr=int(split_nr) task=get_object_or_404(Task, pk=id) img = [task.get_split_image(split_nr)] #import pdb #pdb.set_trace() if (img == None): return None # why it does not work ? from pylab import axis axis('off') from StringIO import StringIO dpi=60 bgcol='#ffffff' fig = Figure(figsize=(7,0.3), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) bx = fig.add_subplot(111) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) #import pdb #pdb.set_trace() bx.imshow(img,aspect='auto',interpolation='nearest',vmin=0,vmax=3,cmap=cmap_mldata) # bx = fig.add_subplot(212) # bx.set_yticklabels([]) # bx.set_xticklabels([]) # bx.imshow(img,aspect='auto',interpolation='nearest',cmap=cm.jet,extent=[0,len(img[0])-1,0,1]) canvas.draw() imdata=StringIO() fig.savefig(imdata,format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(),mimetype='image/png')
def draw_matplotlib_figure(self, figure): """Draws matplotlib figure to context""" class CustomRendererCairo(RendererCairo): """Workaround for older versins with limited draw path length""" if sys.byteorder == 'little': BYTE_FORMAT = 0 # BGRA else: BYTE_FORMAT = 1 # ARGB def draw_path(self, gc, path, transform, rgbFace=None): ctx = gc.ctx transform = transform + Affine2D().scale(1.0, -1.0).\ translate(0, self.height) ctx.new_path() self.convert_path(ctx, path, transform) try: self._fill_and_stroke(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) except AttributeError: # Workaround for some Windiws version of Cairo self._fill_and_stroke(ctx, rgbFace, gc.get_alpha()) def draw_image(self, gc, x, y, im): # bbox - not currently used rows, cols, buf = im.color_conv(self.BYTE_FORMAT) surface = cairo.ImageSurface.create_for_data( buf, cairo.FORMAT_ARGB32, cols, rows, cols * 4) ctx = gc.ctx y = self.height - y - rows ctx.save() ctx.set_source_surface(surface, x, y) if gc.get_alpha() != 1.0: ctx.paint_with_alpha(gc.get_alpha()) else: ctx.paint() ctx.restore() if pyplot is None: # Matplotlib is not installed return FigureCanvasCairo(figure) dpi = float(figure.dpi) # Set a border so that the figure is not cut off at the cell border border_x = 200 / (self.rect[2] / dpi)**2 border_y = 200 / (self.rect[3] / dpi)**2 width = (self.rect[2] - 2 * border_x) / dpi height = (self.rect[3] - 2 * border_y) / dpi figure.set_figwidth(width) figure.set_figheight(height) renderer = CustomRendererCairo(dpi) renderer.set_width_height(width, height) renderer.gc.ctx = self.context renderer.text_ctx = self.context self.context.save() self.context.translate(border_x, border_y + height * dpi) figure.draw(renderer) self.context.restore()
def tiled_axis(ts, filename=None): fig = Figure((2.56 * 4, 2.56 * 4), 300) canvas = FigureCanvas(fig) #ax = fig.add_subplot(111) grid = ImageGrid( fig, 111, # similar to subplot(111) nrows_ncols=(3, 1), axes_pad=0.5, add_all=True, label_mode="L", ) # pad half a day so that major ticks show up in the middle, not on the edges delta = dates.relativedelta(days=2, hours=12) # XXX: gets a list of days. timestamps = glucose.get_days(ts.time) xmin, xmax = (timestamps[0] - delta, timestamps[-1] + delta) fig.autofmt_xdate() def make_plot(ax, limit): preferspan = ax.axhspan(SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor='#003333', linewidth=1) def draw_glucose(ax, limit): xmin, xmax = limit # visualize glucose using stems ax.set_xlim([xmin, xmax]) markers, stems, baselines = ax.stem(ts.time, ts.value, linefmt='b:') plt.setp(markers, color='red', linewidth=.5, marker='o') plt.setp(baselines, marker='None') def draw_title(ax, limit): ax.set_title('glucose history') def get_axis(ax, limit): xmin, xmax = limit ax.set_xlim([xmin, xmax]) ax.grid(True) #ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] ) #ax.set_xlabel('time') majorLocator = dates.DayLocator() majorFormatter = dates.AutoDateFormatter(majorLocator) minorLocator = dates.HourLocator(interval=6) minorFormatter = dates.AutoDateFormatter(minorLocator) #ax.xaxis.set_major_locator(majorLocator) #ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_minor_formatter(minorFormatter) labels = ax.get_xminorticklabels() plt.setp(labels, rotation=30, fontsize='small') plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium') xmin, xmax = ax.get_xlim() log.info( pformat({ 'xlim': [dates.num2date(xmin), dates.num2date(xmax)], 'xticks': dates.num2date(ax.get_xticks()), })) for i, day in enumerate(timestamps): ax = grid[i] get_axis(ax, [day, day + delta]) name = '%s-%d.png' % (day.isoformat(), i) #fig.savefig( name ) canvas.print_figure(name) # fig.clf() #make_plot( ax, #ax.set_ylabel('glucose mm/dL') return canvas
def plot_legend(request): import numpy img=numpy.array([[0,1,2,3]]) #from pylab import axis #axis('off') from StringIO import StringIO dpi=25 bgcol='#ffffff' fig = Figure(figsize=(7,1.5), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) ax = fig.add_subplot(171) ax.set_title('not used') ax.title.set_fontsize(30) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_yticks([]) ax.set_xticks([]) ax.imshow([[0]],interpolation='nearest',vmin=0,vmax=3,cmap=cmap_mldata) bx = fig.add_subplot(173) bx.set_title('train') bx.title.set_fontsize(30) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) bx.set_xticks([]) bx.imshow([[1]],interpolation='nearest',vmin=0,vmax=3,cmap=cmap_mldata) cx = fig.add_subplot(175) cx.set_title('validation') cx.title.set_fontsize(30) cx.set_yticklabels([]) cx.set_xticklabels([]) cx.set_yticks([]) cx.set_xticks([]) cx.imshow([[2]],interpolation='nearest',vmin=0,vmax=3,cmap=cmap_mldata) dx = fig.add_subplot(177) dx.set_title('test') dx.title.set_fontsize(30) dx.set_yticklabels([]) dx.set_xticklabels([]) dx.set_yticks([]) dx.set_xticks([]) dx.imshow([[3]],interpolation='nearest',vmin=0,vmax=3,cmap=cmap_mldata) #bx.set_title('legend') #bx.set_yticklabels([]) #bx.set_xticklabels([]) #bx.set_yticklabels([]) #bx.set_xticklabels(['not used','train','validation','test']) #bx.set_yticks([]) #bx.set_xticks([2,7,12,17]) #for label in bx.get_xticklabels(): # label.set_fontsize(12) #bx.imshow([[0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3]],aspect=None,interpolation='nearest',cmap=cm.Greys) canvas.draw() imdata=StringIO() fig.savefig(imdata,format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(),mimetype='image/png')
def __init__(self, figure, wpx, hpx): FigureCanvasCairo.__init__(self, figure) self.wpx = wpx self.hpx = hpx
signal= cplx_randn(SIGLEN) sc_half_seq= cplx_randn(SCLEN) sc_seq= np.concatenate((sc_half_seq[-CPLEN:], sc_half_seq, sc_half_seq)) start= (len(signal) - len(sc_seq)) // 2 end= start + len(sc_seq) signal[start:end]+= sc_seq for (fqname, fqoff) in (('nooff', 0), ('fqoff', 0.01)): df= np.exp(1j * np.linspace(0, fqoff * SIGLEN, len(signal))) fqadj= signal * df detection= fqadj[SCLEN:] * fqadj[:-SCLEN].conj() detection= np.convolve(detection, np.ones(SCLEN) / SCLEN, mode='valid') for (name, src) in (('abs', abs(detection)), ('arg', np.angle(detection))): fig= Figure() canvas= FigureCanvas(fig) ax= fig.add_subplot('111') sl= len(src) ax.plot( np.linspace(-sl/2, sl/2, sl), src, 'b' ) canvas.print_pdf('sc_detector_output_{}_{}.pdf'.format(fqname, name))
def plot_legend(request): import numpy img = numpy.array([[0, 1, 2, 3]]) #from pylab import axis #axis('off') from StringIO import StringIO dpi = 25 bgcol = '#ffffff' fig = Figure(figsize=(7, 1.5), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) ax = fig.add_subplot(171) ax.set_title('not used') ax.title.set_fontsize(30) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_yticks([]) ax.set_xticks([]) ax.imshow([[0]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) bx = fig.add_subplot(173) bx.set_title('train') bx.title.set_fontsize(30) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) bx.set_xticks([]) bx.imshow([[1]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) cx = fig.add_subplot(175) cx.set_title('validation') cx.title.set_fontsize(30) cx.set_yticklabels([]) cx.set_xticklabels([]) cx.set_yticks([]) cx.set_xticks([]) cx.imshow([[2]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) dx = fig.add_subplot(177) dx.set_title('test') dx.title.set_fontsize(30) dx.set_yticklabels([]) dx.set_xticklabels([]) dx.set_yticks([]) dx.set_xticks([]) dx.imshow([[3]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) #bx.set_title('legend') #bx.set_yticklabels([]) #bx.set_xticklabels([]) #bx.set_yticklabels([]) #bx.set_xticklabels(['not used','train','validation','test']) #bx.set_yticks([]) #bx.set_xticks([2,7,12,17]) #for label in bx.get_xticklabels(): # label.set_fontsize(12) #bx.imshow([[0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3]],aspect=None,interpolation='nearest',cmap=cm.Greys) canvas.draw() imdata = StringIO() fig.savefig(imdata, format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(), mimetype='image/png')
from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas import commpy as cp import numpy as np IMPRESLEN = 1000 SAMP_RATE = 100 SYMPERIOD = 1 MPDELAYS = ((90, 0.1), (90, 0.3), (90, 0.5), (90, 0.7)) imp_res_t, imp_res = cp.filters.rcosfilter(IMPRESLEN, 0.6, SYMPERIOD, SAMP_RATE) for (delay, mag) in MPDELAYS: rand = np.random.RandomState(1) fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot('111') ax.set_title('Δt={}T, a={}'.format(delay / SAMP_RATE, mag)) target = list() for i in range(64): seq = np.zeros(IMPRESLEN) seq[::SAMP_RATE] = rand.choice((-1, 1), IMPRESLEN // SAMP_RATE) full = np.convolve(seq, imp_res) start = (len(full) - 3 * SAMP_RATE) // 2 end = (len(full) + 3 * SAMP_RATE) // 2 full[:-delay] += mag * full[delay:]
def stats_helper(request, software_id, type, dpi): # matplotlib needs a writable home directory if settings.PRODUCTION: import os os.environ['HOME']='/home/mloss/tmp' import matplotlib import datetime matplotlib.use('Cairo') from matplotlib.figure import Figure from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas from matplotlib.dates import DayLocator, WeekdayLocator, HourLocator, MonthLocator, YearLocator from matplotlib.dates import DateFormatter, date2num from StringIO import StringIO if dpi<=40: bgcol='#f7f7f7' else: bgcol='#ffffff' fig = Figure(figsize=(8,6), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) stat = SoftwareStatistics.objects.filter(software=software_id).distinct().order_by('date') if stat.count()<=0: return HttpResponseForbidden() x=list() y=list() for entry in stat: x.append(date2num(entry.date)) if type=='downloads': y.append(entry.number_of_downloads) elif type=='views': y.append(entry.number_of_views) #ax.plot(x,y,'bo', alpha=0.7) #ax.plot(x,y,'b-',linewidth=1, alpha=0.5) ax.bar(x,y) days = DayLocator() weeks= WeekdayLocator() months= MonthLocator() years= YearLocator() dateFmt = DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) if len(x)<=14: ax.xaxis.set_major_locator(days) elif len(x)<60: ax.xaxis.set_major_locator(weeks) ax.xaxis.set_minor_locator(days) elif len(x)<720: ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(weeks) else: ax.xaxis.set_major_locator(years) ax.xaxis.set_minor_locator(months) if dpi>40: if type=='downloads': ax.set_title('Number of Downloads') ax.set_ylabel('Downloads per Day') elif type=='views': ax.set_title('Number of Views') ax.set_ylabel('Views per Day') ax.grid(True) ax.axis("tight") for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30) canvas.draw() imdata=StringIO() fig.savefig(imdata,format='png', dpi=dpi, facecolor=bgcol) del fig del ax return HttpResponse(imdata.getvalue(), mimetype='image/png')
def tiled_axis( ts, filename=None ): fig = Figure( ( 2.56 * 4, 2.56 * 4), 300 ) canvas = FigureCanvas(fig) #ax = fig.add_subplot(111) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols = (3, 1), axes_pad = 0.5, add_all=True, label_mode = "L", ) # pad half a day so that major ticks show up in the middle, not on the edges delta = dates.relativedelta( days=2, hours=12 ) # XXX: gets a list of days. timestamps = glucose.get_days( ts.time ) xmin, xmax = ( timestamps[ 0 ] - delta, timestamps[ -1 ] + delta ) fig.autofmt_xdate( ) def make_plot( ax, limit ): preferspan = ax.axhspan( SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor = '#003333', linewidth=1 ) def draw_glucose( ax, limit ): xmin, xmax = limit # visualize glucose using stems ax.set_xlim( [ xmin, xmax ] ) markers, stems, baselines = ax.stem( ts.time, ts.value, linefmt='b:' ) plt.setp( markers, color='red', linewidth=.5, marker='o' ) plt.setp( baselines, marker='None' ) def draw_title( ax, limit ): ax.set_title('glucose history') def get_axis( ax, limit ): xmin, xmax = limit ax.set_xlim( [ xmin, xmax ] ) ax.grid(True) #ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] ) #ax.set_xlabel('time') majorLocator = dates.DayLocator( ) majorFormatter = dates.AutoDateFormatter( majorLocator ) minorLocator = dates.HourLocator( interval=6 ) minorFormatter = dates.AutoDateFormatter( minorLocator ) #ax.xaxis.set_major_locator(majorLocator) #ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_minor_formatter(minorFormatter) labels = ax.get_xminorticklabels() plt.setp(labels, rotation=30, fontsize='small') plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium') xmin, xmax = ax.get_xlim( ) log.info( pformat( { 'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ], 'xticks': dates.num2date( ax.get_xticks( ) ), } ) ) for i, day in enumerate(timestamps): ax = grid[i] get_axis( ax, [ day, day + delta ] ) name = '%s-%d.png' % ( day.isoformat( ), i ) #fig.savefig( name ) canvas.print_figure(name) # fig.clf() #make_plot( ax, #ax.set_ylabel('glucose mm/dL') return canvas
def plot(self, res=70, show=False, dir='test', ext='0', bounds=None): ''' plot D(u,v) and diff(D,u) between min and max boundaries and save the plot to a .vtk file. It saves to path.join(dir,dir+'MCDiff'+ext+'.vtk') Open file with mayavi or paraview Resolution of 70 ''' if self.modified : self.make_diff_func() if not os.path.isdir(dir): print ("Error, plot diffusion not possible, directory does not exist") sys.exit() if not bounds: bounds = [self.umin, self.umax, self.vmin, self.vmax] #nrpoints nr = complex(0,res) #we make equal x,y,z axes for vtk plot: stepu = (bounds[1] - bounds[0] )/ (res-1) stepv = (bounds[3] - bounds[2] )/ (res-1) unew,vnew = mgrid[bounds[0]:bounds[1]:nr,bounds[2]:bounds[3]:nr] if self.difftype == 'function' : #create the arrays to hold gridfunction from GridUtils import GridFunc2D uval = list(mgrid[bounds[0]:bounds[1]:nr]) vval = list(mgrid[bounds[2]:bounds[3]:nr]) listu = [] listv = [] for i in range(0,res) : for j in range(0,res) : listu.append(uval[i]) listv.append(vval[j]) val = self.D_a(1,1, listu, listv) self.diff11_grideval = GridFunc2D([uval,vval],N.asarray(val),True) val = self.D_a(1,2, listu, listv) self.diff12_grideval = GridFunc2D([uval,vval],N.asarray(val),True) val = self.D_a(2,1, listu, listv) self.diff21_grideval = GridFunc2D([uval,vval],N.asarray(val),True) val = self.D_a(2,2, listu, listv) self.diff22_grideval = GridFunc2D([uval,vval],N.asarray(val),True) ##first way: use matplotlib import matplotlib.pyplot as pypl import matplotlib.cm as cm fig = pypl.figure() #fig.subplots_adjust(left=0.15, bottom = 0.1, top=0.95, hspace=0.8) X, Y = N.meshgrid(unew[:,0],vnew[0,:]) for pidx, func, label in [(221, self.diff11_grideval, 'D11'), (222, self.diff12_grideval, 'D12'), (223, self.diff21_grideval, 'D21'), (224, self.diff22_grideval, 'D22'), ]: ax = fig.add_subplot(pidx, aspect='equal') vals = func(unew[:,0],vnew[0,:]).transpose() implot = ax.contourf(X, Y, vals) cplot = ax.contour(X, Y, vals) fig.colorbar(implot) ax.set_title(label) ax.set_xlabel('u [mol/mm^3]') ax.set_ylabel('v [mol/mm^3]') ax.clabel(cplot) if show: pypl.show() from matplotlib.backends.backend_cairo import FigureCanvasCairo \ as FigureCanvas canvas = FigureCanvas(fig) canvas.print_figure(os.path.join(dir, 'interdiff_%s.png'%ext), format='png') # now print one fig per coefficient for pidx, func, label in [(221, self.diff11_grideval, 'D11'), (222, self.diff12_grideval, 'D12'), (223, self.diff21_grideval, 'D21'), (224, self.diff22_grideval, 'D22'), ]: fig = pypl.figure() vals = func(unew[:,0],vnew[0,:]).transpose() implot = pypl.contourf(X, Y, vals) cplot = pypl.contour(X, Y, vals) pypl.colorbar(implot) pypl.title(label) pypl.xlabel('u [mol/mm^3]') pypl.ylabel('v [mol/mm^3]') pypl.clabel(cplot) #if label == 'D22': # pypl.show() canvas = FigureCanvas(fig) canvas.print_figure(os.path.join(dir, '%s_%s.png' % (label, ext)), format='png') ##second way: gnuplot #plot with gnuplot g = Gnuplot.Gnuplot(persist=0) g.title('D11 Interdiffusion coefficient') g.xlabel('Al conc [mol/mm^3]') g.ylabel('Si conc [mol/mm^3]') g.__call__('set zlabel "D11') g.__call__('set xtics 1e-5') g.__call__('set ytics 1e-5') g.__call__('set ztics 2') g.splot(Gnuplot.GridData(self.diff11_grideval(unew[:,0],vnew[0,:]), unew[:,0],vnew[0,:],binary=False)) g.hardcopy(filename=os.path.join(dir, 'D11%s.ps'%ext), enhanced=1,mode='eps', color=0,fontname='Times-Roman',fontsize=28) g.title('D12 Interdiffusion coefficient') g.__call__('set zlabel "D12') g.splot(Gnuplot.GridData(self.diff12_grideval(unew[:,0],vnew[0,:]), unew[:,0],vnew[0,:],binary=False)) g.hardcopy(filename=os.path.join(dir, 'D12%s.ps'%ext), enhanced=1,mode='eps', color=0,fontname='Times-Roman',fontsize=28) g.title('D21 Interdiffusion coefficient') g.__call__('set zlabel "D21') g.splot(Gnuplot.GridData(self.diff21_grideval(unew[:,0],vnew[0,:]), unew[:,0],vnew[0,:],binary=False)) g.hardcopy(filename=os.path.join(dir, 'D21%s.ps'%ext), enhanced=1,mode='eps', color=0,fontname='Times-Roman',fontsize=28) g.title('D22 Interdiffusion coefficient') g.__call__('set zlabel "D22') g.splot(Gnuplot.GridData(self.diff22_grideval(unew[:,0],vnew[0,:]), unew[:,0],vnew[0,:],binary=False)) g.hardcopy(filename=os.path.join(dir, 'D22%s.ps'%ext), enhanced=1,mode='eps', color=0,fontname='Times-Roman',fontsize=28) """ znew11 = self.diff11_grideval(unew[:,0],vnew[0,:]) znew12 = self.diff12_grideval(unew[:,0],vnew[0,:]) znew21 = self.diff21_grideval(unew[:,0],vnew[0,:]) znew22 = self.diff22_grideval(unew[:,0],vnew[0,:]) # Flatten the 2D array data as per VTK's requirements. z11 = reshape(transpose(znew11), (-1,)) z12 = reshape(transpose(znew12), (-1,)) z21 = reshape(transpose(znew21), (-1,)) z22 = reshape(transpose(znew22), (-1,)) # now dump the data to a VTK file. import pyvtk s11 = pyvtk.Scalars(z11, name = '11', lookup_table = 'default') s21 = pyvtk.Scalars(z12, name = '21', lookup_table = 'default') s12 = pyvtk.Scalars(z21, name = '12', lookup_table = 'default') s22 = pyvtk.Scalars(z22, name = '22', lookup_table = 'default') #s11.default_float = 'double'; s12.default_float = 'double' #s21.default_float = 'double'; s22.default_float = 'double' point_data11 = pyvtk.PointData(s11) point_data12 = pyvtk.PointData(s12) point_data21 = pyvtk.PointData(s21) point_data22 = pyvtk.PointData(s22) #StructuredPoints: dimension of grid (nr points in x, y, z dir), # origin of made grid (we take it in 0) # spacing of grid # We do not need z axis so we obtain a 2d grid, with z component = 0 # We scale the grid to have a better picture scale = 1e6 grid = pyvtk.StructuredPoints((res,res, 1), #(self.umin*scale, self.vmin*scale, 0),\ (0.,0.,0.), (stepu*scale, stepv*scale, 10e-6)) #grid.default_float = 'double' #Data over this grid, these are scalars given in the points data11 = pyvtk.VtkData(grid, 'Interdiffusion Al-Si D11', point_data11) data12 = pyvtk.VtkData(grid, 'Interdiffusion Al-Si D12', point_data12) data21 = pyvtk.VtkData(grid, 'Interdiffusion Al-Si D21', point_data21) data22 = pyvtk.VtkData(grid, 'Interdiffusion Al-Si D22', point_data22) try: data11.tofile(os.path.join(dir, 'MCDiff11'+ext+'.vtk')) data12.tofile(os.path.join(dir, 'MCDiff12'+ext+'.vtk')) data21.tofile(os.path.join(dir, 'MCDiff21'+ext+'.vtk')) data22.tofile(os.path.join(dir, 'MCDiff22'+ext+'.vtk')) except ValueError, msg: print 'Could not write vtk files, error:', msg """ '''