Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from functools import partial
- import matplotlib.pyplot as plt
- import numpy as np
- from IPython.display import HTML
- from matplotlib.animation import FuncAnimation
- plt.style.use("ggplot")
- def put_labels(axis):
- axis.set_title("Анимация модулированного сигнала",
- fontsize=16,
- fontweight="bold",
- c="black")
- axis.set_ylabel("Амплитуда",
- fontsize=13,
- fontweight="bold",
- c="dimgray")
- axis.set_xlabel("Время (секунды)",
- fontsize=13,
- fontweight="bold",
- c="dimgray"
- )
- plt.legend(handles=[plt.Line2D([0], [0], color='red', label='Сигнал')],
- bbox_to_anchor=(1, 1), loc="upper right")
- def create_ordinates(abscissa, modulation, fc, frame_id):
- if not modulation:
- ordinates = np.sin(2 * np.pi * (abscissa + frame_id * animation_step) * fc)
- else:
- ordinates = modulation(abscissa + frame_id * animation_step) * np.sin(
- 2 * np.pi * (abscissa + frame_id * animation_step) * fc)
- return ordinates
- def save_file(path, animation):
- if path == "":
- pass
- else:
- animation.save(path, writer="pillow", fps=30)
- def create_modulation_animation(
- modulation,
- fc,
- num_frames,
- plot_duration,
- time_step=0.001,
- animation_step=0.01,
- save_path=""
- ) -> FuncAnimation:
- def update_frame(
- frame_id: int,
- *,
- line: plt.Line2D,
- abscissa: np.ndarray,
- ) -> tuple[plt.Line2D]:
- ordinates = create_ordinates(abscissa, modulation, fc, frame_id)
- line.set_data(abscissa + frame_id * animation_step, ordinates)
- axis.set_xlim((abscissa + frame_id * animation_step)[0], (abscissa + frame_id * animation_step)[-1])
- return line,
- abscissa = np.arange(0, plot_duration, time_step)
- figure, axis = plt.subplots(figsize=(16, 9))
- axis: plt.Axes
- put_labels(axis)
- axis.set_xlim(abscissa.min(), abscissa.max())
- line, *_ = axis.plot(
- abscissa,
- create_ordinates(abscissa, modulation, fc, 0),
- c="red",
- )
- animation = FuncAnimation(
- figure,
- partial(update_frame, line=line, abscissa=abscissa),
- frames=num_frames,
- interval=50,
- blit=True,
- )
- save_file(save_path, animation)
- return animation
- def modulation_function(t):
- return np.sin(t)
- num_frames = 100
- plot_duration = np.pi / 2
- time_step = 0.001
- animation_step = np.pi / 200
- fc = 50
- save_path_with_modulation = "modulated_signal.gif"
- animation = create_modulation_animation(
- modulation=modulation_function,
- fc=fc,
- num_frames=num_frames,
- plot_duration=plot_duration,
- time_step=time_step,
- animation_step=animation_step,
- save_path=save_path_with_modulation
- )
- HTML(animation.to_jshtml())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement