diff --git a/func.gif b/func.gif new file mode 100644 index 00000000..e9febe17 Binary files /dev/null and b/func.gif differ diff --git a/labyrinth.gif b/labyrinth.gif new file mode 100644 index 00000000..fdcbdb00 Binary files /dev/null and b/labyrinth.gif differ diff --git a/loaded_labyrinth.gif b/loaded_labyrinth.gif new file mode 100644 index 00000000..741e11b1 Binary files /dev/null and b/loaded_labyrinth.gif differ diff --git a/medic.png b/medic.png new file mode 100644 index 00000000..ea12941a Binary files /dev/null and b/medic.png differ diff --git a/modulated_signal.gif b/modulated_signal.gif new file mode 100644 index 00000000..b5c936c0 Binary files /dev/null and b/modulated_signal.gif differ diff --git a/solutions/sem02/lesson07/task1.py b/solutions/sem02/lesson07/task1.py index 3a505d89..52d45305 100644 --- a/solutions/sem02/lesson07/task1.py +++ b/solutions/sem02/lesson07/task1.py @@ -13,8 +13,110 @@ def visualize_diagrams( ordinates: np.ndarray, diagram_type: Any, ) -> None: - # ваш код - pass + if abscissa.shape != ordinates.shape: + raise ShapeMismatchError + + if not (diagram_type == "hist" or diagram_type == "violin" or diagram_type == "box"): + raise ValueError + + space = 0.2 + + figure = plt.figure(figsize=(8, 8)) + grid = plt.GridSpec(4, 4, wspace=space, hspace=space) + + axis_scatter = figure.add_subplot(grid[:-1, 1:]) + axis_vert = figure.add_subplot( + grid[:-1, 0], + sharey=axis_scatter, + ) + + axis_hor = figure.add_subplot( + grid[-1, 1:], + sharex=axis_scatter, + ) + + axis_scatter.scatter(abscissa, ordinates, color="deeppink", alpha=0.3) + + if diagram_type == "hist": + axis_hor.hist( + abscissa, + bins=50, + color="lightpink", + density=True, + alpha=0.5, + edgecolor="palevioletred", + linewidth=1, + ) + + axis_vert.hist( + ordinates, + bins=50, + color="lightpink", + orientation="horizontal", + density=True, + alpha=0.5, + edgecolor="palevioletred", + linewidth=1, + ) + + axis_hor.invert_yaxis() + axis_vert.invert_xaxis() + + if diagram_type == "violin": + violin_hor = axis_hor.violinplot( + abscissa, + vert=False, + showmedians=True, + ) + + for body in violin_hor["bodies"]: + body.set_facecolor("violet") + body.set_edgecolor("darkmagenta") + body.set_linewidth(2) + + for part in violin_hor: + if part == "bodies": + continue + + violin_hor[part].set_edgecolor("darkmagenta") + + violin_vert = axis_vert.violinplot( + ordinates, + vert=True, + showmedians=True, + ) + + for body in violin_vert["bodies"]: + body.set_facecolor("violet") + body.set_edgecolor("darkmagenta") + body.set_linewidth(2) + + for part in violin_vert: + if part == "bodies": + continue + + violin_vert[part].set_edgecolor("darkmagenta") + + if diagram_type == "box": + axis_hor.boxplot( + ordinates, + vert=False, + patch_artist=True, + boxprops=dict(facecolor="lightcoral"), + medianprops=dict(color="firebrick"), + ) + axis_vert.set_xticks([]) + axis_vert.set_xlabel("y values") + + axis_vert.boxplot( + abscissa, + vert=True, + patch_artist=True, + boxprops=dict(facecolor="lightcoral"), + medianprops=dict(color="firebrick"), + ) + axis_hor.set_yticks([]) + axis_hor.set_xlabel("x values") if __name__ == "__main__": @@ -25,4 +127,7 @@ def visualize_diagrams( abscissa, ordinates = np.random.multivariate_normal(mean, cov, size=1000).T visualize_diagrams(abscissa, ordinates, "hist") + visualize_diagrams(abscissa, ordinates, "violin") + visualize_diagrams(abscissa, ordinates, "box") + plt.show() diff --git a/solutions/sem02/lesson07/task2.py b/solutions/sem02/lesson07/task2.py index decd607e..f6c373d8 100644 --- a/solutions/sem02/lesson07/task2.py +++ b/solutions/sem02/lesson07/task2.py @@ -1 +1,41 @@ -# ваш код (используйте функции или классы для решения данной задачи) +import matplotlib.pyplot as plt +import numpy as np + +before = [0]*4 +after = [0]*4 +file_path = 'D:/GitHub/python_mipt_dafe_tasks/solutions/sem02/lesson07/data/medic_data.json' +with open(file_path, 'r') as file: + content = file.read() + +before_part = content.split('"before"')[1].split('"after"')[0] +after_part = content.split('"after"')[1] + +before[0] = before_part.count('"I"') - before_part.count('"IV"') +before[1] = before_part.count('"II"') +before[2] = before_part.count('"III"') +before[3] = before_part.count('"IV"') + +after[0] = after_part.count('"I"') - after_part.count('"IV"') +after[1] = after_part.count('"II"') +after[2] = after_part.count('"III"') +after[3] = after_part.count('"IV"') + +figure, axis = plt.subplots(figsize=(9, 9)) + +stages = np.array(['I', 'II', 'III', 'IV']) +axis.set_xticks(np.arange(stages.size), labels=stages, weight="bold") + +x = np.arange(4) +width = 0.35 + +axis.bar(x - width/2, before, width, color='goldenrod', edgecolor='brown') +axis.bar(x + width/2, after, width, color='lightgreen', edgecolor='olive') + +axis.set_ylabel('amount of people') +axis.set_title('Mitral desease stages') +axis.legend(["before", "after"], title="Desease stages") + +figure.savefig("medic.png", bbox_inches="tight") +plt.show() + + diff --git a/solutions/sem02/lesson08/task1.py b/solutions/sem02/lesson08/task1.py index 89f88572..42b7572a 100644 --- a/solutions/sem02/lesson08/task1.py +++ b/solutions/sem02/lesson08/task1.py @@ -8,27 +8,60 @@ def create_modulation_animation( - modulation, - fc, - num_frames, - plot_duration, - time_step=0.001, - animation_step=0.01, - save_path="" + modulation, fc, num_frames, plot_duration, time_step=0.001, animation_step=0.01, save_path="" ) -> FuncAnimation: - # ваш код - return FuncAnimation() + abscissa = np.arange(0, plot_duration, time_step) + + def signal(abscissa, modulation, fc): + f = np.sin(2 * np.pi * fc * abscissa) + + if modulation is None: + return f + else: + return modulation(abscissa) * f + + figure, axis = plt.subplots(figsize=(16, 9)) + axis.set_xlim(0, plot_duration) + + line, *_ = axis.plot( + abscissa, + signal(abscissa, modulation, fc), + c="deeppink", + ) + + def update_frame( + frame_id: int, + ) -> tuple[plt.Line2D]: + new_x = abscissa + frame_id * animation_step + sign = signal(new_x, modulation, fc) + line.set_ydata(sign) + + return (line,) + + animation = FuncAnimation( + figure, + update_frame, + frames=num_frames, + interval=50, + blit=True, + ) + + if save_path: + animation.save("func.gif", writer="pillow", fps=24) + + return animation if __name__ == "__main__": + def modulation_function(t): - return np.cos(t * 6) + return np.cos(t * 6) - num_frames = 100 - plot_duration = np.pi / 2 - time_step = 0.001 - animation_step = np.pi / 200 - fc = 50 + 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( @@ -38,6 +71,6 @@ def modulation_function(t): plot_duration=plot_duration, time_step=time_step, animation_step=animation_step, - save_path=save_path_with_modulation + save_path=save_path_with_modulation, ) - HTML(animation.to_jshtml()) \ No newline at end of file + plt.show() diff --git a/solutions/sem02/lesson08/task2.py b/solutions/sem02/lesson08/task2.py index b677c070..ff594f88 100644 --- a/solutions/sem02/lesson08/task2.py +++ b/solutions/sem02/lesson08/task2.py @@ -7,39 +7,153 @@ from matplotlib.animation import FuncAnimation +def animate_wave_algorithm( + maze: np.ndarray, start: tuple[int, int], end: tuple[int, int], save_path: str = "" +) -> FuncAnimation: + def wave(maze, start, end): + x, y = maze.shape + wave = np.ones(shape=maze.shape, dtype=int) * (-1) + wave[start] = 0 + free_mask = maze == 1 + history = [wave.copy()] + step = 0 + found = False + while not found: + mask = wave == step + + if not mask.any(): + break + + up = np.zeros(shape=mask.shape, dtype=bool) + down = np.zeros(shape=mask.shape, dtype=bool) + left = np.zeros(shape=mask.shape, dtype=bool) + right = np.zeros(shape=mask.shape, dtype=bool) + + up[:-1, :] = mask[1:, :] + down[1:, :] = mask[:-1, :] + left[:, :-1] = mask[:, 1:] + right[:, 1:] = mask[:, :-1] + + near = up | down | left | right + can_go_next = near & free_mask & (wave == -1) + + if not can_go_next.any(): + break + + wave[can_go_next] = step + 1 + + if wave[end] != -1: + found = True + + step += 1 + history.append(wave.copy()) + + path = [] + if found: + curr = end + path.append(curr) + while curr != start: + for nowi, nowj in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + previ, prevj = curr[0] + nowi, curr[1] + nowj + if 0 <= previ < x and 0 <= prevj < y: + if wave[previ, prevj] == wave[curr] - 1: + curr = (previ, prevj) + path.append(curr) + break + + return history, path, found + + def update_frame(frame_id, axis, maze, history, path, found, h, w): + axis.clear() + + data = history[min(frame_id, len(history) - 1)] + + for i in range(h): + for j in range(w): + if maze[i, j] == 0: + color = "white" + else: + if data[i, j] >= 0: + color = "lightpink" + else: + color = "black" + axis.add_patch( + plt.Rectangle((j, h - 1 - i), 1, 1, facecolor=color, edgecolor="black") + ) + + for i in range(h): + for j in range(w): + if data[i, j] >= 0 and maze[i, j] == 1: + axis.text( + j + 0.5, + h - 1 - i + 0.5, + str(data[i, j]), + ha="center", + va="center", + fontsize=8, + ) + + axis.scatter(start[1] + 0.5, h - 1 - start[0] + 0.5, c="red", s=100) + axis.scatter(end[1] + 0.5, h - 1 - end[0] + 0.5, c="olivedrab", s=100) + + if frame_id == len(history) - 1 and found: + for i, j in path: + axis.add_patch( + plt.Rectangle((j, h - 1 - i), 1, 1, facecolor="lightgreen", edgecolor="black") + ) + + axis.set_xlim(0, w) + axis.set_ylim(0, h) + + return + + h, w = maze.shape + history, path, found = wave(maze, start, end) + + figure, axis = plt.subplots(figsize=(8, 8)) + + animation = FuncAnimation( + figure, + partial( + update_frame, axis=axis, maze=maze, history=history, path=path, found=found, h=h, w=w + ), + frames=len(history), + interval=200, + blit=False, + ) + + if save_path: + animation.save(save_path, writer="pillow", fps=5) + + return animation -def animate_wave_algorithm( - maze: np.ndarray, - start: tuple[int, int], - end: tuple[int, int], - save_path: str = "" -) -> FuncAnimation: - # ваш код - return FuncAnimation() if __name__ == "__main__": # Пример 1 - maze = np.array([ - [0, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 0, 1, 0], - [0, 0, 1, 1, 0, 1, 0], - [0, 0, 0, 0, 0, 1, 0], - [1, 1, 1, 1, 1, 1, 0], - [0, 0, 0, 0, 0, 0, 0], - ]) + maze = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 0, 1, 0], + [0, 0, 1, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 0], + [1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + ] + ) start = (2, 0) end = (5, 0) save_path = "labyrinth.gif" # Укажите путь для сохранения анимации animation = animate_wave_algorithm(maze, start, end, save_path) - HTML(animation.to_jshtml()) - + plt.show() + # Пример 2 - - maze_path = "./data/maze.npy" + """ + ##maze_path = "./data/maze.npy" + maze_path = "D:/GitHub/python_mipt_dafe_tasks/solutions/sem02/lesson08/data/maze.npy" loaded_maze = np.load(maze_path) # можете поменять, если захотите запустить из других точек @@ -49,5 +163,4 @@ def animate_wave_algorithm( loaded_animation = animate_wave_algorithm(loaded_maze, start, end, loaded_save_path) HTML(loaded_animation.to_jshtml()) - - \ No newline at end of file + """