def animate_helper(self, i, starts=None, ends=None, extra_starts=None, extra_ends=None, simplify=False, **kwargs): if starts is None: starts = self.window_starts if ends is None: ends = self.window_ends window = self.get_window(self.data, starts[i], ends[i]) if extra_starts is not None: extra = self.get_window(self.data, extra_starts[i], extra_ends[i]) else: extra = None if simplify: if self.bounding_box: bb = plot_bounding_box(get_bounds(self.data), simplify=True) else: bb = [] if extra is not None: # noinspection PyTypeChecker return go.Frame(data=[*bb, *Animator.get_datadict(window), *Animator.get_datadict(extra)], name=str(i), **kwargs) else: return go.Frame(data=[*bb, *Animator.get_datadict(window)], name=str(i), **kwargs) else: if self.bounding_box: self.fig = plot_bounding_box(get_bounds(self.data), fig=self.fig) static_plot(window, **self.get_opts(starts=starts[i], ends=ends[i]), fig=self.fig) if extra is not None: static_plot(extra, **self.tail_opts(starts=extra_starts[i], ends=extra_ends[i]), fig=self.fig, showlegend=False) return self.fig
def animate_real_imag(): """ Animate the time evolution of real and imag part of the wave function """ data = np.load("npz/p8.npz") m = int(np.sqrt(data.shape[1] - 1)) t = data[:, 0] real = np.load("npz/p8_real.npz").reshape(len(t), m, m) imag = np.load("npz/p8_imag.npz").reshape(len(t), m, m) axes = np.linspace(0, 1, m + 2)[1:-1] real_ = go.Contour(x=axes, y=axes, z=real[0]) imag_ = go.Contour(x=axes, y=axes, z=imag[0]) real_frames = [ go.Frame(data=[go.Contour(x=axes, y=axes, z=real[i])]) for i in range(1, len(t)) ] imag_frames = [ go.Frame(data=[go.Contour(x=axes, y=axes, z=imag[i])]) for i in range(1, len(t)) ] layout = go.Layout(updatemenus=[ dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]) ]) rf = go.Figure(data=real_, layout=layout, frames=real_frames) imf = go.Figure(data=imag_, layout=layout, frames=imag_frames) rf.show() imf.show()
def animate(file="p9_3_slit.npz", h=0.005): """ Animate time evolution of a simulation """ data = np.load("npz/" + file) m = int(np.sqrt(data.shape[1] - 1)) t = data[:, 0] Z = data[:, 2:].reshape(len(t), m, m) axes = np.linspace(h, 1 - h, m) data = go.Contour( x=axes, y=axes, z=Z[0], ) frames = [ go.Frame(data=[go.Contour(x=axes, y=axes, z=Z[i].reshape(m, m))]) for i in range(1, len(t)) ] layout = go.Layout(updatemenus=[ dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]) ]) fig = go.Figure(data=data, layout=layout, frames=frames) fig.show()
def plot_array_evolution(exp_progress_dict, exp_interval, field, width_plot, height_plot, zmax=None, zmin=None): matrix_list = [exp_progress_dict[x][field] for x in exp_progress_dict.keys()] fig = go.Figure( data=[go.Heatmap(z=matrix_list[0], zmax=zmax, zmin=zmin)],layout=go.Layout( title="Step 0", updatemenus=[dict( type="buttons", buttons=[dict(label="Play", method="animate", args=[None]), dict(label="Pause", method="animate", args=[None, {"frame": {"duration": 0, "redraw": False}, "mode": "immediate", "transition": {"duration": 0}}], )])] ), frames=[go.Frame(data=[go.Heatmap(z=matrix_list[i])], layout=go.Layout(title_text=f"Step {i * exp_interval}")) for i in range(1, len(matrix_list))] ) fig.update_yaxes(autorange="reversed") fig.update_layout({ 'height': height_plot, 'width': width_plot} ) fig.show()
def plot_frames(fig, xps, yps, zps): fig.update_layout( width=1800, scene_camera_eye_z=0.75, title="Start Title", updatemenus=[ dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]) ]) for i in range(len(xps)): b = list(fig.frames) b.append( go.Frame(data=go.Scatter3d( x=np.asarray(xps[i]) * 1000, y=np.asarray(yps[i]) * 1000, z=np.asarray(zps[i]) * 1000, marker=dict(size=[58, 58, 48, 48, 37.5, 37.5, 37.5, 37.5], colorscale='Viridis', color=('rgb(0, 0, 0)'), opacity=0), line=dict( colorscale="Viridis", width=50, ), ))) fig.frames = tuple(b) # fig.add_trace(data) return fig
def animate_bar_chart(self): frames = [] grouped = self.df[self.df['Date'] > '2020/03'][['Date', 'State/UnionTerritory', 'Confirmed', 'Deaths', 'Cured']].groupby(['Date']) for name, group in iter(grouped): merged = pd.merge(group, self.dummy, how='outer', left_on='State/UnionTerritory', right_on='State') merged.fillna(0, inplace=True) merged.sort_values('State', inplace=True) frames.append(go.Frame(data = [go.Bar(x = merged['State'].tolist(), y=merged['Confirmed'].tolist(), marker_color=self.colors)], layout=go.Layout(title='Confirmed cases - '+group.Date.iloc[0].strftime('%Y-%m-%d')))) fig = go.Figure( data = [go.Bar(x = merged['State'].tolist(), y = [0] * len(merged['State'].tolist()))], frames=frames, layout=go.Layout( autosize=True, xaxis=dict(type='category'), yaxis=dict(range=[0, 3500], autorange=True), title="Confirmed cases", xaxis_title="State", yaxis_title="Count", updatemenus=[dict( type="buttons", buttons=[dict(label="Play", method="animate", args=[None])])])) return dcc.Graph(figure=fig)
def scatter_3d_animate(values): fig = go.Figure(data=[ go.Scatter3d(x=values[0][0], y=values[0][1], z=values[0][2], mode='markers', marker=dict(size=12, color=values[0][2], colorscale='Viridis', opacity=0.8)) ], layout=go.Layout(margin=dict(l=0, r=0, b=0, t=0), updatemenus=[ dict(type="buttons", buttons=[ dict(label="Play", method="animate", args=[None]) ]) ]), frames=[ go.Frame(data=[go.Scatter3d(x=k[0], y=k[1], z=k[2])]) for k in values ]) fig.show()
def step_stage_final(self): temp_bider = np.where(self.bid_store == 1,1,None) self.frames.append(go.Frame(data = [go.Heatmap(z=temp_bider,colorscale=self.colorscale,showscale = False,opacity = 1), go.Contour(z=self.matrix,colorscale='Greys',opacity = 0.65,autocolorscale=False)])) #self.frames.append(go.Frame(data = [go.Contour(z=self.matrix,colorscale='Greys',opacity = 1,visible = True), #go.Scatter(x = np.where(self.bid_store == 1)[1], #y =np.where(self.bid_store == 1)[0],mode='markers',marker = dict(size = 5,line=dict(width=1,color='DarkSlateGrey')))])) tot_view = len(np.where(self.explored == 1)[1]) num_wining_bids = len(np.where(self.bid_store == 1)[1]) self.num_wining_bids.append(num_wining_bids) self.explored_rate.append(tot_view) to_plot = self.model.to_plot if self.model.timestep % int(self.model.plot_interval) == 0 and to_plot: plt.figure(figsize=(15,15)) plt.suptitle(str(self.unique_id+'('+str(tot_view)+'/'+str(self.size**2)+')____'+str(num_wining_bids))) plt.subplot(121) plt.imshow(self.explored) plt.contour(self.matrix,alpha = 0.75) plt.subplot(122) plt.contour(self.matrix,alpha = 0.75) plt.imshow(self.bid_store) plt.show()
def pose_subplot(in_data, idx, plot_type): frame_data = get_frame_info(in_data, idx) vid_shape = in_data['shape'] # (height, width) frame_id = frame_data['frame_id'] vid_image = frame_data['image'] bbox = frame_data['bbox'] extr_body_image = extract_body_image(vid_image, bbox) img_str = img_to_b64(extr_body_image) #img_str = frame_data['b64_img'] pose = frame_data['pose'] fig = make_subplots(rows=1, cols=2, specs=[[{ "type": "xy" }, { "type": "scene" }]], subplot_titles=('Target Body', 'Pose Estimate')) # Add video frame + bbox trace with the show_bbox_frame function add_bbox_frame(fig, img_str, bbox) # Add 3d pose figure body3d(fig, pose) fig.update_xaxes(showticklabels=False) fig.update_yaxes(showticklabels=False) if plot_type == 'init': return fig elif plot_type == 'frame': out_dict = fig.to_dict() out_dict['name'] = str('f' + str(frame_id)) return go.Frame(out_dict)
def simulate(x, y): x = x y = y x1=[] x1=x x1.append(0) x1.append(199) frames = [] for i in range(0, len(x) + 1): x_axis_frame = x[:i] y_axis_frame = y[:i] curr_frame = go.Frame(data=[go.Scatter(x=x_axis_frame, y=y_axis_frame, line_color="black")]) print(curr_frame) frames.append(curr_frame) fig = go.Figure( data=go.Scatter(x=x, y=y), layout={"xaxis": {"mirror": "allticks", 'side': 'top','tickvals':x1}, "yaxis": {"showticklabels": False}, "title": "Disk scheduling algorithm chart", "updatemenus": [ {"type": "buttons", "buttons": [{"method": "animate", "label": "play again", "args": [None, { "frame": {"duration": 500, "redraw": False}, }]}]}] }, frames=frames ) fig.layout.plot_bgcolor = '#ffeeec' fig.layout.paper_bgcolor = '#fff' fig.update_xaxes(range=[0, 200]) fig.update_yaxes(range=[0, max(y) + 1]) fig.update_layout(transition_duration=3000) return fig
def animate(self, fig, data, key, dates): frames = [ go.Frame( data=[ go.Bar(visible=True), self.get_bar_ratings(data, key, date), self.get_pop_map(data, date), ], traces=[0, 1, 2], name=date, ) for date in dates ] steps = [ dict( method="animate", args=[ [date], dict( mode="e", frame=dict(duration=20, redraw=True), transition=dict(duration=0), ), ], label=date, ) for date in dates ] sliders = [dict(steps=steps, active=0)] fig.frames = frames fig.update_layout(sliders=sliders)
def visualize(volume): volume = np.rot90(volume[:, 30:70, :]) st.title("3D Coronal Section Visualization of Segmentation") r, c = volume[0].shape n_slices = volume.shape[0] height = (volume.shape[0] - 1) / 10 grid = np.linspace(0, height, n_slices) slice_step = grid[1] - grid[0] initial_slice = go.Surface(z=height * np.ones((r, c)), surfacecolor=np.flipud(volume[-1]), showscale=False, colorscale='Gray') frames = [ go.Frame(data=[ dict(type='surface', z=(height - k * slice_step) * np.ones((r, c)), surfacecolor=np.flipud(volume[-1 - k])) ], name=f'frame{k+1}') for k in range(1, n_slices) ] sliders = [ dict( steps=[ dict(method='animate', args=[[f'frame{k+1}'], dict(mode='immediate', frame=dict(duration=40, redraw=True), transition=dict(duration=0))], label=f'{k+1}') for k in range(n_slices) ], active=17, transition=dict(duration=0), x=0, # slider starting position y=0, currentvalue=dict(font=dict(size=12), prefix='slice: ', visible=True, xanchor='center'), len=1.0) #slider length ] layout3d = dict( title_text='Coronal View', title_x=0.5, width=600, height=600, scene_zaxis_range=[-0.1, 6.8], sliders=sliders, ) fig = go.Figure(data=[initial_slice], layout=layout3d, frames=frames) #fig.show() st.plotly_chart(fig)
def create_frames(shuffled_array, permutations): f = [] for elt in permutations: shuffled_array[elt[0]], shuffled_array[elt[1]] = ( shuffled_array[elt[1]], shuffled_array[elt[0]], ) f.append(go.Frame(data=[go.Bar(x=x_range, y=shuffled_array)])) return f
def get_frames(self): frames = [] slider_steps = [] for i in range(len(self.df_values)): bar_locs = self.df_ranks.iloc[i].values top_filt = (bar_locs >= 0) & (bar_locs < self.n_bars + 1) bar_vals = self.df_values.iloc[i].values bar_vals[bar_locs == 0] = 0 bar_vals[bar_locs == self.n_bars + 1] = 0 # self.set_value_limit(bar_vals) # plotly bug? not updating range cols = self.df_values.columns.values.copy() cols[bar_locs == 0] = ' ' colors = self.bar_colors bar_locs = bar_locs + np.random.rand(len(bar_locs)) / 10_000 # done to prevent stacking of bars x, y = (bar_vals, bar_locs) if self.orientation == 'h' else (bar_locs, bar_vals) label_axis = dict(tickmode='array', tickvals=bar_locs, ticktext=cols, tickfont=self.tick_label_font) label_axis['range'] = self.ylimit if self.orientation == 'h' else self.xlimit if self.orientation == 'v': label_axis['tickangle'] = -90 value_axis = dict(showgrid=True, type=self.scale)#, tickformat=',.0f') value_axis['range'] = self.xlimit if self.orientation == 'h' else self.ylimit bar = go.Bar(x=x, y=y, width=self.bar_size, textposition=self.bar_textposition, texttemplate=self.bar_texttemplate, orientation=self.orientation, marker_color=colors, insidetextfont=self.bar_label_font, cliponaxis=False, outsidetextfont=self.bar_label_font, hovertemplate=self.hovertemplate, **self.bar_kwargs) data = [bar] xaxis, yaxis = (value_axis, label_axis) if self.orientation == 'h' \ else (label_axis, value_axis) annotations = self.get_annotations(i) if self.slider and i % self.steps_per_period == 0: slider_steps.append( {"args": [[i], {"frame": {"duration": self.duration, "redraw": False}, "mode": "immediate", "fromcurrent": True, "transition": {"duration": self.duration} }], "label": self.get_period_label_text(i), "method": "animate"}) layout = go.Layout(xaxis=xaxis, yaxis=yaxis, annotations=annotations, margin={'l': 150}, **self.layout_kwargs) if self.perpendicular_bar_func: pbar = self.get_perpendicular_bar(bar_vals, i, layout) layout.update(shapes=[pbar], overwrite=True) frames.append(go.Frame(data=data, layout=layout, name=i)) return frames, slider_steps
def warm(self, l0, l1, c, p, l, u, h, s, a, times=20): ''' Прогрев мембраны. Предполагается, что внутренних источников тепла нет Параметры: l0, l1 - массивы состояний мембраны, l1 - конечное состояние с - удельная теплоёмкость материала p - плотность материала l - коэффициент теплопроводности u - температура греющей среды h - шаг разбиения сетки s - шаг времени a - скорость распространения times - количество итераций(кол-во фреймов анимации) Сохраняет массив фреймов для анимации ''' def step(l0, l1): ''' Функция шага уравнения прогрева Возвращает обновленное состояние температуры пластины ''' #Обновление текущего состояния на основе предыдущего в центре n = len(l0) - 1 for i in range(1, n): for j in range(1, n): l1[i][j] = (l*s)/(c*p*h**2)* \ (l0[i+1][j] + l0[i-1][j] + l0[i][j+1] + l0[i][j-1] - 4*l0[i][j]) + l0[i][j] #Обновление текущего состояния на основе предыдущего по бокам for i in range(n + 1): l1[0][i] = (a * h / l * u + l1[1][i]) / (1 + a * h / l) l1[n][i] = (a * h / l * u + l1[n - 1][i]) / (1 + a * h / l) l1[i][0] = (a * h / l * u + l1[i][1]) / (1 + a * h / l) l1[i][n] = (a * h / l * u + l1[i][n - 1]) / (1 + a * h / l) l0 = np.copy(l1) #Поиск минимального и максимального z для корректного масштабирования анимации if self.scale_min > np.amin(l0): self.scale_min = np.amin(l0) - 1 if self.scale_max < np.amax(l1): self.scale_max = np.amax(l1) + 1 return l0, l1 l0 = np.array(l0) l1 = np.array(l1) # Текущее состояние температуры self.start_frame = np.copy(l1) # Стартовый фрейм анимации # Заполение массива фреймов frames = [] for i in range(times): l0, l1 = step(l0, l1) frames.append(go.Frame(data=[go.Surface(z=l1)])) self.frames = frames
def make_animation(self): maze_trace = self.get_maze_trace() fig = go.Figure( data=[ self.frames[0][0], self.frames[0][1], self.frames[0][2], maze_trace ], layout=go.Layout(xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False), plot_bgcolor='#1e1e55', showlegend=False, updatemenus=[ dict(type="buttons", buttons=[ dict(label="Play", method="animate", args=[None]) ]) ]), frames=[ go.Frame(data=[ self.frames[k][0], self.frames[k][1], self.frames[k][2] ]) for k in range(len(self.frames)) ]) fig.update_layout(margin=dict(l=0, r=0, b=0, t=0)) fig.add_annotation(x=-2 if self.is_maze else 13, y=9 if self.is_maze else 20, text="start", showarrow=False, font=dict(family="arial", size=25, color="LightSeaGreen")) fig.add_annotation(x=22 if self.is_maze else -2, y=4 if self.is_maze else 0, text="goal", showarrow=False, font=dict(family="arial", size=25, color="#FF8888")) if self.edge_weight: for edge in self.edge_list: x0, y0 = self.graph.nodes[edge[0]]['pos'] x1, y1 = self.graph.nodes[edge[1]]['pos'] w = edge[2] fig.add_annotation(x=(x0 + x1) / 2 + 1, y=(y0 + y1) / 2, text=str(w), showarrow=False, font=dict(family="arial", size=25, color="#DD0000")) return fig
def construct_animation_frames(self): self.fig_dict['data'] = plot_list[0] frames = [] for frame_id, plot in enumerate(self.plot_list): data = [plot] # list of one or more plots (equal length for # all frames or error probably) name = f"frame_{frame_id}" frames.append(go.Frame(data=data, name=name)) self.fig_dict['frames'] = frames
def set_data(dataset): if dataset == 1: title = "Dataset A" data = get_scatter(1, 0) frames = [ go.Frame(data=get_scatter(1, 1)), ] elif dataset == 2: title = "Dataset B" data = get_scatter(-1, 0) frames = [ go.Frame(data=get_scatter(-1, 1)), ] else: title = "Select a dataset" data = [] frames = [] fig = get_figure(data, frames, title) return fig
def step_stage_final(self): self.tot_sig.append(np.sum(self.matrix)) self.bid_win_store.append(sum(self.bid_win_sig_store)) self.best_bid_store.append( sum(top_k_2d_array(self.original_mat, len(self.bid_win_sig_store)))) temp_bider = np.where(self.bid_store == 1, 1, None) self.frames.append( go.Frame( data=[ go.Heatmap( z=temp_bider, colorscale=self.colorscale, showscale=False, opacity=1, ), go.Contour( z=self.matrix, colorscale="Greys", opacity=0.7, autocolorscale=False, ), ], traces=[0, 1], )) # self.frames.append(go.Frame(data = [go.Contour(z=self.matrix,colorscale='Greys',opacity = 1,visible = True), # go.Scatter(x = np.where(self.bid_store == 1)[1], # y =np.where(self.bid_store == 1)[0],mode='markers',marker = dict(size = 5,line=dict(width=1,color='DarkSlateGrey')))])) tot_view = len(np.where(self.explored == 1)[1]) num_wining_bids = len(np.where(self.bid_store == 1)[1]) self.num_wining_bids.append(num_wining_bids) self.explored_rate.append(tot_view) self.bid_win_count = 0 self.bid_win_sig_store = [] to_plot = self.model.to_plot if self.model.timestep % int( self.model.plot_interval) == 0 and to_plot: plt.figure(figsize=(15, 15)) plt.suptitle( str(self.unique_id + "(" + str(tot_view) + "/" + str(self.size**2) + ")____" + str(num_wining_bids))) plt.subplot(121) plt.imshow(self.explored) plt.contour(self.matrix, alpha=0.75) plt.subplot(122) plt.contour(self.matrix, alpha=0.75) plt.imshow(self.bid_store) plt.show()
def multi_animate(x, y, title): ### animate takes in N x 2 numpy arrays of data. x tracks the path of the predator (red), and y tracks the path of the prey (blue) ### n = len(x) sizes = [len(x[k]) for k in range(n)] x_all = np.vstack(x) y_all = np.vstack(y) xlim = np.max(y_all) + 5 ylim = np.max(y_all) + 5 fig = go.Figure( # initial data data=[go.Scatter(x=x_all[:, 0], y=x_all[:, 1], marker=dict(color="rgba(255, 0, 0, 0.5)")), go.Scatter(x=y_all[:, 0], y=y_all[:, 1], marker=dict(color="rgba(0,0,255, 0.5)")), go.Scatter(x=x_all[:, 0], y=x_all[:, 1], marker=dict(color="rgba(255, 0, 0, 0.5)")), go.Scatter(x=y_all[:, 0], y=y_all[:, 1], marker=dict(color="rgba(0,0,255, 0.5)")) ], # config axes layout=go.Layout( xaxis=dict(range=[-xlim, xlim], autorange=False, zeroline=False), yaxis=dict(range=[-ylim, ylim], autorange=False, zeroline=False), title=title, updatemenus=[dict( type="buttons", buttons=[dict(label="Play", method="animate", args=[None])] )] ), # config frames frames=[go.Frame( data=[ go.Scatter( # predator data x=[x[j][k, 0]], y=[x[j][k, 1]], mode="markers", marker_symbol=202, marker=dict(color="red", size=10) ), go.Scatter( x=[y[j][k, 0]], y=[y[j][k, 1]], # prey data mode="markers", marker_symbol=200, marker=dict(color="blue", size=10) ), go.Scatter( x=x[j][:, 0], y=x[j][:, 1], # predator trace mode="lines", line=dict(color="rgba(255,0,0,0.5)", width=1) ), go.Scatter( x=y[j][:, 0], y=y[j][:, 1], # prey trace mode="lines", line=dict(color="rgba(0,0,255,0.5)", width=1) ) ], traces=[0, 1, 2, 3] ) for j in range(n) for k in range(sizes[j])] ) fig.show()
def animate_optimization(function, x, f_limits=(-15, 15)): function_x_points = np.linspace(f_limits[0], f_limits[1], len(x) * 2) function_y_points = [function.F(x) for x in function_x_points] #plt limits: xm = np.maximum(-300, np.min(function_x_points)) - 5 xM = np.minimum(700, np.max(function_x_points)) + 5 ym = np.maximum(-300, np.min(function_y_points)) - 10 yM = np.minimum(700, np.max(function_y_points)) + 10 opt_x_points = x opt_y_points = [function.F(x) for x in opt_x_points] # Create figure fig = go.Figure(data=[ go.Scatter(x=function_x_points, y=function_y_points, mode="lines", line=dict(width=2, color="blue")), go.Scatter(x=function_x_points, y=function_y_points, mode="lines", line=dict(width=2, color="blue")) ], layout=go.Layout( xaxis=dict(range=[xm, xM], autorange=False, zeroline=False), yaxis=dict(range=[ym, yM], autorange=False, zeroline=False), title_text="Gauss Newton Optimization in 1D", hovermode="closest", updatemenus=[ dict(type="buttons", buttons=[ dict(label="Play", method="animate", args=[None]) ]) ]), frames=[ go.Frame(data=[ go.Scatter(x=[opt_x_points[k]], y=[opt_y_points[k]], mode="markers", marker=dict(color="red", size=10)) ]) for k in range(len(x)) ]) fig.show()
def get_frames(self, frame_range, pitch_control=False, velocities=True, ball=True): frames = [] for frameID in tqdm(frame_range): data_ = self.get_traces(frameID, pitch_control, velocities, ball) name_ = f"f{frameID}" frames.append(go.Frame(data=data_, name=name_)) return frames
def redraw(self): fig = go.Figure(data=self.create(0), layout=go.Layout( xaxis=dict(range=(0, 5), autorange=False), yaxis=dict(range=(0, 5), autorange=False), title="Physarum Polycephalum", updatemenus=[dict( type="buttons", buttons=[dict(label="grow", method="animate", args=(None,))])]), frames=[go.Frame(data=self.create(i)) for i in range(len(self.frames))]) fig.show()
def deflection(self, l_1, l0, l1, a, s, h, times=50): ''' Колебания мембраны. Параметры: l_1, l0, l1 - массивы состояний мембраны, l1 - конечное состояние a - скорость распространения колебаний s - шаг времени h - шаг разбиения сетки times - количество итераций(кол-во фреймов анимации) Сохраняет массив фреймов для анимации ''' def step(l_1, l0, l1): ''' Функция шага уравнения колебания Возвращает обновленное состояние пластины ''' #Обновление текущего состояния на основе предыдущих n = len(l0) m = len(l0[0]) for i in range(1, n - 1): for j in range(1, m - 1): l1[i][j] = a**2 * s**2 / h**2 * \ (l0[i+1][j] + l0[i-1][j] + l0[i][j+1] + l0[i][j-1] - 4*l0[i][j]) + \ 2* l0[i][j] - l_1[i][j] #Обновление предыдущих двух состояний for i in range(1, n - 1): for j in range(1, m - 1): l_1[i][j] = l0[i][j] l0[i][j] = l1[i][j] #Поиск минимального и максимального z для корректного масштабирования анимации if self.scale_min > np.amin(l_1): self.scale_min = np.amin(l_1) - 1 if self.scale_max < np.amax(l1): self.scale_max = np.amax(l1) + 1 return l_1, l0, l1 l_1 = np.array(l_1) l0 = np.array(l0) l1 = np.array(l1) # Текущее состояние пластины self.start_frame = l1 # Стартовый фрейм анимации # Заполение массива фреймов frames = [] for i in range(times): l_1, l0, l1 = step(l_1, l0, l1) frames.append(go.Frame(data=[go.Surface(z=l1)])) self.frames = frames
def play(images, show=True): if len(images.shape) == 4: pass elif len(images.shape) == 3: images = images[..., np.newaxis] layout = __layout_noaxis__() frames = [ go.Frame(data=go.Image(z=images[i]), name=str(i)) for i in range(len(images)) ] fig = go.Figure(data=go.Image(z=images[0]), frames=frames, layout=layout) updatemenus = [{ "buttons": [__play__(50), __pause__()], "direction": "left", "pad": { "r": 10, "t": 70 }, "type": "buttons", "x": 0.1, "y": 0 }] sliders = [{ "pad": { "b": 10, "t": 60 }, "len": 0.9, "x": 0.1, "y": 0, "steps": [{ "args": [[f.name], __frame_args__(0)], "label": str(k), "method": "animate" } for k, f in enumerate(fig.frames)] }] fig.update_layout(updatemenus=updatemenus, sliders=sliders) if show: fig.show() return fig
def write_graph(grouped: Dict): frames = [] with open('austria.json', 'r') as reader: geojson = json.load(reader) print(geojson) for date, simple_counties in grouped.items(): df = pd.DataFrame({ 'date_str': [str(item.time) for item in simple_counties], 'date': [item.time for item in simple_counties], 'lat': [item.lat for item in simple_counties], 'lon': [item.lng for item in simple_counties], 'value': [item.cases for item in simple_counties] }) absolute = sum(df['value']) date_str = date.strftime('%d.%m.%Y') frame = go.Frame( layout=dict(title=f' {date_str}, total: {absolute}'), name=date_str, data=[ go.Scattergeo( locationmode='USA-states', lon=df['lon'], lat=df['lat'], text=df['value'], marker=dict( size=df['value'], autocolorscale=False, line_color='rgb(10,10,10)', line_width=0.5, sizemode='area', colorscale= 'ylorrd', # https://plotly.com/python/builtin-colorscales/ color=df['value'], opacity=0.7)) ]) frames.append(frame) SLIDERS_DICT['steps'].append( get_slider_dict(date_str, txt=f' {date_str}, total: {absolute}')) fig = go.Figure(data=frames[-1].data[0], frames=frames) fig.update_layout(title=f'Timeline der Coronazahlen nach Bezirk', updatemenus=[BUTTON_MENU_DICT], geo=GEO_SETTING, sliders=[SLIDERS_DICT]) fig.show() fig.write_html('bubble.html')
def set_frames(self): frames = [] available_steps = self.trial.steps() for step in available_steps[0:self.steps]: layers = [] if self.label is not None: if len(self.input[step].shape) == 2: # plot predicted image layers.append({ "type": "surface", "surfacecolor": self.input[step] }) for i in range(len(self.tensors[step])): if len(self.tensors[step][i][1].shape) == 1: # set color of fully connected layer for corresponding step layers.append({ "type": "scatter3d", "marker": { "color": self.tensors[step][i][1] } }) elif len(self.tensors[step][i][1].shape) == 2: # set color of convolutional/pooling layer for corresponding step layers.append({ "type": "surface", "surfacecolor": self.tensors[step][i][1] }) if self.prediction is not None: if len(self.output[step].shape) == 1: # plot predicted class for first input in batch layers.append({ "type": "scatter3d", "text": "Predicted class " + str(self.output[step][0]), "textfont": { "size": 40 }, }) elif len(self.output[step].shape) == 2: # plot predicted image layers.append({ "type": "surface", "surfacecolor": self.output[step] }) frames.append(go.Frame(data=layers)) self.fig.frames = frames
def _setup_frames( self, color_countries: int, color_lines: str) -> Tuple[List[go.Frame], list, list, dict]: # Create frames for visualization: frames = list() self.all_sequences.append(self.best_sequence) self.all_dists.append(self.best_dist) for i in range(0, len(self.all_sequences), 1): seq = self.all_sequences[i] # Calculate color for current frame: color = int(color_countries + i / len(self.all_sequences) * (255.0 - color_countries)) # Store all coordinates of the cities for the current frame in correct order: lon_vals = [] lat_vals = [] for s in seq: lon_vals.append(self.dataframe["Längengrad"][s]) lat_vals.append(self.dataframe["Breitengrad"][s]) # Append current frame with all lines connection the cities: frames.append( go.Frame( data=[ go.Scattergeo(lon=lon_vals, lat=lat_vals, line=dict(width=2, color=color_lines), opacity=0.8) ], name=str(i), layout=go.Layout( geo=dict(landcolor='rgb({p},{p},{p})'.format(p=color)), annotations=[ go.layout.Annotation(text="Step {i}".format(i=i), align='left', showarrow=False, xref='paper', yref='paper', x=0, y=0, bordercolor='black', borderwidth=0) ]))) return frames, lon_vals, lat_vals
def get_frames(self, frame_range, pitch_control=False, velocities=True, ball=True): frames = [] for frameID in tqdm(frame_range): data_ = self.get_traces(frameID, pitch_control, velocities, ball) name_ = f"f{frameID}" frames.append(go.Frame(data=data_, name=name_)) # frame = {"data": [], "name": str(frameID)} # frame["data"].extend(self.get_traces(frameID, pitch_control, velocities, ball)) # frames.append(frame) return frames
def _get_animation_frames(locations, order): frames = [] frame_data = [] for i in range(0, len(order) - 1): start_location = locations[order[i]] end_location = locations[order[i + 1]] frame_data.append(go.Scattergeo( locationmode='ISO-3', lon=[start_location.longitude, end_location.longitude], lat=[start_location.latitude, end_location.latitude], text=f'Section {i}', mode='lines+markers', line={'width': 1, 'color': 'red'}, )) frames.append(go.Frame(data=frame_data)) return frames