Best Python code snippet using avocado_python
trajectory_plot.py
Source:trajectory_plot.py
1"""2Plot the state and input trajectory.3D. Malyuta -- ACL, University of Washington4B. Acikmese -- ACL, University of Washington5Copyright 2019 University of Washington. All rights reserved.6"""7import pickle8import numpy as np9import numpy.linalg as la10import matplotlib11import matplotlib.pyplot as plt12import progressbar13from csm import ApolloCSM14import tools15matplotlib.rc('font',**{'family':'serif','size':14})16matplotlib.rc('text', usetex=True)17matplotlib.rc('font',**{'family':'serif','size':14})18matplotlib.rc('text', usetex=True)19with open('data/tf_150_tc_2.pkl','rb') as f:20 data = pickle.load(f)21csm = ApolloCSM()22t_f = tools.get_values(data,'solver_input','t_f')[0]23q_f = tools.get_values(data,'solver_input','xf')[0]['q']24t_pulse_max = tools.get_values(data,'solver_input','t_pulse_max')[0]25r_a = tools.get_values(data,'solver_input','r_app')[0]26idx = 027t_sol = tools.get_values(data,'solver_output','optimizer','t')[idx]28p_sol = tools.get_values(data,'solver_output','optimizer','p')[idx]29v_sol = tools.get_values(data,'solver_output','optimizer','v')[idx]30q_sol = tools.get_values(data,'solver_output','optimizer','q')[idx]31omega_sol = tools.get_values(data,'solver_output','optimizer','w')[idx]32u_sol = tools.get_values(data,'solver_output','optimizer','u')[idx]33vc_sol = tools.get_values(data,'solver_output','history','vc')[idx][-1]34t_nl = tools.get_values(data,'solver_output','nl_prop','t')[idx]35p_nl = tools.get_values(data,'solver_output','nl_prop','p')[idx]36v_nl = tools.get_values(data,'solver_output','nl_prop','v')[idx]37q_nl = tools.get_values(data,'solver_output','nl_prop','q')[idx]38omega_nl = tools.get_values(data,'solver_output','nl_prop','w')[idx]39ang_err_sol = np.array([np.rad2deg(2.*np.arccos(max(-1,min(1,tools.qmult(40 tools.qconj(q_sol_k),q_f)[0])))) for q_sol_k in q_sol.T])41ang_err_nl = np.array([np.rad2deg(2.*np.arccos(max(-1,min(1,tools.qmult(42 tools.qconj(q_nl_k),q_f)[0])))) for q_nl_k in q_nl.T])43vc_sol_norm1 = np.array([la.norm(vc_sol[k],ord=1)44 for k in range(vc_sol.shape[0])])45rpy_sol = np.column_stack([tools.q2rpy(q_sol.T[k])46 for k in range(q_sol.shape[1])])47rpy_nl = np.column_stack([tools.q2rpy(q_nl.T[k])48 for k in range(q_nl.shape[1])])49time_app = np.array([t_nl[k] for k in range(p_nl.shape[1])50 if la.norm(p_nl[:,k]-p_nl[:,-1])<r_a])51# translation52fig = plt.figure(1)53plt.clf()54ax = fig.add_subplot(211)55ax.grid()56ax.plot(t_sol,p_sol[0],color='red',linestyle='none',marker='.',markersize=5)57ax.plot(t_sol,p_sol[1],color='green',linestyle='none',marker='.',markersize=5)58ax.plot(t_sol,p_sol[2],color='blue',linestyle='none',marker='.',markersize=5)59ax.plot(t_nl,p_nl[0],color='red')60ax.plot(t_nl,p_nl[1],color='green')61ax.plot(t_nl,p_nl[2],color='blue')62ax.set_xlabel('Time $t$ [s]')63ax.set_ylabel('Position [m]')64ax.autoscale(tight=True)65y_lim = ax.get_ylim()66x_lim = ax.get_xlim()67ax.fill_between(time_app,68 np.repeat(y_lim[0],time_app.size),69 np.repeat(y_lim[1],time_app.size),70 linewidth=0,color='black',alpha=0.2,zorder=1)71ax.set_xlim(x_lim)72ax.set_ylim(y_lim)73ax = fig.add_subplot(212)74ax.grid()75ax.plot(t_sol,v_sol[0],color='red',linestyle='none',marker='.',markersize=5)76ax.plot(t_sol,v_sol[1],color='green',linestyle='none',marker='.',markersize=5)77ax.plot(t_sol,v_sol[2],color='blue',linestyle='none',marker='.',markersize=5)78ax.plot(t_nl,v_nl[0],color='red')79ax.plot(t_nl,v_nl[1],color='green')80ax.plot(t_nl,v_nl[2],color='blue')81ax.set_xlabel('Time $t$ [s]')82ax.set_ylabel('Velocity [m/s]')83ax.autoscale(tight=True)84plt.tight_layout()85y_lim = ax.get_ylim()86x_lim = ax.get_xlim()87ax.fill_between(time_app,88 np.repeat(y_lim[0],time_app.size),89 np.repeat(y_lim[1],time_app.size),90 linewidth=0,color='black',alpha=0.2,zorder=1)91ax.set_xlim(x_lim)92ax.set_ylim(y_lim)93plt.show(block=False)94fig.savefig('./figures/translation.pdf',95 bbox_inches='tight',format='pdf',transparent=True)96# attitude97fig = plt.figure(2)98plt.clf()99ax = fig.add_subplot(211)100ax.grid()101ax.plot(t_sol,np.unwrap(rpy_sol[0],discont=359.)-360.,color='red',linestyle='none',marker='.',markersize=5)102ax.plot(t_sol,rpy_sol[1],color='green',linestyle='none',marker='.',markersize=5)103ax.plot(t_sol,rpy_sol[2],color='blue',linestyle='none',marker='.',markersize=5)104ax.plot(t_nl,np.unwrap(rpy_nl[0],discont=359.)-360.,color='red')105ax.plot(t_nl,rpy_nl[1],color='green')106ax.plot(t_nl,rpy_nl[2],color='blue')107ax.set_xlabel('Time $t$ [s]')108ax.set_ylabel('Roll, pitch, yaw [$^\circ$]')109ax.autoscale(tight=True)110y_lim = ax.get_ylim()111x_lim = ax.get_xlim()112ax.fill_between(time_app,113 np.repeat(y_lim[0],time_app.size),114 np.repeat(y_lim[1],time_app.size),115 linewidth=0,color='black',alpha=0.2,zorder=1)116ax.set_xlim(x_lim)117ax.set_ylim(y_lim)118ax = fig.add_subplot(212)119ax.grid()120ax.plot(t_sol,np.rad2deg(omega_sol[0]),color='red',linestyle='none',marker='.',markersize=5)121ax.plot(t_sol,np.rad2deg(omega_sol[1]),color='green',linestyle='none',marker='.',markersize=5)122ax.plot(t_sol,np.rad2deg(omega_sol[2]),color='blue',linestyle='none',marker='.',markersize=5)123ax.plot(t_nl,np.rad2deg(omega_nl[0]),color='red')124ax.plot(t_nl,np.rad2deg(omega_nl[1]),color='green')125ax.plot(t_nl,np.rad2deg(omega_nl[2]),color='blue')126ax.set_xlabel('Time $t$ [s]')127ax.set_ylabel('Angular velocity [$^\circ$/s]')128ax.autoscale(tight=True)129plt.tight_layout()130y_lim = ax.get_ylim()131x_lim = ax.get_xlim()132ax.fill_between(time_app,133 np.repeat(y_lim[0],time_app.size),134 np.repeat(y_lim[1],time_app.size),135 linewidth=0,color='black',alpha=0.2,zorder=1)136ax.set_xlim(x_lim)137ax.set_ylim(y_lim)138plt.show(block=False)139fig.savefig('./figures/attitude.pdf',140 bbox_inches='tight',format='pdf',transparent=True)141# RCS thrusts142fig = plt.figure(3,figsize=(9.6,9.86))143plt.clf()144for i in range(4): # quad number145 for j in range(4): # thruster of quad146 k = i*4+j147 ax = fig.add_subplot(4,4,k+1)148 ax.grid()149 ax.plot(t_sol[:-1],u_sol[k]*1e3,color='black',marker='.',150 linestyle='none',markersize=5)151 ax.axhline(y=csm.t_pulse_max*1e3,color='red',linestyle='--',linewidth=1)152 ax.axhline(y=csm.t_pulse_min*1e3,color='blue',linestyle='--',153 linewidth=1)154 ax.set_xlabel('Time $t$ [s]')155 ax.set_ylabel('Pulse width $\Delta t_k^{%d}$ [ms]'%(k+1))156 ax.set_title('Thruster $i=%d$'%(k+1))157 ax.autoscale(tight=True)158 yticks = (np.ceil(np.linspace(0,0.6,7)*1e3)).astype(int)159 xticks = (np.linspace(0,t_f,3)).astype(int)160 plt.yticks(yticks,yticks)161 plt.xticks(xticks,xticks)162 ax.set_ylim([0,t_pulse_max*1.1*1e3])163 if 'p_f' in csm.i2thruster[4*i+j]:164 y_lim = ax.get_ylim()165 x_lim = ax.get_xlim()166 ax.fill_between(time_app,167 np.repeat(y_lim[0],time_app.size),168 np.repeat(y_lim[1],time_app.size),169 linewidth=0,color='black',alpha=0.2,zorder=1)170 ax.set_xlim(x_lim)171 ax.set_ylim(y_lim)172 173plt.tight_layout()174plt.show(block=False)175fig.savefig('./figures/inputs.pdf',...
MSP.py
Source:MSP.py
1import matplotlib.pyplot as plt2import torch3import torch.nn as nn4import torch.nn.functional as F5class MultiSimilarity(nn.Module):6 def __init__(self):7 super().__init__()8 def forward(self, s_g, t_g):9 # --------------------------------------------10 # Shape of s_g : ((s_nl,), (bs, s_ch, s_h, s_w))11 # Shape of t_g : ((t_nl,), (bs, t_ch, t_h, t_w))12 # --------------------------------------------13 s_nl = len(s_g)14 t_nl = len(t_g)15 s_g_mtx = torch.stack([self.get_sim_matrix(s_f) for s_f in s_g]) # (s_nl, bs, bs)16 t_g_mtx = torch.stack([self.get_sim_matrix(t_f) for t_f in t_g]) # (t_nl, bs, bs)17 s_g_mtx = torch.unsqueeze(s_g_mtx, dim=1).repeat(1, t_nl, 1, 1) # (s_nl, t_nl, bs, bs)18 t_g_mtx = torch.unsqueeze(t_g_mtx, dim=0).repeat(s_nl, 1, 1, 1) # (s_nl, t_nl, bs, bs)19 loss = (s_g_mtx - t_g_mtx).pow(2).view(s_nl, -1).mean(1).mean(0) # (1,)20 return loss21 def get_sim_matrix(self, f, is_at=True):22 # --------------------------------------------23 # Shape of f : (bs, ch, h, w)24 # --------------------------------------------25 if is_at:26 f = self.at(f)27 f = f.view(f.shape[0], -1) # (bs, ch * h * w)28 f = F.normalize(f, dim=1) # (bs, ch * h * w)29 mtx = torch.matmul(f, torch.t(f)) # (bs, bs)30 mtx = F.normalize(mtx, dim=1) # (bs, bs)31 return mtx32 def at(self, f, is_flat=True):33 # --------------------------------------------34 # Shape of f : (bs, ch, h, w)35 # --------------------------------------------36 out = f.pow(2).mean(1) # (bs, h, w)37 if is_flat:38 out =F.normalize(out.view(f.size(0), -1)) # (bs, h * w)39 return out40class MultiSimilarityPlotter(MultiSimilarity):41 def __init__(self):42 super().__init__()43 def plot(self, s_g, t_g, input, target, n_samp=10):44 # --------------------------------------------45 # Shape of s_g : ((s_nl,), (bs, s_ch, s_h, s_w))46 # Shape of t_g : ((t_nl,), (bs, t_ch, t_h, t_w))47 # Shape of input : (bs, ch, h, w)48 # Shape of target : (bs,)49 # --------------------------------------------50 s_g = [s_f.detach() for s_f in s_g]51 t_g = [t_f.detach() for t_f in t_g]52 input = input.permute(0, 2, 3, 1) # (bs, h, w, ch)53 s_attn_g = [self.at(s_f, is_flat=False) for s_f in s_g] # ((s_nl,), (bs, s_h, s_w))54 t_attn_g = [self.at(t_f, is_flat=False) for t_f in t_g] # ((t_nl,), (bs, t_h, t_w))55 s_sim_g = torch.stack([self.get_sim_matrix(s_f) for s_f in s_g]) # (s_nl, bs, bs)56 t_sim_g = torch.stack([self.get_sim_matrix(t_f) for t_f in t_g]) # (t_nl, bs, bs)57 s_pos_ind_g = torch.argsort(-s_sim_g, dim=2) # (s_nl, bs, bs)58 t_pos_ind_g = torch.argsort(-t_sim_g, dim=2) # (t_nl, bs, bs)59 s_neg_ind_g = torch.argsort(s_sim_g, dim=2) # (s_nl, bs, bs)60 t_neg_ind_g = torch.argsort(t_sim_g, dim=2) # (t_nl, bs, bs)61 pivot = 062 for i, (t_pos_ind_f, t_neg_ind_f, t_attn_f) in enumerate(zip(t_pos_ind_g, t_neg_ind_g, t_attn_g)):63 pos_ind = t_pos_ind_f[pivot, :n_samp] # (n_samp,)64 neg_ind = t_neg_ind_f[pivot, :n_samp] # (n_samp,)65 r_pos_imgs = input[pos_ind] # (n_samp, h, w, ch). Sampled raw images66 r_neg_imgs = input[neg_ind] # (n_samp, h, w, ch). Sampled raw images67 t_pos_attns = t_attn_f[pos_ind] # (n_samp, t_h, t_w)68 t_neg_attns = t_attn_f[neg_ind] # (n_samp, t_h, t_w)69 fig, axs = plt.subplots(4, n_samp) # 4 rows and n_samp columns70 for j in range(n_samp):71 axs[0, j].imshow(r_pos_imgs[j], interpolation="bicubic")72 axs[1, j].imshow(t_pos_attns[j], cmap="jet")73 axs[2, j].imshow(r_neg_imgs[j], interpolation="bicubic")74 axs[3, j].imshow(t_neg_attns[j], cmap="jet")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!