def plot_perc_scaling(q, sizes=np.logspace(1,2,50,dtype=int)): """Count the number of cells filled across range of sizes. q: proportion of porous cells sizes: iterable of array sizes """ res = [] for size in sizes: perc = Percolation(size, q) if test_perc(perc): num_filled = perc.num_wet() - size res.append((size, size**2, num_filled)) sizes, cells, filled = zip(*res) options = dict(linestyle='dashed', color='gray', alpha=0.7) fig, ax = plt.subplots() ax.plot(sizes, cells, label='d=2', **options) ax.plot(sizes, filled, 'k.', label='filled') ax.plot(sizes, sizes, label='d=1', **options) decorate( xlabel = 'Array Size', ylabel = 'Cell Count', xscale = 'log', xlim = [9, 110], yscale = 'log', ylim = [9, 20000], loc = 'upper left') plt.show() for ys in [cells, filled, sizes]: params = linregress(np.log(sizes), np.log(ys)) print('Slope of lines:\n', params[0])
def compare_fb_to_ba(): """Plots Facebook network data vs. Barabasi-Albert network of same size""" dirname = '/Users/bensmith/Documents/ThinkSeries/ThinkComplexity2/data/' fin = dirname + 'facebook_combined.txt.gz' fb = read_graph(fin) print('Facebook') n, k, pmf_fb = analyze_graph(fb) ba = barabasi_albert_graph(n, k, seed=15) print('Barabasi-Albert') n, k, pmf_ba = analyze_graph(ba) plt.figure(figsize=(8,4)) options = dict(ls='', marker='.') plt.subplot(1,2,1) plt.plot([20, 1000], [5e-2, 2e-4], color='gray', linestyle='dashed') pmf_fb.plot(label='Facebook', color='C0', **options) decorate(xlabel='Degree', ylabel='PMF', xscale='log', yscale='log') plt.subplot(1,2,2) pmf_ba.plot(label='BA graph', color='C1', **options) decorate(xlabel='Degree', xscale='log', yscale='log') savefig('myfigs/chap04-2') plt.show()
def evol_dphre(P): mss = [-0.1, 0, 0.2, 1] alphas = np.arange(ut.rad_of_deg(-10), ut.rad_of_deg(20), ut.rad_of_deg(1)) km = 0.1 for ms in mss: P.set_mass_and_static_margin(km, ms) dphrs = [] dphrs = np.array([(P.ms * P.CLa * (alpha - P.a0) - P.Cm0) / P.Cmd for alpha in alphas]) plt.plot(ut.deg_of_rad(alphas), ut.deg_of_rad(dphrs)) legends = ['ms {}'.format(ms) for ms in mss] ut.decorate(plt.gca(), "Evolution de DPHRe en fonction de l'incidence", 'Incidence', 'Delta de braquage équilibré', legend=legends) plt.figure() Vts = [0.9, 1, 1.1] for Vt in Vts: P.Vt = Vt P.Cmd = -P.Vt * P.CLat dphrs = np.array([(P.ms * P.CLa * (alpha - P.a0) - P.Cm0) / P.Cmd for alpha in alphas]) plt.plot(ut.deg_of_rad(alphas), ut.deg_of_rad(dphrs)) legends = ['Vt {}'.format(Vt) for Vt in Vts] ut.decorate(plt.gca(), "Evolution de DPHRe en fonction de l'incidence", 'Incidence', 'Delta de braquage équilibré', legend=legends) plt.show()
def polaire_equi(P): q = 0 mss = [0.2, 1] alphas = np.arange(ut.rad_of_deg(-10), ut.rad_of_deg(20), ut.rad_of_deg(1)) km = 0.1 for ms in mss: P.set_mass_and_static_margin(km, ms) dphrs = [] dphrs = np.array([(P.ms * P.CLa * (alpha - P.a0) - P.Cm0) / P.Cmd for alpha in alphas]) CLe = [] CLe = [ dyn.get_aero_coefs(dyn.va_of_mach(0.7, 7000), alpha, q, dphr, P)[0] for alpha, dphr in zip(alphas, dphrs) ] Cxe = [ dyn.get_aero_coefs(dyn.va_of_mach(0.7, 7000), alpha, q, dphr, P)[1] for alpha, dphr in zip(alphas, dphrs) ] finesse = [CL / Cx for Cx, CL in zip(Cxe, CLe)] fmax = np.max(finesse) idmax = np.argmax(finesse) print(fmax) plt.plot([0, Cxe[idmax]], [0, CLe[idmax]]) plt.plot(Cxe, CLe) label1 = patches.Patch(color='blue', label='fmax (ms = 0.2)') label2 = patches.Patch(color='green', label='Polaire (ms = 0.2)') label3 = patches.Patch(color='red', label='fmax (ms = 1)') label4 = patches.Patch(color='cyan', label='Polaire (ms = 1)') plt.legend(loc='upper left', handles=[label1, label2, label3, label4]) ut.decorate(plt.gca(), "Evolution de la polaire équilibrée", 'Coefficient de trainée équilibrée', 'Coefficient de portance équilibrée') plt.show
def encryptFile(self, input_f): try: key = self.key delimiter = self.delimiter size = int(self.GetSize(input_f)) crypt_f = input_f + '.crypt' cipher = Blowfish(key) print '' decorate(' Encrypting ' + input_f + '...', 64, '-') with open(input_f, 'rb') as f1: with open(crypt_f, 'wb') as f2: for i in tqdm(range(size)): t = f1.read(1) u = cipher.encrypt(str( base64.b64encode(t) * 2)) + delimiter f2.write(u) f1.close() f2.close() self.cleanUp(input_f) except Exception as e: print e, 'exception caught while encrypting', input_f finally: decorate('Success', 64, '-')
def plot_fire_scaling(p, f, sizes=np.logspace(1.5, 3, 6, dtype=int)): """Count the number of trees and number of burning trees in stable forest fire. p: proportion of trees added each step f: proportion of new fires added each step sizes: iterable of array sizes """ res = [] for size in sizes: fire = ForestFire(size, p, f) n_trees, n_burning = test_fire(fire) res.append((size, size**2, n_trees, n_burning)) sizes, cells, trees, burning = zip(*res) options = dict(linestyle='dashed', color='gray', alpha=0.7) fig, ax = plt.subplots() ax.plot(sizes, cells, label='d=2', **options) ax.plot(sizes, trees, 'k.', label='Trees') ax.plot(sizes, burning, 'r.', label='Burning') ax.plot(sizes, sizes, label='d=1', **options) decorate(xlabel='Array Size', ylabel='Cell Count', xscale='log', xlim=[10, 2000], yscale='log', ylim=[3, 2000000], loc='upper left') for ys in [cells, trees, burning, sizes]: params = linregress(np.log(sizes), np.log(ys)) print('Slope of lines:\n', params[0]) return fig
def test_fractal(rule, ax=None, plotting=False, ylabel='Number of Cells'): """Compute the fractal dimension of a rule. rule: int rule for Wolfram's 1-D CA ax: matplotlib.Axes ylabel: string returns: ax: matplotlib.Axes """ res = count_cells(rule) steps, steps2, cells = zip(*res) for ys in [cells]: params = linregress(np.log(steps), np.log(ys)) print('Slope of Rule %i: ' % rule, params[0]) if plotting: if ax == None: fig, ax = plt.subplots() options = dict(linestyle='dashed', color='gray', alpha=0.7) ax.plot(steps, steps2, label='d=2') ax.plot(steps, cells, label='Rule %i' % rule) ax.plot(steps, steps, label='d=1') decorate( xscale='log', yscale='log', xlabel='Time Steps', ylabel=ylabel, xlim = [1,600], loc='upper left') return ax, params[0], rule
def encryptFile(self, input_f): try: key = self.key delimiter = self.delimiter size=int(self.GetSize(input_f)) crypt_f=input_f+'.crypt' cipher = Blowfish(key) print '' decorate(' Encrypting ' + input_f + '...', 64, '-') with open(input_f,'rb') as f1: with open(crypt_f,'wb') as f2: for i in tqdm(range(size)): t= f1.read(1) u = cipher.encrypt(str(base64.b64encode(t)*2))+delimiter f2.write(u) f1.close() f2.close() self.cleanUp(input_f) except Exception as e: print e, 'exception caught while encrypting', input_f finally: decorate('Success', 64, '-')
def plot_CL(P, filename=None): alphas = np.linspace(ut.rad_of_deg(-10), ut.rad_of_deg(20), 30) dms = np.linspace(ut.rad_of_deg(20), ut.rad_of_deg(-30), 3) figure = ut.prepare_fig(None, u'Coefficient de Portance {}'.format(P.name)) for dm in dms: plt.plot(ut.deg_of_rad(alphas), CL(P, alphas, dm)) ut.decorate(plt.gca(), u'Coefficient de Portance', r'$\alpha$ en degres', '$C_L$') plt.legend(['$\delta _{{PHR}} = ${:.1f}'.format(ut.deg_of_rad(dm)) for dm in dms], loc='best') if filename<> None: plt.savefig(filename, dpi=160)
def plot_Cm(P, filename=None): alphas = np.linspace(ut.rad_of_deg(-10), ut.rad_of_deg(20), 30) mss = np.array([-0.1, 0, 0.2, 1]) figure = ut.prepare_fig(None, u'Coefficient du moment de tangage {}'.format(P.name)) for ms1 in mss: plt.plot(ut.deg_of_rad(alphas), Cm(P, alphas, ms1)) ut.decorate(plt.gca(), u'Coefficient du moment de tangage', r'$\alpha$ en degres', '$C_m$') plt.legend(['ms = {}'.format(ms) for ms in mss], loc='best') if filename<> None: plt.savefig(filename, dpi=160)
def plot_result(index, **options): """Plot the results of the indicated instrument. index: int """ sim.plot(index, **options) instrument = sim.instruments[index] print('Mean ', instrument.label, np.mean(instrument.metrics[:])) decorate(xlabel='Time steps', ylabel=instrument.label)
def metabolism_distribution(env): """Make CDF of metabolism distribution. env: Sugarscape """ cdf = Cdf.from_seq(agent.metabolism for agent in env.agents) cdf.plot() decorate(xlabel='Metabolism', ylabel='CDF') plt.show(block=True)
def vision_distribution(env): """Make CDF of vision distance. env: Sugarscape """ cdf = Cdf.from_seq(agent.vision for agent in env.agents) cdf.plot() decorate(xlabel='Vision', ylabel='CDF') plt.show(block=True)
def plot_dphr_e(P, filename=None): alphas = np.linspace(ut.rad_of_deg(-10), ut.rad_of_deg(20), 30) mss = [-0.1, 0., 0.2, 1.] figure = ut.prepare_fig(None, u'Équilibre {}'.format(P.name)) for ms in mss: P.set_mass_and_static_margin(0.5, ms) dmes = np.array([dphr_e(P, alpha) for alpha in alphas]) plt.plot(ut.deg_of_rad(alphas), ut.deg_of_rad(dmes)) ut.decorate(plt.gca(), r'$\delta_{PHR_e}$', r'$\alpha$ en degres', r'$\delta_{PHR_e}$ en degres', ['$ms = ${: .1f}'.format(ms) for ms in mss])
def plot_fitnesses(sim): """Plot the CDF of fitnesses. sim: Simulation object """ fits = sim.get_fitnesses() cdf_fitness = Cdf.from_seq(fits) print('Mean fitness\n', np.mean(fits)) cdf_fitness.plot() decorate(xlabel='Fitness', ylabel='CDF') plt.show(block=True)
def plot_CLe(P): alphas = np.linspace(ut.rad_of_deg(-10), ut.rad_of_deg(20), 30) figure = ut.prepare_fig(None, u'Coefficient de portance équilibrée {}'.format(P.name)) sms = [0.2, 1] for sm in sms: P.set_mass_and_static_margin(0.5, sm) dphres = [dphr_e(P, alpha) for alpha in alphas] CLes = [CL(P, alpha, dphr) for alpha, dphr in zip(alphas, dphres)] plt.plot(ut.deg_of_rad(alphas), CLes) ut.decorate(plt.gca(), u'Coefficient de portance équilibrée', r'$\alpha$ en degres', r'$CL_e$', ['$ms = ${: .1f}'.format(sm) for sm in sms])
def plot(time, X, U=None, figure=None, window_title="Trajectory"): figure = ut.prepare_fig(figure, window_title, (20.48, 10.24)) plots = [("$y$", "m", X[:, s_y], None), ("$h$", "m", X[:, s_h], 2.), ("$v_a$", "m/s", X[:, s_va], 1.), ("$\\alpha$", "deg", ut.deg_of_rad(X[:, s_a]), 2.), ("$\\theta$", "deg", ut.deg_of_rad(X[:, s_th]), 2.), ("$q$", "deg/s", ut.deg_of_rad(X[:, s_q]), 2.)] for i, (title, ylab, data, min_yspan) in enumerate(plots): ax = plt.subplot(3, 2, i + 1) plt.plot(time, data) ut.decorate(ax, title=title, ylab=ylab, min_yspan=min_yspan) return figure
def plot_polar(P): alphas = np.linspace(ut.rad_of_deg(-10), ut.rad_of_deg(20), 30) figure = ut.prepare_fig(None, u'Polaire équilibrée{}'.format(P.name)) sms = [0.2, 1] for sm in sms: P.set_mass_and_static_margin(0.5, sm) dphres = [dphr_e(P, alpha) for alpha in alphas] CLes = [CL(P, alpha, dphr) for alpha, dphr in zip(alphas, dphres)] CDes = [P.CD0 + P.ki * CL1**2 for CL1 in CLes] plt.plot(CDes, CLes) ut.decorate(plt.gca(), u'Polaire équilibrée', r'$CD_e$', r'$CL_e$', ['$ms = ${: .1f}'.format(sm) for sm in sms])
def plot(self, n_col=7): margins = (0.08, 0.06, 0.97, 0.95, 0.15, 0.33) fig = utils.prepare_fig(window_title='database', margins=margins) n_row = int(math.ceil(len(self.ms) / float(n_col))) + 2 for i in range(n_row): for j in range(n_col): k = i * n_col + j if k >= len(self.ms): break ax = plt.subplot(n_row, n_col, k + 1) _m = self.ms[k]['marker'] plt.scatter(_m.pts[:, 0], _m.pts[:, 1]) plt.scatter(_m.Xc[0], _m.Xc[1], color='r') s = 0.025 #pdb.set_trace() has = ax.arrow(_m.Xc[0], _m.Xc[1], _m.smallest_evec[0] * s, _m.smallest_evec[1] * s, head_width=0.005, head_length=0.01, fc='g', ec='k', alpha=0.5) hal = ax.arrow(_m.Xc[0], _m.Xc[1], _m.largest_evec[0] * s, _m.largest_evec[1] * s, head_width=0.005, head_length=0.01, fc='r', ec='k', alpha=0.5) leg = plt.legend(handles=[has, hal], labels=['smallest ev', 'largest ev']) leg.get_frame().set_alpha(0.2) utils.decorate(ax, title=_m.name, xlab='x', ylab='y') #, legend=['1', '2']) ax.set_aspect('equal') for i in range(n_col): ax = plt.subplot(n_row, n_col, n_col + i + 1) m = self.ms[i]['marker'] plt.scatter(m.pts_c2[:, 0], m.pts_c2[:, 1]) ax.set_aspect('equal') utils.decorate(ax, title='normalized', xlab='x', ylab='y') ax = plt.subplot(n_row, 1, n_row) plt.text(0.5, 0.5, "{}".format(self.inter_marker_dists), family='monospace')
def compare_drivers(eps=0.0): """Compare different driver constructors. """ for constructor in [Driver, BetterDriver]: xs, ys = run_simulation(eps=eps, constructor=constructor) plt.plot(xs, ys, label=constructor.__name__) decorate(xlabel='Number of cars', ylabel='Average speed', xlim=[0, 100], ylim=[0, 42]) plt.show(block=True)
def plot_thrust(P, filename=None): figure = ut.prepare_fig(None, u'Poussée {}'.format(P.name)) hs = np.linspace(3000, 11000, 5) for h in hs: Machs = np.linspace(0.5, 0.8, 30) thrusts = np.zeros(len(Machs)) for i in range(0, len(Machs)): thrusts[i] = dyn.propulsion_model([0, h, dyn.va_of_mach(Machs[i], h), 0, 0, 0], [0, 1., 0, 0], P) plt.plot(Machs, thrusts) ut.decorate(plt.gca(), u'Poussée maximum {}'.format(P.name), r'Mach', '$N$', ['{} m'.format(h) for h in hs]) if filename<> None: plt.savefig(filename, dpi=160) return figure
def seg_v_steps_bishop(k): """Plot segregation vs k.""" np.random.seed(17) grid = Bishop(100, 1) res = [] for s in range(k): res.append(grid.step()) plt.plot(res, label='Segregation') decorate(xlabel='Moves', ylabel='Segregation') savefig('myfigs/chap09-5') plt.show(block=True)
def plot_short(time, X, U, figure=None, window_title="trajectory"): margins = (0.06, 0.05, 0.98, 0.96, 0.20, 0.34) figure = utils.prepare_fig(figure, window_title, figsize=(0.75 * 20.48, 0.75 * 10.24), margins=margins) plots = [("x", "m", X[:, Plant.s_x]), ("$\\theta$", "deg", utils.deg_of_rad(X[:, Plant.s_theta])), ("$\\tau$", "N.m", U[:, Plant.i_t])] for i, (title, ylab, data) in enumerate(plots): ax = plt.subplot(3, 1, i + 1) plt.plot(time, data, linewidth=2) utils.decorate(ax, title=title, ylab=ylab) return figure
def evol_poussee(P): U = [0, 1, 0, 0] hs = np.linspace(3000, 11000, 5) machs = np.linspace(0.5, 0.8, 30) for h in hs: Poussee = [ dyn.propulsion_model([0, h, dyn.va_of_mach(mach, h), 0, 0, 0], U, P) for mach in machs ] plt.plot(machs, Poussee) ut.decorate(plt.gca(), title='Poussée maximale en fonction du Mach', xlab='Mach', ylab='Poussee (N)', legend=['{} m'.format(h) for h in hs]) plt.show()
def plot_ws_experiment(ps, data): L, C = np.transpose(data) print('L\n', L) print('C\n', C) L /= L[0] C /= C[0] plt.plot(ps, C, 's-', linewidth=1, label='C(p) / C(0)') plt.plot(ps, L, 'o-', linewidth=1, label='L(p) / L(0)') decorate(xlabel='Rewiring probability (p)', xscale='log', title='Normalized clustering coefficient and path length', xlim=[0.00009, 1.1], ylim=[-0.01, 1.01]) savefig('myfigs/chap03-3') plt.show()
def speed_v_eps(): """Plot speed versus epsilon for range of drivers. """ np.random.seed(20) set_palette('Blues', 4, reverse=True) for eps in [0.0, 0.001, 0.01]: xs, ys = run_simulation(eps) plt.plot(xs, ys, label='eps=%g' % eps) decorate(xlabel='Number of cars', ylabel='Average speed', xlim=[0, 100], ylim=[0, 42]) savefig('myfigs/chap10-2') plt.show(block=True)
def wealth_distribution(env, plot=True): """Make CDF of sugar distribution. env: Sugarscape """ qs = [0.25, 0.5, 0.75, 0.9] cdf = Cdf.from_seq(agent.sugar for agent in env.agents) for q in qs: print('Wealth of {:.0%}'.format(q), end='') print(': %i' %cdf.quantile(q)) if plot: cdf.plot() decorate(xlabel='Wealth', ylabel='CDF') plt.show(block=True) return cdf
def plot_poles(aicraft, hs, Mas, sms, kms, filename=None): ''' Affichage graphique de la position des poles pour une série de points de trim ''' margins = (0.03, 0.05, 0.98, 0.95, 0.2, 0.38) fig = ut.prepare_fig(window_title='Poles {}'.format(aircraft.name), figsize=(20.48, 10.24), margins=margins) for i, h in enumerate(hs[::-1]): for j, Ma in enumerate(Mas): ax = plt.subplot(len(hs), len(Mas), i*len(Mas)+j+1) legend = [] for k, sm in enumerate(sms): for l, km in enumerate(kms): A, B, poles, vect_p = get_linearized_model(aicraft, h, Ma, sm, km) print('{}'.format(poles)) plt.plot(poles.real, poles.imag, '*', markersize=10) legend.append('ms={} km={}'.format(sm, km)) ut.decorate(ax, r'$h={}m \quad Ma={}$'.format(h, Ma), legend=legend, xlim=[-3., 0.1]) if filename<> None: plt.savefig(filename, dpi=160)
def plot_marker(m, label_points=True, plot_pc=False): margins = (0.08, 0.06, 0.97, 0.95, 0.15, 0.33) fig = utils.prepare_fig(window_title='{}'.format(m.name), figsize=(10.24, 10.24), margins=margins) ax = plt.subplot(1, 2, 1) plt.scatter(m.pts[:, 0], m.pts[:, 1]) plt.scatter(m.Xc[0], m.Xc[1], color='r') if label_points: for i, p in enumerate(m.pts): ax.text(p[0], p[1], '{}'.format(i)) if plot_pc: s = 0.25 * m.scale ax.arrow(m.Xc[0], m.Xc[1], m.smallest_evec[0] * s, m.smallest_evec[1] * s, head_width=0.005, head_length=0.01, fc='g', ec='g', alpha=0.5) ax.arrow(m.Xc[0], m.Xc[1], m.largest_evec[0] * s, m.largest_evec[1] * s, head_width=0.005, head_length=0.01, fc='r', ec='r', alpha=0.5) plt.plot(m.pts[:, 0], m.pts[:, 1]) utils.decorate(ax, title='original', xlab='x', ylab='y') ax.set_aspect('equal') ax = plt.subplot(1, 2, 2) n_pts = m.pts_c1 #m.pts_c2 plt.scatter(n_pts[:, 0], n_pts[:, 1]) plt.scatter(0, 0, color='r') if label_points: for i, p in enumerate(n_pts): ax.text(p[0], p[1], '{}'.format(i)) utils.decorate(ax, title="normalized") ax.set_aspect('equal')
def trees_vs_time(m, p, f, iters): fire = ForestFire(m, p, f) res = [] for step in range(iters): res.append((step, 40 * fire.num_burning(), fire.num_trees())) fire.step() steps, burning, trees = zip(*res) fig, ax = plt.subplots() ax.plot(steps, burning, label='40 x Burning') ax.plot(steps, trees, label='Trees') decorate(xlabel='Step', xlim=[0, iters], ylim=[0, 0.5 * m**2], loc='upper left') return fig
def seg_v_steps(): """Plot segregation vs time steps for different p values. """ np.random.seed(17) set_palette('Blues', 5, reverse=True) print('p Final segregation value Final seg val - p') for p in [0.5, 0.4, 0.3, 0.2]: grid = Schelling(100, p) segs = [grid.step() for i in range(12)] plt.plot(segs, label='p = %.1f' % p) print(p, segs[-1], segs[-1] - p) decorate(xlabel='Time Steps', ylabel='Segregation', loc='lower right', ylim=[0, 1]) savefig('myfigs/chap09-2') plt.show()
def evol_Cm(P): ms = [-0.1, 0, 0.2, 1] dphr = 0 alphas = np.arange(ut.rad_of_deg(-10), ut.rad_of_deg(20), ut.rad_of_deg(1)) Cm_tab1 = [] Cm_tab2 = [] Cm_tab3 = [] Cm_tab4 = [] q = 0 for alpha in alphas: Cm1 = P.Cm0 - ms[0] * P.CLa * (alpha - P.a0) + P.Cmq * P.lt / dyn.va_of_mach( 0.7, 7000) * q + P.Cmd * dphr Cm_tab1.append(Cm1) Cm2 = P.Cm0 - ms[1] * P.CLa * (alpha - P.a0) + P.Cmq * P.lt / dyn.va_of_mach( 0.7, 7000) * q + P.Cmd * dphr Cm_tab2.append(Cm2) Cm3 = P.Cm0 - ms[2] * P.CLa * (alpha - P.a0) + P.Cmq * P.lt / dyn.va_of_mach( 0.7, 7000) * q + P.Cmd * dphr Cm_tab3.append(Cm3) Cm4 = P.Cm0 - ms[3] * P.CLa * (alpha - P.a0) + P.Cmq * P.lt / dyn.va_of_mach( 0.7, 7000) * q + P.Cmd * dphr Cm_tab4.append(Cm4) plt.plot(ut.deg_of_rad(alphas), Cm_tab1) plt.plot(ut.deg_of_rad(alphas), Cm_tab2) plt.plot(ut.deg_of_rad(alphas), Cm_tab3) plt.plot(ut.deg_of_rad(alphas), Cm_tab4) label1 = patches.Patch(color='blue', label='ms = -0.1') label2 = patches.Patch(color='green', label='ms = 0') label3 = patches.Patch(color='red', label='ms = 0.2') label4 = patches.Patch(color='cyan', label='ms = 1') plt.legend(loc='upper right', handles=[label1, label2, label3, label4]) ut.decorate(plt.gca(), title="Evolution du Cm en fonction de l'incidence", xlab='Incidence', ylab='Cm') plt.show()
def plot_all_trims(aircraft, hs, Mas, sms, kms, trims, filename=None): ''' Affichage graphique des valeurs de trim ''' margins = (0.03, 0.05, 0.98, 0.95, 0.15, 0.46) fig = ut.prepare_fig(window_title='Trims {}'.format(aircraft.name), figsize=(20.48, 10.24), margins=margins) m=0 for k, sm in enumerate(sms): for l,km in enumerate(kms): for i, h in enumerate(hs): for j, Ma in enumerate(Mas): alpha, dphr, dth = trims[i, j, k, l] fmt = 'alt {:5.0f} Ma {:.1f} sm {:.1f} km {:.1f} -> alpha {:5.2f} deg phr {:-5.1f} deg throttle {:.1f} %' print fmt.format(h, Ma, sm, km, ut.deg_of_rad(alpha), ut.deg_of_rad(dphr), 100*dth) legend, params = ['Mach {}'.format(Ma) for Ma in Mas], r'\quad sm={} \quad km={}'.format(sm, km) ax = plt.subplot(4, 3, 3*m+1) plt.plot(hs, ut.deg_of_rad(trims[:, 0, k, l, 0])) plt.plot(hs, ut.deg_of_rad(trims[:, 1, k, l, 0])) ut.decorate(ax, r'$\alpha {}$'.format(params), r'altitude', '$deg$', legend=legend) ax = plt.subplot(4, 3, 3*m+2) plt.plot(hs, ut.deg_of_rad(trims[:, 0, k, l, 1])) plt.plot(hs, ut.deg_of_rad(trims[:, 1, k, l, 1])) ut.decorate(ax, r'$\delta_{{PHR}} {}$'.format(params), r'altitude', '$deg$', legend=legend) ax = plt.subplot(4, 3, 3*m+3) plt.plot(hs, trims[:, 0, k, l, 2]*100) plt.plot(hs, trims[:, 1, k, l, 2]*100) ut.decorate(ax, r'$\delta_{{th}} {}$'.format(params), r'altitude', '$\%$', legend=legend) m = m+1 if filename<> None: plt.savefig(filename, dpi=160)
def plot_population(env): """Plots population change over time steps. """ seq = env.agent_count_seq print('Starting population: %i \nEnding population: %i' %(seq[0], seq[-1])) if isinstance(env, Sugarscape_Grow): metabolism = env.average_metabolism_seq print('Starting metabolism: %.2f \nEnding metabolism: %.2f' %(metabolism[0], metabolism[-1])) vision = env.average_vision_seq print('Starting vision: %.2f \nEnding vision: %.2f' %(vision[0], vision[-1])) plt.figure(figsize=(10, 7)) if isinstance(env, Sugarscape_Grow): plt.subplot(3, 1, 1) plt.plot(seq, label='Population') decorate(xlabel='Time Steps', ylabel='Number of Agents') if isinstance(env, Sugarscape_Grow): plt.subplot(3,1,2) plt.plot(vision, label='Vision') decorate(ylabel='Vision') plt.subplot(3,1,3) plt.plot(metabolism, label='Metabolism') decorate(ylabel='Metabolism') plt.show(block=True)
def plot_sims(fit_land, agent_maker, sim_maker, instrument_maker, **plot_options): """Runs simulations and plots metrics. fit_land: FitnessLandscape agent_maker: function that makes an array of Agent sim_maker: function that makes a Simulation instrument_maker: function that makes an Instrument plot_options: dict passed to plot """ plot_options['alpha'] = 0.4 for _ in range(10): agents = agent_maker(fit_land) sim = sim_maker(fit_land, agents) instrument = instrument_maker() sim.add_instrument(instrument) sim.run() sim.plot(index=0, **plot_options) decorate(xlabel='Time', ylabel=instrument.label) return sim
def evol_CLe(P): q = 0 mss = [0.2, 1] alphas = np.arange(ut.rad_of_deg(-10), ut.rad_of_deg(20), ut.rad_of_deg(1)) km = 0.1 for ms in mss: P.set_mass_and_static_margin(km, ms) dphrs = [] dphrs = np.array([(P.ms * P.CLa * (alpha - P.a0) - P.Cm0) / P.Cmd for alpha in alphas]) CLe = [] CLe = [ dyn.get_aero_coefs(dyn.va_of_mach(0.7, 7000), alpha, q, dphr, P)[0] for alpha, dphr in zip(alphas, dphrs) ] plt.plot(ut.deg_of_rad(alphas), CLe) label1 = patches.Patch(color='blue', label='ms = 0.2') label2 = patches.Patch(color='green', label='ms = 1') plt.legend(loc='upper left', handles=[label1, label2]) ut.decorate(plt.gca(), "Evolution de CLe en fonction de l'incidence", 'Incidence', 'Coefficient de portance équilibrée') plt.show
def box_count(pile, level, plot=False): """Estimates the fractal dimension by box counting. pile: SandPile level: which level from the pile to count plot: boolean, whether to generate plot returns: estimated fractal dimension """ res = count_cells(pile.array == level) steps, steps2, cells = res # select the range where we have a nonzero number of cells legit = np.nonzero(cells) steps = steps[legit] steps2 = steps2[legit] cells = cells[legit] if plot: # only put labels on the left and bottom subplots xlabel = 'Box Size' if level in [2, 3] else '' ylabel = 'Cell Count' if level in [0, 2] else '' options = dict(linestyle='dashed', color='gray', alpha=0.7) plt.plot(steps, steps2, **options) plt.plot(steps, cells, label='level=%d' % level) plt.plot(steps, steps, **options) decorate(xscale='log', yscale='log', xlim=[1, 200], loc='upper left', xlabel=xlabel, ylabel=ylabel) params = linregress(np.log(steps), np.log(cells)) print('Slope: ', params[0]) return params[0]
def decryptFile(self, crypt_f): key = self.key delimiter = self.delimiter c_file = crypt_f + '.crypt' if os.path.isfile(c_file): try: cipher = Blowfish(key) decorate(' Decrypting ' + c_file + '...', 64, '-') with open(c_file, 'rb') as f1: with open(crypt_f, 'wb') as f2: dt = f1.read().split(delimiter) tot = len(dt) - 1 for i in tqdm(range(tot)): f2.write( (base64.b64decode(cipher.decrypt(dt[i])[4:]))) f1.close() f2.close() decorate('Success', 64, '-') except Exception as e: if str(e) == 'Incorrect padding': print 'ACCESS DENIED' self.retryDecrypting(crypt_f) else: print e, 'exception caught while decrypting', crypt_f elif os.path.isfile(crypt_f): print 'encrypting keychain with a new key...' new_pass = raw_input('enter new pass --->>') if isinstance(new_pass, str): try: self.key = new_pass self.encryptFile(crypt_f) self.retryDecrypting(crypt_f) except Exception as e: print e
def cdf_evolution(cdfs): """Plot CDF evolution over time. cdfs: list of Cdf """ def plot_cdfs(cdfs, **options): for cdf in cdfs: cdf.plot(**options) plt.figure(figsize=(10, 6)) plt.subplot(1, 2, 1) plot_cdfs(cdfs[:-1], color='gray', alpha=0.3) plot_cdfs(cdfs[-1:], color='C0') decorate(xlabel='Wealth', ylabel='CDF') plt.subplot(1,2,2) plot_cdfs(cdfs[:-1], color='gray', alpha=0.3) plot_cdfs(cdfs[-1:], color='C0') decorate(xlabel='Wealth', ylabel='CDF', xscale='log') savefig('myfigs/chap09-4') plt.show(block=True)
def decryptFile(self, crypt_f): key = self.key delimiter = self.delimiter c_file = crypt_f + '.crypt' if os.path.isfile(c_file): try: cipher = Blowfish(key) decorate(' Decrypting ' + c_file + '...', 64, '-') with open(c_file, 'rb') as f1: with open(crypt_f, 'wb') as f2: dt = f1.read().split(delimiter) tot = len(dt)-1 for i in tqdm(range(tot)): f2.write((base64.b64decode(cipher.decrypt(dt[i])[4:]))) f1.close() f2.close() decorate('Success', 64, '-') except Exception as e: if str(e) == 'Incorrect padding': print 'ACCESS DENIED' self.retryDecrypting(crypt_f) else: print e, 'exception caught while decrypting', crypt_f elif os.path.isfile(crypt_f): print 'encrypting keychain with a new key...' new_pass = raw_input('enter new pass --->>') if isinstance(new_pass, str): try: self.key = new_pass self.encryptFile(crypt_f) self.retryDecrypting(crypt_f) except Exception as e: print e
def __init__( self, config_dict, T, num_dims, controller_sym_path_obj, min_smt_sample_dist, plant_abstraction_type, controller_abstraction_type, graph_lib, plant_abs=None, controller_abs=None, prog_bar=False, ): # super(Abstraction, self).__init__() self.graph_lib = graph_lib self.num_dims = num_dims self.G = g.factory(graph_lib) self.T = T self.N = None self.state = None self.scale = None self.controller_sym_path_obj = controller_sym_path_obj self.min_smt_sample_dist = min_smt_sample_dist self.plant_abstraction_type = plant_abstraction_type self.controller_abstraction_type = controller_abstraction_type # The list of init_cons is interpreted as [ic0 \/ ic1 \/ ... \/ icn] # self.init_cons_list = init_cons_list # self.final_cons_list = final_cons_list self.eps = None # self.refinement_factor = 0.5 self.delta_t = None self.num_samples = None # TODO: replace this type checking by passing dictionaries and parsing # outside the class. This will also avoid parsing code duplication. # Keep a single configuration format. self.parse_config(config_dict) # TAG:Z3_IND - default init smt_solver = None # TAG:Z3_IND - shuffled the plant abstraction creation after controller # abstraction. This lets us get the smt_solver depending upon the # requeseted controller abstraction if controller_abstraction_type == 'symbolic_pathcrawler': import smtSolver as smt smt_solver = smt.smt_solver_factory('z3') import CASymbolicPCrawler as CA controller_abs = CA.ControllerSymbolicAbstraction(self.num_dims, controller_sym_path_obj, min_smt_sample_dist, smt_solver) elif controller_abstraction_type == 'symbolic_klee': import CASymbolicKLEE as CA controller_abs = CA.ControllerSymbolicAbstraction(self.num_dims, controller_sym_path_obj, min_smt_sample_dist) #elif controller_abstraction_type == 'concolic': # import CAConcolic as CA # controller_abs = CA.ControllerCollectionAbstraction(self.num_dims) elif controller_abstraction_type == 'concrete': import CAConcolic as CA controller_abs = CA.ControllerCollectionAbstraction(self.num_dims) elif controller_abstraction_type == 'concrete_no_controller': DummyControllerAbs = type('DummyControllerAbs', (), {}) controller_abs = DummyControllerAbs() controller_abs.is_symbolic = False # can not use None because of a check in # get_abs_state_from_concrete_state() which silently makes # the entire abstract state None if a None is encountered # in either plant or contorller abs state. def dummy(*args): return 0 controller_abs.get_abs_state_from_concrete_state = dummy controller_abs.get_reachable_abs_states = sample_abs_state controller_abs.get_concrete_states_from_abs_state = dummy else: print(controller_abstraction_type) raise NotImplementedError if plant_abstraction_type == 'cell': #from PACell import * import PACell as PA else: raise NotImplementedError # Overriding the passed in plant and conctroller abstractions plant_abs = PA.PlantAbstraction( self.T, self.N, self.num_dims, self.delta_t, self.eps, self.refinement_factor, self.num_samples, smt_solver, #TAG:Z3_IND - Add solver param ) print(U.decorate('new abstraction created')) print('eps:', self.eps) print('num_samples:', self.num_samples) print('refine:', self.refinement_factor) print('deltaT:', self.delta_t) print('TH:', self.T) print('num traces:', self.N) print('=' * 50) # ##!!##logger.debug('==========abstraction parameters==========') # ##!!##logger.debug('eps: {}, refinement_factor: {}, num_samples: {},delta_t: {}'.format(str(self.eps), self.refinement_factor, self.num_samples, self.delta_t)) initial_state_list = [] # WHy was this needed in the first place? # for node in self.initial_state_set: # self.G.add_node(node) # for node in self.final_state_set: # self.G.add_node(node) # Not very useful when the graph is discovered incrementally from the # intial states! self.final_augmented_state_set = set() # self.sanity_check() self.plant_abs = plant_abs self.controller_abs = controller_abs #if self.controller_abstraction_type.startswith('symbolic'): if self.controller_abs.is_symbolic: self.get_reachable_states = self.get_reachable_states_sym else: self.get_reachable_states = self.get_reachable_states_conc return
def random_test( A, system_params, initial_state_list, ci_seq_list, pi_seq_list, init_cons, init_d, initial_controller_state, sample_ci ): # ##!!##logger.debug('random testing...') A.prog_bar = False res = [] # initial_state_set = set(initial_state_list) if A.num_dims.ci != 0: if sample_ci: ci_seq_array = np.array([np.array(ci_seq_list).T]).T else: ci_seq_array = np.array(ci_seq_list) # print('ci_seq_array', ci_seq_array) # print('ci_seq_array.shape', ci_seq_array.shape) if A.num_dims.pi != 0: pi_seq_array = np.array([np.array(pi_seq_list).T]).T #print(ci_seq_array.shape) #print(pi_seq_array.shape) x_array = np.empty((0.0, A.num_dims.x), dtype=float) print('checking initial states') # for abs_state in initial_state_set: for abs_state in initial_state_list: ival_cons = A.plant_abs.get_ival_cons_abs_state(abs_state.plant_state) # ##!!##logger.debug('ival_cons: {}'.format(ival_cons)) # find the intersection b/w the cell and the initial cons # print('init_cons', init_cons) ic = ival_cons & init_cons if ic is not None: # scatter the continuous states x_samples = ic.sample_UR(A.num_samples) # ##!!##logger.debug('ic: {}'.format(ic)) # ##!!##logger.debug('samples: {}'.format(x_samples)) x_array = np.concatenate((x_array, x_samples)) else: raise err.Fatal('Can not happen! Invalid states have already been filtered out by filter_invalid_abs_states()') # # ##!!##logger.debug('{}'.format(samples.x_array)) # ##!!##logger.debug('ignoring abs states: {}'.format(ival_cons)) # ignore the state as it is completely outside the initial # constraints # print(x_array) # print(x_array.shape) print(x_array.shape) num_samples = len(x_array) if num_samples == 0: print(initial_state_list) print('no valid sample found during random testing. STOP') return False else: # ##!!##logger.debug('num_samples = 0') print('simulating {} samples'.format(num_samples)) trace_list = [traces.Trace(A.num_dims, A.N) for i in range(num_samples)] s_array = np.tile(initial_controller_state, (num_samples, 1)) # if system_params.pi is not None: # pi_array = SaMpLe.sample_ival_constraints(system_params.pi, num_samples) # print(pi_array) # exit() # else: # pi_array = None t_array = np.tile(0.0, (num_samples, 1)) d_array = np.tile(init_d, (num_samples, 1)) # TODO: initializing pvt states to 0 p_array = np.zeros((num_samples, 1)) # save x_array to print x0 in case an error is found # TODO: need to do something similar for u,ci,pi x0_array = x_array d0_array = d_array # sanity check if len(x_array) != len(s_array): raise err.Fatal('internal: how is len(x_array) != len(s_array)?') # while(simTime < A.T): sim_num = 0 simTime = 0.0 i = 0 while sim_num < A.N: if A.num_dims.ci == 0: ci_array = np.zeros((num_samples, 0)) else: if sample_ci: ci_cons_list = list(ci_seq_array[:, i, :]) ci_cons_list = [ci_cons.tolist()[0] for ci_cons in ci_cons_list] ci_lb_list = [np.tile(ci_cons.l, (A.num_samples, 1)) for ci_cons in ci_cons_list] ci_ub_list = [np.tile(ci_cons.h, (A.num_samples, 1)) for ci_cons in ci_cons_list] ci_cons_lb = reduce(lambda acc_arr, arr: np.concatenate((acc_arr, arr)), ci_lb_list) ci_cons_ub = reduce(lambda acc_arr, arr: np.concatenate((acc_arr, arr)), ci_ub_list) random_arr = np.random.rand(num_samples, A.num_dims.ci) ci_array = ci_cons_lb + random_arr * (ci_cons_ub - ci_cons_lb) else: ci_array = ci_seq_array[:, i, :] ci_array = np.repeat(ci_array, A.num_samples, axis=0) if A.num_dims.pi == 0: pi_array = np.zeros((num_samples, 0)) else: pi_cons_list = list(pi_seq_array[:, i, :]) pi_cons_list = [pi_cons.tolist()[0] for pi_cons in pi_cons_list] #print(pi_cons_list) #pi_cons_list = map(A.plant_abs.get_ival_cons_pi_cell, pi_cells) pi_lb_list = [np.tile(pi_cons.l, (A.num_samples, 1)) for pi_cons in pi_cons_list] pi_ub_list = [np.tile(pi_cons.h, (A.num_samples, 1)) for pi_cons in pi_cons_list] pi_cons_lb = reduce(lambda acc_arr, arr: np.concatenate((acc_arr, arr)), pi_lb_list) pi_cons_ub = reduce(lambda acc_arr, arr: np.concatenate((acc_arr, arr)), pi_ub_list) random_arr = np.random.rand(num_samples, A.num_dims.pi) # print('pi_cons_lb.shape:', pi_cons_lb.shape) # print('pi_cons_ub.shape:', pi_cons_ub.shape) # print('num_samples', num_samples) pi_array = pi_cons_lb + random_arr * (pi_cons_ub - pi_cons_lb) (s_array_, u_array) = compute_concrete_controller_output( A, system_params.controller_sim, ci_array, x_array, s_array, num_samples, ) concrete_states = st.StateArray( # t # cont_state_array # abs_state.discrete_state # abs_state.pvt_stat t_array, x_array, d_array, p_array, s_array_, u_array, pi_array, ci_array, ) # print(concrete_states) # enforce property checking even if it has not been requested # by the user pc = PropertyChecker(system_params.final_cons) rchd_concrete_state_array, property_violated_flag = ( system_params.plant_sim.simulate_with_property_checker( concrete_states, A.delta_t, pc )) for kdx, rchd_state in enumerate(rchd_concrete_state_array.iterable()): trace = trace_list[kdx] trace.append(rchd_state.s, rchd_state.u, rchd_state.x, rchd_state.ci, rchd_state.pi, rchd_state.t, rchd_state.d) if property_violated_flag: print(U.decorate('concretized!')) for (idx, xf) in enumerate(rchd_concrete_state_array.iterable()): if xf.x in system_params.final_cons: res.append(idx) print(x0_array[idx, :], d0_array[idx, :], '->', '\t', xf.x, xf.d) #if A.num_dims.ci != 0: # print('ci:', ci_array[idx]) #if A.num_dims.pi != 0: # print('pi:', pi_array[idx]) break i += 1 sim_num += 1 # increment simulation time simTime += A.delta_t t_array += A.delta_t concrete_states = rchd_concrete_state_array x_array = concrete_states.cont_states s_array = concrete_states.controller_states d_array = concrete_states.discrete_states p_array = concrete_states.pvt_states # u_array = return map(trace_list.__getitem__, res)