def run(self): import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import matplotlib.animation as animation from matplotlib import cm cmap = cm.gray dpi = 100 repeat = 1 fps = 15 writer = animation.writers['ffmpeg'](fps=fps) fig = plt.figure() ax = plt.Axes(fig, [0, 0, 1, 1]) ax.set_axis_off() for input_ in self.input(): data = plt.imread(input_.path) m, n, _ = data.shape fig.set_size_inches((m / dpi, n / dpi)) break fig.add_axes(ax) with writer.saving(fig, self.output().path, dpi): for input_ in self.input(): data = plt.imread(input_.path) m, n, _ = data.shape ax.imshow(data, interpolation='none', cmap=cmap, vmin=low, vmax=high) for _ in range(repeat): writer.grab_frame()
def make_image(data, outputname, size=(1, 1), dpi=100): fig = plt.figure() fig.set_size_inches(size) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.set_cmap('gray') ax.imshow(data, aspect='equal', interpolation='nearest') plt.savefig(outputname, dpi=dpi) plt.close()
def plot_imshow(self, output_file): """ Plot data to output_file using imshow. Note: This can produce a file with extra colors due to a bug in imshow. """ # Create an image that has one data point per pixel. fig = plt.figure(frameon=False) fig.set_size_inches(len(self.lons), len(self.lats)) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) extent = (0, 1, 0, 1) if self.cmap is None: ax.imshow(self.data, interpolation='none', aspect='auto', origin='lower', extent=extent, ) else: ax.imshow(self.data, interpolation='none', cmap=self.cmap, norm=self.norm, aspect='auto', origin='lower', extent=extent, ) (fd, intermediate) = tempfile.mkstemp(suffix=".png", prefix="map", dir=tempfile.gettempdir()) os.close(fd) os.chmod( intermediate, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP) fig.savefig(intermediate, dpi=1, transparent=True) if (self.isScaled): # Use imagemagick's convert to make this image the right size. NOTE: # When I tried creating a figure of the correct size and using # 'nearest' interpolation, the image was incorrect. cmd = ["convert", "-sample", "%dx%d!" % (self.width, self.height), intermediate, output_file] subprocess.check_call(cmd) os.remove(intermediate) else: # Just move the file over. No need to run convert because the image # is already the correct size. shutil.move(intermediate, output_file)
def mt_plot(): """ Return a moment tensor image. """ formats = {"png": "image/png", "svg": "image/svg+xml"} args = flask.request.args m_rr = float(args["m_rr"]) m_tt = float(args["m_tt"]) m_pp = float(args["m_pp"]) m_rt = float(args["m_rt"]) m_rp = float(args["m_rp"]) m_tp = float(args["m_tp"]) focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) # Allow hexcolors. color = args.get("color", "red") try: hexcolor = "#" + color hex2color(hexcolor) color = hexcolor except ValueError: pass size = int(args.get("size", 32)) lw = float(args.get("lw", 1)) format = args.get("format", "png") if format not in formats.keys(): flask.abort(500) dpi = 100 fig = plt.figure(figsize=(float(size) / float(dpi), float(size) / float(dpi)), dpi=dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) bb = beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color) ax.add_collection(bb) ax.set_xlim(-105, 105) ax.set_ylim(-105, 105) temp = io.BytesIO() plt.savefig(temp, format=format, dpi=dpi, transparent=True) plt.close(fig) plt.close("all") temp.seek(0, 0) return flask.send_file(temp, mimetype=formats[format], add_etags=False, attachment_filename="mt.%s" % format)
def contour(self, output_file): """ Plot data to filled contour in output_file. """ fig = plt.figure(frameon=False) fig.set_size_inches(self.width, self.height) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) extent = (0, 1, 0, 1) # draw the regular map underneath to fill in the pixels at the edges if self.cmap is None: ax.contourf(self.data) else: # create a masked array where everything is masked mask = np.empty(self.data.shape, bool) mask.fill(True) allFill = np.ma.MaskedArray(data=np.zeros(self.data.shape), mask=mask) # plot this first, under the real data, so we get the fill value # color ax.imshow(allFill, cmap=self.cmap, norm=self.norm, aspect='auto', origin='lower', extent=extent) # set the levels to the thresholds. Add in -infinite at the bottom # and +infinite at the top so we get the gutters levels = list( itertools.chain.from_iterable([[float('-inf')], self.thresholds, [float('inf')]])) ax.contourf( self.data, cmap=self.cmap, norm=self.norm, levels=levels, aspect='auto', origin='lower', extent=extent ) fig.savefig(output_file, dpi=1, transparent=True) self._convert_to_colormapped_png(output_file)
def merging_page(): ''' not working if full country is actual region ''' try: s = session session_cou = open(s['cou_path'], 'rb') COU = cPickle.load(session_cou) session_cou.close() COU.load_data(quiet=True, filename_filter=s['indicator'], load_mask=False, load_raw=True, load_area_averages=False, load_region_polygons=False) empty_object = COU.selection( [s['indicator'], s['dataset'], 'ensemble_mean'])[0] asp = (float(len(empty_object.lon)) / float(len(empty_object.lat)))**0.5 regions_plot = 'app/static/COU_images/' + s['country'] + '/' + s[ 'region'] + '.png' if os.path.isfile(regions_plot) == False: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) fig.set_size_inches(6 * asp, 6 / asp) fig.add_axes(ax) # fig,ax=plt.subplots(nrows=1,ncols=1,figsize=(6*asp,6/asp+1)) empty_object.plot_map(to_plot='empty', show_region_names=True, color_bar=False, ax=ax, show_all_adm_polygons=True) #title=COU._region_names[s['region']]) if s['region'] != s['country']: print COU._adm_polygons[s['region']] patch = PolygonPatch(COU._adm_polygons[s['region']], facecolor='orange', edgecolor=[0, 0, 0], alpha=0.7, zorder=2) ax.add_patch(patch) ax.set_axis_off() plt.savefig(regions_plot, dpi=300) choosable_regions = [ reg for reg in s['region_avail'][:] if reg != s['country'] and len(reg.split('+')) < 2 ] form_region = forms.regionForm(request.form) form_region.regions.choices = zip(choosable_regions, [ COU._region_names[reg].replace('_', ' ') for reg in choosable_regions ]) form_NewRegion = forms.NewRegionForm(request.form) form_NewRegion = forms.NewRegionForm( request.form, region_name=session['new_region_name']) half_lon_step = abs(np.diff(empty_object.lon.copy(), 1)[0] / 2) half_lat_step = abs(np.diff(empty_object.lat.copy(), 1)[0] / 2) xmin, xmax = min(empty_object.lon) - half_lon_step, max( empty_object.lon) + half_lon_step ymin, ymax = min(empty_object.lat) - half_lat_step, max( empty_object.lat) + half_lat_step x_w = 500 * asp y_h = 500 / asp clickable = [] for region in choosable_regions: poly = COU._adm_polygons[region] if poly.geom_type == 'MultiPolygon': area = [] for subpoly in poly: area.append(subpoly.area) x, y = poly[area.index(max(area))].simplify(0.1).exterior.xy elif poly.geom_type == 'Polygon': x, y = poly.simplify(0.1).exterior.xy point_list = '' for xx, yy in zip(x, y): point_list += str((xx - xmin) / (xmax - xmin) * x_w) + ', ' point_list += str(y_h - (yy - ymin) / (ymax - ymin) * y_h) + ', ' clickable.append({'poly': point_list[:-2], 'name': region}) context = { 'form_region': form_region, 'form_NewRegion': form_NewRegion, 'regions_plot': regions_plot.replace('app/', ''), 'small_region_warning': s['small_region_warning'], 'language': get_language_tag(), 'regions': clickable, 'x_width': x_w, 'y_height': y_h, } context.update(clickable) context.update(text_dict[s['language']]) context.update(button_dict[s['language']]) session['location'] = 'merging_page' return render_template('merging_page_' + s['language'] + '.html', **context) except Exception, e: print str(e) return render_template('error.html')
Tmax = 50000 dim = 120 delta = .3 ut = A + delta * np.random.rand(dim, dim) vt = B / A + delta * np.random.rand(dim, dim) ims = np.empty(Tmax + 1, dtype=np.object) # FFMpegWriter = animation.writers['ffmpeg'] # writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800) fig = plt.figure(figsize=(8, 8)) sizes = ut.shape fig.set_size_inches(1. * sizes[0] / sizes[1], 1, forward=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ims[0] = [plt.imshow(ut, animated=True, cmap="jet")] for t in range(Tmax): u, v = ut, vt ut = dt * (Du * laplace(input=u, mode='wrap') + f(u, v, A, B)) + u vt = dt * (Dv * laplace(input=v, mode='wrap') + g(u, v, A, B)) + v ims[t + 1] = [plt.imshow(ut, animated=True, cmap="jet")] movie = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=100) # movie.save('diffusion.mp4', writer=writer)
def grid_evaluate(self, fi, plane, d, grid_size, n_grid_pts, boundP, boundU, ylimit, savename=None): """ Evaluates and plots the SPL in symmetrical grid for a mesh centered at [0,0,0]. Inputs: fi = frequency index of array f_range plane = string containg axis to plot. eg: 'xy' d = Posistion of free axis (in relation to center) grid_size = Size of dimension to plot n_grid_pts = number of grid points boundP = output from bemsolve() boundU = output from bemsolve() """ pT = {} k = 2 * np.pi * self.f_range[fi] / self.c0 ymin = ylimit[0] ymax = ylimit[1] if plane == 'xy': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundData[fi][1] + dlp_pot * boundData[fi][0]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet', vmin=ymin, vmax=ymax) plt.savefig('plane_xy.png', dpi=500) plt.show() return grid_pT if plane == 'xy_c': n_grid_points = n_grid_pts plot_grid = np.mgrid[grid_size[0]:0:n_grid_points * 1j, grid_size[1]:0:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet', vmin=ymin, vmax=ymax) plt.colorbar() plt.savefig('colorbar.png', dpi=500) plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet', vmin=ymin, vmax=ymax) plt.savefig('plane_xy.png', dpi=500) plt.show() return grid_pT if plane == 'yx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[1].ravel(), plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[1], 0, grid_size[0]), cmap='jet') plt.colorbar() plt.show() return grid_pT if plane == 'xz_c': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, grid_size[1]:0:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(-grid_size[0] / 2, grid_size[0] / 2, 0, grid_size[1]), cmap='jet') plt.colorbar() plt.savefig('colorbar.png', dpi=500) plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet', vmin=ymin, vmax=ymax) plt.savefig('plane_xz.png', dpi=500) plt.show() return grid_pT if plane == 'xz': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.savefig('%s.png' % ax, dpi=500) plt.show() return grid_pT if plane == 'zx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[1].ravel(), d + np.zeros(plot_grid[1].size), plot_grid[0].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet', vmin=ymin, vmax=ymax) plt.savefig('%s.png' % savename, dpi=500) plt.show() return grid_pT if plane == 'yz': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[0].size), plot_grid[0].ravel(), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.savefig('%s.png' % ax, dpi=500) plt.show() return grid_pT if plane == 'yz_c': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, grid_size[1]:0:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[0].size), plot_grid[0].ravel(), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(-grid_size[0] / 2, grid_size[0] / 2, 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet', extent=(-grid_size[0] / 2, grid_size[0] / 2, 0, grid_size[1]), vmin=ymin, vmax=ymax) plt.savefig('plane_yz.png', dpi=500) plt.show() return grid_pT if plane == 'zx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[1].size), plot_grid[1].ravel(), plot_grid[0].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[1], 0, grid_size[0]), cmap='jet') plt.colorbar() plt.show() return grid_pT """ Evaluates and plots the SPL in symmetrical grid for a mesh centered at [0,0,0]. Inputs: fi = frequency index of array f_range plane = string containg axis to plot. eg: 'xy' d = Posistion of free axis (in relation to center) grid_size = Size of dimension to plot n_grid_pts = number of grid points boundP = output from bemsolve() boundU = output from bemsolve() """ pT = {} pTI = {} pTS = {} k = 2 * np.pi * self.f_range[fi] / self.c0 bempp.api.set_default_device(1, 0) print('\nSelected device:', bempp.api.default_device().name) if plane == 'z': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel(), d + np.zeros(plot_grid[0].size))) if plane == 'y': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size), plot_grid[1].ravel())) if plane == 'x': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[0].size), plot_grid[0].ravel(), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) pScat = -slp_pot.evaluate(boundP[fi]) pInc = self.planewave(fi, grid_pts.T) grid_pT = (pScat + pInc) grid_pTI = (np.real(pInc)) grid_pTS = (np.abs(pScat)) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) pTI[fi] = grid_pTI.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pTI[fi].T) / 2e-5), cmap='jet') plt.colorbar() plt.title('Incident Pressure Field') plt.show() pTS[fi] = grid_pTS.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pTS[fi].T) / 2e-5), cmap='jet') plt.colorbar() plt.title('Scattered Pressure Field') plt.show() plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet') plt.colorbar() plt.title('Total Pressure Field') plt.show() return pT[fi]
def grid_evaluate(self, fi, plane, d, grid_size, n_grid_pts, boundP, boundU, savename=None): """ Evaluates and plots the SPL in symmetrical grid for a mesh centered at [0,0,0]. Inputs: fi = frequency index of array f_range plane = string containg axis to plot. eg: 'xy' d = Posistion of free axis (in relation to center) grid_size = Size of dimension to plot n_grid_pts = number of grid points boundP = output from bemsolve() boundU = output from bemsolve() """ pT = {} k = 2 * np.pi * self.f_range[fi] / self.c0 if plane == 'xy': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.savefig('colorbar.png', dpi=500) plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet', extent=(0, grid_size[0], 0, grid_size[1])) plt.colorbar() plt.savefig('plane_xy.png', dpi=500) plt.show() return grid_pT return grid_pT if plane == 'xy_c': n_grid_points = n_grid_pts plot_grid = np.mgrid[grid_size[0]:0:n_grid_points * 1j, grid_size[1]:0:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] + dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pScat + pInc) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) if savename == None: plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.savefig('colorbar.png', dpi=500) plt.show() else: fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), cmap='jet') plt.savefig('plane_xy.png', dpi=500) plt.show() return grid_pT if plane == 'yx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack((plot_grid[1].ravel(), plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size))) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[1], 0, grid_size[0]), cmap='jet') plt.colorbar() plt.show() return grid_pT if plane == 'xz': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[0].ravel(), d + np.zeros(plot_grid[0].size), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() return grid_pT if plane == 'zx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack( (plot_grid[1].ravel(), d + np.zeros(plot_grid[1].size), plot_grid[0].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[1], 0, grid_size[0]), cmap='jet') plt.colorbar() plt.show() return grid_pT if plane == 'yz': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j, -grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[0].size), plot_grid[0].ravel(), plot_grid[1].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[0], 0, grid_size[1]), cmap='jet') plt.colorbar() plt.show() return grid_pT if plane == 'zx': n_grid_points = n_grid_pts plot_grid = np.mgrid[-grid_size[1] / 2:grid_size[1] / 2:n_grid_points * 1j, -grid_size[0] / 2:grid_size[0] / 2:n_grid_points * 1j] grid_pts = np.vstack((d + np.zeros(plot_grid[1].size), plot_grid[1].ravel(), plot_grid[0].ravel())) slp_pot = bempp.api.operators.potential.helmholtz.single_layer( self.space, grid_pts, k) dlp_pot = bempp.api.operators.potential.helmholtz.double_layer( self.space, grid_pts, k) pScat = (slp_pot * boundU[fi] - dlp_pot * boundP[fi]) pInc = self.monopole(fi, grid_pts.T) grid_pT = np.conj(pInc + pScat) pT[fi] = grid_pT.reshape((n_grid_points, n_grid_points)) plt.imshow(20 * np.log10(np.abs(pT[fi].T) / 2e-5), extent=(0, grid_size[1], 0, grid_size[0]), cmap='jet') plt.colorbar() plt.show() return grid_pT
data = data[:, :, 1] # spot-detection spots = spot_detection(data, min_sigma=2.0, max_sigma=4.0, num_sigma=20, threshold=10, overlap=0.5) # show figures dpi = 100 fig = plt.figure() m, n = data.shape fig.set_size_inches((m / dpi, n / dpi)) ax = plt.Axes(fig, [0, 0, 1, 1]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(data, interpolation='none', cmap='gray') for spot in spots: (height, center_x, center_y, width_x, width_y, bg) = spot radius = max(width_x, width_y) c = plt.Circle((center_x, center_y), radius, color='red', linewidth=1, fill=False) ax.add_patch(c)
import scipy import numpy import scipy.io.wavfile as wav import matplotlib.pylab as pylab import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file') parser.add_argument('-d', '--dest') args = parser.parse_args() filepath = args.file destination_filename = args.dest fs, audio = wav.read(filepath) print(audio.shape) X = stft.spectrogram(audio, framelength=4096, transform=[scipy.fftpack.fft, numpy.fft.fft]) print(X.shape) fig = pylab.figure() ax = pylab.Axes(fig, [0, 0, 1, 1]) ax.set_axis_off() fig.add_axes(ax) pylab.imshow(scipy.absolute(X[:][:]), origin='lower', aspect='auto', interpolation='nearest') pylab.savefig(destination_filename)
def train(**kwargs): """ Train model Load the whole train data in memory for faster operations args: **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters batch_size = kwargs["batch_size"] n_batch_per_epoch = kwargs["n_batch_per_epoch"] nb_epoch = kwargs["nb_epoch"] generator = kwargs["generator"] model_name = kwargs["model_name"] image_dim_ordering = kwargs["image_dim_ordering"] img_dim = kwargs["img_dim"] bn_mode = kwargs["bn_mode"] label_smoothing = kwargs["label_smoothing"] label_flipping = kwargs["label_flipping"] noise_scale = kwargs["noise_scale"] dset = kwargs["dset"] use_mbd = kwargs["use_mbd"] epoch_size = n_batch_per_epoch * batch_size # Setup environment (logging directory etc) general_utils.setup_logging(model_name) # Load and rescale data # if dset == "celebA": # X_real_train = data_utils.load_celebA(img_dim, image_dim_ordering) # if dset == "mnist": # X_real_train, _, _, _ = data_utils.load_mnist(image_dim_ordering) # img_dim = X_real_train.shape[-3:] img_dim = (3, 64, 64) noise_dim = (100, ) try: # Create optimizers opt_dcgan = Adam(lr=1E-3, beta_1=0.5, beta_2=0.999, epsilon=1e-08) opt_discriminator = SGD(lr=1E-3, momentum=0.9, nesterov=True) # Load generator model generator_model = models.load("generator_%s" % generator, noise_dim, img_dim, bn_mode, batch_size, dset=dset, use_mbd=use_mbd) # Load discriminator model discriminator_model = models.load("DCGAN_discriminator", noise_dim, img_dim, bn_mode, batch_size, dset=dset, use_mbd=use_mbd) #load the weights here for e in range(200, 355, 5): gen_weights_path = os.path.join( '../../CNN/gen_weights_epoch%s.h5' % (e)) # gen_weight_file = h5py.File(gen_weights_path, 'r') file_path_to_save_img = 'GeneratedImages1234/Epoch_%s/' % (e) os.mkdir(file_path_to_save_img) # generate images generator_model.load_weights(gen_weights_path) generator_model.compile(loss='mse', optimizer=opt_discriminator) noise_z = np.random.normal(scale=0.5, size=(32, noise_dim[0])) X_generated = generator_model.predict(noise_z) # print('Epoch%s.png' % (i)) X_gen = inverse_normalization(X_generated) for img in range(X_gen.shape[0]): ret = X_gen[img].transpose(1, 2, 0) fig = plt.figure(frameon=False) fig.set_size_inches(64, 64) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(ret, aspect='normal') fig.savefig(file_path_to_save_img + 'retina_%s.png' % (img), dpi=1) plt.clf() plt.close() # Xg = X_gen[:8] # Xr = X_gen[8:] # # if image_dim_ordering == "tf": # X = np.concatenate((Xg, Xr), axis=0) # list_rows = [] # for i in range(int(X.shape[0] / 4)): # Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1) # list_rows.append(Xr) # # Xr = np.concatenate(list_rows, axis=0) # # if image_dim_ordering == "th": # X = np.concatenate((Xg, Xr), axis=0) # list_rows = [] # for i in range(int(X.shape[0] / 4)): # Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2) # list_rows.append(Xr) # # Xr = np.concatenate(list_rows, axis=1) # Xr = Xr.transpose(1,2,0) # # if Xr.shape[-1] == 1: # plt.imshow(Xr[:, :, 0], cmap="gray") # else: # plt.imshow(Xr) # plt.savefig(file_path_to_save_img+'Epoch%s.png' % (e)) # plt.clf() # plt.close() # generator_model.load_weights('gen_weights_epoch245.h5') # generator_model.compile(loss='mse', optimizer=opt_discriminator) # discriminator_model.trainable = False # # DCGAN_model = models.DCGAN(generator_model, # discriminator_model, # noise_dim, # img_dim) # # loss = ['binary_crossentropy'] # loss_weights = [1] # DCGAN_model.compile(loss=loss, loss_weights=loss_weights, optimizer=opt_dcgan) # # discriminator_model.trainable = True # discriminator_model.compile(loss='binary_crossentropy', optimizer=opt_discriminator) # noise_z = np.random.normal(scale=0.5, size=(32, noise_dim[0])) # X_generated = generator_model.predict(noise_z) # # X_gen = inverse_normalization(X_generated) # # Xg = X_gen[:8] # Xr = X_gen[8:] # # if image_dim_ordering == "tf": # X = np.concatenate((Xg, Xr), axis=0) # list_rows = [] # for i in range(int(X.shape[0] / 4)): # Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1) # list_rows.append(Xr) # # Xr = np.concatenate(list_rows, axis=0) # # if image_dim_ordering == "th": # X = np.concatenate((Xg, Xr), axis=0) # list_rows = [] # for i in range(int(X.shape[0] / 4)): # Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2) # list_rows.append(Xr) # # Xr = np.concatenate(list_rows, axis=1) # Xr = Xr.transpose(1,2,0) # # if Xr.shape[-1] == 1: # plt.imshow(Xr[:, :, 0], cmap="gray") # else: # plt.imshow(Xr) # plt.savefig("current_batch.png") # plt.clf() # plt.close() # gen_loss = 100 # disc_loss = 100 # # # Start training # print("Start training") # k = 0 # for e in range(nb_epoch): # # Initialize progbar and batch counter # progbar = generic_utils.Progbar(epoch_size) # batch_counter = 1 # start = time.time() # # for X_real_batch in data_utils.gen_batch(X_real_train, batch_size): # # # Create a batch to feed the discriminator model # X_disc, y_disc = data_utils.get_disc_batch(X_real_batch, # generator_model, # batch_counter, # batch_size, # noise_dim, # noise_scale=noise_scale, # label_smoothing=label_smoothing, # label_flipping=label_flipping) # # # Update the discriminator # disc_loss = discriminator_model.train_on_batch(X_disc, y_disc) # # # Create a batch to feed the generator model # X_gen, y_gen = data_utils.get_gen_batch(batch_size, noise_dim, noise_scale=noise_scale) # # # Freeze the discriminator # discriminator_model.trainable = False # gen_loss = DCGAN_model.train_on_batch(X_gen, y_gen) # # Unfreeze the discriminator # discriminator_model.trainable = True # # batch_counter += 1 # progbar.add(batch_size, values=[("D logloss", disc_loss), # ("G logloss", gen_loss)]) # # # Save images for visualization # if batch_counter % 100 == 0: # data_utils.plot_generated_batch(X_real_batch, generator_model, # batch_size, noise_dim, image_dim_ordering,k) # k = k +1 # if batch_counter >= n_batch_per_epoch: # break # # print("") # print('Epoch %s/%s, Time: %s' % (e + 1, nb_epoch, time.time() - start)) # # if e % 5 == 0: # gen_weights_path = os.path.join('../../models/%s/gen_weights_epoch%s.h5' % (model_name, e)) # generator_model.save_weights(gen_weights_path, overwrite=True) # # disc_weights_path = os.path.join('../../models/%s/disc_weights_epoch%s.h5' % (model_name, e)) # discriminator_model.save_weights(disc_weights_path, overwrite=True) # # DCGAN_weights_path = os.path.join('../../models/%s/DCGAN_weights_epoch%s.h5' % (model_name, e)) # DCGAN_model.save_weights(DCGAN_weights_path, overwrite=True) except KeyboardInterrupt: pass