-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators.py
83 lines (65 loc) · 2.11 KB
/
operators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from numpy import arange
import scipy.sparse as sp
from scipy.sparse.linalg import LinearOperator
def blur_matrix(n, m):
"""
Construct an elementary sparse blur matrix via nearest-neighbor
averaging.
"""
### Your code here ###
N = n * m
rows = []
cols = []
data = []
for i in range(n):
for j in range(m):
# Index of the current pixel in the flattened array
index = i * m + j
# Central pixel
rows.append(index)
cols.append(index)
data.append(1/2)
# Right neighbor
if j + 1 < m:
rows.append(index)
cols.append(index + 1)
data.append(1/8)
# Left neighbor
if j - 1 >= 0:
rows.append(index)
cols.append(index - 1)
data.append(1/8)
# Lower neighbor
if i + 1 < n:
rows.append(index)
cols.append(index + m)
data.append(1/8)
# Upper neighbor
if i - 1 >= 0:
rows.append(index)
cols.append(index - m)
data.append(1/8)
# Create the sparse matrix in CSR format
blur_matrix = sp.csr_matrix((data, (rows, cols)), shape=(N, N))
return blur_matrix
def tychonov_matrices(n, m, radius=1, alpha=0.1):
### Your code here ###
B = (blur_matrix(n, m))**radius
# Calculate BT
BT = B.transpose()
# Calculate M
# M = (B^T B + alpha*I) x_alpha
M = BT.dot(B) + alpha * sp.eye(B.shape[0])
return M, BT
def tychonov_operators(n, m, radius=1, alpha=0.1):
### Your code here ###
N = n * m
B = blur_matrix(n, m)**radius
# Define matvec for M operator
def Mvec(x):
return (B.transpose()).dot(B.dot(x)) + alpha * x
# Define matvec for BT operator
def BTvec(x):
return (B.dot(x).transpose())
return (LinearOperator((N,N), matvec=Mvec),
LinearOperator((N,N), matvec=BTvec))