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
14 changes: 14 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"markdown.validate.enabled": false
}
{
// Использовать ruff как форматер для Python
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports.ruff": true,
"source.fixAll.ruff": true
}
}
}
Binary file added 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 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.
3 changes: 0 additions & 3 deletions solutions/sem01/lesson12/task3.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import sys


class FileOut:
def __init__(
self,
Expand Down
20 changes: 17 additions & 3 deletions solutions/sem02/lesson03/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,27 @@ class ShapeMismatchError(Exception):
def sum_arrays_vectorized(
lhs: np.ndarray,
rhs: np.ndarray,
) -> np.ndarray: ...
) -> np.ndarray:
if lhs.shape != rhs.shape:
raise ShapeMismatchError
return lhs + rhs


def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray: ...
def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray:
# result = abscissa.copy()
# result **= 2
# result += abscissa *5
# result += 1
# return result
return (abscissa**2) * 3 + abscissa * 2 + 1


def get_mutual_l2_distances_vectorized(
lhs: np.ndarray,
rhs: np.ndarray,
) -> np.ndarray: ...
) -> np.ndarray:
if len(lhs[0]) != len(rhs[0]):
raise ShapeMismatchError
diff_coord = lhs[:, np.newaxis, :] - rhs[np.newaxis, :, :]
summ_coord = np.sum(diff_coord**2, 2)
return summ_coord**0.5
32 changes: 24 additions & 8 deletions solutions/sem02/lesson03/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,31 @@ class ShapeMismatchError(Exception):
pass


def convert_from_sphere(
distances: np.ndarray,
azimuth: np.ndarray,
inclination: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]: ...


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
distance = np.sqrt(abscissa**2 + ordinates**2 + applicates**2)
azimuth = np.arctan2(ordinates, abscissa)

angel_mest = np.zeros(distance.shape)
mask = distance > 0
angel_mest[mask] = np.arccos(applicates[mask] / distance[mask])

return (distance, azimuth, angel_mest)


def convert_from_sphere(
distances: np.ndarray,
azimuth: np.ndarray,
inclination: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
if not (distances.shape == azimuth.shape == inclination.shape):
raise ShapeMismatchError
abscissa = distances * np.sin(inclination) * np.cos(azimuth)
ordinates = distances * np.sin(inclination) * np.sin(azimuth)
applicates = distances * np.cos(inclination)
return (abscissa, ordinates, applicates)
18 changes: 17 additions & 1 deletion solutions/sem02/lesson03/task3.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,20 @@

def get_extremum_indices(
ordinates: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]: ...
) -> tuple[np.ndarray, np.ndarray]:
if len(ordinates) < 3:
raise ValueError

prev = ordinates[:-2]
curr = ordinates[1:-1]
next = ordinates[2:]

min_mask = (curr < prev) & (curr < next)
max_mask = (curr > prev) & (curr > next)

indices = np.arange(1, len(ordinates) - 1)

min_index = indices[min_mask]
max_index = indices[max_mask]

return (min_index, max_index)
66 changes: 62 additions & 4 deletions solutions/sem02/lesson04/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,73 @@


def pad_image(image: np.ndarray, pad_size: int) -> np.ndarray:
# ваш код
return image
if pad_size < 1:
raise ValueError
if image.ndim == 2:
strok, stolb = image.shape
new_strok = strok + 2 * pad_size
new_stolb = stolb + 2 * pad_size
new = np.zeros((new_strok, new_stolb), dtype=image.dtype)
new[pad_size : pad_size + strok, pad_size : pad_size + stolb] = image
return new
strok, stolb, applicate = image.shape
new_strok = strok + 2 * pad_size
new_stolb = stolb + 2 * pad_size
new = np.zeros((new_strok, new_stolb, applicate), dtype=image.dtype)
new[pad_size : pad_size + strok, pad_size : pad_size + stolb, :] = image
return new


def blur_image(
image: np.ndarray,
kernel_size: int,
) -> np.ndarray:
# ваш код
return image
if kernel_size == 1:
return image
if kernel_size % 2 == 0 or kernel_size < 1:
raise ValueError

pad = kernel_size // 2
anticrop = pad_image(image, pad)

integral = np.cumsum(np.cumsum(anticrop, axis=0), axis=1)

if image.ndim == 2:
strok, stolb = image.shape
strok_pad, stolb_pad = anticrop.shape

integral_padded = np.zeros((strok_pad + 1, stolb_pad + 1))
integral_padded[1:, 1:] = integral

i = np.arange(strok)[:, None]
j = np.arange(stolb)[None, :]

total = (
integral_padded[i + kernel_size, j + kernel_size]
- integral_padded[i, j + kernel_size]
- integral_padded[i + kernel_size, j]
+ integral_padded[i, j]
)

return (total / (kernel_size * kernel_size)).astype(image.dtype)

strok, stolb, applicate = image.shape
strok_pad, stolb_pad, _ = anticrop.shape

integral_padded = np.zeros((strok_pad + 1, stolb_pad + 1, applicate))
integral_padded[1:, 1:, :] = integral

i = np.arange(strok)[:, None]
j = np.arange(stolb)[None, :]

total = (
integral_padded[i + kernel_size, j + kernel_size, :]
- integral_padded[i, j + kernel_size, :]
- integral_padded[i + kernel_size, j, :]
+ integral_padded[i, j, :]
)

return (total / (kernel_size * kernel_size)).astype(image.dtype)


if __name__ == "__main__":
Expand All @@ -25,3 +82,4 @@ def blur_image(
image_blured = blur_image(image, kernel_size=21)

compare_images(image, image_blured)
# Саму идею суммы подсмотрел в интернете,ведь мое первое решение с фором внутри фора вычислялось>'
31 changes: 28 additions & 3 deletions solutions/sem02/lesson04/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,34 @@


def get_dominant_color_info(
image: np.ndarray[np.uint8],
image: np.ndarray,
threshold: int = 5,
) -> tuple[np.uint8, float]:
# ваш код
if threshold < 1:
raise ValueError("threshold must be positive")

return 0, 0
histogram = np.zeros(256, dtype=int)

flat_image = image.flatten()
for pixel in flat_image:
histogram[pixel] += 1

max_sum = 0
dominant_color = 0

colors_with_pixels = np.where(histogram > 0)[0]

for color in colors_with_pixels:
left_bound = max(0, int(color) - threshold + 1)
right_bound = min(255, int(color) + threshold - 1)
current_sum = np.sum(histogram[left_bound : right_bound + 1])

if current_sum > max_sum:
max_sum = current_sum
dominant_color = color

percentage = (max_sum / image.size) * 100
return np.uint8(dominant_color), float(percentage)


# Я знаю, что это долго но так и не придумал как можно еще больше векторизовать функцию
12 changes: 11 additions & 1 deletion solutions/sem02/lesson05/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,14 @@ def can_satisfy_demand(
costs: np.ndarray,
resource_amounts: np.ndarray,
demand_expected: np.ndarray,
) -> bool: ...
) -> bool:
if costs.ndim != 2 or resource_amounts.ndim != 1 or demand_expected.ndim != 1:
raise ShapeMismatchError()

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

resources_needed = costs @ demand_expected

return bool(np.all(resources_needed <= resource_amounts))
16 changes: 15 additions & 1 deletion solutions/sem02/lesson05/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,18 @@ 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]:
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
raise ShapeMismatchError()
if matrix.shape[1] != vector.shape[0]:
raise ShapeMismatchError()
N = matrix.shape[0]
if np.linalg.matrix_rank(matrix) < N:
return None, None
dots_av = matrix @ vector
dots_vv = np.linalg.norm(matrix, axis=1) ** 2
scalars = dots_av / dots_vv
projections = scalars[:, np.newaxis] * matrix
orthogonal_components = vector - projections

return projections, orthogonal_components
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:
M = Vs.shape[0]

if Vj.shape[0] != M:
raise ShapeMismatchError()
if diag_A.shape[0] != Vj.shape[1]:
raise ShapeMismatchError()
K = Vj.shape[1]
Vj_H = Vj.conj().T
A = np.diag(diag_A)
I_K = np.eye(K, dtype=complex)
inner = np.linalg.solve(I_K + Vj_H @ Vj @ A, Vj_H @ Vs)
y = Vs - Vj @ inner
return y
59 changes: 53 additions & 6 deletions solutions/sem02/lesson07/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,73 @@
import matplotlib.pyplot as plt
import numpy as np

plt.style.use("ggplot")


class ShapeMismatchError(Exception):
pass


def _plot_dist(ax, data, dtype, vert):
if dtype == "hist":
ax.hist(
data,
bins=50,
color="cornflowerblue",
density=True,
alpha=0.7,
orientation="horizontal" if vert else "vertical",
)
elif dtype == "box":
ax.boxplot(
data,
vert=vert,
patch_artist=True,
boxprops=dict(facecolor="lightsteelblue"),
medianprops=dict(color="k"),
)
elif dtype == "violin":
p = ax.violinplot(data, vert=vert, showmedians=True)
for b in p["bodies"]:
b.set_facecolor("cornflowerblue")
b.set_edgecolor("blue")
for k in p:
if k != "bodies":
p[k].set_edgecolor("cornflowerblue")


def visualize_diagrams(
abscissa: np.ndarray,
ordinates: np.ndarray,
diagram_type: Any,
) -> None:
# ваш код
pass
if abscissa.shape != ordinates.shape:
raise ShapeMismatchError
if diagram_type not in ("hist", "violin", "box"):
raise ValueError

fig = plt.figure(figsize=(8, 8))
gs = plt.GridSpec(4, 4, wspace=0.2, hspace=0.2)

ax1 = fig.add_subplot(gs[:-1, 1:])
ax2 = fig.add_subplot(gs[:-1, 0], sharey=ax1)
ax3 = fig.add_subplot(gs[-1, 1:], sharex=ax1)

ax1.scatter(abscissa, ordinates, color="cornflowerblue", alpha=0.7)
ax1.set_title("Диаграмма рассеяния", fontsize=14, color="dimgray")

_plot_dist(ax3, abscissa, diagram_type, vert=False)
_plot_dist(ax2, ordinates, diagram_type, vert=True)

ax3.invert_yaxis()
ax2.invert_xaxis()

plt.savefig("task1.png")


if __name__ == "__main__":
np.random.seed(42)
mean = [2, 3]
cov = [[1, 1], [1, 2]]
space = 0.2

abscissa, ordinates = np.random.multivariate_normal(mean, cov, size=1000).T

visualize_diagrams(abscissa, ordinates, "hist")
plt.show()
Loading
Loading