How to use show_elements method in SeleniumBase

Best Python code snippet using SeleniumBase

visualize.py

Source:visualize.py Github

copy

Full Screen

1""" A wrapper class for visualizing propagation models. """2import os3import sys4import matplotlib.pyplot as plt5import matplotlib.patches as mpatches6import numpy as np7from utils.occ_map_utils import load_map, display_occ_map, plot_grid_map_hmm, show_traj, red_cm, blue_cm, greens_cm8from utils.occ_map_utils import show_map as show_walls9from utils.scene_utils import caculate_traj_from_scene10from data_generator.ped_sim import sample_trajectories11from metrics import cross_entropy12from animation import Plot13map_resolution = 0.214word_to_vel = { 'UP': [0, 1], 'LEFT': [-1, 0],15 'RIGHT': [1, 0], 'DOWN': [0, -1],16 'UPLEFT': [-1, 1], 'UPRIGHT': [1, 1],17 'DOWNLEFT': [-1, -1], 'DOWNRIGHT': [1, -1]}18# key press to update figure for the next tracking setp19def on_press(event, visualization):20 sys.stdout.flush()21 if event.key == ' ':22 visualization.visualize_next()23 visualization.fig.canvas.draw()24# show an arrow point to the cell clicked25def onclick(event, visualization):26 res = visualization.res27 ix, iy = event.xdata+res/2, event.ydata+res/228 delta = .329 for idx in np.ndindex(visualization.axes.shape):30 if visualization.axes[idx] == event.inaxes:31 visualization.axes[idx].arrow(ix+delta, iy+delta, -delta, -delta,32 head_width=0.2, head_length=0.1, fc='r', ec='r', zorder=15)33 visualization.fig.canvas.draw()34class Visualize(object):35 """36 A class for visualizing propagation models.37 """38 element_to_title = {"obser": "observation", "pred":"prediction", "corr":"after correction"}39 def __init__(self, models, num_steps, simulated_data=True, tracking=False, measurement_lost=None,40 dynamically=True, show_map=True, show_seen=False, show_elements=['obser', 'pred', 'corr'],41 show_colorbar=True, num_col=5, model_names=None, show_at=None, show_metric=True, **kwargs):42 self.models = models43 self.num_models = len(self.models)44 self.map = models[0].map45 self.res = models[0].map_res46 self.extent = models[0].extent47 self.num_steps = num_steps48 self.dynamically = dynamically49 self.simulated_data = simulated_data50 self.tracking = tracking51 self.measurement_lost = measurement_lost52 self.show_map = show_map53 self.show_seen = show_seen54 self.show_metric = show_metric55 show_order = {'pred': 0, 'obser':1, 'corr':2}56 show_elements.sort(key=lambda name: show_order[name])57 self.show_elements = show_elements if tracking else ['pred']58 self.num_col = self._get_num_col(num_col, self.show_elements)59 self.show_at = show_at60 if not self.dynamically and show_at is not None:61 self.num_col = len(show_at)62 self.show_colorbar = show_colorbar63 self.model_names = [model.name for model in self.models]64 if model_names is not None:65 self.model_names = model_names66 self.fig, self.axes, self.plots = self._init_figure()67 # bind key press event to update figure68 self.fig.canvas.mpl_connect('key_press_event', lambda event: on_press(event, self))69 self.fig.canvas.mpl_connect('button_press_event', lambda event: onclick(event, self))70 self.initialize_models()71 self.init_plot_contents()72 def initialize_models(self):73 """ This method has to be implemented by subclasses. """74 pass75 def _get_num_col(self, num_col, show_elements):76 """ Determine number of columns in the figure."""77 if self.dynamically:78 all_elements = ['obser', 'pred', 'corr']79 require_show = map(lambda e: e in all_elements, show_elements)80 return sum(require_show)81 else:82 return num_col83 def _init_figure(self):84 num_rows, num_cols = self.num_models, self.num_col85 fig_size = (4 * num_cols, 3.5 * num_rows)86 fig = plt.figure(figsize=fig_size)87 axes = np.empty((num_rows, num_cols), dtype=object)88 plots = np.empty((num_rows, num_cols), dtype=object)89 for i in range(num_rows):90 for j in range(num_cols):91 plot_idx = i * num_cols + j + 192 ax = fig.add_subplot(num_rows, num_cols, plot_idx)93 axes[i, j] = ax94 # no ticks on axis95 ax.set_xticklabels([])96 ax.set_yticklabels([])97 ax.xaxis.set_ticks_position('none')98 ax.yaxis.set_ticks_position('none')99 return fig, axes, plots100 # plot = Plot(ax, self.map, self.res, plot_seen=self., title='')101 def init_plot_contents(self):102 """ Decide plot contents for every plot."""103 colorbar_dict = {'pred': 'occupancy_axes', 'obser': 'map_axes', 'corr': 'occupancy_axes'}104 for i in range(self.num_models):105 for j in range(self.num_col):106 if not self.show_colorbar:107 colorbar_on = None108 else:109 if self.dynamically:110 colorbar_on = colorbar_dict[self.show_elements[j]]111 else:112 colorbar_on = "occupancy_axes" if not self.tracking else None113 self.plots[i, j] = Plot(self.axes[i ,j], self.map, self.res,114 colorbar_on=colorbar_on,115 plot_map=self.show_map,116 plot_seen=self.show_seen,117 title='')118 if self.tracking and not self.dynamically:119 self.add_custom_elements_to_plot(self.plots[i, j])120 if j == 0:121 self.plots[i, j].set_ylabel(self.model_names[i])122 if self.traj_overlay:123 # trajectory from scene can only be calculated for one target124 num_targets = self.num_targets if self.simulated_data else 1125 self.plots[i, j].add_traj_line(num_targets=num_targets)126 # add title to figure127 if self.simulated_data and self.init_moves is not None:128 self.fig.suptitle("Initial movements = {}".format(str(self.init_moves)))129 # add legend if neccessary130 if self.tracking and not self.dynamically:131 self.add_legend()132 def add_custom_elements_to_plot(self, plot):133 # add false negative axes134 # it shows locations where ground truth is occupied135 # but BOFUM fails to track136 plot.add_custom_image("fn_axes", blue_cm)137 # add true positive axes138 # it shows locations where ground truth is occupied139 # and BOFUM predicts occupancy prob higher than 0140 plot.add_custom_image("tp_axes", greens_cm)141 plot.add_colorbar("tp_axes")142 # add false positive axes143 plot.add_custom_image("fp_axes", red_cm)144 def add_legend(self):145 g_patch = mpatches.Patch(color='g', label='True positive')146 #b_patch = mpatches.Patch(color='b', label='False negative')147 o_patch = mpatches.Patch(color='orange', label='False positive', alpha=.6)148 #handles = [g_patch, b_patch, o_patch]149 handles = [g_patch, o_patch]150 plt.legend(handles=handles, bbox_to_anchor=(.6, 0., .35, .1),151 loc = 'lower right',152 ncol=3, mode='expand', borderaxespad=.0,153 bbox_transform=self.fig.transFigure)154 # plt.legend(handles=[g_patch, b_patch, o_patch], bbox_to_anchor=(0., 1.1),155 # loc=1, ncol=1, mode="expand", borderaxespad=None,156 # bbox_transform=self.fig.transFigure)157 def start(self):158 # reset model's step counter159 # for model in self.models:160 # model.t = 0161 plt.show()162 def visualize_next(self):163 if self.dynamically:164 if(self.models[0].t < self.num_steps):165 t = self.models[0].t166 print("t is " + str(t))167 # generate measurement data168 measurement = self.models[0].measurement_at() if self.tracking else None169 for model in self.models:170 measurement = model.tracking_step(measurement=measurement)171 self.show_dynamically(measurement)172 else:173 self.show_occupancies()174 def show_dynamically(self, observation):175 Ot_pred_max, Ot_pred_min = None, None176 Ot_max, Ot_min = None, None177 if 'pred' in self.show_elements:178 Ot_pred_max = max(map(lambda model: model.P_Ot_pred.max(), self.models))179 Ot_pred_min = min(map(lambda model: model.P_Ot_pred.min(), self.models))180 if 'corr' in self.show_elements:181 Ot_max = max(map(lambda model: model.P_Ot.max(), self.models))182 Ot_min = min(map(lambda model: model.P_Ot.min(), self.models))183 for i, model in enumerate(self.models):184 for j, element in enumerate(self.show_elements):185 if element == 'pred' or element == 'corr':186 if element == 'pred':187 Ot, max_, min_ = model.P_Ot_pred, Ot_pred_max, Ot_pred_min188 ap = model.calc_average_precision(evaluate_prediction=True)189 else:190 Ot, max_, min_ = model.P_Ot, Ot_max, Ot_min191 ap = model.calc_average_precision()192 title = self.element_to_title[element]193 if self.tracking and self.show_metric:194 self.plots[i, j].text.set_text(" Aver. Precision: {:.3f}".format(ap))195 self.plots[i, j].set_axes_data("occupancy_axes", Ot, min_, max_)196 else:197 Ot = observation198 if observation is None:199 Ot = np.zeros_like(self.map)200 title = 'observation'201 self.plots[i, j].set_axes_data("map_axes", Ot)202 if self.show_seen:203 t = self.models[0].t - 1204 seen = self.models[0].evaluate_loc_at(t)205 self.plots[i, j].set_axes_data("seen_axes", seen)206 self.plots[i, j].set_title(title)207 self.plots[i, j].refresh_colorbar()208 if self.simulated_data and self.traj_overlay:209 self.add_traj_overlay()210 def show_occupancies(self):211 if self.show_at is None:212 gap = self.num_steps // (self.num_col-1)213 self.show_at = [i*gap+1 for i in range(self.num_col)]214 for j, plot_t in enumerate(self.show_at):215 while self.models[0].t < plot_t:216 # generate measurement data217 measurement = self.models[0].measurement_at() if self.tracking else None218 for model in self.models:219 measurement = model.tracking_step(measurement=measurement)220 occupancies = np.array(map(lambda model: model.P_Ot, self.models))221 Ot_max = occupancies.max()222 Ot_min = occupancies.min()223 for i, model in enumerate(self.models):224 if plot_t > 0 and self.tracking and self.show_metric:225 x_ent = model.calc_cross_entropy()226 f1_score = model.calc_f1_score()227 ap = model.calc_average_precision()228 self.plots[i, j].text.set_text(" Aver. Precision: {:.3f}".format(ap))229 if not self.tracking:230 self.plots[i, j].set_axes_data("occupancy_axes", occupancies[i], Ot_min, Ot_max)231 else:232 self.update_custom_element(i, j, Ot_max)233 self.plots[i, j].refresh_colorbar()234 if i == 0:235 title = 't={}'.format(plot_t)236 self.plots[i, j].set_title(title)237 if self.tracking and self.traj_overlay:238 self.add_traj_overlay(i, j, plot_t)239 def update_custom_element(self, row, col, Ot_max):240 t = self.models[0].t - 1241 model = self.models[row]242 plot = self.plots[row, col]243 occupancy_prob = model.P_Ot244 h_max = occupancy_prob.max()/2245 #occupancy_prob = np.where(occupancy_prob>h_max, occupancy_prob, 0)246 ground_truth = model.ground_truth_at(t)247 overlap = np.logical_and(occupancy_prob, ground_truth)248 # if occupany on ground truth location is higher than 0.1,249 # it is not thought as a false negative250 occupancy_temp = np.where(overlap, occupancy_prob, 0)251 #predicted = np.where(occupancy_temp>0.1, 1, 0)252 false_negative = np.where(occupancy_temp>0.1, 0, ground_truth)253 # if model predicts occupancy higher than 0 on ground truth locations,254 # it is thought as a true positive255 true_positive = np.where(overlap, occupancy_prob, 0)256 # if model predicts occupancy higher than 0 on non-ground truth locations,257 # it is thought as a false positive258 false_positive = occupancy_prob.copy()259 false_positive[overlap] = 0260 # only show for occupancies higher than 1/4 highest occupancy261 # h_max = false_positive.max() / 4262 # false_positive = np.where(false_positive>h_max, false_positive, 0)263 plot.set_axes_data("fn_axes", false_negative, 0, 1)264 plot.set_axes_data("tp_axes", true_positive, 0, Ot_max)265 plot.set_axes_data("fp_axes", false_positive, 0, Ot_max)266 plot.set_axes_data("occupancy_axes", np.zeros_like(occupancy_prob))267class VisualizeRealdata(Visualize):268 def __init__(self, models, num_steps, scene, tracking=True, measurement_lost=None,269 dynamically=False, show_map=True, show_seen=True, show_elements=['obser', 'pred', 'corr'],270 show_colorbar=True, num_col=5, model_names=None, show_at=None, show_metric=True, **kwargs):271 self.scene = scene272 self.traj_overlay = kwargs.get('traj_overlay', False)273 if self.traj_overlay:274 self.traj = caculate_traj_from_scene(scene)275 super(VisualizeRealdata, self).__init__(models, num_steps, False, tracking,276 measurement_lost, dynamically, show_map, show_seen,277 show_elements, show_colorbar, num_col, model_names,278 show_at, show_metric, **kwargs)279 def initialize_models(self):280 map(lambda model: model.initialize(self.scene), self.models)281 def add_traj_overlay(self, i, j, t):282 """ Add trajectory lines on plots. """283 plot = self.plots[i, j]284 line = plot.lines[0]285 small_idx = max(0, t-4)286 big_idx = min(t+4, self.num_steps)287 xs, ys = self.traj.T[0][small_idx:big_idx], self.traj.T[1][small_idx:big_idx]288 line.set_data(xs, ys)289class VisualizeSimulation(Visualize):290 def __init__(self, models, num_steps, tracking=True, measurement_lost=None, num_targets=1,291 dynamically=False, show_map=True, show_elements=['obser', 'pred', 'corr'],292 show_colorbar=True, num_col=5, model_names=None, diagonal=False, show_at=None,293 show_metric=True, **kwargs):294 """295 :param models: list296 models to be visualized.297 :param num_steps: int298 number of time steps.299 :param dynamically: bool300 show propagation per time step or show all time steps at once301 :param kwargs:302 show_condition_probs : bool303 if True, show per time step with plots with quiver overlay. This304 option only has effect when dynamically is set to true.305 show_map : bool306 show map overlay. Default is True.307 num_plot : int308 number of plots for each propagation model.309 traj_overlay : bool310 if True, show the sampled trajectory along with propagation.311 init_loc : list312 a list of coordinate [int, int] of initial locations.313 init_move : list314 a list of initial movements. Movement could be one of "UP", "DOWN", "LEFT", "RIGHT".315 Note if init_move or init_loc is not provided, then trajectory316 is sampled from the map and its initial state is used.317 model_names : list318 list of model names.319 """320 self.num_targets = num_targets321 self.diagonal = diagonal322 self.current_speed = np.ones((self.num_targets), dtype=int)323 self.steps = np.zeros((self.num_targets), dtype=int)324 self.init_moves = None325 self.kwargs = kwargs326 self.traj_overlay = True327 if 'traj_overlay' in kwargs:328 self.traj_overlay = kwargs['traj_overlay']329 if 'init_locs' in kwargs and 'init_moves' in kwargs:330 tracking = False331 self.traj_overlay = False332 super(VisualizeSimulation, self).__init__(models, num_steps, True, tracking,333 measurement_lost, dynamically, show_map, False,334 show_elements, show_colorbar, num_col, model_names,335 show_at, show_metric, **kwargs)336 def initialize_models(self):337 kwargs = self.kwargs338 if 'init_locs' in kwargs and 'init_moves' in kwargs:339 self.num_targets = len(kwargs['init_locs'])340 Vt0, Ot0 = self.get_initial_state(from_traj=False,341 init_locs=kwargs['init_locs'],342 init_moves=kwargs['init_moves'])343 else:344 self.distances, self.trajs = self.models[0].initialize(self.num_targets, self.num_steps, diagonal=self.diagonal)345 Vt0, Ot0 = self.get_initial_state(from_traj=True)346 for model in self.models:347 if not self.tracking:348 model.initialize(self.num_targets, self.num_steps,349 P_Vt=Vt0, P_Ot=Ot0)350 else:351 model.initialize(self.num_targets, self.num_steps,352 distances=self.distances, trajectories=self.trajs)353 def _words_to_idx(self, direction):354 """ Transform words of directions to array indices of Vt. """355 extent = self.extent356 idx = np.array([extent // 2, extent // 2])357 for word in direction.split('_'):358 idx += word_to_vel[word]359 idx = np.where(idx >= 0, idx, 0)360 idx = np.where(idx <= extent-1, idx, extent-1)361 return list(idx)362 def _locs_to_idx(self, from_loc, to_loc):363 """ Transform velocity to array indices of Vt. """364 extent = self.extent365 vel_x = to_loc[0] - from_loc[0]366 vel_y = to_loc[1] - from_loc[1]367 vel = np.array([vel_x, vel_y])368 center_idx = np.array([extent // 2, extent // 2])369 return center_idx + vel370 def get_initial_state(self, from_traj, **kwargs):371 Vt0 = np.zeros_like(self.models[0].P_Vt)372 Ot0 = np.zeros_like(self.models[0].P_Ot)373 if not from_traj:374 self.init_moves = kwargs['init_moves']375 init_locs = kwargs['init_locs']376 # indices of initial movements377 mv_idxs = map(self._words_to_idx, kwargs['init_moves'])378 else:379 init_locs = map(lambda traj: traj[0], self.trajs)380 next_locs = map(lambda traj: traj[1], self.trajs)381 mv_idxs = map(self._locs_to_idx, init_locs, next_locs)382 # indices of initial locations383 idxs = np.array(init_locs).T.tolist()384 # occupancy is 1 at init_locs385 Ot0[idxs] = 1.0386 # put locations and movements together387 v_idxs = map(lambda loc, mv_ix: np.concatenate((loc, mv_ix)), init_locs, mv_idxs)388 v_idxs = np.array(v_idxs).T.tolist()389 Vt0[v_idxs] = 1.0390 return Vt0, Ot0391 # def init_plot_contents(self):392 # """ Decide plot contents for every plot."""393 # colorbar_dict = {'pred': 'occupancy', 'obser': 'map', 'corr': 'occupancy'}394 # for i in range(self.num_models):395 # for j in range(self.num_col):396 #397 # if not self.tracking:398 # colorbar_on = 'occupancy'399 # else:400 # colorbar_on = colorbar_dict[self.show_elements[j]]401 #402 # self.plots[i, j] = Plot(self.axes[i ,j], self.map, self.res,403 # colorbar_on=colorbar_on,404 # plot_map=self.show_map,405 # title='')406 # if j == 0:407 # self.plots[i, j].set_ylabel(self.model_names[i])408 #409 # if self.traj_overlay:410 # self.plots[i, j].add_traj_line(num_targets=self.num_targets)411 # # add title to figure412 # if self.init_moves is not None:413 # self.fig.suptitle("Initial movements = {}".format(str(self.init_moves)))414 def add_traj_overlay(self, i=None, j=None, t=None):415 """ Add trajectory lines on plots. """416 if t is None:417 t = self.models[0].t - 1418 if t >= 0:419 truncated_trajs = self.models[0].traversed_traj_at()420 if i is not None and j is not None:421 plot = self.plots[i, j]422 for idx, line in enumerate(plot.lines):423 xs, ys = truncated_trajs[idx].T[0][-5:], truncated_trajs[idx].T[1][-5:]424 line.set_data(xs, ys)425 else:426 for plot in self.plots.flatten():427 for idx, line in enumerate(plot.lines):428 xs, ys = truncated_trajs[idx].T[0][-5:], truncated_trajs[idx].T[1][-5:]429 line.set_data(xs, ys)430 def show_dynamically_with_condition_probs(self, show_map=True):431 model = None432 for model in self.models:433 if model.__class__.__name__ == 'conditionalPropagateModel':434 model = model435 break436 res = map_resolution437 trans_prob = model.conditional_probs438 fig, axes_ = plt.subplots(2, 2, sharex='all', sharey='all', figsize=(10, 10))439 for i in range(4):440 plot = plt.subplot(2, 2, i + 1)441 probs = np.zeros_like(trans_prob)442 probs[i, ...] = trans_prob[i, ...]443 plot_grid_map_hmm(probs, 'probs', grid_res=res, map_=None, map_res=res)444 directions = {0: 'UP', 1: 'RIGHT', 2: 'DOWN', 3: 'LEFT'}445 if not show_map:446 show_walls(model.P_Ot, resolution=res, cmap='OrRd')447 else:448 show_walls(model.P_Ot, resolution=res, cmap='OrRd', zorder=1)449 show_walls(model.map, resolution=res)...

Full Screen

Full Screen

15_queues.py

Source:15_queues.py Github

copy

Full Screen

...3import threading4import queue5from time import sleep6logging.basicConfig(level=logging.DEBUG, format=THREAD_FORMAT)7def show_elements(queue: queue.Queue) -> None:8 while not queue.empty():9 item = queue.get()10 info(f"The element is: {item}")11 queue.task_done()12 sleep(0.5)13if __name__ == "__main__":14 my_queue = queue.Queue() # FIFO15 for val in range(20):16 my_queue.put(val)17 info("Queue already has elements!")18 for _ in range(4):...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

...3DLL.append(5)4DLL.append(10)5DLL.append(15)6print('\nLista inicial: ')7DLL.show_elements()8print(f'\nValor insertado: {DLL.insert(3,21)} ')9DLL.show_elements()10print(f'\nValor eliminado: {DLL.delete(2)}')11DLL.show_elements()12print('\nLista invertida')13DLL.reverse()14DLL.show_elements()15print('\nLista invertida y elevar al cuadrado')16DLL.reverse_and_pow()...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumBase automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful