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
2 changes: 2 additions & 0 deletions deprecated_tests/sem02/tests/task3/test_lesson03_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,3 +494,5 @@ def test_get_extremum_indices_validation(self):

with pytest.raises(ValueError):
get_extremum_indices(np.array([1.0, 2.0]))


5 changes: 3 additions & 2 deletions deprecated_tests/sem02/tests/task4/test_lesson04_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def test_pad_size_validate(self):
id="3d_blur_3",
),
pytest.param(
np.arange(4095 * 4095 * 2).reshape(4095, 4095 * 2) % 256,
np.arange(4095 * 4095 * 2, dtype=np.uint8).reshape(4095, 4095 * 2),
5,
np.load(os.path.join(DATA_PATH, "test_task12_data_res.npy")),
id="large_data",
Expand All @@ -256,7 +256,7 @@ def test_blur_image_validate(self):
with pytest.raises(ValueError):
blur_image(image, -1)


'''
class TestTask2:
@pytest.mark.parametrize(
"image, threshold, expected_color, expected_ratio",
Expand Down Expand Up @@ -354,3 +354,4 @@ def test_get_dominant_color_info_validate(self):

with pytest.raises(ValueError, match="threshold must be positive"):
get_dominant_color_info(image, -1)
'''
Binary file added func.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions ksvenvScriptsActivate.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

SSUUMMMMAARRYY OOFF LLEESSSS CCOOMMMMAANNDDSS

Commands marked with * may be preceded by a number, _N.
Notes in parentheses indicate the behavior if _N is given.
A key preceded by a caret indicates the Ctrl key; thus ^K is ctrl-K.

h H Display this help.
q :q Q :Q ZZ Exit.
---------------------------------------------------------------------------

MMOOVVIINNGG

e ^E j ^N CR * Forward one line (or _N lines).
y ^Y k ^K ^P * Backward one line (or _N lines).
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 loaded_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 medic.png
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.
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 image.ndim == 2:
i, j = image.shape
newimage = np.zeros((i + 2 * pad_size, j + 2 * pad_size), dtype=np.uint8)
newimage[pad_size : pad_size + i, pad_size : pad_size + j] = image

else:
i, j, k = image.shape
newimage = np.zeros((i + 2 * pad_size, j + 2 * pad_size, k), dtype=np.uint8)
newimage[pad_size : pad_size + i, pad_size : pad_size + j, :] = image

return newimage


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

Есть решение быстрее

raise ValueError

if kernel_size == 1:
return image

newimage = pad_image(image, kernel_size // 2)

if image.ndim == 2:
i, j = image.shape
result = np.zeros((i, j), dtype=np.float32)

for a in range(i):
for b in range(j):
result[a, b] = np.mean(newimage[a : a + kernel_size, b : b + kernel_size])

else:
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.

Можно было без if, так код был бы проще

i, j, k = image.shape
result = np.zeros((i, j, k), dtype=np.float32)

for a in range(i):
for b in range(j):
result[a, b] = np.mean(
newimage[a : a + kernel_size, b : b + kernel_size, :], axis=(0, 1)
)

return result.astype(image.dtype)


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

return 0, 0
image.flatten()

colours, counts = np.unique(image, return_counts=True)

maxcolor = colours[0]
maxcount = 0

for color in colours:
mask = np.abs(colours.astype(int) - int(color)) < threshold
count = np.sum(counts[mask])

if count > maxcount:
maxcount = count
maxcolor = color

return np.uint8(maxcolor), maxcount / image.size * 100
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 np.shape(costs) != (len(resource_amounts), len(demand_expected)):
raise ShapeMismatchError

needs = costs @ demand_expected

mask = needs > resource_amounts
if np.any(mask):
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.

А почему не так?!

return not np.any(mask)

return False

return True
19 changes: 18 additions & 1 deletion solutions/sem02/lesson05/task2.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,21 @@ 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]:
i, j = matrix.shape
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.

i, j чаще используются для индексов. Для размеров обычно используются n, m, rows, cols, size и т.д.


if i != j or vector.size != j:
raise ShapeMismatchError

if i != np.linalg.matrix_rank(matrix):
return (None, None)

lens = (np.linalg.norm(matrix, axis=1)) ** 2

pros_norm = (matrix @ vector) / lens

pros = pros_norm[..., np.newaxis] * matrix

orts = vector - pros

return pros, orts
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]
p, k = Vj.shape
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.

Когда так моного одно буквенных переменных, то становится сложно понимать код, лучше тогда использовать Vj_rows, Vj_cols или что-то подобное, чтобы было понятно, что размеры именно для Vj

n = diag_A.size

if m != p or n != k:
raise ShapeMismatchError

A = np.diag(diag_A)

Vjh = np.transpose(np.conj(Vj))
One = np.eye(k)

return Vs - Vj @ (np.linalg.inv(One + (Vjh @ Vj) @ A)) @ (Vjh @ Vs)
109 changes: 107 additions & 2 deletions solutions/sem02/lesson07/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,110 @@ def visualize_diagrams(
ordinates: np.ndarray,
diagram_type: Any,
) -> None:
# ваш код
pass
if abscissa.shape != ordinates.shape:
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.

Функции в 120 строк кода лучше разделять на несколько функций, а то падает читаемость кода.
Так еще и много повторящегося кода.

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__":
Expand All @@ -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()
42 changes: 41 additions & 1 deletion solutions/sem02/lesson07/task2.py
Original file line number Diff line number Diff line change
@@ -1 +1,41 @@
# ваш код (используйте функции или классы для решения данной задачи)
import matplotlib.pyplot as plt
import numpy as np

before = [0]*4
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.

Лучше было бы вынести код в фукнцию

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()
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.

В билиотеке json есть функции для парсинга файлов .json


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"')
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.

А зачем вычитать четвертое? Это не надо было делать

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.

Ну такой повторяющийся код лучше было бы делать в цикле

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()


Loading
Loading