def get_dataset_color(dataset,depth=None): """Set the colors to ensure a uniform scheme for each dataset """ dataset=string.lower(dataset) d={} d["dai"]=cm.Blues(.5) d["tree"]=cm.summer(.3) d["cru"]=cm.Blues(.9) #models d["picontrol"]=cm.Purples(.8) d["h85"]="k" d["tree_noise"]=cm.PiYG(.2) #Soil moisture d["merra2"]={} d["merra2"]["30cm"]=cm.copper(.3) d["merra2"]["2m"]=cm.copper(.3) d["gleam"]={} d["gleam"]["30cm"]=cm.Reds(.3) d["gleam"]["2m"]=cm.Reds(.7) if depth is None: return d[dataset] else: return d[dataset][depth]
def four_Vm_traces(data, ax, tzoom=[1000, 2000], Tbar=50, Vshift=30, vpeak=-42, vbottom=-80): t = np.arange(int(data['tstop'] / data['dt'])) * data['dt'] cond = (t > tzoom[0]) & (t < tzoom[1]) ## excitatory traces: for i in range(3): ax.plot(t[cond], data['VMS_RecExc'][i][cond] + Vshift * i, color=copper(i / 3 / 1.5), lw=1) # adding spikes for i in range(3): tspikes = data['tRASTER_RecExc'][np.argwhere( data['iRASTER_RecExc'] == i).flatten()] for ts in tspikes[(tspikes > tzoom[0]) & (tspikes < tzoom[1])]: ax.plot([ts, ts], Vshift * i + np.array([-50, vpeak]), '--', color=copper(i / 3 / 1.5), lw=1) # ## inhibitory trace: cond = (t > tzoom[0]) & (t < tzoom[1]) ax.plot(t[cond], data['VMS_RecInh'][0][cond] + Vshift * 3, color=Red, lw=1) tspikes = data['tRASTER_RecInh'][np.argwhere( data['iRASTER_RecInh'] == 0).flatten()] for ts in tspikes[(tspikes > tzoom[0]) & (tspikes < tzoom[1])]: ax.plot([ts, ts], Vshift * 3 + np.array([-53, vpeak]), '--', color=Red, lw=1) ax.plot(tzoom[0] * np.ones(2), [-50, -40], lw=5, color='gray') ax.annotate('10mV', (-0.1, .4), rotation=90, fontsize=14, xycoords='axes fraction') ax.plot([tzoom[0], tzoom[0] + Tbar], [-75, -75], lw=5, color='gray') ax.annotate(str(Tbar) + ' ms', (0.1, -0.1), fontsize=14, xycoords='axes fraction') set_plot(ax, [], xticks=[], yticks=[])
def plot_profiles(): fnames = [ "chgl_10_00000001000.tsv", "chgl_10_00000005000.tsv", "chgl_10_00000010000.tsv", "chgl_10_00000030000.tsv", "chgl_10_00000040000.tsv", "chgl_10_00000050000.tsv" ] times = list(range(len(fnames))) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) folder = "data/almgsi_ch500K_run3" folder = "data/almgsi_ch500K_run_truncnorm" times = np.array(times, dtype=np.float64) times -= np.min(times) times /= np.max(times) times = times.tolist() for t, fname in zip(times, fnames): full_fname = folder + "/" + fname freq, prof = fft(full_fname) print(np.mean(prof)) ax.plot(freq, prof / np.sum(prof), drawstyle='steps', color=cm.copper(t)) ax.set_yscale('log') ax.set_xlabel("Frequency (nm \${-1}\$)") ax.set_ylabel("Occurence probability") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.show()
def setup_figure(): fig=plt.figure(1) plt.clf() ax = fig.add_subplot(1,1,1) ax.set_xlim([-rho-1,rho+1]) ax.set_ylim([-rho-1,rho+1]) ax.set_aspect('equal') cells=[] springs=[] borders=[] for i in range(0,N): c = plt.Circle((-0,0),0.5,color=cm.copper(0)) cells.append(ax.add_artist(c)) if plot_springs: for i in range(0,len(pairs)): springs += ax.plot([], [], color=cm.spectral(0)) if plot_voronoi: for i in range(0, pairs2.shape[0]): borders += ax.plot([], [], color='k') ang_mom = ax.add_patch(FancyArrowPatch((0,0),(1,1),ec='r', fc='r', zorder=0, arrowstyle=u'simple,head_width=20, head_length=10')) return(fig,cells,springs,borders,ang_mom)
def first(): filename = "scatter.txt" file = open(filename, "r") tmp = [] x = [] y = [] for line in file: tmp.append(line) for word in tmp[0].split(): x.append(float(word)) for word in tmp[1].split(): y.append(float(word)) file.close plt.axes(polar=True) data = [] for num in y: data.append((num+5)*20) clr = cm.copper(data) plt.scatter(x, y, 10, y) plt.show()
def get_colors(self, qty): qty = np.power(qty / qty.max(), 1.0 / CONTRAST) if COLORMAP == 0: rgba = cm.gray(qty, alpha=ALPHA) elif COLORMAP == 1: rgba = cm.afmhot(qty, alpha=ALPHA) elif COLORMAP == 2: rgba = cm.hot(qty, alpha=ALPHA) elif COLORMAP == 3: rgba = cm.gist_heat(qty, alpha=ALPHA) elif COLORMAP == 4: rgba = cm.copper(qty, alpha=ALPHA) elif COLORMAP == 5: rgba = cm.gnuplot2(qty, alpha=ALPHA) elif COLORMAP == 6: rgba = cm.gnuplot(qty, alpha=ALPHA) elif COLORMAP == 7: rgba = cm.gist_stern(qty, alpha=ALPHA) elif COLORMAP == 8: rgba = cm.gist_earth(qty, alpha=ALPHA) elif COLORMAP == 9: rgba = cm.spectral(qty, alpha=ALPHA) return rgba
def distributions(self, number_of_agents, row_agents, col_agents, row_strategies, col_strategies,plot): self.row_strategies_distribution = self.proportion_classified_strategies(row_agents, row_strategies) for rs in range(len(row_strategies)): self.row_accumulated_strategies[rs].append(self.row_strategies_distribution[rs]) self.col_strategies_distribution = self.proportion_classified_strategies(col_agents, col_strategies) for cs in range(len(col_strategies)): self.col_accumulated_strategies[cs].append(self.col_strategies_distribution[cs]) self.total_strategies_per_generation = self.total_classified_strategies(row_agents, row_strategies, col_agents, col_strategies) for sh in range(len(self.strategies_history)): self.strategies_history[sh].append(self.total_strategies_per_generation[sh]) print "\n Row players' strategy distribution:" print "\t", self.row_strategies_distribution print "\n Column players' strategy distribution:" print "\t", self.col_strategies_distribution ga.kill_agents(env.row_agents, env.number_of_agents, env.number_of_row_agents, env.row_strategies) ga.kill_agents(env.col_agents, env.number_of_agents, env.number_of_col_agents, env.col_strategies) print "Row agents eliminated", (number_of_agents / 2) - len(env.col_agents) print "Col agents eliminated", (number_of_agents / 2) - len(env.row_agents) ga.reproduce_agents(env.row_agents, env.number_of_agents, env.number_of_row_agents, env.row_strategies) ga.reproduce_agents(env.col_agents, env.number_of_agents, env.number_of_col_agents, env.col_strategies) if plot==True: for k in range(len(env.row_strategies)): c = cm.copper((k + 1) / len(env.row_strategies)) pl.plot(self.row_accumulated_strategies[k], color=c, label="Row strategies: %s" % (k + 1)) for k in range(len(env.col_strategies)): c = cm.winter((k + 1) / len(env.row_strategies)) pl.plot(self.col_accumulated_strategies[k], color=c, label="Col strategies: %s" % (k + 1)) pl.draw()
def plt_bw(ground_truth, predicted, loss, rows, ymax=None): """Plot windows and color encode by loss""" if ymax is None: ymax = np.max(ground_truth[rows]) lossmax = np.max(loss[rows]) bg = "#ffffff" n = rows.size plt.figure(figsize=(20, n * 2)) for i, k in enumerate(rows): # display original ax = plt.subplot(n * 2, 1, i * 2 + 1) ax.set_facecolor("#888888") plt.bar(np.arange(ground_truth[k].size), ground_truth[k], color=bg) plt.ylim(0, ymax) ax.get_xaxis().set_visible(False) c = rgba_to_hex(copper((lossmax - loss[k]) / lossmax)) # display reconstruction ax = plt.subplot(n * 2, 1, i * 2 + 2) ax.set_facecolor(c) plt.bar(np.arange(predicted[k].size), predicted[k], color=bg) plt.ylim(0, ymax) ax.get_xaxis().set_visible(False) plt.show()
def plot_global_reion_runs(zs, data): # Take data (e.g. from get_global_reion_runs) and plot. nzeta = zs.shape[0] ntvir = zs.shape[1] nmfp = zs.shape[2] plt.figure('Global runs') plt.clf() plt.subplot(131) colors = iter(cm.copper(np.linspace(0, 1, nzeta))) for i in xrange(nzeta): plt.plot(zs[i, ntvir / 2, nmfp / 2, :], data[i, ntvir / 2, nmfp / 2, :], color=next(colors)) plt.subplot(132) colors = iter(cm.copper(np.linspace(0, 1, ntvir))) for i in xrange(ntvir): plt.plot(zs[nzeta / 2, i, nmfp / 2, :], data[nzeta / 2, i, nmfp / 2, :], color=next(colors)) plt.subplot(133) colors = iter(cm.copper(np.linspace(0, 1, nmfp))) for i in xrange(nmfp): plt.plot(zs[nzeta / 2, ntvir / 2, i, :], data[nzeta / 2, ntvir / 2, i, :], color=next(colors))
def animate_system(positions: pd.DataFrame, steps: int = 10, size: int = 100) -> int: """ Creates an interactive plot to visualize the positions of the moons at each step """ velocities = pd.DataFrame({ 'x': [0] * len(positions), 'y': [0] * len(positions), 'z': [0] * len(positions) }) # Create empty plot fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111, projection='3d') x, y, z = [], [], [] colors = cm.copper(4) sc = ax.scatter(x, y, z, s=size) # Compute all positions step_pos = [] for i in range(steps): # Apply gravity velocities = update_velocity(positions, velocities) # Apply velocity positions = positions + velocities step_pos.append(positions) # Set plot limits allx = [i for sl in [list(p['x']) for p in step_pos] for i in sl] ally = [i for sl in [list(p['y']) for p in step_pos] for i in sl] allz = [i for sl in [list(p['z']) for p in step_pos] for i in sl] ax.set_xlim3d(min(allx), max(allx)) ax.set_ylim3d(min(ally), max(ally)) ax.set_zlim3d(min(allz), max(allz)) # Animation def animate(i): pos = step_pos[i] sc._offsets3d = (pos['x'].values, pos['y'].values, pos['z'].values) ani = matplotlib.animation.FuncAnimation(fig, animate, frames=steps, interval=200, repeat=False) return ani
def get_colors(color_c=3, color_step=100): cmap_colors = np.vstack(( cm.Oranges(np.linspace(0.4, 1, color_step)), cm.Reds(np.linspace(0.4, 1, color_step)), cm.Greys(np.linspace(0.4, 1, color_step)), cm.Purples(np.linspace(0.4, 1, color_step)), cm.Blues(np.linspace(0.4, 1, color_step)), cm.Greens(np.linspace(0.4, 1, color_step)), cm.pink(np.linspace(0.4, 1, color_step)), cm.copper(np.linspace(0.4, 1, color_step)), )) return cmap_colors[np.arange(color_c * color_step) % (color_step * 8)]
def soilmoisture_fingerprints(mask, name=None, fortalk=False): Fingerprints = {} depths = ["pdsi", "30cm", "2m"] if fortalk: letters = ["", "", ""] else: letters = ["(a): ", "(b): ", "(c): "] pcs = [] pclabels = [] for depth in depths: i = depths.index(depth) if fortalk: plt.figure() else: plt.subplot(2, 2, i + 1) sm = soilmoisture(depth, mask=mask) solver = Eof(MV.average(sm, axis=0), weights='area') Fingerprints[depth] = solver fac = da.get_orientation(solver) if name is None: m = b.landplot(fac * solver.eofs()[0], vmin=-.1, vmax=.1) plt.colorbar(orientation='horizontal', label='EOF loading') else: m = b.plot_regional(fac * solver.eofs()[0], name, vmin=-.1, vmax=.1) m.drawcountries() m.drawcoastlines(color='gray') if depth is not "pdsi": plt.title(letters[i] + depth + " fingerprint") else: plt.title(letters[i] + " PDSI fingerprint") pcs += [fac * solver.pcs()[:, 0]] if fortalk: plt.figure() else: plt.subplot(2, 2, 4) for i in range(3): if depths[i] == "pdsi": label = "PDSI" else: label = depths[i] time_plot(pcs[i], label=label, lw=3, color=cm.copper(i / 2.)) plt.legend(loc=0) plt.title("(d): Principal Components") plt.xlabel("Time") plt.ylabel("Temporal amplitude") plt.xlim(1900, 2100) return Fingerprints
def analyze_scan(Model, smooth=10, filename=None): F_aff, seeds, Model, DATA = get_scan(Model, filename=filename) fig1, ax1 = plt.subplots(1, figsize=(4, 2.5)) plt.subplots_adjust(left=.3, bottom=.4) fig2, ax2 = plt.subplots(1, figsize=(4, 2.5)) plt.subplots_adjust(left=.3, bottom=.4) for i in range(len(F_aff)): TRACES = [] for j in range(len(seeds)): data = DATA[i * len(seeds) + j] # TRACES.append(data['POP_ACT_RecExc']) TRACES.append( gaussian_smoothing(data['POP_ACT_RecExc'], int(smooth / data['dt']))) mean = np.array(TRACES).mean(axis=0) std = np.array(TRACES).std(axis=0) # smoothing cond = data['t'] > 350 ax1.plot(data['t'][cond], mean[cond], color=cm.copper(i / len(F_aff)), lw=2) ax1.fill_between(data['t'][cond], mean[cond] - std[cond], mean[cond] + std[cond], color=cm.copper(i / len(F_aff)), alpha=.5) ax2.plot(data['t'][cond], data['faff'][cond], color=cm.copper(i / len(F_aff))) set_plot(ax1, xlabel='time (ms)', ylabel='rate (Hz)') set_plot(ax2, xlabel='time (ms)', ylabel='rate (Hz)') # put_list_of_figs_to_svg_fig([fig1, fig2]) return fig1, fig2
def animate(f): global pairs, pairs2 # load data F=F_vs_t[f] r=r_vs_t[f] n=n_vs_t[f] p=(rho+0.9)*p_angular[f]/np.sqrt(np.sum(p_angular[f]**2)) ang_mom.set_positions((0, 0), (p[x_plane], p[y_plane])) if update_nn: pairs = simforces.get_all_pairs(getDelaunayTrianglesOnSphere(r)+1) for i in range(0,N): #j=indsort[i] c=int((r[z_plane,i]+1)/2*256) cells[i].center=(r[x_plane,i],r[y_plane,i]) cells[i].set_facecolor(cm.copper(c)) cells[i].set_zorder(r[z_plane,i]) if plot_springs: for i in range(0,len(pairs)): i1 = pairs[i,0] - 1 i2 = pairs[i,1] - 1 if (r[z_plane,i1] > 0) and (r[z_plane,i2] > 0): dist = np.sqrt(np.sum((r[:,i1]- r[:,i2])**2)) c=int((dist-1)*128) springs[i].set_data([r[x_plane,i1], r[x_plane,i2]], [r[y_plane,i1], r[y_plane,i2]]) springs[i].set_color(cm.spectral(c)) else: springs[i].set_data([], []) if plot_voronoi: list_, baricenters, out_polygon_dict, pairs2, all_areas = getVoronoiOnSphere(r) b = rho*baricenters for i in range(0,len(pairs2)): i1 = pairs2[i,0] i2 = pairs2[i,1] if (b[z_plane,i1] > 0) and (b[z_plane,i2] > 0): borders[i].set_data([b[x_plane,i1], b[x_plane,i2]], [b[y_plane,i1], b[y_plane,i2]]) else: borders[i].set_data([], []) if f == 20: fig.savefig('test.png') return (cells,springs,borders,ang_mom)
def run(self, plot=False, stack=False): if plot==True: pl.ion() pl.ylim(0, 1) pl.xlabel("Generations") pl.ylabel("Probability") for k in range(len(env.row_strategies)): c = cm.copper((k + 1) / len(env.row_strategies)) pl.plot(self.row_accumulated_strategies[k], color=c, label="Row strategies: %s" % (k + 1)) for k in range(len(env.col_strategies)): c = cm.winter((k + 1) / len(env.row_strategies)) pl.plot(self.col_accumulated_strategies[k], color=c, label="Col strategies: %s" % (k + 1)) #pl.legend(bbox_to_anchor=(0.7, 0.85), loc=2, prop={'size':7}) pl.legend(loc=2, prop={'size':7}) pl.draw() self.generations_passing(ga.generations, ga.rounds_per_generation, env.number_of_agents, env.row_agents, env.col_agents, plot, stack)
def not_used05(): jet = cm.get_cmap( 'jet' ) # <matplotlib.colors.LinearSegmentedColormap object at 0x000002D606451E80> print(jet(0)) print(jet(127)) print(jet(255)) print(jet(2550)) print('-' * 50) # 색상을 표현하는 다양한 방법 print(jet([0, 255])) print(jet(range(0, 5, 2))) print(jet(np.linspace(0.3, 0.7, 5))) print('-' * 50) print(cm.jet(0)) print(cm.copper(0))
L = 32 datamaker0 = fs.SuperRegistration(np.zeros((2, L, L)), deg=deg) datamaker0.shifts = np.array([3 * np.random.randn(2)]) shifts = datamaker0.shifts fdata = datamaker0.model fdata /= fdata.std() data = fdata + 0.05 * np.random.randn(*fdata.shape) reg = SuperRegistration(data, 16) #print(reg.fit(iprint=2, delta=1E-4)) evd, bias = [], [] fig, ax = plt.subplots(1, 2, sharex=True) order = list(range(10, 25)) nlist = list(range(2, 9, 2)) # [2] colors = copper(Normalize()(nlist)) shifts = np.random.randn(max(nlist) - 1, 2) datalist = [] biases = [] evidences = [] # This sequence plots the evidence as a function of complexity as a # function of the number of images for n, c in zip(nlist, colors): dm = fs.SuperRegistration(np.zeros((n, L, L)), deg) dm.coef = datamaker0.coef dm.shifts = shifts[:n - 1] data = dm.model / dm.model.std() data += 0.05 * np.random.randn(*data.shape)
def get_stability_condition(plot_results=True): current_factors = [0.6, 0.7, 0.8, 0.9, 1.0] colors = cm.copper(np.linspace(0.0, 1.0, len(current_factors))) # Get profiles dat = np.loadtxt(os.path.join('input_profiles.dat')) # Modify and plot input profiles r = dat[:, 0] R = dat[:, 1] j_phi = dat[:, 2] B_z = dat[:, 3] B_theta = dat[:, 4] psi_n = dat[:, 5] r_to_psin = interpolate.interp1d(r, psi_n) psin_to_r = interpolate.interp1d(r, psi_n) q = r * B_z / (R * B_theta) q[0] = q[1] if plot_results: fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True) ax[0, 0].plot(r, B_z, c='k') ax[0, 0].set_ylabel('$B_{\phi}$ [T]', fontsize=fontsize) ax[1, 0].plot(r, B_theta, c='k') ax[1, 0].set_ylabel('$B_{\\theta}$ [T]', fontsize=fontsize) for i, factor in enumerate(current_factors[::-1]): linestyle = '--' if i > 0 else '-' ax[0, 1].plot(r, factor * j_phi * 1e-3, linestyle=linestyle, c=colors[i]) ax[0, 1].set_ylabel('$j_{\phi}$ [kA]', fontsize=fontsize) ax[1, 1].plot(r, q, c='k') ax[1, 1].set_ylabel('q', fontsize=fontsize) ax[1, 1].set_xlabel('r [m]', fontsize=fontsize) ax[1, 0].set_xlabel('r [m]', fontsize=fontsize) ax[0, 0].set_xlim([0.0, 1.0]) fig.tight_layout() plt.savefig('input_profiles') plt.show() plt.figure() for epsilon in [1e-12, 1e-8, 1e-6, 1e-4]: r_max = r[-1] deltas = list() alphas = list() for factor in current_factors: j_phi_sim = j_phi * factor solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi_sim, q, num_pts, delta=epsilon) solver.find_delta(plot_output=False) deltas.append(solver.delta) alphas.append(1 - factor) plt.plot(alphas, deltas, label="$\epsilon$={}".format(epsilon)) np.savetxt('deltas_{}.dat'.format(epsilon), np.stack((alphas, deltas), axis=-1)) plt.grid(linestyle='--') plt.ylabel('$\Delta\'$', fontsize=fontsize) plt.xlabel('$\\alpha$', fontsize=fontsize) plt.legend() plt.xlim([0.0, 1.0]) plt.savefig('current_stability_{}'.format(m)) plt.show()
def main(): args = parse_args() q_mean, p_mean, Q, P, W = prepare_data(args) no_steps = Q.shape[0] q_min = Q[:, 0, 0].min() q_max = Q[:, 0, -1].max() p_min = P[:, 0, 0].min() p_max = P[:, -1, 0].max() if args.vmin[-1] == "%": W_min = numpy.percentile(W[:], float(args.vmin[:-1])) else: W_min = float(args.vmin) if args.vmax[-1] == "%": W_max = numpy.percentile(W[:], 100. - float(args.vmax[:-1])) else: W_max = float(args.vmax) midpoint = 1 - W_max / (W_max + abs(W_min)) cmap = shifted_color_map(cm.coolwarm, midpoint=midpoint, name="shifted") fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(q_min, q_max) ax.set_ylim(p_min, p_max) ax.set_xlabel("q") ax.set_ylabel("p") if args.visualization == "polished": shading = "gouraud" else: shading = "flat" quad = QuadContainer( ax.pcolormesh(Q[0], P[0], W[0], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.set_aspect("equal") if args.track: ax.set_color_cycle( [cm.copper(1. * i / (no_steps - 1)) for i in range(no_steps - 1)]) for i in range(no_steps - 1): ax.plot(q_mean[i:i + 2], p_mean[i:i + 2], alpha=.3) cb = fig.colorbar(quad.quad) cb.set_label("Quasiprobability Density") cb.solids.set_rasterized(True) if args.visualization == "polished": ax.set_axis_bgcolor(cb.to_rgba(0.)) no_digits = int(ceil(log10(no_steps)) + 1) title_string = "Wigner Function at step {:{width}}/{:{width}}" title = ax.set_title(title_string.format(0, no_steps, width=no_digits)) ax.grid(True) if args.output: fig.savefig(args.output + "_thumb.pdf") def animate(i): title.set_text(title_string.format(i, no_steps, width=no_digits)) quad.update_quad( ax.pcolormesh(Q[i], P[i], W[i], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.grid(True) return quad.quad, ani = FuncAnimation(fig, animate, no_steps, interval=100, repeat_delay=1000) if args.output: print("Saving movie to {}. This may take a couple of minutes.".format( args.output)) ani.save(args.output + ".mp4", fps=10, extra_args=['-vcodec', 'libx264']) pyplot.show()
def get_stability_condition(plot_results=True): current_factors = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65, 0.675, 0.6875, 0.7, 0.8, 0.9, 1.0] colors = cm.copper(np.linspace(0.0, 1.0, len(current_factors))) # Get profiles dat = np.loadtxt(os.path.join('input_profiles.dat')) # Modify and plot input profiles r = dat[:, 0] R = dat[:, 1] j_phi = dat[:, 2] B_z = dat[:, 3] B_theta = dat[:, 4] psi_n = dat[:, 5] r_to_psin = interpolate.interp1d(r, psi_n) psin_to_r = interpolate.interp1d(r, psi_n) q = r * B_z / (R * B_theta) q[0] = q[1] if plot_results: fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True) ax[0, 0].plot(r, B_z, c='k') ax[0, 0].set_ylabel('$B_{\phi}$ [T]', fontsize=fontsize) ax[1, 0].plot(r, B_theta, c='k') ax[1, 0].set_ylabel('$B_{\\theta}$ [T]', fontsize=fontsize) for i, factor in enumerate(current_factors[::-1]): linestyle = '--' if i > 0 else '-' ax[0, 1].plot(r, factor * j_phi * 1e-3, linestyle=linestyle, c=colors[i]) ax[0, 1].set_ylabel('$j_{\phi}$ [kA]', fontsize=fontsize) ax[1, 1].plot(r, q, c='k') ax[1, 1].set_ylabel('q', fontsize=fontsize) ax[1, 1].set_xlabel('r [m]', fontsize=fontsize) ax[1, 0].set_xlabel('r [m]', fontsize=fontsize) ax[0, 0].set_xlim([0.0, 1.0]) fig.tight_layout() plt.savefig('input_profiles') plt.show() r_max = r[-1] deltas = list() gammas = list() alphas = list() if os.path.exists(data_output): alphas = 1 - np.asarray(current_factors) deltas = np.loadtxt(data_output) gammas = np.loadtxt(gamma_output) else: for factor in current_factors: j_phi_sim = j_phi * factor solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi_sim, q, num_pts, delta=1e-12) solver.find_delta(plot_output=False) solver.get_gamma() # Transform to psi_norm for comparison with JOREK psin_lower = r_to_psin(solver.r_lower) psin_upper = r_to_psin(solver.r_upper) if plot_results: fig, ax = plt.subplots(2, sharex=True) ax[0].plot(psin_lower, solver.psi_sol_lower[:, 0], label='solution from axis') ax[0].plot(psin_upper, solver.psi_sol_upper[:, 0], label='solution from boundary') # Plot comparison solution if it exists validation_file = 'flux_validation_vc_{}.csv'.format(factor) if os.path.exists(validation_file): flux_validation = np.loadtxt(validation_file, delimiter=',') flux_validation[:, 1] /= np.max(flux_validation[:, 1]) flux_validation[:, 1] *= np.max(solver.psi_sol_lower[:, 0]) ax[0].plot(flux_validation[:, 0], flux_validation[:, 1], linestyle='--', label='JOREK') ax[0].set_ylabel('$\Psi_1$', fontsize=fontsize) ax[0].legend() ax[0].set_xlim([0.0, 1.0]) ax[1].plot(psin_lower, solver.psi_sol_lower[:, 1]) ax[1].plot(psin_upper, solver.psi_sol_upper[:, 1]) ax[1].set_ylabel('$\\frac{\partial \Psi_1}{\partial r}$', fontsize=fontsize) ax[1].set_xlabel('$\hat \Psi$', fontsize=fontsize) plt.show() deltas.append(solver.delta) gammas.append(solver.gamma) alphas.append(1 - factor) np.savetxt(data_output, np.asarray(deltas)) np.savetxt(gamma_output, np.asarray(gammas)) alphas = np.asarray(alphas) deltas = np.asarray(deltas) gammas = np.asarray(gammas) # Plot gammas gammas_jor = np.asarray([0.000112257, 7.25606e-5, 3.87257e-5, 2.29265e-5, 1.50064e-5, 6.86054e-6, 2.586e-6]) gammas_jor /= 6.4836e-7 alphas_jor = [0.0, 0.1, 0.2, 0.25, 0.275, 0.3, 0.3125] eta = 1e-7 * 1.9382 rho = 1e20 * 2 * 1.673 * 1e-27 gammas *= eta ** 0.6 / rho ** 0.2 fig, ax = plt.subplots(1) ax.plot(alphas, gammas, label='Linear $\Delta\'$') ax.scatter(alphas, gammas) ax.plot(alphas_jor, gammas_jor, label='JOREK $\Delta\'$') ax.scatter(alphas_jor, gammas_jor) plt.savefig('current_stability_gammas_{}'.format(m)) ax.set_ylabel('$\gamma\ [s^{-1}]$', fontsize=fontsize) ax.set_xlabel('$\\alpha$', fontsize=fontsize) plt.show() alphas_jor_8 = [0.0, 0.1, 0.2, 0.3] gammas_8 = np.asarray([41.701, 25.616, 12.98966, 2.5974]) gammas_9 = np.asarray([6.809, 4.0393, 1.99651, 0.46058]) # Plot deltas solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi, q, num_pts, delta=1e-12) deltas_jor = gammas_jor / 0.55 / (eta / PhysicalConstants.mu_0) ** 0.6 deltas_jor /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho)) ** 0.4 deltas_jor /= (solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability))) ** 0.4 deltas_jor = deltas_jor ** (5.0 / 4.0) deltas_jor_8 = gammas_8 / 0.55 / (eta * 0.1 / PhysicalConstants.mu_0) ** 0.6 deltas_jor_8 /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho)) ** 0.4 deltas_jor_8 /= (solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability))) ** 0.4 deltas_jor_8 = deltas_jor_8 ** (5.0 / 4.0) deltas_jor_9 = gammas_9 / 0.55 / (eta * 0.01 / PhysicalConstants.mu_0) ** 0.6 deltas_jor_9 /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho)) ** 0.4 deltas_jor_9 /= (solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability))) ** 0.4 deltas_jor_9 = deltas_jor_9 ** (5.0 / 4.0) scaling = 1.05 fig, ax = plt.subplots(1) ax.plot(alphas, deltas, label='Linear $\Delta\'$') ax.scatter(alphas, deltas) ax.plot(alphas_jor, deltas_jor, label='JOREK $\Delta\'$') ax.scatter(alphas_jor, deltas_jor) ax.plot(alphas_jor_8, deltas_jor_8, label='JOREK $\Delta\' for $\eta=10^{-8}$') ax.scatter(alphas_jor_8, deltas_jor_8) ax.plot(alphas_jor_8, deltas_jor_9, label='JOREK $\Delta\'$ for $\eta=10^{-9}$') ax.scatter(alphas_jor_8, deltas_jor_9) ax.axhline(0.0, c='k', linestyle='--') ax.axvline(0.346, linestyle='--', color='grey', label='Linear stability boundary') ax.axvline(0.3125, linestyle='--', color='g', label='JOREK stability boundary') ax.axvline(0.325, linestyle='--', color='g') ax.fill_betweenx(scaling * deltas, 0.3125, 0.325, facecolor='green', alpha=0.2) ax.set_ylabel('$\Delta\'$', fontsize=fontsize) ax.set_xlabel('$\\alpha$', fontsize=fontsize) ax.set_xlim([0.0, 1.0]) ax.set_ylim([scaling * min(deltas), scaling * max(deltas)]) ax.grid(linestyle='--') ax.legend() plt.savefig('current_stability_deltas_{}'.format(m)) plt.show()
"params_dam_nilc.yml", "params_dam_wfixed.yml", "params_dam_tinker10.yml", # "params_wnarrow_ns.yml", # "params_masked.yml" ] sci = [r"$\mathrm{2MPZ}$"] + \ [r"$\mathrm{WI \times SC}$ - $\mathrm{%d}$" % i for i in range(1, 6)] lbls = [ "Fiducial", "NILC", "Fixed $w_z$", "Tinker 2010", r"$\langle N_s \rangle$ independent" "tSZ-masked" ] colours = ["k", "grey", "r", "brown", "orange"] col = [copper(i) for i in np.linspace(0, 1, len(sci))] fmts = ["o", "o", "v", "s", "*", "d"] p = ParamRun(param_yml[0]) #temp = [chan(paryml, diff=True, error_type="hpercentile", chains=False, b_hydro=0.5*np.ones([1,6])) # for paryml in param_yml] #pars = [t[0] for t in temp] #data = np.array([[p["b_hydro"] for p in par] for par in pars]) #data = [d.T for d in data] print("HI") BF = [chan(fname).get_best_fit("b_hydro") for fname in param_yml] print("Best fits OK") widths = chan(param_yml[0]).get_best_fit("width") widths = np.hstack((widths["width"][:, 0])) dz, dN = [[] for i in range(2)]
def excess(temps): ref_energies = {"Al": -3.73667187, "Mg": -1.59090625} if (temps == "all"): db = connect(mc_db_name) all_temps = [] for row in db.select(converged=1): if (row.temperature not in all_temps): all_temps.append(row.temperature) temps = all_temps res = get_free_energies() try: for key, value in res.iteritems(): F = np.array(value["free_energy"]) plt_set = False for i in range(1, len(F)): if (F[i] < F[i - 1]): print(value["temperature"][i]) plt_set = True F -= F[0] if (plt_set): print(key) plt.plot(value["temperature"], F) plt.show() for key, value in res.iteritems(): E = np.array(value["internal_energy"]) E -= E[0] plt.plot(value["temperature"], E) plt.show() except Exception as exc: print(str(exc)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) markers = ["o", "x", "^", "v", "d"] colors = [ '#b2182b', '#ef8a62', '#fddbc7', '#f7f7f7', '#d1e5f0', '#67a9cf', '#2166ac' ] fig_entropy = plt.figure() ax_entropy = fig_entropy.add_subplot(1, 1, 1) fig_mg_weighted = plt.figure() ax_mg_weighted = fig_mg_weighted.add_subplot(1, 1, 1) fig_F = plt.figure() ax_F = fig_F.add_subplot(1, 1, 1) Tmin = np.min(temps) Tmax = np.max(temps) print("Min temp: {}, Max temp: {}".format(Tmin, Tmax)) all_excess = [] all_concs = [] all_temps = [] for count, T in enumerate(temps): excess = [] concs = [] entropy = [] free_eng = [] temperature = None for key, entry in res.iteritems(): if ("Mg" in entry["conc"].keys()): mg_conc = entry["conc"]["Mg"] else: mg_conc = 0.0 concs.append(mg_conc) diff = np.abs(entry["temperature"] - T) indx = np.argmin(diff) if (diff[indx] > 1.0): print( "Warning! Difference {}. Temperature might not be simulated!" .format(diff[indx])) excess.append(entry["internal_energy"][indx] - ref_energies["Al"] * entry["conc"]["Al"] - ref_energies["Mg"] * entry["conc"]["Mg"]) free_eng.append(entry["free_energy"][indx] - ref_energies["Al"] * entry["conc"]["Al"] - ref_energies["Mg"] * entry["conc"]["Mg"]) if (temperature is None): temperature = entry["temperature"][indx] #excess[-1] += entry["TS"][indx] entropy.append(entry["entropy"][indx]) #excess.append( entry["free_energy"][indx]+entry["TS"][indx] ) #excess.append( entry["free_energy"][indx] ) concs += [0.0, 1.0] excess += [0.0, 0.0] entropy += [0.0, 0.0] free_eng += [0.0, 0.0] srt_indx = np.argsort(concs) concs = [concs[indx] for indx in srt_indx] excess = np.array([excess[indx] for indx in srt_indx]) entropy = np.array([entropy[indx] for indx in srt_indx]) free_eng = np.array([free_eng[indx] for indx in srt_indx]) all_excess.append(excess) all_concs.append(concs) mapped_temp = float(temperature - Tmin) / (Tmax - Tmin) print(mapped_temp) all_temps.append(temperature) ax.plot(concs, excess * mol / kJ, marker=markers[count % len(markers)], label="{}K".format(temperature), mfc="none", color=cm.copper(mapped_temp), lw=2) ax_entropy.plot(concs, 1000.0 * entropy * mol / kJ, marker=markers[count % len(markers)], label="{}K".format(temperature), color=cm.copper(mapped_temp), lw=2, mfc="none") ax_F.plot(concs, free_eng * mol / kJ, marker=markers[count % len(markers)], label="{}K".format(temperature), mfc="none", color=cm.copper(mapped_temp), lw=2) ax_mg_weighted.plot(concs, (excess / concs) * mol / kJ, marker=markers[count % len(markers)], color=cm.copper(mapped_temp), lw=2, mfc="none") ax.legend(frameon=False) ax.set_xlabel("Mg concentration") ax.set_ylabel("Enthalpy of formation (kJ/mol)") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax_entropy.set_xlabel("Mg concentration") ax_entropy.set_ylabel("Entropy (J/K mol)") ax_entropy.spines["right"].set_visible(False) ax_entropy.spines["top"].set_visible(False) fig_info = plt.figure() Z = [[0, 0], [0, 0]] #temp_info = [np.min(T),np.max(T)] ax_info = fig_info.add_subplot(1, 1, 1) temp_info = np.linspace(np.min(temps), np.max(temps), 256) Cb_info = ax_info.contourf(Z, temp_info, cmap="copper") cbar = fig.colorbar(Cb_info, orientation="horizontal", ticks=[100, 300, 500, 700]) cbar.ax.xaxis.set_ticks_position("top") cbar.ax.set_xticklabels([100, 300, 500, 700]) cbar.ax.xaxis.set_label_position("top") #cbar.ax.tick_params(axis='x',direction='in',labeltop='on') cbar.set_label("Temperature (K)") cbar2 = fig_entropy.colorbar(Cb_info, orientation="horizontal", ticks=[100, 300, 500, 700]) cbar2.ax.xaxis.set_ticks_position("top") cbar2.ax.set_xticklabels([100, 300, 500, 700]) cbar2.ax.xaxis.set_label_position("top") cbar2.set_label("Temperature (K)") all_maxima, all_minima = find_extremal_points(all_concs, all_excess, show_plot=False) ax_F.set_ylabel("Free Energy of Formation (kJ/mol)") all_data = [] for temp, maxima, minima in zip(all_temps, all_maxima, all_minima): all_data.append({ "temperature": temp, "maxima": maxima, "minima": minima }) with open("data/extremal_points.json", 'w') as outfile: json.dump(all_data, outfile, indent=2, separators=(",", ":")) plt.show()
hist_dat.append([apc.loc['resp'].drop('v4', level='layer_label').loc[layer] for layer in layers_to_examine] + [apc.loc['resp'].loc['v4'],]) #hist_dat.append([apc.loc['resp'].drop('v4', level='layer_label').loc[layer] # for layer in layers_to_examine]) hist_dat_leg.append({'title':'CN resp', 'labels':layers_to_examine, 'fontsize':'xx-small' , 'frameon':True, 'loc':4,'markerscale':100}) for leg in hist_dat_leg: leg['fontsize'] = fs leg['labelspacing'] = 0 for i, ax_ind in enumerate(hist_pos): ax = ax_list[ax_ind] if not (ax_ind==hist_pos[-1]): colors = ['g','r','b','m','c', 'k', '0.5'] else: colors = cm.copper(np.linspace(0,1,len(hist_dat[i]))) colors[-1] = [1, 0, 0, 0] for apc_vals, color in zip(hist_dat[i], colors): x = apc_vals.dropna().values y_c, bins_c = d_hist(ax, np.sqrt(x), cumulative=True, color=color, alpha=0.75, lw=2) bins_c = np.concatenate([apc_vals.dropna().values for apc_vals in hist_dat[i]]).ravel() beautify(ax, spines_to_remove=['top','right']) ax.set_xticks([0,0.5,1]) ax.set_xticklabels([0,0.5,1], fontsize=10) ax.spines['left'].set_bounds(0,1) ax.set_xlim(0,1) ax.set_yticks([0, 0.5, 1]) ax.set_yticklabels([0, 0.5, 1], fontsize=10) ax.set_ylim(0,1.1) if not (ax_ind==hist_pos[-1]):
from PIL import Image import numpy as np from matplotlib import pyplot as plt from matplotlib import cm im = Image.open('../data/grenouille.jpg') rouge, vert, bleu = im.split() z = np.array(rouge) z = np.uint8(cm.copper(z) * 255) im2 = Image.fromarray(z) im2.save("grenouille_saved.jpg")
import matplotlib.pyplot as plt from matplotlib import cm with open('bars.txt') as f: lines = f.readlines() x = [float(i) for i in lines[0].split()] y = [float(i) for i in lines[1].split()] color = cm.copper(y) fig = plt.figure() ax = fig.add_subplot(111) rects = ax.bar(x, y, color=color) for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.005 * height, '%.2f' % float(height), ha='center', va='bottom') plt.show()
def main(): T = np.array([ 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 800, 700, 600, 500, 400, 375, 350, 325, 300, 275, 250, 225, 200, 175, 150 ]) mg_concs = [] enthalpies = [] free_energy = [] ref_energies = {"Al": -3.73667187, "Mg": -1.59090625} temps = [] concs = [] filenames = glob.glob("data/mfa217/*") ignore_indx = [] for i, filename in enumerate(filenames): with open(filename, 'r') as infile: data = json.load(infile) mg_concs.append(data["conc"]["Mg"]) concs.append(data["conc"]) print(data["conc"], filename) enthalpies.append( np.array(data["internal_energy"]) / data["natoms"] - ref_energies["Mg"] * data["conc"]["Mg"] - ref_energies["Al"] * data["conc"]["Al"]) free_energy.append( np.array(data["free_energy"]) / data["natoms"] - ref_energies["Mg"] * data["conc"]["Mg"] - ref_energies["Al"] * data["conc"]["Al"]) try: temps.append(data["temperature"]) except Exception as exc: ignore_indx.append(i) print("Error occured in {}. Message: {}".format( filename, str(exc))) if (save_free_eng): res = {} i = 0 for indx in range(len(filenames)): if (indx in ignore_indx): continue res[filenames[i]] = {} res[filenames[i]]["conc"] = concs[i] res[filenames[i]]["free_energy"] = free_energy[i].tolist() res[filenames[i]]["temperature"] = temps[i] i += 1 with open(free_eng_file, 'w') as outfile: json.dump(res, outfile, indent=2, separators=(",", ":")) print("Free energies written to {}".format(free_eng_file)) figH = plt.figure() axH = figH.add_subplot(1, 1, 1) figF = plt.figure() axF = figF.add_subplot(1, 1, 1) figS = plt.figure() axS = figS.add_subplot(1, 1, 1) Tmax = 800 Tmin = 150 print(len(temps[0])) print(len(enthalpies[0])) for i in range(len(enthalpies[0])): try: T = temps[0][i] if (T > Tmax): continue srt_indx = np.argsort(mg_concs) H = [enthalpies[j][i] for j in range(len(enthalpies))] F = [free_energy[j][i] for j in range(len(free_energy))] srt_mg = [mg_concs[indx] for indx in srt_indx] H = np.array([H[indx] for indx in srt_indx]) F = np.array([F[indx] for indx in srt_indx]) mapped_T = float(T - Tmin) / (Tmax - Tmin) S = (H - F) / T axH.plot(srt_mg, H * mol / kJ, marker="x", color=cm.copper(mapped_T)) axF.plot(srt_mg, F * mol / kJ, marker="o", color=cm.copper(mapped_T)) axS.plot(srt_mg, 1E6 * S * mol / kJ, marker="o", color=cm.copper(mapped_T)) except Exception as exc: print(str(exc)) axH.set_xlabel("Mg concentration") axH.set_ylabel("Enthalpy of Formation (kJ/mol)") axF.set_xlabel("Mg concentration") axF.set_ylabel("Free Energy of Formation (kJ/mol)") axS.set_xlabel("Mg concentration") axS.set_ylabel("Entropy (mJ/K mol)") axH.spines["right"].set_visible(False) axH.spines["top"].set_visible(False) axF.spines["right"].set_visible(False) axF.spines["top"].set_visible(False) axS.spines["right"].set_visible(False) axS.spines["top"].set_visible(False) plt.show()
if pltcolor: plt.figure(1) plt.plot(t, en, label=runname) plt.figure(2) plt.plot(t, hdiss + hdissz, label=runname) plt.figure(3) plt.plot(t, enz, label=runname) plt.figure(4) plt.plot(t, diss + dissz, label=runname) else: plt.figure(1) plt.plot(t, en, label=r"$\Omega = %.3f$" % omegas[runname], color=cm.copper(cscale(omegas[runname], omegas))) plt.figure(2) plt.plot(t, hdiss + hdissz, label=r"$\Omega = %.3f$" % omegas[runname], color=cm.copper(cscale(omegas[runname], omegas))) plt.figure(3) plt.plot(t, enz, label=r"$\Omega = %.3f$" % omegas[runname], color=cm.copper(cscale(omegas[runname], omegas))) plt.figure(4) plt.plot(t,
def get_stability_condition(plot_results=True): current_factors = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65, 0.675, 0.6875, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 ] colors = cm.copper(np.linspace(0.0, 1.0, len(current_factors))) # Get profiles dat = np.loadtxt(os.path.join('input_profiles.dat')) # Modify and plot input profiles r = dat[:, 0] R = dat[:, 1] j_phi = dat[:, 2] B_z = dat[:, 3] B_theta = dat[:, 4] psi_n = dat[:, 5] r_to_psin = interpolate.interp1d(r, psi_n) psin_to_r = interpolate.interp1d(r, psi_n) q = r * B_z / (R * B_theta) q[0] = q[1] if plot_results: fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True) ax[0, 0].plot(r, B_z, c='k') ax[0, 0].set_ylabel('$B_{\phi}$ [T]', fontsize=fontsize) ax[1, 0].plot(r, B_theta, c='k') ax[1, 0].set_ylabel('$B_{\\theta}$ [T]', fontsize=fontsize) for i, factor in enumerate(current_factors[::-1]): linestyle = '--' if i > 0 else '-' ax[0, 1].plot(r, factor * j_phi * 1e-3, linestyle=linestyle, c=colors[i]) ax[0, 1].set_ylabel('$j_{p}$ [kA]', fontsize=fontsize) ax[1, 1].plot(r, q, c='k') ax[1, 1].set_ylabel('q', fontsize=fontsize) ax[1, 1].set_xlabel('r [m]', fontsize=fontsize) ax[1, 0].set_xlabel('r [m]', fontsize=fontsize) ax[0, 0].set_xlim([0.0, 1.0]) fig.tight_layout() plt.savefig('input_profiles') plt.show() r_max = r[-1] deltas = list() gammas = list() alphas = list() current = np.zeros((len(current_factors), 3)) if os.path.exists(data_output): alphas = 1 - np.asarray(current_factors) deltas = np.loadtxt(data_output) gammas = np.loadtxt(gamma_output) for i, factor in enumerate(current_factors): j_phi_sim = j_phi * (1 - factor) solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi_sim, q, num_pts, delta=1e-12) current[i, 0] = factor current[i, 1] = solver.r_to_j_phi(solver.r_instability) current[i, 2] = solver.r_to_j_phi_deriv(solver.r_instability) np.savetxt('instability_currents.dat', current, header='Alpha\t\tJ [A]\t\tdJ_dr [A/m]') else: for factor in current_factors: j_phi_sim = j_phi * factor solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi_sim, q, num_pts, delta=1e-12) solver.find_delta(plot_output=False) solver.get_gamma() # Transform to psi_norm for comparison with JOREK psin_lower = r_to_psin(solver.r_lower) psin_upper = r_to_psin(solver.r_upper) if plot_results: fig, ax = plt.subplots(2, sharex=True) ax[0].plot(psin_lower, solver.psi_sol_lower[:, 0], label='solution from axis') ax[0].plot(psin_upper, solver.psi_sol_upper[:, 0], label='solution from boundary') # Plot comparison solution if it exists validation_file = 'flux_validation_vc_{}.csv'.format(factor) if os.path.exists(validation_file): flux_validation = np.loadtxt(validation_file) flux_validation[:, 1] /= np.max(flux_validation[:, 1]) flux_validation[:, 1] *= np.max(solver.psi_sol_lower[:, 0]) ax[0].plot(flux_validation[:, 0], flux_validation[:, 1], linestyle='--', label='JOREK') ax[0].set_ylabel('$\Psi_1$', fontsize=fontsize) ax[0].legend() ax[0].set_xlim([0.0, 1.0]) ax[1].plot(psin_lower, solver.psi_sol_lower[:, 1]) ax[1].plot(psin_upper, solver.psi_sol_upper[:, 1]) ax[1].set_ylabel('$\\frac{\partial \Psi_1}{\partial r}$', fontsize=fontsize) ax[1].set_xlabel('$\hat \Psi$', fontsize=fontsize) plt.show() deltas.append(solver.delta) gammas.append(solver.gamma) alphas.append(1 - factor) alphas = np.stack( (np.asarray(alphas[::-1]), np.asarray(deltas[::-1]))).transpose() gammas = np.stack( (np.asarray(alphas[::-1]), np.asarray(gammas[::-1]))).transpose() np.savetxt(data_output, alphas) np.savetxt(gamma_output, gammas) # Load JOREK gammas alphas_jor = [ -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.25, 0.275, 0.3, 0.3125, 0.325, 0.3375 ] gammas_jor = np.asarray([ 0.000305073, 0.000216954, 0.000154881, 0.000110055, 7.14455e-5, 3.94265e-5, 2.48401e-5, 1.77428e-5, 1.0663e-5, 7.15803e-6, 3.77522e-6, 9.28732e-7 ]) gammas_jor /= 6.4836e-7 np.savetxt( 'gammas_jor_vs_alpha.dat', np.stack((np.asarray(alphas_jor), np.asarray(gammas_jor))).transpose()) alphas_jor_8 = [0.0, 0.1, 0.2, 0.3] gammas_8 = np.asarray([41.701, 25.616, 12.98966, 2.5974]) gammas_9 = np.asarray([6.809, 4.0393, 1.99651, 0.46058]) # Load tm1 data tm1_data = np.loadtxt('gammas_tm1_vs_alpha.dat') # Multiply normalised solver gamma by density and resistivity eta = 1e-7 * 1.9382 rho = 1e20 * 2 * 1.673 * 1e-27 gammas[:, 1] *= eta**0.6 / rho**0.2 np.savetxt('gammas_vs_alpha_si.dat', gammas) # Plot gammas fig, ax = plt.subplots(2, sharex=True) ax[0].plot(gammas[:, 0], gammas[:, 1], label='Linear') ax[0].scatter(gammas[:, 0], gammas[:, 1]) ax[0].plot(alphas_jor, gammas_jor, label='JOREK') ax[0].scatter(alphas_jor, gammas_jor) ax[0].plot(tm1_data[:, 0], tm1_data[:, 1], label='TM1') ax[0].scatter(tm1_data[:, 0], tm1_data[:, 1]) ax[0].set_ylabel('$\gamma\ [s^{-1}]$', fontsize=fontsize) ax[0].set_xlim([0.0, 1.0]) ax[0].set_ylim([0.0, 250.0]) ax[0].legend() gammas_interp = interpolate.interp1d(gammas[:, 0], gammas[:, 1]) gammas_tm1_interp = interpolate.interp1d(tm1_data[:, 0], tm1_data[:, 1]) ax[1].plot(alphas_jor, 100 * np.abs(gammas_jor - gammas_interp(alphas_jor)) / gammas_interp(alphas_jor), label='JOREK vs. Linear', c='orange') ax[1].scatter(alphas_jor, 100 * np.abs(gammas_jor - gammas_interp(alphas_jor)) / gammas_interp(alphas_jor), c='orange') ax[1].plot(tm1_data[:, 0], 100 * np.abs(tm1_data[:, 1] - gammas_interp(tm1_data[:, 0])) / gammas_interp(tm1_data[:, 0]), label='TM1 vs. Linear', c='g') ax[1].scatter(tm1_data[:, 0], 100 * np.abs(tm1_data[:, 1] - gammas_interp(tm1_data[:, 0])) / gammas_interp(tm1_data[:, 0]), c='g') skipped_index_low = 3 skipped_index_high = -3 ax[1].plot( alphas_jor[skipped_index_low:skipped_index_high], 100 * np.abs(gammas_jor[skipped_index_low:skipped_index_high] - gammas_tm1_interp( alphas_jor[skipped_index_low:skipped_index_high])) / gammas_tm1_interp(alphas_jor[skipped_index_low:skipped_index_high]), label='TM1 vs. JOREK', c='r') ax[1].scatter( alphas_jor[skipped_index_low:skipped_index_high], 100 * np.abs(gammas_jor[skipped_index_low:skipped_index_high] - gammas_tm1_interp( alphas_jor[skipped_index_low:skipped_index_high])) / gammas_tm1_interp(alphas_jor[skipped_index_low:skipped_index_high]), c='r') ax[1].set_ylabel('Relative difference $[\%]$', fontsize=fontsize) ax[1].set_xlabel('$\\alpha$', fontsize=fontsize) ax[1].set_xlim([0.0, 0.4]) plt.savefig('current_stability_gammas_{}'.format(m)) plt.show() # Get equivalent JOREK and TM1 delta solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi, q, num_pts, delta=1e-12) deltas_jor = gammas_jor / 0.55 / (eta / PhysicalConstants.mu_0)**0.6 deltas_jor /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho))**0.4 deltas_jor /= ( solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability)))**0.4 deltas_jor = deltas_jor**(5.0 / 4.0) deltas_jor_8 = gammas_8 / 0.55 / (eta * 0.1 / PhysicalConstants.mu_0)**0.6 deltas_jor_8 /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho))**0.4 deltas_jor_8 /= ( solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability)))**0.4 deltas_jor_8 = deltas_jor_8**(5.0 / 4.0) deltas_jor_9 = gammas_9 / 0.55 / (eta * 0.01 / PhysicalConstants.mu_0)**0.6 deltas_jor_9 /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho))**0.4 deltas_jor_9 /= ( solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability)))**0.4 deltas_jor_9 = deltas_jor_9**(5.0 / 4.0) deltas_tm1 = tm1_data[:, 1] / 0.55 / (eta / PhysicalConstants.mu_0)**0.6 deltas_tm1 /= (m * solver.r_to_B_theta(solver.r_instability) / np.sqrt(PhysicalConstants.mu_0 * rho))**0.4 deltas_tm1 /= ( solver.r_to_q_deriv(solver.r_instability) / (solver.r_instability * solver.r_to_q(solver.r_instability)))**0.4 deltas_tm1 = deltas_tm1**(5.0 / 4.0) # Plot equivalent gammas scaling = 1.05 # Factor to improve plot fig, ax = plt.subplots(1) ax.plot(deltas[:, 0], deltas[:, 1], label='Linear') ax.scatter(deltas[:, 0], deltas[:, 1]) ax.plot(alphas_jor, deltas_jor, label='JOREK') ax.scatter(alphas_jor, deltas_jor) # ax.plot(alphas_jor_8, deltas_jor_8, label='JOREK $\Delta\'$ for $\eta=10^{-8}$') # ax.scatter(alphas_jor_8, deltas_jor_8) # ax.plot(alphas_jor_8, deltas_jor_9, label='JOREK $\Delta\'$ for $\eta=10^{-9}$') # ax.scatter(alphas_jor_8, deltas_jor_9) ax.plot(tm1_data[:, 0], deltas_tm1, label='TM1') ax.scatter(tm1_data[:, 0], deltas_tm1) ax.axhline(0.0, c='k', linestyle='--') ax.axvline(0.358, linestyle='--', color='grey', label='Linear stability boundary') ax.axvline(0.3375, linestyle='--', color='g', label='JOREK stability boundary') ax.axvline(0.35, linestyle='--', color='g') ax.fill_betweenx(scaling * deltas[:, 1], 0.3375, 0.35, facecolor='green', alpha=0.2) ax.set_ylabel('$\Delta\'$', fontsize=fontsize) ax.set_xlabel('$\\alpha$', fontsize=fontsize) ax.set_xlim([0.0, 1.0]) ax.set_ylim([scaling * min(deltas[:, 1]), 22.0]) ax.grid(linestyle='--') ax.legend() plt.savefig('current_stability_deltas_{}'.format(m)) plt.show()
def enthalpy_form(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) markers = ["o", "x", "^", "v", "d"] all_data = [] folder = "data/mc_hcp" for conc in concs: new_data = {} fname = "{}/thermo_{}.csv".format(folder, conc) T, conc, H_form = np.loadtxt(fname, delimiter=",", unpack=True, usecols=(0, 2, 3)) new_data["T"] = T[1:] new_data["H"] = H_form[1:] new_data["conc"] = conc[1:] all_data.append(new_data) n_temps = len(all_data[0]["T"]) Tmax = np.max(all_data[0]["T"]) Tmin = np.min(all_data[0]["T"]) for i in range(n_temps): T = all_data[0]["T"][i] form = [] conc = [] for dset in all_data: form.append(dset["H"][i]) conc.append(dset["conc"][i]) srt_indx = np.argsort(conc) conc = [conc[indx] for indx in srt_indx] form = [form[indx] for indx in srt_indx] conc.append(1.0) form.append(0.0) mapped_temp = (T - Tmin) / (Tmax - Tmin) ax.plot(conc, form, marker=markers[i % len(markers)], color=cm.copper(mapped_temp), label="{}K".format(T)) ax.set_xlabel("Mg concentration") ax.set_ylabel("Enthalpy of formation (kJ/mol)") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) #ax.legend() Z = [[0, 0], [0, 0]] fig_info = plt.figure() #temp_info = [np.min(T),np.max(T)] ax_info = fig_info.add_subplot(1, 1, 1) temp_info = np.linspace(Tmin, Tmax, 256) Cb_info = ax_info.contourf(Z, temp_info, cmap="copper") cbar = fig.colorbar(Cb_info, orientation="horizontal", ticks=[100, 300, 500, 700]) cbar.ax.xaxis.set_ticks_position("top") cbar.ax.set_xticklabels([100, 300, 500, 700]) cbar.ax.xaxis.set_label_position("top") #cbar.ax.tick_params(axis='x',direction='in',labeltop='on') cbar.set_label("Temperature (K)")
def get_random_plot(name, direc): """ Random plot generation method. Inputs: name: (string) name of the plot which will be saved. Outputs: ax : (matplotlib obj) Matplotlib object of the axes of the plot fig : (matplotlib obj) Matplotlib object of the figure of the plot x, y : (list, list) Actuall x and y coordinates of the points. s : (list) sizes of the points. categories : (list) categories of the points. tick_size : (list) Tick size on the plot. [width, length] axes_x_pos, axes_y_pos: (float, float) Position of the labels of the axis. """ # PLOT STYLE style = random.choice(styles) plt.style.use(style) # POINT DISTRIBUTION distribution = random.choice(point_dist) # RESOLUTION AND TICK SIZE dpi = int(dpi_min + np.random.rand(1)[0] * (dpi_max - dpi_min)) figsize = (figsize_min + np.random.rand(2) * (figsize_max - figsize_min)).astype(int) tick_size = [(tick_size_width_min + np.random.rand(1)[0] * (tick_size_width_max - tick_size_width_min)), (tick_size_length_min + np.random.rand(1)[0] * (tick_size_length_max - tick_size_length_min))] tick_size.sort() fig, ax = plt.subplots(figsize=figsize, dpi=dpi) # ACTUAL POINTS points_nb = int(points_nb_min + (np.random.rand(1)[0]**1.5) * (points_nb_max - points_nb_min)) #print points_nb x_scale = int(x_min_top + np.random.rand(1)[0] * (x_max_top - x_min_top)) #print x_scale y_scale = int(y_min_top + np.random.rand(1)[0] * (y_max_top - y_min_top)) #print y_scale x_scale_range = x_scale + int(np.random.rand(1)[0] * x_scale_range_max) #print x_scale_range y_scale_range = y_scale + int(np.random.rand(1)[0] * y_scale_range_max) #print y_scale_range x_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(x_scale) x_max = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(x_scale_range) x_min, x_max = min(x_min, x_max), max(x_min, x_max) y_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(y_scale) y_max = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(y_scale_range) y_min, y_max = min(y_min, y_max), max(y_min, y_max) if distribution == 'uniform': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = y_min + np.random.rand(points_nb) * (y_max - y_min) elif distribution == 'linear': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = x * (max(y_max, -y_min) / (max(x_max, -x_min))) * random.choice( [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) * (y_max - y_min)) * np.random.rand(1)[0] / 2.0 elif distribution == 'quadratic': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = x**2 * (1.0 / (max(x_max, -x_min)))**2 * max( y_max, -y_min) * random.choice( [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) * (y_max - y_min)) * np.random.rand(1)[0] / 2.0 # POINTS VARIATION nb_points_var = 1 + int(np.random.rand(1)[0] * max_points_variations) nb_points_var_colors = 1 + int(np.random.rand(1)[0] * nb_points_var) nb_points_var_markers = 1 + int( np.random.rand(1)[0] * (nb_points_var - nb_points_var_colors)) nb_points_var_size = max( 1, 1 + nb_points_var - nb_points_var_colors - nb_points_var_markers) rand_color_number = np.random.rand(1)[0] if rand_color_number <= 0.5: colors = cm.rainbow(np.random.rand(nb_points_var_colors)) elif rand_color_number > 0.5 and rand_color_number <= 0.7: colors = cm.gnuplot(np.random.rand(nb_points_var_colors)) elif rand_color_number > 0.7 and rand_color_number <= 0.8: colors = cm.copper(np.random.rand(nb_points_var_colors)) else: colors = cm.gray(np.linspace(0, 0.6, nb_points_var_colors)) s_set = (size_points_min + np.random.rand(nb_points_var_size) * (size_points_max - size_points_min))**2 markers_subset = list(np.random.choice(markers, size=nb_points_var_markers)) markers_empty = np.random.rand(1)[0] > 0.75 markers_empty_ratio = random.choice([0.0, 0.5, 0.7]) # BUILDING THE PLOT s = [] categories = [] cat_dict = {} index_cat = 0 for _x, _y, in zip(x, y): s_ = random.choice(s_set) c_ = random.choice(colors) m_ = random.choice(markers_subset) if m_ in markers_with_full and markers_empty: e_ = np.random.rand(1)[0] > markers_empty_ratio else: e_ = False cat = [s_, c_, m_, e_] if cat_in_dict(cat, cat_dict) is False: cat_dict[index_cat] = cat index_cat += 1 categories.append(cat_in_dict(cat, cat_dict)) s.append(s_) if e_: plt.scatter(_x, _y, s=s_, color=c_, marker=m_, facecolors='none') else: plt.scatter(_x, _y, s=s_, color=c_, marker=m_) # PAD BETWEEN TICKS AND LABELS #labs = [item.get_text() for item in ax.get_xticklabels()] #print labs pad_x = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) pad_y = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) direction_ticks_x = random.choice(direction_ticks) direction_ticks_y = random.choice(direction_ticks) # NON-DEFAULT TICKS PROB, WITH THRESHOLD OF 0.6 weid_ticks_prob = np.random.rand(1)[0] # TICKS STYLE AND LOCATION (X AXIS) if np.random.rand(1)[0] > 0.5: axes_x_pos = 1 ax.xaxis.tick_top() ax.xaxis.set_label_position("top") if weid_ticks_prob > 0.6: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_x, direction=direction_ticks_x, bottom=np.random.rand(1)[0] > 0.5, top=True) else: ax.xaxis.set_tick_params(bottom=np.random.rand(1)[0] > 0.5, top=True) if np.random.rand(1)[0] > 0.5: ax.spines['bottom'].set_visible(False) ax.xaxis.set_tick_params(bottom=False) if np.random.rand(1)[0] > 0.5: axes_x_pos = np.random.rand(1)[0] ax.spines['top'].set_position(('axes', axes_x_pos)) else: axes_x_pos = 0 if weid_ticks_prob > 0.6: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_x, direction=direction_ticks_x, bottom=True, top=np.random.rand(1)[0] > 0.5) else: ax.xaxis.set_tick_params(bottom=True, top=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['top'].set_visible(False) ax.xaxis.set_tick_params(top=False) if np.random.rand(1)[0] > 0.5: axes_x_pos = np.random.rand(1)[0] ax.spines['bottom'].set_position(('axes', axes_x_pos)) # TICKS STYLE AND LOCATION (Y AXIS) if np.random.rand(1)[0] > 0.5: axes_y_pos = 1 ax.yaxis.tick_right() ax.yaxis.set_label_position("right") if weid_ticks_prob > 0.6: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_y, direction=direction_ticks_y, left=np.random.rand(1)[0] > 0.5, right=True) else: ax.yaxis.set_tick_params(left=np.random.rand(1)[0] > 0.5, right=True) if np.random.rand(1)[0] > 0.5: ax.spines['left'].set_visible(False) ax.yaxis.set_tick_params(left=False) if np.random.rand(1)[0] > 0.5: axes_y_pos = np.random.rand(1)[0] ax.spines['right'].set_position(('axes', axes_y_pos)) else: axes_y_pos = 0 if weid_ticks_prob > 0.6: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_y, direction=direction_ticks_y, left=True, right=np.random.rand(1)[0] > 0.5) else: ax.yaxis.set_tick_params(left=True, right=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['right'].set_visible(False) ax.yaxis.set_tick_params(right=False) if np.random.rand(1)[0] > 0.5: axes_y_pos = np.random.rand(1)[0] ax.spines['left'].set_position(('axes', axes_y_pos)) # LABEL ROTATION if np.random.rand(1)[0] > 0.77: plt.xticks(rotation=int(np.random.rand(1)[0] * 90)) if np.random.rand(1)[0] > 0.77: plt.yticks(rotation=int(np.random.rand(1)[0] * 90)) # SUB-TICKs if weid_ticks_prob > 0.6: color_subtick = random.choice(color_subtick_list) length_subtick = 0.75 * np.random.rand(1)[0] * tick_size[1] if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_tick_params(which='minor', length=length_subtick, direction=direction_ticks_x, color=color_subtick, bottom=ax.spines['bottom'].get_visible(), top=ax.spines['top'].get_visible()) if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.yaxis.set_minor_locator(minorLocator) ax.yaxis.set_tick_params(which='minor', length=length_subtick, direction=direction_ticks_y, color=color_subtick, left=ax.spines['left'].get_visible(), right=ax.spines['right'].get_visible()) # FONT AND SIZE FOR LABELS (tick labels, axes labels and title) font = random.choice(font_list) size_ticks = int(tick_label_size_min + np.random.rand(1)[0] * (tick_label_size_max - tick_label_size_min)) size_axes = int(axes_label_size_min + np.random.rand(1)[0] * (axes_label_size_max - axes_label_size_min)) size_title = int(title_size_min + np.random.rand(1)[0] * (title_size_max - title_size_min)) ticks_font = font_manager.FontProperties(fname=font, style='normal', size=size_ticks, weight='normal', stretch='normal') axes_font = font_manager.FontProperties(fname=font, style='normal', size=size_axes, weight='normal', stretch='normal') title_font = font_manager.FontProperties(fname=font, style='normal', size=size_title, weight='normal', stretch='normal') # TEXTS FOR AXIS LABELS AND TITLE label_x_length = int(axes_label_length_min + np.random.rand(1)[0] * (axes_label_length_max - axes_label_length_min)) #print label_x_length label_y_length = int(axes_label_length_min + np.random.rand(1)[0] * (axes_label_length_max - axes_label_length_min)) title_length = int(title_length_min + np.random.rand(1)[0] * (title_length_max - title_length_min)) x_label = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(label_x_length) ])).strip() #print x_label y_label = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(label_y_length) ])).strip() title = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(title_length) ])).strip() plt.xlabel(x_label, fontproperties=axes_font) plt.ylabel(y_label, fontproperties=axes_font, color='black') if axes_x_pos == 1: plt.title(title, fontproperties=title_font, color='black', y=1.1) else: plt.title(title, fontproperties=title_font, color='black') for label in ax.get_xticklabels(): label.set_fontproperties(ticks_font) for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) # GRID if np.random.rand(1)[0] > 0.7: plt.grid(b=True, which='major', color=random.choice(color_grid), linestyle=random.choice(linestyles)) # AXIS LIMITS xmin = min(x) xmax = max(x) deltax = 0.05 * abs(xmax - xmin) plt.xlim(xmin - deltax, xmax + deltax) ymin = min(y) ymax = max(y) deltay = 0.05 * abs(ymax - ymin) plt.ylim(ymin - deltay, ymax + deltay) # BACKGROUND AND PATCH COLORS if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) ax.set_axis_bgcolor(color_bg) if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) fig.patch.set_facecolor(color_bg) # MAKE SURE THE PLOT FITS INSIDE THE FIGURES try: plt.tight_layout() plt.savefig("./data/{}/".format(direc) + name, dpi='figure', facecolor=fig.get_facecolor()) except RuntimeError: pass return ax, fig, x, y, s, categories, tick_size, axes_x_pos, axes_y_pos
def main(): ''' set paths & parameters ''' # Parse information from the command line parser = argparse.ArgumentParser(prog='LES_CP') parser.add_argument("casename") parser.add_argument("path_root") parser.add_argument("path1") parser.add_argument("path2") parser.add_argument("path_out") parser.add_argument("--tmin") parser.add_argument("--tmax") parser.add_argument("--kmax") parser.add_argument("--everysecond") args = parser.parse_args() set_input_parameters(args) # ic_arr, jc_arr = define_geometry(nml) if args.everysecond: every_second = args.everysecond else: every_second = True print('every_second', every_second) file_name = 'stats_radial_averaged.nc' file1 = nc.Dataset(os.path.join(path1, 'data_analysis', file_name)) file2 = nc.Dataset(os.path.join(path2, 'data_analysis', file_name)) dx1 = file1.groups['dimensions'].dimensions['dx'].size dx2 = file2.groups['dimensions'].dimensions['dx'].size dz1 = file1.groups['dimensions'].dimensions['dz'].size dz2 = file2.groups['dimensions'].dimensions['dz'].size if dx1 < dx2: # want to have file2 higher resolution file_aux = file2 file2 = file1 file1 = file_aux del file_aux print('dx: ', dx1_nml[0], dx2_nml[0], dx1) print('dz: ', dx1_nml[2], dx2_nml[2], dz1) print('nx: ', nx1[0], nx2[0]) print('nz: ', nx1[2], nx2[2]) grp_stats1 = file1.groups['stats'].variables grp_stats2 = file2.groups['stats'].variables time1 = file1.groups['timeseries'].variables['time'][:] time2 = file2.groups['timeseries'].variables['time'][:] print('times: ') print time1 print time2 nt = np.minimum(len(time1), len(time2)) time1 = time1[:nt] time2 = time2[:nt] if len(time1) != len(time2): time1 = time1[:nt] time2 = time2[:nt] if time1.any() != time2.any(): print 'problem with times' sys.exit() r1 = file1.groups['stats'].variables['r'][:] r2 = file2.groups['stats'].variables['r'][:] ri1 = file1.groups['stats'].variables['ri'][:] ri2 = file2.groups['stats'].variables['ri'][:] try: krange1 = file1.groups['dimensions'].variables['krange'][:] krange2 = file2.groups['dimensions'].variables['krange'][:] except: krange1 = np.arange(kmax) krange2 = np.arange(kmax) print '' print 'kranges:' print krange1 print krange2 if dz1 > dz2: print 'dz1 > dz2' dz12 = np.double(dz1) / dz2 kmax_ = np.int( np.minimum(np.int(np.round(kmax / dz12)), len(krange2) / dz12)) krange1 = krange1[:kmax_] krange2 = krange2[0::np.int(dz12)] elif dz1 < dz2: print 'dz1 < dz2' dz12 = np.double(dz2) / dz1 kmax_ = np.int(np.round(kmax / dz12)) krange1 = krange1[0::2] krange2 = krange2[:kmax_] else: dz12 = 1. kmax_ = kmax print('') print 'dz: ', dz1, dz2, dz12 print 'kmax: ', kmax, kmax_ print krange1 print krange2 print 'zranges:' print krange1 * dz1 print krange2 * dz2 var_list = ['w', 'v_rad', 's'] ncol = len(var_list) rmax = 8e3 irmax1 = np.where(r1 == rmax)[0] irmax2 = np.where(r2 == rmax)[0] # irmax1 = -1 # irmax2 = -1 print '' print r1[-1], r2[-1] print 'irmax: ', irmax1, irmax2 print 'rmax', r1[irmax1], r2[irmax2] print '' for k0 in range(kmax_): k1 = krange1[k0] k2 = krange2[k0] print('z1, z2: ', k1 * dz1, k2 * dz2) fig_name = 'radial_average_z' + str(k1 * dz1) + '.png' fig, axes = plt.subplots(1, ncol, sharey='none', figsize=(7 * ncol, 5)) for i, ax in enumerate(axes): var1 = grp_stats1[var_list[i]][:, :, :] var2 = grp_stats2[var_list[i]][:, :, :] if var_list[i] == 'w': ax.set_ylim( -6, np.maximum(np.amax(var1[:, :, k0]), np.amax(var2[:, :, k0]))) if every_second == True: for it, t0 in enumerate(time1[1::2]): # print('- t='+str(t0)) count_color = 2 * np.double(it) / len(time1) if it == 0: ax.plot(r1[:irmax1], var1[2 * it + 1, :irmax1, k1], color=cm.copper(count_color), linewidth=3, label='t=' + str(t0) + ', dx=' + str(dx1)) else: ax.plot(r1[:irmax1], var1[2 * it + 1, :irmax1, k1], color=cm.copper(count_color), linewidth=3, label='t=' + str(t0)) for it, t0 in enumerate(time1[1::2]): #print('t=' + str(t0)) count_color = 2 * np.double(it) / len(time1) if it == 0: ax.plot(r2[:irmax2], var2[2 * it + 1, :irmax2, k2], '-', color=cm.jet(count_color), linewidth=3, label='dx=' + str(dx2)) else: # ax.plot(r2[:irmax2], ) ax.plot(r2[:irmax2], var2[2 * it + 1, :irmax2, k2], '-', color=cm.jet(count_color), linewidth=2, label='dx=' + str(dx2)) else: for it, t0 in enumerate(time1): print('t=' + str(t0)) count_color = np.double(it) / len(time1) if it == 0: ax.plot(r1[:irmax1], var1[it, :irmax1, k1], color=cm.copper(count_color), linewidth=3, label='t=' + str(t0) + ', dx=' + str(dx1)) else: ax.plot(r1[:irmax1], var1[it, :irmax1, k1], color=cm.copper(count_color), linewidth=3, label='t=' + str(t0)) for it, t0 in enumerate(time1): print('t=' + str(t0)) count_color = np.double(it) / len(time1) if it == 0: ax.plot(r2[:irmax2], var2[it, :irmax2, k2], '-', color=cm.jet(count_color), linewidth=2, label='dx=' + str(dx2)) else: ax.plot(r2[:irmax2], var2[it, :irmax2, k2], '-', color=cm.jet(count_color), linewidth=2, label='dx=' + str(dx2)) ax.set_title(var_list[i]) ax.set_xlabel('radius r [m]') ax.set_ylabel(var_list[i]) axes[2].legend(loc='upper center', bbox_to_anchor=(1.15, 0.8), fancybox=True, ncol=2, fontsize=8) # plt.tight_layout() plt.subplots_adjust(bottom=0.12, right=.9, left=0.04, top=0.9, wspace=0.15) fig.suptitle('Radially averaged variables (k=' + str(k0) + ')') fig.savefig(os.path.join(path_out_figs, fig_name)) plt.close(fig) file1.close() file2.close() return
def few_Vm_fig(SET_OF_DATA, pop_key='Exc', tspace=200., tzoom=[200, np.inf], VMS1=np.arange(3), VMS2=None, Tbar=100, Vbar=10, Vshift=30, vpeak=-42, vbottom=-80): fig, ax = plt.subplots(figsize=(5 * len(SET_OF_DATA), 5)) # plt.subplots_adjust(left=.15, bottom=.1, right=.99) if VMS2 is None: VMS2 = VMS1 # ID of cells t0 = 0 for k, data in enumerate(SET_OF_DATA): VMS = [VMS1, VMS2][k] t = np.arange(int(data['tstop'] / data['dt'])) * data['dt'] cond = (t > tzoom[0]) & (t < tzoom[1]) for i, j in enumerate(VMS): ax.plot(t[cond]+t0, data['VMS_'+str(pop_key)][j][cond]+Vshift*i,\ color=copper(i/len(VMS)/1.5), lw=1) ax.plot(t[cond] + t0, 0 * t[cond] + -70 + Vshift * i, ':', color=copper(i / len(VMS) / 1.5), lw=1) ax.plot([t[cond][0] + t0], [-70 + Vshift * i], '>', color=copper(i / len(VMS) / 1.5)) # adding spikes for i, j in enumerate(VMS): tspikes = data['tRASTER_' + str(pop_key)][np.argwhere( data['iRASTER_' + str(pop_key)] == j).flatten()] cond = (tspikes > tzoom[0]) & (tspikes < tzoom[1]) for ts in tspikes[cond]: ax.plot([ts + t0, ts + t0], Vshift * i + np.array([-50, vpeak]), '--', color=copper(i / len(VMS) / 1.5), lw=1) t0 = tspace + tzoom[1] - tzoom[0] ax.plot([tzoom[0], tzoom[0] + Tbar], ax.get_ylim()[0] * np.ones(2), lw=5, color='gray') ax.annotate(str(Tbar) + 'ms', (tzoom[0], .9 * ax.get_ylim()[0]), fontsize=14) ax.plot(tzoom[1] * np.ones(2), [-60, -60 + Vbar], lw=5, color='gray') ax.annotate(str(Vbar) + 'mV', (tzoom[1], -60), fontsize=14) ax.annotate('-70mV', (tzoom[1], -70), fontsize=14) set_plot(ax, [], xticks=[], yticks=[]) c = plt.axes([.5, .5, .01, .2]) cmap = mpl.colors.ListedColormap(copper(np.linspace(0, 1 / 1.5, len(VMS1)))) cb = mpl.colorbar.ColorbarBase(c, cmap=cmap, orientation='vertical') cb.set_label('Cell ID', fontsize=12) cb.set_ticks([]) return fig
import numpy as np import scipy as sp from matplotlib.widgets import Slider from matplotlib.colors import Normalize from matplotlib import cm import matplotlib.pyplot as pl sizes = np.array([128, 256, 512, 1024, 2048]) data = -np.array([np.loadtxt("./df-hist-raw-%i.txt" % i) for i in sizes]) dev = np.array([91.0 / 48 - d.mean() for d in data]) std = np.array([d.std() for d in data]) colors = cm.copper(Normalize()(np.arange(len(dev)))) x, y = [], [] for t in data: ty, tx = np.histogram(t, bins=24, normed=True) x.append((tx[1:] + tx[:-1]) / 2) y.append(ty) x = np.array(x).T y = np.array(y).T def rescale(sizes, xs, ys, dfc, tau): return (dfc - xs) * sizes ** tau, ys * sizes ** -tau def plotall(): """ Note: to save, use dpi=300 to match other plots """
import numpy as np import scipy as sp from matplotlib.widgets import Slider from matplotlib.colors import Normalize from matplotlib import cm import matplotlib.pyplot as pl sizes = np.array([128, 256, 512, 1024, 2048]) data = -np.array([np.loadtxt("./df-hist-raw-%i.txt" % i) for i in sizes]) dev = np.array([91. / 48 - d.mean() for d in data]) std = np.array([d.std() for d in data]) colors = cm.copper(Normalize()(np.arange(len(dev)))) x, y = [], [] for t in data: ty, tx = np.histogram(t, bins=24, normed=True) x.append((tx[1:] + tx[:-1]) / 2) y.append(ty) x = np.array(x).T y = np.array(y).T def rescale(sizes, xs, ys, dfc, tau): return (dfc - xs) * sizes**tau, ys * sizes**-tau def plotall(): """ Note: to save, use dpi=300 to match other plots """
def plot_frequency_statistics(): folder = "data/almgsi_ch500K_run_truncnorm/postproc" folder = "/work/sophus/almgsi_ch500K_run2/postproc" fnames = [ "chgl_50_frequency_statistics.csv", "chgl_40_frequency_statistics.csv", "chgl_30_frequency_statistics.csv", "chgl_20_frequency_statistics.csv", "chgl_10_frequency_statistics.csv" ] fnames = [folder + "/" + f for f in fnames] concs = [0.5, 0.4, 0.3, 0.2, 0.1] orig_concs = deepcopy(concs) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) freqs = [] profiles = [] markers = ['o', 'd', 'v', '^', 'h', 'p'] concs = np.array(concs) concs -= np.min(concs) concs /= np.max(concs) col = 1 if col == 2: print("Plotting second moment of distribution") elif col == 1: print("Plotting first moment of distribution") else: raise ValueError("col has to be 1 or 2") for i, fname in enumerate(fnames): data = np.loadtxt(fname, delimiter=",") freqs.append(data[:, 0]) profiles.append(data[:, col]) ax.plot(data[:, 0], data[:, col], markers[i], mfc="none", color=cm.copper(concs[i]), ms=8, markeredgewidth=1.5, label="{}%".format(int(100 * orig_concs[i]))) # Fit a linear line to beginning slope, interscept, _, _, _ = linregress(np.log(freqs[0][:12]), np.log(profiles[0][:12])) print("Slope (exponent)", slope) freq_fit = np.logspace(-1.5, 3, 10) ax.plot(freq_fit, np.exp(interscept) * freq_fit**slope, ls='--', color="#5d5C61") ax.set_xscale("log") ax.set_yscale("log", basey=2) ax.set_xlabel("Dimensionless time") ax.set_ylabel("Frequency (nm\$^{-1}\$)") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.legend(frameon=False) plt.show()
def get_stability_condition(plot_results=True): current_factors = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] colors = cm.copper(np.linspace(0.0, 1.0, len(current_factors))) # Get profiles dat = np.loadtxt(os.path.join('input_profiles.dat')) # Modify and plot input profiles r = dat[:, 0] R = dat[:, 1] j_phi = dat[:, 2] B_z = dat[:, 3] B_theta = dat[:, 4] psi_n = dat[:, 5] r_to_psin = interpolate.interp1d(r, psi_n) psin_to_r = interpolate.interp1d(r, psi_n) q = r * B_z / (R * B_theta) q[0] = q[1] if plot_results: fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True) ax[0, 0].plot(r, B_z, c='k') ax[0, 0].set_ylabel('$B_{\phi}$ [T]', fontsize=fontsize) ax[1, 0].plot(r, B_theta, c='k') ax[1, 0].set_ylabel('$B_{\\theta}$ [T]', fontsize=fontsize) for i, factor in enumerate(current_factors[::-1]): linestyle = '--' if i > 0 else '-' ax[0, 1].plot(r, factor * j_phi * 1e-3, linestyle=linestyle, c=colors[i]) ax[0, 1].set_ylabel('$j_{\phi}$ [kA]', fontsize=fontsize) ax[1, 1].plot(r, q, c='k') ax[1, 1].set_ylabel('q', fontsize=fontsize) ax[1, 1].set_xlabel('r [m]', fontsize=fontsize) ax[1, 0].set_xlabel('r [m]', fontsize=fontsize) ax[0, 0].set_xlim([0.0, 1.0]) fig.tight_layout() plt.savefig('input_profiles') plt.show() r_max = r[-1] deltas = list() alphas = list() for factor in current_factors: j_phi_sim = j_phi * factor solver = TearingModeSolver(m, r, r_max, B_theta, B_z, j_phi_sim, q, num_pts, delta=1e-12) solver.find_delta(plot_output=False) psin_lower = r_to_psin(solver.r_lower) psin_upper = r_to_psin(solver.r_upper) if plot_results: fig, ax = plt.subplots(2, sharex=True) ax[0].plot(psin_lower, solver.psi_sol_lower[:, 0], label='solution from axis') ax[0].plot(psin_upper, solver.psi_sol_upper[:, 0], label='solution from boundary') # Plot comparison solution if it exists validation_file = 'flux_validation_vc_{}.csv'.format(factor) if os.path.exists(validation_file): flux_validation = np.loadtxt(validation_file, delimiter=',') flux_validation[:, 1] /= np.max(flux_validation[:, 1]) flux_validation[:, 1] *= np.max(solver.psi_sol_lower[:, 0]) ax[0].plot(flux_validation[:, 0], flux_validation[:, 1], linestyle='--', label='JOREK') ax[0].set_ylabel('$\Psi_1$', fontsize=fontsize) ax[0].legend() ax[0].set_xlim([0.0, 1.0]) ax[1].plot(psin_lower, solver.psi_sol_lower[:, 1]) ax[1].plot(psin_upper, solver.psi_sol_upper[:, 1]) ax[1].set_ylabel('$\\frac{\partial \Psi_1}{\partial r}$', fontsize=fontsize) ax[1].set_xlabel('$\hat \Psi$', fontsize=fontsize) plt.show() deltas.append(solver.delta) alphas.append(1 - factor) np.savetxt('deltas', np.asarray(deltas)) plt.figure() plt.plot(alphas, deltas) plt.axvline(0.346, linestyle='--', color='grey', label='Linear stability boundary') plt.axvline(0.25, linestyle='--', color='g', label='JOREK stability boundary') plt.grid(linestyle='--') plt.ylabel('$\Delta\'$', fontsize=fontsize) plt.xlabel('$\\alpha$', fontsize=fontsize) plt.legend() plt.xlim([0.0, 1.0]) plt.savefig('current_stability_{}'.format(m)) plt.show()
def main(): args = parse_args() q_mean, p_mean, Q, P, W = prepare_data(args) no_steps = Q.shape[0] q_min = Q[:,0,0].min() q_max = Q[:,0,-1].max() p_min = P[:,0,0].min() p_max = P[:,-1,0].max() if args.vmin[-1]=="%": W_min = numpy.percentile(W[:], float(args.vmin[:-1])) else: W_min = float(args.vmin) if args.vmax[-1]=="%": W_max = numpy.percentile(W[:], 100.-float(args.vmax[:-1])) else: W_max = float(args.vmax) midpoint = 1 - W_max/(W_max + abs(W_min)) cmap = shifted_color_map(cm.coolwarm, midpoint=midpoint, name="shifted") fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_xlim(q_min, q_max) ax.set_ylim(p_min, p_max) ax.set_xlabel("q") ax.set_ylabel("p") if args.visualization=="polished": shading="gouraud" else: shading="flat" quad = QuadContainer(ax.pcolormesh(Q[0], P[0], W[0], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.set_aspect("equal") if args.track: ax.set_color_cycle([cm.copper(1.*i/(no_steps-1)) for i in range(no_steps-1)]) for i in range(no_steps-1): ax.plot(q_mean[i:i+2],p_mean[i:i+2], alpha=.3) cb = fig.colorbar(quad.quad) cb.set_label("Quasiprobability Density") cb.solids.set_rasterized(True) if args.visualization=="polished": ax.set_axis_bgcolor(cb.to_rgba(0.)) no_digits = int(ceil(log10(no_steps))+1) title_string = "Wigner Function at step {:{width}}/{:{width}}" title = ax.set_title(title_string.format(0, no_steps, width=no_digits)) ax.grid(True) if args.output: fig.savefig(args.output+"_thumb.pdf") def animate(i): title.set_text(title_string.format(i, no_steps, width=no_digits)) quad.update_quad(ax.pcolormesh(Q[i], P[i], W[i], vmin=W_min, vmax=W_max, cmap=cmap, shading=shading)) ax.grid(True) return quad.quad, ani = FuncAnimation(fig, animate, no_steps, interval=100, repeat_delay=1000) if args.output: print("Saving movie to {}. This may take a couple of minutes.".format(args.output)) ani.save(args.output+".mp4", fps=10, extra_args=['-vcodec', 'libx264']) pyplot.show()