Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions solutions/sem02/lesson03/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,22 @@ class ShapeMismatchError(Exception):
def sum_arrays_vectorized(
lhs: np.ndarray,
rhs: np.ndarray,
) -> np.ndarray: ...
) -> np.ndarray:
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не проходит ruff format

if lhs.shape != rhs.shape:
raise ShapeMismatchError
return rhs+lhs


def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray: ...
def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray:
ans = 3 * (abscissa ** 2) + 2 * abscissa + 1
return ans


def get_mutual_l2_distances_vectorized(
lhs: np.ndarray,
rhs: np.ndarray,
) -> np.ndarray: ...
) -> np.ndarray:
if lhs.shape != rhs.shape:
raise ShapeMismatchError

return np.sqrt(np.sum((lhs[:, np.newaxis, :] - rhs[np.newaxis, :, :])**2, axis=2))
25 changes: 23 additions & 2 deletions solutions/sem02/lesson03/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,32 @@ def convert_from_sphere(
distances: np.ndarray,
azimuth: np.ndarray,
inclination: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]: ...
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не проходит ruff format

if not distances.shape == azimuth.shape == inclination.shape:
raise ShapeMismatchError

x = distances * np.sin(inclination) * np.cos(azimuth)
y = distances * np.sin(inclination) * np.sin(azimuth)
z = distances * np.cos(inclination)
return x, y, z



def convert_to_sphere(
abscissa: np.ndarray,
ordinates: np.ndarray,
applicates: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]: ...
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:

if not abscissa.shape == ordinates.shape == applicates.shape:
raise ShapeMismatchError

distances = np.sqrt(abscissa**2 + ordinates**2 + applicates**2)
azimuth = np.arctan2(ordinates, abscissa)
inclinatian = np.zeros(distances.shape)

not_zero = distances > 0
devide = applicates[not_zero] / distances[not_zero]
inclinatian[not_zero] = np.arccos(devide)

return distances, azimuth, inclinatian
16 changes: 15 additions & 1 deletion solutions/sem02/lesson03/task3.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,18 @@

def get_extremum_indices(
ordinates: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]: ...
) -> tuple[np.ndarray, np.ndarray]:
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не проходит ruff format

n = len(ordinates)
if n < 3:
raise ValueError

ordinates_safe = ordinates[1:-1]

max_mask = (ordinates_safe > ordinates[:-2]) & (ordinates_safe > ordinates[2:])
min_mask = (ordinates_safe < ordinates[:-2]) & (ordinates_safe < ordinates[2:])
indexes = np.arange(1,n-1)

ans = (indexes[min_mask], indexes[max_mask])

return ans

2 changes: 1 addition & 1 deletion solutions/sem02/lesson04/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
matplotlib==3.8.0
numpy==1.26.1
numpy
opencv-python-headless==4.9.0.80
45 changes: 41 additions & 4 deletions solutions/sem02/lesson04/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,53 @@


def pad_image(image: np.ndarray, pad_size: int) -> np.ndarray:
# ваш код
return image
if pad_size < 1:
raise ValueError
if len(image.shape) != 2:
padded = np.zeros(
(image.shape[0] + pad_size * 2, image.shape[1] + pad_size * 2, image.shape[2]),
dtype=image.dtype,
)
padded[pad_size:-pad_size, pad_size:-pad_size, :] = image
else:
padded = np.zeros(
(image.shape[0] + pad_size * 2, image.shape[1] + pad_size * 2), dtype=image.dtype
)
padded[pad_size:-pad_size, pad_size:-pad_size] = image

return padded


def blur_image(
image: np.ndarray,
kernel_size: int,
) -> np.ndarray:
# ваш код
return image

N = image.shape[0]
M = image.shape[1]

if kernel_size % 2 == 0:
raise ValueError
if kernel_size < 1:
raise ValueError
if kernel_size == 1:
return image

blurred_image = np.zeros_like(image)
image = pad_image(image, kernel_size // 2)

if len(image.shape) == 3:
for i in range(N):
for j in range(M):
blurred_image[i, j] = np.mean(
image[i : i + kernel_size, j : j + kernel_size], axis=(0, 1)
)
else:
for i in range(N):
for j in range(M):
blurred_image[i, j] = np.mean(image[i : i + kernel_size, j : j + kernel_size])

return blurred_image


if __name__ == "__main__":
Expand Down
23 changes: 21 additions & 2 deletions solutions/sem02/lesson04/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ def get_dominant_color_info(
image: np.ndarray[np.uint8],
threshold: int = 5,
) -> tuple[np.uint8, float]:
# ваш код

return 0, 0
if threshold < 1:
raise ValueError("threshold must be positive")

colors = [0] * 256

for i in range(image.shape[0]):
for j in range(image.shape[1]):
colors[image[i, j]] += 1

max_sum = 0
dominant_color = -1
for i in range(256):
if colors[i] > 0:
start = max(0, i - threshold + 1)
end = min(255, i + threshold - 1)
now_sum = sum(colors[start : end + 1])
if now_sum > max_sum:
max_sum = now_sum
dominant_color = i

return np.uint8(dominant_color), max_sum / (image.shape[0] * image.shape[1])
11 changes: 10 additions & 1 deletion solutions/sem02/lesson05/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,13 @@ def can_satisfy_demand(
costs: np.ndarray,
resource_amounts: np.ndarray,
demand_expected: np.ndarray,
) -> bool: ...
) -> bool:

M, N = costs.shape
if len(resource_amounts) != M or len(demand_expected) != N:
raise ShapeMismatchError

required = costs @ demand_expected
ans = required <= resource_amounts
ans = ans.all()
return ans
20 changes: 19 additions & 1 deletion solutions/sem02/lesson05/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,22 @@ class ShapeMismatchError(Exception):
def get_projections_components(
matrix: np.ndarray,
vector: np.ndarray,
) -> tuple[np.ndarray | None, np.ndarray | None]: ...
) -> tuple[np.ndarray | None, np.ndarray | None]:
M, N = matrix.shape

if M != N:
raise ShapeMismatchError
if N != len(vector):
raise ShapeMismatchError

sign_det, _ = np.linalg.slogdet(matrix)
if sign_det == 0:
return (None, None)

scalar_res = matrix @ vector
norm_matrix_2 = np.sum(matrix**2, axis=1)
ortogonal_proj_c = scalar_res / norm_matrix_2
ortogonal_proj = ortogonal_proj_c[:, np.newaxis] * matrix
ortogonal_parts = vector - ortogonal_proj

return (ortogonal_proj, ortogonal_parts)
15 changes: 14 additions & 1 deletion solutions/sem02/lesson05/task3.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,17 @@ def adaptive_filter(
Vs: np.ndarray,
Vj: np.ndarray,
diag_A: np.ndarray,
) -> np.ndarray: ...
) -> np.ndarray:

if Vs.shape[0] != Vj.shape[0]:
raise ShapeMismatchError
if len(diag_A) != Vj.shape[1]:
raise ShapeMismatchError

print(diag_A)
Vjh = Vj.conj().T
VjA = Vj * diag_A
inn = np.eye(Vj.shape[1]) + Vjh @ VjA
temp = np.linalg.inv(inn)
y = Vs - Vj @ (temp @ (Vjh @ Vs))
return y
Binary file added solutions/sem02/lesson07/class_distribution.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 61 additions & 1 deletion solutions/sem02/lesson07/task1.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Any

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

Expand All @@ -13,7 +14,66 @@ def visualize_diagrams(
ordinates: np.ndarray,
diagram_type: Any,
) -> None:
# ваш код

if abscissa.shape != ordinates.shape:
raise ShapeMismatchError
if diagram_type not in ("hist", "violin", "box"):
raise ValueError

fig = plt.figure(figsize=(10, 10), facecolor="#cfd3cd")

gs = gridspec.GridSpec(
2,
2,
width_ratios=[1, 4],
height_ratios=[4, 1],
hspace=0.1,
wspace=0.1,
left=0.08,
right=0.98,
top=0.98,
bottom=0.08,
)

ax_scatter = fig.add_subplot(gs[0, 1])
ax_diag_x = fig.add_subplot(gs[1, 1])
ax_diag_y = fig.add_subplot(gs[0, 0])
ax_diag_x.grid(True)
ax_diag_y.grid(True)
ax_scatter.grid(True)
ax_scatter.tick_params(labelsize=16)
ax_diag_x.tick_params(labelsize=16)
ax_diag_y.tick_params(labelsize=16)

ax_scatter.scatter(abscissa, ordinates, alpha=0.5, marker="o", s=100, color="sandybrown")

if diagram_type == "hist":
ax_diag_x.hist(
abscissa, bins=30, color="cornflowerblue", edgecolor="dimgray", alpha=0.7, density=True
)
ax_diag_y.hist(
ordinates,
bins=30,
orientation="horizontal",
color="cornflowerblue",
edgecolor="dimgray",
alpha=0.7,
density=True,
)

elif diagram_type == "violin":
ax_diag_x.violinplot(abscissa, vert=False)
ax_diag_y.violinplot(ordinates, vert=True)

elif diagram_type == "box":
ax_diag_x.boxplot(abscissa, vert=False)
ax_diag_y.boxplot(ordinates, vert=True)

ax_diag_x.invert_yaxis()
ax_diag_y.invert_xaxis()

plt.savefig("scatter_with_diagrams.png")

pass


Expand Down
49 changes: 48 additions & 1 deletion solutions/sem02/lesson07/task2.py
Original file line number Diff line number Diff line change
@@ -1 +1,48 @@
# ваш код (используйте функции или классы для решения данной задачи)
import json

import matplotlib.pyplot as plt
import numpy as np


def get_data_for_plot(file_path: str) -> tuple[np.ndarray, np.ndarray]:
with open(file_path, "r") as f:
data = json.load(f)
before = np.array(data["before"])
after = np.array(data["after"])
return before, after


def sum_classes(before: np.ndarray, after: np.ndarray, classes=["I", "II", "III", "IV"]):
before_sum = {}
after_sum = {}
for cl in classes:
mask = before == cl
before_sum[cl] = np.sum(mask)
mask = after == cl
after_sum[cl] = np.sum(mask)
return before_sum, after_sum


classes = ["I", "II", "III", "IV"]
before, after = get_data_for_plot("data/medic_data.json")
before_sum, after_sum = sum_classes(before, after)

fig, ax = plt.subplots(figsize=(9, 6))
x = np.arange(len(classes))
ax.tick_params(labelsize=16)

width = 0.35
bars1 = ax.bar(x - width / 2, before_sum.values(), width, label="before", color="cornflowerblue")
bars2 = ax.bar(x + width / 2, after_sum.values(), width, label="after", color="sandybrown")

ax.set_xlabel("Mitral disease stage", fontsize=16)
ax.set_ylabel("Amount of people", fontsize=16)
ax.set_title("Mitral disease stages", fontsize=16)
ax.grid(axis="y", color="#cacaca", linewidth=0.8)
ax.set_axisbelow(True)
ax.set_xticks(x)
ax.set_xticklabels(classes)
ax.legend(fontsize=16)

plt.savefig("class_distribution.png")
plt.show()
Binary file added solutions/sem02/lesson08/labyrinth.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added solutions/sem02/lesson08/modulated_signal.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading