def determine_application_protocol_for_tcp(source_port,dest_port): if source_port <= dest_port: port = source_port else: port = dest_port return file_reader.read_data_file("TCP ports",port,"unknown application protocol")
def plot_convergence(): """ Code to plot the convergence, also makes a linear model of the points """ runs = read_data_file("data/BucklingBeam.dat") N = [] n_iter = [] for run in runs: N.append(run('N')+1) # +1 since the the matrix is has N-1 x N-1 dims n_iter.append(run('n_iter')) # Number of iterations to reach epsilon slope, const, r_value, p_value, std_err = stats.linregress(np.log10(N), np.log10(n_iter)) with sns.axes_style("darkgrid"): fig, ax = plt.subplots() ax.set(xscale="log", yscale="log") ax.set_xlabel("N", fontsize=14) ax.set_ylabel("Iterations before $\epsilon$", fontsize=14) ax.plot(N, 10**const * N**slope, c="k" ,linestyle="dashed",\ label=f"Linear fit, slope = {slope:.2f}$\pm${std_err:.2f}",marker='o', markersize=3) ax.scatter(N, n_iter) ax.set_xticks([20, 30, 40, 60, 100, 150, 200]) ax.set_xticklabels(["$10$", "$20$", "$40$", "$60$", "$10^2$", r"$1.5 \times 10^2$", "$10^2$"]) """ ax.set_yticks([7e2, 2.6e3, 1e4 ,3e4, 8.8e4]) ax.set_yticklabels([r"$7 \times 10^2$", r"$2.6 \times 10^3$", "$10^4$", r"$3 \times 10^4$", r"$8.8 \times 10^4$"]) """ ax.legend(fontsize=12) plt.show()
def plot_qo_eigvecs(no_electrons, n): """ args: no_electrons: either 'one' or 'two', specifying whether to plot data from one- or two-electron systems. n : energy level to plot (int) """ runs = read_data_file("data/QuantumOscillator_" + no_electrons + ".dat") with sns.axes_style("darkgrid"): fig, ax = plt.subplots() for run in runs: N = run('N') rho_max = run('rho_max') lbl = f"N = {N}" lbl += r", $\rho_{max}$ = " + f"{rho_max}" if no_electrons == 'two': lbl += r", $\omega_r$ = " + f"{run('omega_r')}" lbl += ", $\lambda_{%i}$ = " % n + f"{run.vals[n-1]:.2f}" ground_state = run.vecs[:,n-1] # Getting the eigenvector corresponding to the lowest eigenvalue ground_state *= np.sqrt((N+1)/rho_max) # Normalizing it rho_0 = rho_max / (N+1) rho = np.linspace(rho_0, rho_max - rho_0, N) ax.plot(rho, ground_state**2, label=lbl) ax.set_xlabel(r"$\rho$", fontsize=12) ax.set_ylabel("$|u_{%i,0}(r)|^2$" % n, fontsize=12) ax.legend() plt.show()
def escapeVelocity(n=20, T=100): """ Code to plot different inital velocities in the v_y direction Args: n: (int) Number of orbits/escapes T: (float/int) Total time to run over """ v = np.linspace(2 * np.pi, 3 * np.pi, n, endpoint=True) T = 100 dt = -4 N = np.log10(T) - dt orbits = [] for i in range(n): system_dict = { "Sun": [0, 0, 0, 0, 0, 0], "Earth": [1, 0, 0, 0, v[i], 0] } # Store the different velocities setInitialConditions(f"escape_init_{i}.dat", system_dict) simulate(N=N, dt=dt, Nwrite=1000, sys=f"escape_init_{i}.dat", out=f"escape_{i}.dat", fixSun=True, quiet=True) system = read_data_file(f"escape_{i}.dat") orbits.append(system["Earth"].r) NoOfColors = n colors = list(Color("cyan").range_to(Color("orange"), NoOfColors)) colors = [color.get_rgb() for color in colors] vticks = [round(v_i, 2) for v_i in v] fig, ax = plt.subplots(1, 1) ax.set_facecolor('black') ax.set_xlabel("x [AU]", fontsize=15) ax.set_ylabel("y [AU]", fontsize=15) ax.set(xlim=(-50, 2), ylim=(-26, 26)) for i, r in enumerate(orbits): ax.plot(r[0], r[1], color=colors[i], alpha=0.7) cmap = mpl.colors.ListedColormap(colors) norm = mpl.colors.Normalize(vmin=v[0], vmax=v[-1]) cbar = ax.figure.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, orientation='vertical', ticks=vticks) cbar.ax.set_ylabel(r' $v_y$', rotation=0, fontsize=17) cbar.ax.tick_params(labelsize=13) ax.tick_params(axis='both', which='major', labelsize=12) ax.scatter(0, 0, c="yellow", s=2) ax.text(0, 15.5, ' $v_{esc}$', color="black", fontsize=17) ax.text(-49, 6.5, "$v_{esc}=8.89$ [AU/yr]", color="white", fontsize=14) ax.arrow(-43, 8.5, 4, 4, ec="white", fc="white", head_width=1) plt.show()
def check_escape(): # checks for a given simulation whether the Earth fulfills the escape condition system = read_data_file("escape.dat") # reads simulation data r = system["Earth"].r[:, -1] # grabs last position v = system["Earth"].v[:, -1] # grabs last veloicty v_rad = np.dot(r, v) / np.linalg.norm(r) # calculating the radial velocity escape = v_rad**2 / np.dot( v, v) >= 0.99 # if the velocity is almost solely radial, Earth escaped return escape
def plot_error_vs_rho_N(slash): """ Code to produce 3D plot of error vs rho_max and N Demonstrates how the error (in this case 4 lowest eigenvalues) is dependent on both rho_max and N """ filename = "data/QuantumOscillator_one.dat" if filename.replace("data/", "") in os.listdir("data/"): # If a file is already there, delete it os.remove(filename) N_start, N_end = 100, 200 # start and stop for the matrix sices rho_max_start, rho_max_end = 3.5, 6.5 # start and stop for the rho_maxes to test dN = 5 # space between each matrix sice dRho_max = 0.1 # space between each rho_max N = np.arange(N_start, N_end+dN, dN) # array of all Ns Rho_max = np.arange(rho_max_start, rho_max_end+dRho_max, dRho_max) # array of all rho_maxes error = np.zeros((len(N), len(Rho_max))) # grid to hold error for n in N: # Run the c++ code for rho_max in Rho_max: args = "1 " + str(n) + " " + str(rho_max) + " 1" os.system(slash + "QuantumOscillator.exe " + args) runs = read_data_file(filename, drop_vecs=True) # Read .dat file, excluding eigenvectors due to memory ana_val = np.array([3, 7, 11, 15]) # 4 lowest analytical eigenvalues i, j = 0, 0 # i is the index for each N, j is index for each rho_max for run in runs: num_val = run.vals[:4] # Get 4 lowest eigenvalues err = np.max(np.abs(num_val-ana_val)) # Calc max error of the 4 eigenvalues error[i,j] = err # Store in error grid j += 1 # Go to next rhomax for a N if j == len(Rho_max): # If we have done all rhomax for this N j = 0 i += 1 # Go to next N Rho_max, N = np.meshgrid(Rho_max, N) error = np.log10(error) # Log10 of error due to visibility fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(N, Rho_max, error,cmap="gnuplot") ax.set_xlabel("N", fontsize=13) ax.set_ylabel(r"$\rho_{max}$", fontsize=13) ax.set_zlabel("log10($|\lambda_{num}-\lambda_{ana}|$)", fontsize=13) plt.show()
def read_final_state(filename="precession.dat"): # reads the final datapoints of precession.dat and creates a system-dictionary of them system = read_data_file(filename) rM = system['Mercury'].r[:, -1] vM = system['Mercury'].v[:, -1] rS = system['Sun'].r[:, -1] vS = system['Sun'].v[:, -1] system_dict = { "Sun": [rS[0], rS[1], rS[2], vS[0], vS[1], vS[2]], "Mercury": [rM[0], rM[1], rM[2], vM[0], vM[1], vM[2]] } return system_dict
def getPerihelionAngle(dt, GR=True): # finds the perihelion angle of the last orbit of Mercury around the Sun that has been simulated GR_string = {True: "GR", False: "CLASSIC"}[GR] system = read_data_file(f"prec/final_{dt}_{GR_string}.dat") rM = system['Mercury'].r rS = system['Sun'].r rel_pos = rM - rS # relative position of Mercury and Sun rel_dist = np.linalg.norm(rel_pos, axis=0) # relative distance of Mercury and Sun peridx = rel_dist.argmin( ) # index value for the shortest distance between Mercury and Sun x_peri = rel_pos[0, peridx] y_peri = rel_pos[1, peridx] per_ang = np.rad2deg(np.arctan2( y_peri, x_peri)) # perihelion angle of x-axis in degree return per_ang * 3600 # converts to arcseconds
def plot_bb_eigvectors(run_index=0, vec_start=0, vec_end=0): """ args: run_index: What run (from the BucklingBeam.dat file) to choose vectors from preferably one with N > 100 (for better resolution in the plot) vec_start: The first eigenvector to plot vec_end : Up to and including this eigenvector to plot """ runs = read_data_file("data/BucklingBeam.dat") with sns.axes_style("darkgrid"): fig, ax = plt.subplots() if vec_start == vec_end: # If only one is needed vec_indexes = [0] else: vec_indexes = np.arange(vec_start, vec_end+1) # If multiple make a list with all desired Ns N = runs[run_index]("N") rho = np.linspace(0, 1, N) ana_vec = np.zeros((N, vec_end-vec_start+1)) # Array for the analytical eigenvectors for j in range(vec_end-vec_start+1): # For each vector for i in range(N): # For each vector element ana_vec[i,j] = np.sin((j+1)*(i+1)*np.pi/(N+1)) ana_vec[:,j] /= np.linalg.norm(ana_vec[:,j]) # Normalise the j'th eigenvector for i in vec_indexes: # For each eigenvector num_vecs = runs[run_index].vecs[:,i] # Numerical eigenvectors eigen_val = runs[run_index].vals[i] # Analytical eigenvectors ax.plot(rho, num_vecs, label=f"Eigen Vec: {i+1}") ax.plot(rho, ana_vec[:,i], c="k", \ linestyle="dashed", dashes=(5,10)) ax.set_xlabel(xlabel=r"$\xi$", fontsize=14) ax.set_ylabel(ylabel=r"$u(\xi)$", fontsize=14) ax.legend(fontsize=12) plt.show()
def print_eigenvals(no_electrons, start_idx, stop_idx): """ This function prints a table of the eigenvalues for the specified data. args: no_electrons: either 'one' or 'two'; specifies whether to print the eigenvalues of the one- or two-electron systems start_idx : (int) specifies the first eigenvalue to print, counting as 0, 1, ... stop_idx : (int) specifies the last eigenvalue to print """ runs = read_data_file("data/QuantumOscillator_" + no_electrons + ".dat") no_cols = stop_idx - start_idx + 2 rows = np.zeros((len(runs)+1, no_cols), dtype=object) rows[0,0] = r"Parameters [$N, \rho_\text{max}$]" rows[0,1:] = [r"$\lambda_" + f"{i}$" for i in np.arange(start=start_idx+1, stop=stop_idx+2)] for i, run in enumerate(runs): eigs = ["${:.4f}$".format(eigval) for eigval in run.vals[start_idx:stop_idx+1]] rows[i+1,0] = f"${run('N')}$, ${run('rho_max')}$" rows[i+1,1:] = eigs print_table(rows)
N = np.log10(simYears/10**dt) Nwrite = int(10**N/1000) beta = 2.92 body_dict = {"Sun": [0,0,0,0,0,0], "Earth": [1,0,0,0,5,0]} #sic("varyingBeta.dat", body_dict, fixedCoM=True) #run(f'python3.8 master.py {_dt} {_N} -sys initData/varyingBeta.dat -out beta_{beta}.out -time years -Nwrite {Nwrite} -beta {beta} --log'.split() ) with plt.style.context("seaborn-darkgrid"): f, ax = plt.subplots(1,1, dpi=100,frameon=True) system = read_data_file(f"beta_{beta}.out") x = system["Earth"].r[0,:] y = system["Earth"].r[1,:] cmap=plt.get_cmap('jet') points = np.array([x,y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = mpl.collections.LineCollection(segments, array=np.linspace(0.0, 1.0, len(x)), cmap=cmap, norm=plt.Normalize(0.0, 1.0), linewidth=1) ax.add_collection(lc) cbar = ax.figure.colorbar(mpl.cm.ScalarMappable(norm=plt.Normalize(1.0, 10.0), cmap=cmap), ax=ax, orientation='vertical', ticks=list(range(1,11))) cbar.ax.set_ylabel(r' year', rotation=-36, fontsize=20) ax.set_facecolor((0.15, 0.15, 0.15))
colors_dark = list(Color("cyan", luminance=0.45).range_to(Color("orange", luminance=0.45),bnums)) colors_dark = [color.get_rgb() for color in colors_dark] with plt.style.context("seaborn-darkgrid"): fr, axr = plt.subplots(1,1, dpi=100,frameon=True) fE, axE = plt.subplots(1,1, dpi=100,frameon=True) ls, Es, Eadjs = [], [], [] stdl = np.zeros(len(betas)) stdE = np.zeros(len(betas)) stdEadj = np.zeros(len(betas)) dic = {r"$\beta$":[], r"$\sigma_{\ell}$":[], r"$\bar{\ell}$":[], r"$\sigma_{\mathcal{E}}$":[], r"$\bar{\mathcal{E}}$":[]} for idx,beta in enumerate(betas): beta_ = round(beta,3) system = read_data_file(f"varbeta/{beta_}.out") r1 = system["Earth"].r r0 = system["Sun"].r v1 = system["Earth"].v v0 = system["Sun"].v l = np.linalg.norm(np.cross(r1-r0, v1-v0,axis=-2), axis=-2) ls.append(l) stdl[idx] = np.std(l) E = 1/2*np.linalg.norm(v1-v0,axis=-2)**2 -1/(beta - 1)*GM0*1/((np.linalg.norm(r1-r0, axis=-2))**(beta-1)) Es.append(E) stdE[idx] = np.std(E) maxidx = np.argmax(E) Eadj = np.append(E[:maxidx-1000], E[maxidx+1000:])
import numpy as np import matplotlib.pyplot as plt from file_reader import read_data_file from getInitialConditions import getInitialCondition from subprocess import run # solar_system = ["Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] solar_system = ["Sun", "Mercury", "Earth"] getInitialCondition("FSS_init.dat", bodies=solar_system, fixedCoM=True) T = 365.25 dt = float(1e-4) N = int(T / dt) run(f'python master.py {dt} {N} -sys initData/FSS_init.dat -out FSS.dat -Nwrite 10000 -time days -method verlet' .split()) system = read_data_file("FSS.dat") fig, ax = plt.subplots() NonBodies = ["dt", "N", "N_write", "method", "time"] for body in system: if body not in NonBodies: x = system[body].r[0] y = system[body].r[1] ax.plot(x, y, label=body) ax.axis('equal') ax.legend() plt.show()
def fullSystem(): N = 7 dt = np.log10(10**(-5) * 25) Nwrite = int(1e4) bodynames = [ "Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" ] bodycolors = [ "yellow", "#86511D", "#F7C3F4", "#0EEB58", "red", "orange", "#FCDB0A", "aqua", "blue", "grey" ] gic("fullsystem.dat", bodies=bodynames, fixedCoM=True, date="2018-03-14") simulate(N=N, dt=dt, Nwrite=Nwrite, sys="fullsystem.dat", out="fullsystem.out") system = read_data_file("fullsystem.out") with plt.style.context("seaborn-darkgrid"): fig = plt.figure(figsize=(13, 8), dpi=130) ax = fig.gca(projection='3d') for i, bodyname in enumerate(bodynames): body = system[bodyname] r = body.r v = body.v h = np.cross(r, v, axis=-2) inc = np.mean( np.rad2deg(np.arccos(h[-1, :] / np.linalg.norm(h, axis=-2)))) if i != 0: print(f"Inclination {bodyname}: {round(inc,3)} degr") x, y, z = body.r[0, :], body.r[1, :], body.r[2, :] ax.plot(x, y, z, lw=1, color=bodycolors[i], alpha=0.65, zorder=-1) ax.scatter(x[-1], y[-1], z[-1], color=bodycolors[i], zorder=10, s=18) ax.text(x[-1], y[-1], z[-1], bodyname, color=Color(bodycolors[i], luminance=0.95).rgb, fontsize=12, zorder=1000) ax.set_axis_off() ax.set_facecolor("black") ax.set_title("All bodies over 25 years", color="white") lim = 20 # plot dimensions (AU) zscale = 20 # scaling of z-axis to show inclination ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) ax.set_zlim(-lim / zscale, lim / zscale) plt.show()
def circularOrbit(dt=0.0001, T_end=1, method="verlet", N_write=1000): """ Makes plot of stable Sun/Earth orbit Sun at origin no init vel, earth x = 1 AU vx = 2pi * AU/yr Args: dt: (float) time step in years T_end: (int/float) end time in years method: (string) "euler" or "verlet" N_write: (int) number of points to write to file """ N = int(T_end/dt) if N_write == None: N_write = N body_dict = {"Sun": [0,0,0,0,0,0], "Earth": [1,0,0,0,2*np.pi,0]} # Initial conditions initFilename = "SunEarthStable_init.dat" outFilename = "SunEarthStable_" + "_".join([str(method), str(T_end), str(N), str(N_write)]) + ".dat" # Make filenames check_init(initFilename, body_dict) setInitialConditions(initFilename, body_dict) exists = has_data(outFilename) N = np.log10(N) dt = np.log10(dt) if not exists: # If the datafiles are missing, make them simulate(N=N, dt = dt, method=method, Nwrite=N_write, sys=initFilename, out=outFilename, fixSun=True, quiet=True) system = read_data_file(outFilename) # Reads the data r = system["Earth"].r Ek, Ep = energy(system["Earth"]) # Calculate energy Ek_std, Ep_std = np.std(Ek), np.std(Ep) Ek_mean, Ep_mean = np.mean(Ek), np.mean(Ep) if system["method"] == 0: method = "euler" if system["method"] == 1: method = "verlet" print(f"Method = {method}, dt = {dt:E}, N={N:E}, T_end = {T_end}") print(f"Ek initial = {Ek[0]:.4f}, Ep initial = {Ep[0]:.4f}") print(f"Ek (mean) = {Ek_mean:.4f}, std = {Ek_std:.4E}, relative = {(Ek_std/Ek_mean):.4E}") print(f"Ep (mean) = {Ep_mean:.4f}, std = {Ep_std:.4E}, relative = {(-Ep_std/Ep_mean):.4E}") T = np.linspace(0, T_end, N_write, endpoint=True) with sns.axes_style("darkgrid"): fig, ax = plt.subplots() l = 1.5 ax.set(xlim=(-l,l), ylim=(-l,l)) ax.tick_params(axis='both', which='major', labelsize=13) ax.axis("equal") ax.set_xlabel("x [AU]", fontsize=13) ax.set_ylabel("y [AU]", fontsize=13) ax.scatter(0,0, c="r", label="Sun") ax.plot(r[0], r[1], c="b", label="Earth") ax.legend(fontsize=13) plt.show()
def radialDistance(dt=-4, T=20): """ Plot the radial deviation from Earths orbit without Jupiter Args: dt: (float) step length in years T: (float/int) total time to run the simulation over """ scale_j_mass = [1, 10, 100, 1000] # Hard code in the different scaled masses N = np.log10(T) - dt N_write = 10000 # First run without Jupiter present initFilenameNoJ = "No_jupiter.dat" outFilenameNoJ = f"No_jupiter_{T}_{-dt}.dat" if not initFilenameNoJ in os.listdir("initData"): getInitialCondition(initFilenameNoJ, ["Sun", "Earth"], date="2018-03-14") if not outFilenameNoJ in os.listdir("data"): simulate(N=N, dt=dt, Nwrite=N_write, sys=initFilenameNoJ, out=outFilenameNoJ, fixSun=True, quiet=True) system = read_data_file(outFilenameNoJ) rE_no_j = np.linalg.norm( system["Earth"].r, axis=0) # Earths distance from the sun without Jupiter initFilenames = [f"SEJ_{scale}.dat" for scale in scale_j_mass] outFilenames = [f"SEJ_{T}_{scale}_{N_write}.dat" for scale in scale_j_mass] rE = [ ] # To store the distances with Jupiter present at different scaled masses for i in range(len(scale_j_mass)): if not initFilenames[i] in os.listdir("initData"): getInitialCondition(initFilenames[i], ["Sun", "Earth", "Jupiter"], scaled_mass={"Jupiter": scale_j_mass[i]}) if not outFilenames[i] in os.listdir("data"): simulate(N=N, dt=dt, Nwrite=N_write, sys=initFilenames[i], out=outFilenames[i], fixSun=True, quiet=True) system = read_data_file(outFilenames[i]) R = np.linalg.norm(system["Earth"].r, axis=0) rE.append(R) t = np.linspace(0, T, N_write, endpoint=True) with sns.axes_style("darkgrid"): fig, ax = plt.subplots() for R, lab in zip(rE, scale_j_mass): diff = rE_no_j - R if lab == 1: ax.plot(t, diff, label="$M_J$") else: ax.plot(t, diff, label=f"{lab}$M_J$") diff = np.abs(diff) avg_diff = np.mean(diff) std_diff = np.mean(diff) print( f"Jupiter mass = {lab:5}Mj, Avrage deviation = {avg_diff:.5E}, std = {std_diff:.5E}" ) ax.tick_params(axis='both', which='major', labelsize=13) ax.set_xlabel("Time [yr]", fontsize=14) ax.set_ylabel("Deviation from orbit without Jupiter [AU]", fontsize=14) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.16), ncol=4, fancybox=True, shadow=True, fontsize=14) plt.show()
def determine_application_protocol_for_udp(source_port,dest_port): #toto by slo zlucit do jednej s predoslou if source_port <= dest_port: port = source_port else: port = dest_port return file_reader.read_data_file("UDP ports",port,"unknown application protocol")
def determine_icmp_message(type): return file_reader.read_data_file("ICM types",type,"unknown ICM type")
def determine_transport_protocol(protocol): return file_reader.read_data_file("IP protocols",protocol,"unknown transport protocol")
def ellipticalOrbits(dt=0.0001, T_end=10, n_v = 4, method="verlet", N_write=10000): """ Makes plot of different elliptical orbits Args: dt: (float) Step length in yr T_end: (int/float) Total time to run the simulation n_v: (int) Number of orbits in the range v_y = [pi, 5pi/2] method: (string) Verlet or Euler N_write: (int) How many points to write """ N = int(T_end/dt) if N_write == None: N_write = N VY = np.linspace(np.pi, 5*np.pi/2, n_v, endpoint=True) # Array holding different initial velocities in the y-direction filenames = [f"SunEarthEllip_{n_v}_{i}_{T_end}.dat" for i in range(n_v)] # Storing filenames for i in range(n_v): body_dict = {"Sun": [0,0,0,0,0,0], "Earth": [1,0,0,0,VY[i],0]} check_init(filenames[i], body_dict) exists = has_data(filenames) dt = np.log10(dt) N = np.log10(N) if not exists: for i in range(n_v): simulate(N=N, dt = dt, method=method, Nwrite=N_write, sys=filenames[i], out=filenames[i], fixSun=True, quiet=True) labs = ["$\pi$", "$3\pi/2$", "$2\pi$", "$5\pi/2$"] # Only true if standard parameters are used with sns.axes_style("darkgrid"): fig, ax = plt.subplots() ax.set_xlabel("x [AU]", fontsize=14) ax.set_ylabel("y [AU]", fontsize=14) ax.axis("equal") for i in range(n_v): system = read_data_file(filenames[i]) rE = system["Earth"].r ax.plot(rE[0], rE[1], label=f"$v_y=${labs[i]} AU/yr") ax.scatter(0,0, c="r") ax.tick_params(axis='both', which='major', labelsize=13) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.22), ncol=2, fancybox=True, shadow=True, fontsize=13) plt.show() with sns.axes_style("darkgrid"): fig, ax = plt.subplots() T = np.linspace(0, T_end, N_write, endpoint=True) ax.set_xlabel("Time [yr]", fontsize=14) ax.set_ylabel("Relative error of |$\ell$|", fontsize=14) for i in range(n_v): system = read_data_file(filenames[i]) L = angular_momentum(system["Earth"]) L = np.abs((L[0]-L)/L[0]) ax.plot(T, L, label=f"$v_y=${labs[i]}") ax.tick_params(axis='both', which='major', labelsize=13) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.18), ncol=2, fancybox=True, shadow=True, fontsize=13) plt.show()
def determine_internet_protocol_by_lsap(bytes): lsap = bytes[0] return file_reader.read_data_file( "SAPs", lsap, "unknown internet protocol"), lsap, bytes[3:]
def benchmark(N_start=2, N_end=7, n_tests=50): """ Preform a timing of the two algorithms and make a log-log plot Args: N_start: (int) log10 of the number of integration steps to start at N_end: (int) log10 of the number of integration steps to end at n_tests: (int) number of test between N_start and N_end """ N = np.log10(np.logspace(N_start, N_end, n_tests, endpoint=True, dtype=int)) methods = ["euler", "verlet"] initFilename = "SunEarthStable_init.dat" outFilenames = [] for method in methods: for i in range(n_tests): outFilenames.append(f"SunEarthStable_{method}_{N_start}_{N_end}_{i+1}.dat") body_dict = {"Sun": [0,0,0,0,0,0], "Earth": [1,0,0,0,2*np.pi,0]} check_init(initFilename, body_dict) exists = has_data(outFilenames) i = 0 tot = 2*n_tests if not exists: # If datafiles are missing, make them for method in methods: for n_ in N: dt_ = -n_ simulate(N=n_, dt = dt_, method=method, Nwrite=2, sys=initFilename, out=outFilenames[i], fixSun=True, quiet=True) i += 1 print(f"Done {method}, dt = {n_}, {(i*100/tot):.2f}%") # It takes a while... good to know where your at eulerTime = [] verletTime = [] for outfile in outFilenames: # Sort through files and place the time in euler and verlet system = read_data_file(outfile) if system["method"] == 0: eulerTime.append(system["time"]) if system["method"] == 1: verletTime.append(system["time"]) eulerTime = np.array(eulerTime) # For easier handling verletTime = np.array(verletTime) with sns.axes_style("darkgrid"): fig, ax = plt.subplots() ax.set(xscale="log", yscale="log") ax.tick_params(axis='both', which='major', labelsize=13) ax.set_xlabel(xlabel="N", fontsize=15) ax.set_ylabel(ylabel="Time taken [s]", fontsize=15) ax.scatter(N, eulerTime, label="Euler") ax.scatter(N, verletTime, label="Verlet") # Only linfit if standard params (as some points have to be excluded) if all([val is benchmark.__defaults__[i] for i, val in enumerate([N_start,N_end,n_tests])]): sE, eE = 25, len(N) # What points to fit Euler sV, eV = 25, len(N) # What point to fit Verlet slopeE, constE, r_valueE, p_valueE, std_errE = stats.linregress(np.log10(N[sE:eE]), np.log10(eulerTime[sE:eE])) # Linfit for Verlet slopeV, constV, r_valueV, p_valueV, std_errV = \ stats.linregress(np.log10(N[sV:eV]), np.log10(verletTime[sV:eV])) # Plot Euler and Verlet linfit ax.plot(N[sE:eE], 10**constE * N[sE:eE]**slopeE, c="red",\ label=f"Slope Euler = {slopeE:.3f}$\pm${std_errE:.3f} \n $R^2$ = {(r_valueE**2):.4f}", markersize=3) ax.plot(N[sV:eV], 10**constV * N[sV:eV]**slopeV, c="k" ,\ label=f"Slope Verlet = {slopeV:.3f}$\pm${std_errV:.3f} \n $R^2$ = {(r_valueV**2):.4f}", markersize=3) ax.legend(fontsize=13) plt.show()
sic("stability.dat", body_dict) for dt_, N_ in zip(dt,N): pass run(f'python3.8 master.py {dt_} {N_} -sys initData/stability.dat -out {-dt_}.{N_}.out -Nwrite {int(1e5)} -time years --log'.split() ) colors = list(Color("cyan").range_to(Color("orange"),len(dt))) colors = [str(color) for color in colors] with plt.style.context("seaborn-darkgrid"): f, ax = plt.subplots(1,1, dpi=100,frameon=True) dic = {r"$\beta$":[r"$\log_{10} \sigma_{\mathcal{E}}$",r"$\log_{10}\sigma_{\ell}$"]} for idx,(dt_,N_) in enumerate(zip(dt,N)): if idx == 0: continue system = read_data_file(f"{-dt_}.{N_}.out") r1 = system["Earth"].r r0 = system["Sun"].r v1 = system["Earth"].v v0 = system["Sun"].v dist = np.linalg.norm(r1-r0, axis=-2) ax.plot(np.linspace(dt[0]*N[0], dt[-1]*N[-1], len(dist)), dist,color=colors[idx], lw=2, alpha=0.4) ax.set_facecolor((0.15, 0.15, 0.15)) ax.set_xlabel("$x$ [AU]") ax.set_ylabel("$y$ [AU]") #ax.set_ylim(top=1.1, bottom=-1.1) #ax.set_xlim(-1.1, 1.1)
N = 7 dt = np.log10(10**(-7) * 25) Nwrite = int(1e4) bodynames = [ "Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" ] bodycolors = [ "yellow", "#86511D", "#F7C3F4", "#0EEB58", "red", "orange", "#FCDB0A", "aqua", "blue", "grey" ] #getInitialCondition("fullsystem.dat", bodies=bodynames, fixedCoM=False, timeFormat = "years", date="2018-03-14") #run(f"python3.8 master.py {dt} {N} --log -time years -Nwrite {Nwrite} -sys initData/fullsystem.dat -out fullsystem.out --GR".split()) system = read_data_file("fullsystem.out") with plt.style.context("seaborn-darkgrid"): fig = plt.figure(figsize=(13, 8), dpi=130) ax = fig.gca(projection='3d') for i, bodyname in enumerate(bodynames): body = system[bodyname] r = body.r v = body.v h = np.cross(r, v, axis=-2) inc = np.mean( np.rad2deg(np.arccos(h[-1, :] / np.linalg.norm(h, axis=-2)))[-1]) print(f"Inclination {bodyname}: {round(inc,3)} degr") x, y, z = body.r[0, :], body.r[1, :], body.r[2, :]
def sunEarthJupiter(dt=-4, T=15, jupiter_scale=1000): """ Plot the Sun-Earth-Jupiter system Args: dt: (float) step length in AU/yr T: (float/int) how long to run the simulation in years jupiter_scale: (int/float) In case you want to scale Jupiters mass up/down """ N = np.log10(T) - dt N_write = 10000 initFilename = f"SEJ_{jupiter_scale}.dat" outFilename = f"SEJ_{T}_{jupiter_scale}_{N_write}.dat" bodies = ["Sun", "Earth", "Jupiter"] scaled_mass = {"Jupiter": jupiter_scale} if not initFilename in os.listdir("initData"): getInitialCondition(initFilename, bodies, fixedCoM=False, scaled_mass=scaled_mass, date="2018-03-14") if not outFilename in os.listdir("data"): simulate(N=N, dt=dt, Nwrite=1000, sys=initFilename, out=outFilename, fixSun=True, quiet=True) system = read_data_file(outFilename) rS = system["Sun"].r rE = system["Earth"].r - rS rJ = system["Jupiter"].r - rS l = np.max(rJ) + np.max( rJ) / 10 # Make plot just a little bigger than Jupiters orbit bodynames = ["Earth", "Jupiter"] bodycolors = ["#0EEB58", "orange"] fig = plt.figure() fig.set_facecolor('black') ax = fig.add_subplot(111, projection='3d') ax.set_facecolor('black') ax.grid(False) ax.w_xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.w_yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.w_zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.set(xlim=(-l, l), ylim=(-l, l), zlim=(-l, l)) ax.scatter(0, 0, c="yellow", label="Sun") ax.plot(rE[0, 1:], rE[1, 1:], rE[2, 1:], c="#0EEB58", label="Earth") ax.plot(rJ[0], rJ[1], rJ[2], c="orange", label="Jupiter") ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), ncol=3, fancybox=True, shadow=True, fontsize=15) plt.show()
def determine_internet_protocol_by_ethertype(ethertype): return file_reader.read_data_file("EtherTypes", ethertype, "unknown internet protocol")
def error(dt_start=3, dt_end=7, n_tests=20): """ Making a plot of the relative error in the total energy of the two algorithms Args: dt_start: (int) -log10 of what dt to start at dt_end: (int) -log10 of what dt to end at n_tests: (int) number of tests to preform between dt_start and dt_end """ dt = np.linspace(dt_start, dt_end, n_tests, endpoint=True)*-1 N = -dt methods = ["euler", "verlet"] initFilename = "SunEarthStable_init.dat" outFilenames = [] for method in methods: for i in range(n_tests): outFilenames.append(f"SunEarthStable_{method}_{dt_start}_{dt_end}_{i+1}.dat") body_dict = {"Sun": [0,0,0,0,0,0], "Earth": [1,0,0,0,2*np.pi,0]} setInitialConditions(initFilename, body_dict) check_init(initFilename, body_dict) exists = has_data(outFilenames) i = 0 tot = 2*n_tests if not exists: # If files are missing, create them for method in methods: for N_, dt_ in zip(N,dt): simulate(N=N_, dt = dt_, method=method, Nwrite=2, sys=initFilename, out=outFilenames[i], fixSun=True, quiet=True) i += 1 print(f"{method}, log10(dt)={dt_:.2f}, log10(N)={N_:.2f}, {(i*100/tot):.1f}%") # Again, migth take a while N = 10**N dt = 10**dt systems = [] eulerError = [] verletError = [] for outfile in outFilenames: # Sort through files and place the error in euler and verlet system = read_data_file(outfile) Ek, Ep = energy(system["Earth"]) E = Ek+Ep error = np.abs((E[0]-E[-1])/E[0]) if system["method"] == 0: eulerError.append(error) if system["method"] == 1: verletError.append(error) with sns.axes_style("darkgrid"): fix, ax = plt.subplots() ax.invert_xaxis() ax.tick_params(axis='both', which='major', labelsize=13) ax.set_xlabel("$h$ [yr]", fontsize=14) ax.set_ylabel("Relative error of $E_{tot}$", fontsize=14) ax.set(xscale="log", yscale="log") ax.scatter(dt, eulerError, label="$E_{tot}$ Euler") ax.scatter(dt, verletError, label="$E_{tot}$ Verlet") slope, const, r_value, p_value, std_err = stats.linregress(np.log10(dt), np.log10(eulerError)) ax.plot(dt, 10**const * dt**slope, c="k" ,linestyle="dashed",\ label=f"s = {slope:.3f}$\pm${std_err:.3f} \n$R^2$ = {(r_value**2):.5f}") ax.legend(fontsize=13, loc=6) plt.show()