def triangle_contour(x_center, y_center, values, smoothing, ckwargs={}): """A helper funciton used to draw contorus with pl.tricontour""" # make Triangulation object using the centers of each of the hexbins triag = Triangulation(x_center, y_center) refiner = UniformTriRefiner(triag) # refines the mesh of triangle # returns refines triangle field of triangles and interpolated # contour values by dividing each triangle into 4**subdiv triangles tri_refi, c_refi = refiner.refine_field(values, subdiv=smoothing) T = pl.tricontour(tri_refi, c_refi, **ckwargs) return T
def extract_contour(x_list, y_list, z_list, z_value): import matplotlib matplotlib.use('Agg') import pylab import numpy temp = pylab.tricontour(x_list, y_list, z_list, levels=[z_value]) pylab.clf() return numpy.concatenate([itm.vertices for itm in temp.collections[0].get_paths()])
def plot_mesh(pts, tri, z=None): if z is not None: x = pts[:,0] y = pts[:,1] tripcolor(x, y, tri, z) colorbar() cs = tricontour(x, y, tri, z, colors="black", linestyles="dashed") clabel(cs) else: if len(tri[0]) == 3: plot_tri_mesh(pts, tri) else: plot_quad_mesh(pts, tri) axis('tight') xticks([]) yticks([]) axes().set_aspect('equal')
def plot_mesh(pts, tri, z=None): if z is not None: x = pts[:, 0] y = pts[:, 1] tripcolor(x, y, tri, z) colorbar() cs = tricontour(x, y, tri, z, colors="black", linestyles="dashed") clabel(cs) else: if len(tri[0]) == 3: plot_tri_mesh(pts, tri) else: plot_quad_mesh(pts, tri) axis('tight') xticks([]) yticks([]) axes().set_aspect('equal')
import numpy as np import matplotlib as mpl mpl.use("Agg") import pylab as plt plt.figure() data = np.load("lossgrad_lensing2.npz") c = data['loss']-data['loss'].min() #c = np.minimum(25, c) plt.tricontour(data['entropy/a'], data['entropy/b'], c, levels = [1, 4, 9, 25, 36, 49, 64, 81, 100, 200, 400]) plt.xlabel("a") plt.ylabel("b") plt.scatter(data['entropy/a'], data['entropy/b'], c=c) plt.colorbar() plt.title(data['loss'].min()) plt.savefig("loss.pdf") #plt.figure(figsize = (20, 10)) #data = np.load("mock_lensing.npz") #data2 = np.load("ppd_lensing.npz") ##mu = data['entropy/mu'] #mu2 = data2['entropy/mu'] #obs = data['entropy/obs'] ##plt.plot(mu) #plt.plot(mu2) #plt.plot(obs, marker='.', ls='') #plt.savefig("mu.pdf")
def main(): """ D(R) = <(phi(r) - phi(r+R))^2> = <K^2(TEC(r) - TEC(r + R))^2> = K^2<DTEC(r, -R)^2> :return: """ fig, ax = plt.subplots(1, 1, figsize=(6, 6)) baselines = 10**np.linspace(-1., 2, 100) k_obs = [] for _ in range(500): ds = np.random.uniform(5., 30.) beta = np.random.normal(1.89, 0.1) k_obs.append((baselines / ds)**(beta)) ax.plot(baselines, np.mean(k_obs, axis=0), lw=2., color='black', label='Mevius+ 2016') ax.fill_between(baselines, np.percentile(k_obs, 5, axis=0), np.percentile(k_obs, 95, axis=0), color='yellow', alpha=0.5) k_turb = (baselines / 10.)**(5. / 3.) ax.plot(baselines, k_turb, color='green', lw=2., label=r'Kolmogorov $5/3$') with tf.Session() as sess: x = tf.placeholder(float_type, shape=(3, )) k = tf.placeholder(float_type, shape=(3, )) khat = k / tf.linalg.norm(k) X = tf.concat([khat[None, :], x[None, :]], axis=1) #1,6 theta = tf.constant([6., 14., 1. / 3.], float_type) int_kern = M32(theta) # + RBF(theta/200.) kern = TrapezoidKernel(int_kern, 20, tf.constant(250., float_type), tf.constant(100., float_type), obs_type='DTEC') K = kern.K(X, X) xy = [] z = [] for b in baselines: xy.append([np.concatenate([[b, 0., 0.]], axis=0), [0., 0., 1.]]) # np.concatenate([0.0 * np.random.normal(size=2), [1.]],axis=0) xy[-1][1] /= np.linalg.norm(xy[-1][1]) np_K = sess.run(K, {x: xy[-1][0], k: xy[-1][1]}) z.append(np.sqrt(np_K[0, 0])) xy = np.array(xy) z = 8.448e6 * np.array(z) / 150e6 ax.plot(xy[:, 0, 0], z**2, ls='dotted', lw=2., color='blue', label='dawn') with tf.Session() as sess: x = tf.placeholder(float_type, shape=(3, )) k = tf.placeholder(float_type, shape=(3, )) khat = k / tf.linalg.norm(k) X = tf.concat([khat[None, :], x[None, :]], axis=1) # 1,6 theta = tf.constant([3., 17., 1. / 3.], float_type) int_kern = RBF(theta) # + RBF(theta/200.) kern = TrapezoidKernel(int_kern, 20, tf.constant(350., float_type), tf.constant(200., float_type), obs_type='DTEC') K = kern.K(X, X) xy = [] z = [] for b in baselines: xy.append( [np.concatenate([[b, 0., 0.]], axis=0), [0., 0., 1.]]) # np.concatenate([0.0 * np.random.normal(size=2), [1.]],axis=0) xy[-1][1] /= np.linalg.norm(xy[-1][1]) np_K = sess.run(K, {x: xy[-1][0], k: xy[-1][1]}) z.append(np.sqrt(np_K[0, 0])) xy = np.array(xy) z = 8.448e6 * np.array(z) / 150e6 ax.plot(xy[:, 0, 0], z**2, ls='dashed', lw=2., color='pink', label='dusk') print(z) ax.grid() ax.set_yscale('log') ax.set_xscale('log') ax.set_xlim(0.1, 100.) ax.set_ylim(1e-4, 1e2) ax.set_ylabel(r"$\mathrm{Var}[\phi_{\rm 150}]$ [rad$^2$]") ax.set_xlabel("Baseline [km]") # plt.tricontour(xy[:,0,0],xy[:,1,0], z,levels=10) # plt.title("Over x") ax.legend() plt.savefig("/home/albert/Documents/structure_function.pdf") plt.show() plt.subplot(projection='3d') plt.scatter(xy[:, 1, 0], xy[:, 1, 1], c=z, alpha=0.5, marker='+') plt.tricontour(xy[:, 1, 0], xy[:, 1, 1], z, levels=10) plt.title("Over k") plt.show() diff_scale = [] thetas = np.linspace(0., np.pi / 6., 100) with tf.Session() as sess: x = tf.placeholder(float_type, shape=(3, )) k = tf.placeholder(float_type, shape=(3, )) khat = k / tf.linalg.norm(k) X = tf.concat([khat[None, :], x[None, :]], axis=1) #1,6 theta = tf.constant([10., 14., 1. / 3.], float_type) int_kern = M32(theta) # + RBF(theta/200.) kern = TrapezoidKernel(int_kern, 20, tf.constant(250., float_type), tf.constant(100., float_type), obs_type='DTEC') K = kern.K(X, X) for theta in thetas: xy = [] z = [] for b in baselines: xy.append([ np.concatenate([[b, 0., 0.]], axis=0), [0., np.sin(theta), np.cos(theta)] ]) # np.concatenate([0.0 * np.random.normal(size=2), [1.]],axis=0) xy[-1][1] /= np.linalg.norm(xy[-1][1]) np_K = sess.run(K, {x: xy[-1][0], k: xy[-1][1]}) z.append(np.sqrt(np_K[0, 0])) xy = np.array(xy) z = 8.448e6 * np.array(z) / 150e6 ds = np.interp(1., z, xy[:, 0, 0]) diff_scale.append(ds) fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.plot(np.array(thetas) * 180 / np.pi, diff_scale, lw=2., color='blue') ax.grid() ax.set_ylabel(r'$r_{\rm scale}$ [km]') ax.set_xlabel('Zenith angle [degrees]') plt.savefig('/home/albert/Documents/diffractive_scale.pdf') plt.show()
n_steps=n_steps, lr=1e-3, n_particles=n_particles) losses += swyft.train(network_2d, xz, n_steps=n_steps, lr=1e-4, n_particles=n_particles) # Plot results 1-dim z_lnL = swyft.estimate_lnL(network, x0, swyft.get_z(xz)) plt.clf() plt.plot(z_lnL[0]['z'], np.exp(z_lnL[0]['lnL'])) plt.axvline(0.1) plt.axvline(0.9) plt.savefig("figs/testrun_09a.png") # plot 2-dim results z_lnL = swyft.estimate_lnL_2d(network_2d, x0, swyft.get_z(xz)) lnL = z_lnL['lnL'] z_ij = z_lnL['z'] plt.clf() plt.tricontour([zzz[0] for zzz in z_ij], [zzz[1] for zzz in z_ij], lnL * 2, levels=[-36, -25, -16, -9, -4, -1, 0]) t = np.linspace(0, 6.5, 1000) xc = np.sin(t) * 0.4 + 0.5 yc = np.cos(t) * 0.4 + 0.5 plt.scatter(xc, yc) plt.savefig('figs/testrun_09b.png')
MN = [ 0.1001, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.8999 ] pylab.figure( figsize=(12,12), facecolor='lightgrey' ) axes = [ 0.00, 1.2001, 0.0, 1.0 ] pylab.axis( axes ) pylab.yticks([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) pylab.tick_params(axis='both', which='major', labelsize=16) pylab.ylabel('Area Ratio (Bypass/Tube)', fontsize=18) pylab.xlabel('Bypass Mach Number', fontsize=18) pylab.grid(b=True, which='major', color='grey', linestyle='--') #pylab.title( 'hyperloop' ) pylab.legend(loc="best") CS = pylab.tricontour( MNbyp, AR, MNpod, MN, colors = ['darkblue','red','darkgreen','purple', 'grey','darkorange', 'black', 'lightblue'] ) fmt = {} #tricontour labels strs = [ 'Pod M=0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9' ] for l,s in zip( CS.levels, strs ): fmt[l] = s xx = [0.928, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97] yy = [0.18, 0.34, 0.49, 0.62, 0.75, 0.83, 0.92, 0.96, 0.985] labelpts = zip(xx,yy) pylab.clabel( CS, inline=1,fontsize=14, fmt = fmt , manual=labelpts ) pylab.annotate(" Available pod area \ndecreasing relative to tube", fontsize=16, xy=(1.09, 0.486), xycoords='data', xytext=(0., 0), rotation=90, textcoords='offset points', bbox=dict(boxstyle="square", edgecolor='lightgrey',facecolor='lightgrey') )
def main(num_train, num_test, test_fraction, time_limit, output_folder, num_processes): if test_fraction is None: if num_test is None: raise ValueError( "num_test must be int > 0 if test_fraction is None.") test_fraction = num_test / (num_train + num_test) total_desired = num_train / (1. - test_fraction) logging.info("Total desired examples: {}".format(total_desired)) logging.info("Test fraction: {}".format(test_fraction)) t0 = default_timer() if time_limit is None: time_limit = np.inf logging.info("Simulating with timelimit {} seconds".format(time_limit)) output_folder = os.path.abspath(output_folder) train_folder = os.path.join(output_folder, 'train_examples') test_folder = os.path.join(output_folder, 'test_examples') os.makedirs(train_folder, exist_ok=True) os.makedirs(test_folder, exist_ok=True) logging.info("Using output folder {}".format(output_folder)) num_done = 0 while default_timer() - t0 < time_limit and num_done < total_desired: logging.info("Working on example: {:04d}".format(num_done)) # Create a cluster star_cluster = create_cluster_with_IMF(N=200) star_cluster.position += [-6.5, 0, 0] | units.kpc star_cluster.velocity += [0, 50, 0] | units.kms # Construct the galactic model and make the evolution evolution = RealisticEvolutionCluster(simulation_time=150 | units.Myr) res_dict = evolution.evolution_of_the_cluster(star_cluster) gaia_dict = stars_to_gaia_observables(**res_dict) save_location = os.path.join(train_folder, "example_{:05d}".format(num_done)) # plots plot_location = os.path.join(save_location, 'data_plots') os.makedirs(plot_location, exist_ok=True) for i in range(len(res_dict.keys())): key1 = res_dict.keys()[i] for j in range(i + 1, len(res_dict.keys())): key2 = res_dict.keys()[j] plt.figure(figsize=(6, 6)) plt.scatter(res_dict[key1], res_dict[key2], c='black', marker='+', alpha=0.5) points = np.stack([res_dict[key1], res_dict[key2]], axis=0) kernel = st.gaussian_kde(points) z = kernel(points) plt.tricontour(res_dict[key1], res_dict[key2], z, levels=7, linewidths=0.5, colors='k') plt.xlabel(key1) plt.ylabel(key2) plt.grid() plt.tight_layout() plt.savefig( os.path.join(plot_location, '{}_{}.png'.format(key1, key2))) plt.close('all') with h5py.File(os.path.join(save_location, "starcluster_data.h5"), 'w') as f: for key, value in res_dict.items(): f[key] = np.array(value) with h5py.File(os.path.join(save_location, "gaia_data.h5"), 'w') as f: for key, value in gaia_dict.items(): f[key] = np.array(value)
import pylab class MyDesign(LHSDesign): spec = (('x', (0, 6.28, 'uniform', 10)), ('y', (0, 6.28, 'uniform', 10))) samples = 50 class MyModel: # model can be any class, but it is required to have 'solve' method # which takes sample `d` as argument and returns dict of results `res` def solve(self, d): x, y = d.x, d.y res = {'F': sin(x) * cos(y), 'G': x * y} return res # Evaluate experiments and dump everything to 'test' directory: ex = Experiment(MyDesign(), MyModel(), dirname='test') ex.run() # Plot 'F' x = ex.design.x y = ex.design.y F = ex.result.F pylab.tricontour(x, y, F, levels=14, linewidths=0.5, colors='k') cntr = pylab.tricontourf(x, y, F, levels=14, cmap="RdBu_r") pylab.colorbar(cntr) pylab.plot(x, y, 'ko', ms=3) pylab.title('$\sin(x)\cos(y)$\n (%d LHS samples)' % ex.design.samples)
#slope = np.array([-0.02,-0.01,0.0,0.01,0.02,0.03,0.04]) #flux = np.array([0,2,4,6]) plt.close('all') width = 3.487 * 2 height = width / 1.618 / 2 fig = plt.figure(num=1, figsize=(width, height), facecolor='w', edgecolor='k') fig.subplots_adjust(left=0.073, right=1.05, top=.725, bottom=0.2) #fig.set_size_inches(width, height) #plt.draw() #fig, ax = plt.subplots(constrained_layout=True) dLdt = np.array(dLdt) F = np.array(F) plt.tricontour(S, F / 1e3, dLdt / 1e3, [0], colors='k', linestyles='--') c = plt.tricontourf(S, F / 1e3, dLdt / 1e3, v, cmap='bwr_r', norm=norm, extend='both') #plt.scatter([-0.03],[4],s=50,c=[351.5094769326309 /1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') #plt.scatter([-0.01],[2],s=50,c=[-2137.5210508252835/1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') #plt.scatter([0.0],[5],s=50,c=[487.56420334626046/1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') cbar = plt.colorbar(extend='both', ticks=[vmin, 0, vmax]) #plt.clim([vmin,vmax]) cbar.ax.set_yticklabels([vmin, 0, vmax]) cbar.set_label(r'$dL/dt$ (km/a)')