def plotBfield(ax, n, conf): data = collectMesh(n, conf, getBfield) #magnitude of vectors magn = np.sqrt(data[0, :, :]**2 + data[1, :, :]**2 + data[2, :, :]**2) print("maximum B: {}".format(np.max(magn))) imshow( ax, #np.log10(magn), magn, n.getXmin(), n.getXmax(), n.getYmin(), n.getYmax(), cmap='inferno_r', vmin=magn.min(), vmax=magn.max(), clip=0.001, #vmin = -10.0, #vmax = 1.0, #clip = -10.0, ) plotQuiver(ax, data, conf)
def visualize_model(model, num_images=6): was_training = model.training model.eval() images_so_far = 0 fig = plt.figure() _, dataloaders, dataset_sizes, class_names = data_preprocess.data_loader() with torch.no_grad(): for i, (inputs, labels) in enumerate(dataloaders['val']): inputs = inputs.to(config.DEVICE) labels = labels.to(config.DEVICE) outputs = model(inputs) _, preds = torch.max(outputs, 1) for j in range(inputs.size()[0]): images_so_far += 1 ax = plt.subplot(num_images // 2, 2, images_so_far) ax.axis('off') ax.set_title('predicted: {}'.format(class_names[preds[j]])) visualize.imshow(inputs.cpu().data[j]) if images_so_far == num_images: model.train(mode=was_training) return model.train(mode=was_training)
def plotAdaptiveSlice(ax, m, args): rfl_max = args["rfl"] nx, ny, nz = m.get_size(rfl_max) #empty arrays ready xx = np.zeros((nx)) yy = np.zeros((ny)) ff = np.zeros((nx, ny)) for i in range(nx): x, y, z = m.get_center([i, 0, 0], rfl_max) xx[i] = x for j in range(ny): x, y, z = m.get_center([0, j, 0], rfl_max) yy[j] = y if args["q"] == "mid": q = nz / 2 else: q = args["q"] #adapter = pdev.Adapter(); #adapter.check(m) #cells = adapter.cells_to_refine #cells = m.get_cells(True) #for cid in cells: # rfli = m.get_refinement_level(cid) # indx = m.get_indices(cid) # i,j,k = indx # if k != q: # continue # if rfli != rfl_max: # continue # val = m[i,j,k, rfli] # ff[i,j] = val for i in range(nx): for j in range(ny): indx = [i, j, q] val = m[i, j, q, rfl_max] ff[i, j] = val imshow(ax, ff, xx[0], xx[-1], yy[0], yy[-1], vmin=0.0, vmax=0.02, cmap="plasma_r", clip=0.0) return
def plot2d(ax, val, title="", vmin=None, vmax=None, cmap="RdBu"): nx, ny = np.shape(val) xmin = 0.0 ymin = 0.0 xmax = nx ymax = ny if vmin == None: vmin, vmax = np.min(val), np.max(val) vminmax = np.maximum(np.abs(vmin), np.abs(vmax)) vmin = -vminmax vmax = vminmax elif not (vmin == None) and (vmax == None): vmax = np.max(val) print("2D: vmin: {} vmax: {} {}".format(vmin, vmax, title)) im = imshow( ax, val, xmin, xmax, ymin, ymax, cmap=cmap, vmin=vmin, vmax=vmax, ) cb = colorbar(im) ax.set_title(title) return im, cb
def plot2DSlice(ax, vmesh, args): rfl_max = args["rfl"] mesh = get_leaf_mesh(vmesh, rfl_max) #normalizrfl_max mesh.ff = mesh.ff / np.max(mesh.ff) imshow(ax, mesh.ff, mesh.xx[0], mesh.xx[-1], mesh.yy[0], mesh.yy[-1], vmin = 0.0, vmax = 1.0, cmap = "plasma_r", clip = 0.0 ) return
def plotGradientSlice(ax, m, args): rfl = args["rfl"] nx, ny, nz = m.get_size(rfl) xx, yy, zz = get_guide_grid(m, rfl) gg = np.zeros((nx, ny, 2)) #get 3D gradient cube and flatten into 2D ggg = get_gradient(m, rfl) if args["q"] == "mid": q = nz / 2 print(q) else: q = args["q"] for i in range(nx): for j in range(ny): gg[i, j, 0] = ggg[i, j, q, 0] #vx gg[i, j, 1] = ggg[i, j, q, 1] #vy X, Y = np.meshgrid(xx, yy) U = gg[:, :, 0] V = gg[:, :, 1] speed = np.zeros((nx, ny)) for i in range(nx): for j in range(ny): speed[i, j] = np.maximum(np.abs(U[i, j]), np.abs(V[i, j])) imshow(ax, speed / speed.max(), xx[0], xx[-1], yy[0], yy[-1], vmin=0.0, vmax=1.0, cmap="plasma_r", clip=0.0) lw = 5 * speed / speed.max() ax.streamplot(X, Y, U, V, density=0.9, color="k", linewidth=lw)
def plot2DSliceFlux(ax, vmesh, args): mesh = get_leaf_mesh(vmesh, args) #normalize fmax = np.max(np.abs(mesh.ff)) mesh.ff = mesh.ff / fmax imshow(ax, mesh.ff, mesh.xx[0], mesh.xx[-1], mesh.yy[0], mesh.yy[-1], vmin =-1.0, vmax = 1.0, cmap = "RdBu", clip = None ) return
def plotIndicator(ax, m, args): rfl = args["rfl"] nx, ny, nz = m.get_size(rfl) xx, yy, zz = get_guide_grid(m, rfl) gg = np.zeros((nx, ny)) #get 3D gradient cube and flatten into 2D ggg = get_indicator(m, rfl) if args["q"] == "mid": q = nz / 2 print(q) else: q = args["q"] for i in range(nx): for j in range(ny): gg[i, j] = ggg[i, j, q] X, Y = np.meshgrid(xx, yy) print("maximum of refining indicator: {}", gg.max()) gg = np.log10(gg) #gg /= gg.max() imshow( ax, gg, xx[0], xx[-1], yy[0], yy[-1], #vmin = 0.0, #vmax = 1.0, vmin=-8.0, vmax=2.0, cmap="plasma_r", #clip = 0.0 clip=-9.0)
def auto_select(self, orig): # theta = torch.zeros((n, l, 2, 3)).to(self.centorids.device) # self.model.second_stage.theta # theta[:, :, 0, 0] = self.centorids[: ,:, 0] # theta[:, :, 0, 2] = self.centorids[: ,:, 2] # theta[:, :, 1, 1] = self.centorids[: ,:, 1] # theta[:, :, 1, 2] = self.centorids[: ,:, 3] # Shape (10, 8, 2, 3) p_theta = self.model.second_stage.theta n, l, _, _ = p_theta.shape samples = [] for i in range(l): girds = F.affine_grid(theta=p_theta[:, i], size=[n, 3, 64, 64], align_corners=True) samples.append(F.grid_sample(input=orig, grid=girds)) samples = torch.stack(samples, dim=0) # Shape(8, N, 3, 64, 64) print("Selected Parts:") for i in range(l): im_show = torchvision.utils.make_grid(samples[i]) im_show = im_show.detach().cpu() imshow(im_show)
def show_centroids(self, batch, preds): # Input img Shape(N, 3, H, W) labels Shape(N,C,H,W) centroids Shape(N, C, 2) # img, labels = batch['image'], batch['labels'] orig = batch['orig'] labels = batch['labels'] # pred_arg = preds.argmax(dim=1, keepdim=False) # binary_list = [] # for i in range(preds.shape[1]): # binary = (pred_arg == i).float() # binary_list.append(binary) # preds = torch.stack(binary_list, dim=1) # pred_centroids = calc_centroid(preds) # np_label = labels.detach().cpu().numpy() pred_centroids = self.centorids * 512 true_centroids = calc_centroid(labels[:, 1:9]) # print("True:") # print(true_centroids) # print("Prdicts:") # print(pred_centroids) n = orig.shape[0] c = pred_centroids.shape[1] image_list = [] for i in range(n): image = TF.to_pil_image(orig[i]) draw = ImageDraw.Draw(image) for j in range(c): y_1 = torch.floor(true_centroids[i][j][0]).int().tolist() x_1 = torch.floor(true_centroids[i][j][1]).int().tolist() draw.point((x_1, y_1), fill=(0, 255, 0)) # for k in range(c): # y_2 = torch.floor(pred_centroids[i][k][0]).int().tolist() # x_2 = torch.floor(pred_centroids[i][k][1]).int().tolist() # draw.point((x_2, y_2), fill=(255, 0, 0)) image_list.append(TF.to_tensor(image)) out = torch.stack(image_list) out = torchvision.utils.make_grid(out) imshow(out)
def plot2DSlice(ax, m, args): #mesh = get_mesh(m, args) #mesh = get_interpolated_mesh(m, args) mesh = get_leaf_mesh(m, args) if False: imshow(ax, mesh.ff, mesh.xx[0], mesh.xx[-1], mesh.yy[0], mesh.yy[-1], vmin=0.8, vmax=1.2, cmap="RdYlBu", clip=0.0) return else: #normalize mesh.ff = mesh.ff / np.max(mesh.ff) imshow(ax, mesh.ff, mesh.xx[0], mesh.xx[-1], mesh.yy[0], mesh.yy[-1], vmin=0.0, vmax=1.0, cmap="plasma_r", clip=0.0) return
def plotXmesh(ax, n, conf, spcs, vdir): if vdir == "x": fullNvx = np.int(conf.Nvx * (2.0**conf.refinement_level)) fullNvx = fullNvx if conf.Nvx > 1 else 2*2**conf.refinement_level data = -1.0 * np.ones( (conf.Nx*conf.NxMesh, fullNvx) ) elif vdir == "y": fullNvy = np.int(conf.Nvy * (2.0**conf.refinement_level)) fullNvy = fullNvy if conf.Nvy > 1 else 2*2**conf.refinement_level data = -1.0 * np.ones( (conf.Nx*conf.NxMesh, fullNvy) ) elif vdir == "z": fullNvz = np.int(conf.Nvz * (2.0**conf.refinement_level)) fullNvz = fullNvz if conf.Nvz > 1 else 2*2**conf.refinement_level data = -1.0 * np.ones( (conf.Nx*conf.NxMesh, fullNvz) ) for i in range(conf.Nx): cid = n.id(i) c = n.get_tile(cid) block = c.get_plasma_species(0, spcs) for s in range(conf.NxMesh): vmesh = block[s,0,0] pym = get_leaf_mesh(vmesh, conf.refinement_level) if vdir == "x": sl = xSliceMid(pym) #slice from middle data[ i*conf.NxMesh + s, :] = sl dx = pym.xx[1]-pym.xx[0] vmin = pym.xx[0] -dx/2.0 vmax = pym.xx[-1]+dx/1.0 elif vdir == "y": sl = ySliceMid(pym) #slice from middle data[ i*conf.NxMesh + s, :] = sl dx = pym.yy[1]-pym.yy[0] vmin = pym.yy[0] -dx/2.0 vmax = pym.yy[-1]+dx/1.0 elif vdir == "z": sl = zSliceMid(pym) #slice from middle dx = pym.zz[1]-pym.zz[0] vmin = pym.zz[0] -dx/2.0 vmax = pym.zz[-1]+dx/1.0 data[ i*conf.NxMesh + s, :] = sl #print(np.max(data)) data = data/data.max() imshow(ax, data, n.get_xmin(), n.get_xmax(), vmin, vmax, cmap = 'plasma_r', vmin = 0.0, vmax = 1.0, clip = None, ) if vdir == "x": if spcs == 0: ax.set_ylabel(r'$v_{x,e}$') if spcs == 1: ax.set_ylabel(r'$v_{x,p}$') if vdir == "y": if spcs == 0: ax.set_ylabel(r'$v_{y,e}$') if spcs == 1: ax.set_ylabel(r'$v_{y,p}$')
arrd = arr.diagonal()[0] axs[0].plot(xd - np.sqrt(2.0) * xmid, arrd, "b:", alpha=0.6) xmin = 0 ymin = 0 xmax = conf.NxMesh ymax = conf.NyMesh im = imshow( axs[1], arr[:, :, 0], xmin, xmax, ymin, ymax, cmap='viridis', vmin=0, vmax=np.max(arr), clip=False, aspect=1, ) #-------------------------------------------------- # fft nx = conf.NxMesh // 2 freq = np.fft.fftfreq(conf.NxMesh, d=1.0) farr = np.fft.fft2(arr[:, :, 0]) #farr = np.abs(farr)*np.abs(farr) #power
def plot2d_shock_single( ax, var, info, title=None, vmin=None, vmax=None, cmap=None, clip=None, ): #-------------------------------------------------- # unpack incoming arguments that modify defaults args = {} #general defaults for key in default_values: args[key] = default_values[key] #overwrite with shock defaults try: for key in default_shock_values[var]: args[key] = default_shock_values[var][key] except: pass #finally, overwrite with user given values for key in args: try: user_val = eval(key) if not (user_val == None): args[key] = user_val print("overwriting {} key with {}".format(key, user_val)) except: pass print('--------------------------------------------------') print("reading {}".format(info['fields_file'])) f5F = h5.File(info['fields_file'], 'r') # normal singular variables if not (args['derived']): val = read_var(f5F, var) # composite quantities else: print("building composite variable") if var == "bdens": val = build_bdens(f5F) if var == "edens": val = build_edens(f5F) #-------------------------------------------------- # get shape nx, ny = np.shape(val) #print("nx={} ny={}".format(nx, ny)) walloc = 5.0 xmin = -(walloc) / info['skindepth'] ymin = 0.0 xmax = (nx - walloc) / info['skindepth'] ymax = ny / info['skindepth'] #if winsorize if not (args['winsorize_min'] == None) or not (args['winsorize_max'] == None): wvmin, wvmax = np.quantile( val, [args['winsorize_min'], 1.0 - args['winsorize_max']]) if args['vmin'] == None: args['vmin'] = wvmin if args['vmax'] == None: args['vmax'] = wvmax else: # else set vmin and vmax using normal min/max if args['vmin'] == None: args['vmin'] = np.min(val) if args['vmax'] == None: args['vmax'] = np.max(val) # make color limits symmetric if args['vsymmetric']: vminmax = np.maximum(np.abs(args['vmin']), np.abs(args['vmax'])) args['vmin'] = -vminmax args['vmax'] = vminmax # finally, re-check that user did not give vmin/vmax args['vmin'] = vmin if not (vmin == None) else args['vmin'] args['vmax'] = vmax if not (vmax == None) else args['vmax'] #nor the project default args['vmin'] = default_shock_values[var]['vmin'] if not ( vmin == None) else args['vmin'] args['vmax'] = default_shock_values[var]['vmax'] if not ( vmax == None) else args['vmax'] #-------------------------------------------------- # print all options print("--- {} ---".format(var)) for key in args: if not (key == None): print(" setting {}: {}".format(key, args[key])) #-------------------------------------------------- im = imshow( ax, val, xmin, xmax, ymin, ymax, cmap=args['cmap'], vmin=args['vmin'], vmax=args['vmax'], clip=args['clip'], aspect=args['aspect'], ) #cax, cb = colorbar(im) #-------------------------------------------------- # colorbar #ax.set_xlim((600.0, 900.0)) #ax.set_ylim((300.0, 600.0)) if do_dark: plt.subplots_adjust(left=0.10, bottom=0.05, right=0.90, top=0.97) else: ax.set_xlabel(r"$x$ $(c/\omega_p)$") ax.set_ylabel(r"$y$ $(c/\omega_p)$") plt.subplots_adjust(left=0.15, bottom=0.10, right=0.87, top=0.97) #axleft = 0.10 #axbottom = 0.06 #axright = 0.96 #axtop = 0.92 wskip = 0.0 pad = 0.01 pos = ax.get_position() #print(pos) axleft = pos.x0 axbottom = pos.y0 axright = pos.x0 + pos.width axtop = pos.y0 + pos.height print(axleft) print(axbottom) print(axright) print(axtop) #cax = plt.fig.add_axes([axleft+wskip, axtop+0.01, axright-axleft-2*wskip, 0.01]) cax = plt.fig.add_axes( [axright + pad, axbottom + wskip, 0.01, axtop - axbottom - 2 * wskip]) cb = plt.fig.colorbar(im, cax=cax, orientation='vertical', ticklocation='right') #cb.set_label(args['title']) cax.text(1.0, 1.03, args['title'], transform=cax.transAxes) #if do_dark: # for axis in ['top', 'bottom', 'left', 'right']: # cax.spines[axis].set_visible(False) # #cax.spines[axis].set_linewidth(0) # #cax.spines[axis].set_color('red') #ax.set_title(title) #plot2d_particles(ax, info, args) if do_prtcls: plot2d_particles(ax, info, args) # if plotting with particles; add a tag to name varp = var + '_p' else: varp = var slap = str(info['lap']).rjust(4, '0') if do_dark: fname = fdir + varp + '_{}.png'.format(slap) plt.savefig(fname) else: fname = fdir + varp + '_{}.pdf'.format(slap) plt.savefig(fname) cb.remove()
fig.set_size_inches(6, 10) plt.suptitle(file_iden + '\n nrn # {}'.format(nrn_num)) fig.savefig(os.path.join(\ plot_dir,'{}_nrn{}_raster'\ .format(file_iden,nrn_num))) # Firing rate for all trials fig, ax = plt.subplots(off_firing.shape[0], 1, sharex=True, sharey=True) for taste in range(off_firing.shape[0]): concat_firng_rate = np.concatenate(\ (off_firing[taste,:,nrn_num], on_firing[taste,:,nrn_num])) plt.sca(ax[taste]) visualize.imshow(concat_firng_rate) fig.set_size_inches(6, 10) plt.suptitle(file_iden + '\n nrn # {}'.format(nrn_num)) fig.savefig(os.path.join(\ plot_dir,'{}_nrn{}_all_firing'\ .format(file_iden,nrn_num))) # Firing rate fig, ax = plt.subplots(off_firing.shape[0], 1, sharex=True, sharey=True) for taste in range(off_firing.shape[0]): mean_off = np.mean(off_firing[taste, :, nrn_num], axis=0) std_off = np.std(off_firing[taste, :, nrn_num], axis=0) mean_on = np.mean(on_firing[taste, :, nrn_num], axis=0)
print("atmosphere max dens: ", np.nanmax(meshesL['data'])) norm_fac = np.nanmax(meshesL['data']) #print(norm_fac) meshesL['data'] = meshesL['data'] / norm_fac if useLog: meshesL['data'] = np.log10(meshesL['data']) imL = imshow( axs[0], meshesL['data'], xmin, xmax, meshesL['vmin'], meshesL['vmax'], cmap='plasma_r', #vmin = 0.0, #vmax = 1.0, #clip = 1.0e-5, vmin=-3.0, vmax=0, clip=None) # read right ################################################## meshesR = get_1d_meshes(prefix, lap, conf, 1, vdir) print("beam max dens:", np.nanmax(meshesR['data'])) #norm_fac = np.max(meshesR['data']) norm_fac = np.nanmax(meshesR['data']) meshesR['data'] = meshesR['data'] / norm_fac
################################################## # visualize #print(np.max(data)) data = data/data.max() xmin = 0.0 ymin = 0.0 xmax = conf.dx*conf.Nx*conf.NxMesh ymax = conf.dy*conf.Ny*conf.NyMesh imshow(axs[0], data, xmin, xmax, vmin, vmax, cmap = 'plasma_r', vmin = 0.0, vmax = 1.0, clip = 0.0, ) if vdir == "x": if ispcs == 0: axs[0].set_ylabel(r'$v_{x,e}$') if ispcs == 1: axs[0].set_ylabel(r'$v_{x,p}$') if vdir == "y": if ispcs == 0: axs[0].set_ylabel(r'$v_{y,e}$') if ispcs == 1: axs[0].set_ylabel(r'$v_{y,p}$')