-
Notifications
You must be signed in to change notification settings - Fork 0
/
strassen.py
259 lines (220 loc) · 7.85 KB
/
strassen.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import time
import argparse
def brut_force(A,B):
"""
This function performs matrix multiplication using brute force method
Arguments:
A: First matrix
B: Second matrix
Returns:
C: Resultant matrix
count: Number of multiplications
"""
# Get the dimensions of the matrices
m, n = len(A), len(A[0])
_, p = len(B), len(B[0])
# Initialize the resultant matrix with zeros
C = [[0 for i in range(p)] for j in range(m)]
# Initilaize counter to count for multiplications
count = 0
# Compute the matrix multiplication using brute force method
for i in range(m):
for j in range(p):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
count += 1
return C,count
def add(A, B):
"""
This function performs matrix addition
Arguments:
A: First matrix
B: Second matrix
Returns:
C: Resultant matrix
"""
# Get the dimensions of the matrices
m, n = len(A), len(A[0])
# Initialize the resultant matrix with zeros
C = [[0 for i in range(n)] for j in range(m)]
# Add the matrices
for i in range(m):
for j in range(n):
C[i][j] = A[i][j] + B[i][j]
return C
def subtract(A, B):
"""
This function performs matrix subtraction
Arguments:
A: First matrix
B: Second matrix
Returns:
C: Resultant matrix
"""
# Get the dimensions of the matrices
m, n = len(A), len(A[0])
# Initialize the resultant matrix with zeros
C = [[0 for i in range(n)] for j in range(m)]
# Subtract the matrices
for i in range(m):
for j in range(n):
C[i][j] = A[i][j] - B[i][j]
return C
def split(M):
"""
This function splits a matrix into quadrants
Arguments:
M: Matrix to be split
Returns:
c11: Quadrant 1
c12: Quadrant 2
c21: Quadrant 3
c22: Quadrant 4
"""
mid = len(M) // 2
c11 = [row[:mid] for row in M[:mid]]
c12 = [row[mid:] for row in M[:mid]]
c21 = [row[:mid] for row in M[mid:]]
c22 = [row[mid:] for row in M[mid:]]
return c11, c12, c21, c22
def strassen(A,B):
"""
This function performs matrix multiplication using Strassen's algorithm
Arguments:
A: First matrix
B: Second matrix
Returns:
C: Resultant matrix
count: Number of multiplications
"""
n = len(A)
multiply_ops = 0
# Base case: 1x1 matrix
if n == 1:
multiply_ops = 1
return [[A[0][0] * B[0][0]]], multiply_ops
# Splitting the matrices into quadrants
a11, a12, a21, a22 = split(A)
b11, b12, b21, b22 = split(B)
# Strassen's 7 recursive multiplications
m1, m1_ops = strassen(add(a11, a22), add(b11, b22))
m2, m2_ops = strassen(add(a21, a22), b11)
m3, m3_ops = strassen(a11, subtract(b12, b22))
m4, m4_ops = strassen(a22, subtract(b21, b11))
m5, m5_ops = strassen(add(a11, a12), b22)
m6, m6_ops = strassen(subtract(a21, a11), add(b11, b12))
m7, m7_ops = strassen(subtract(a12, a22), add(b21, b22))
count = m1_ops+ m2_ops+ m3_ops+ m4_ops+ m5_ops+ m6_ops+ m7_ops
# Calculating the result matrix
c11 = add(subtract(add(m1, m4), m5), m7)
c12 = add(m3, m5)
c21 = add(m2, m4)
c22 = add(subtract(add(m1, m3), m2), m6)
# Constructing the result matrix from the quadrants
C = [[0 for i in range(n)] for j in range(n)]
mid = n//2
for i in range(mid):
for j in range(mid):
C[i][j] = c11[i][j]
C[i][j + mid] = c12[i][j]
C[i + mid][j] = c21[i][j]
C[i + mid][j + mid] = c22[i][j]
return C, count
def check_power_of_2(n):
"""
This function checks if the number is a power of 2
Arguments:
n: Number to check
Returns:
True if n is a power of 2, False otherwise
"""
if n <= 0:
return False
while n % 2 == 0:
n /= 2
return n == 1
def read_matrices_from_file(filename):
"""
This function reads the matrices from the file and returns them as a list of tuples.
Arguments:
filename: Name of the file containing the matrices
Returns:
A list of tuples containing the matrices. Each tuple contains two matrices A and B.
"""
matrices = []
with open(filename, 'r') as f:
while True:
line = f.readline()
if not line: # End of file
break
elif line.strip() == '':
continue
try:
n = int(line.strip())
if not check_power_of_2(n):
print(f"Error: {n} is not a power of 2. Skipping matrices.")
#Skip the next 2n lines
for i in range(2*n):
f.readline()
continue
try:
A = [list(map(int, f.readline().split())) for i in range(n)]
except:
print(f"Non numeric entity detected in input at n: {n}")
exit(0)
try:
B = [list(map(int, f.readline().split())) for i in range(n)]
except:
print(f"Non numeric entity detected in input at n: {n}")
exit(0)
# Check if A and B are square matrices
if any(len(row) != n for row in A) or any(len(row) != n for row in B):
print("Error: Non-square matrix detected. Skipping matrices.")
continue
matrices.append((A, B))
except ValueError:
# Errors arising from incorrect file formatting
print(f"Error reading matrices from file. Correct input and run again")
exit(1)
return matrices
if __name__ == "__main__":
# Reading input arguments
parser = argparse.ArgumentParser()
parser.add_argument("--input", default='LabStrassenInput.txt', help="Input file name, $file_path/$input_filename.txt or input_filename.txt if input file in same directory as source.py")
parser.add_argument("--output", default='LabStrassenOutput.txt', help="Output file name, $file_path/$output_filename.txt or output_filename.txt if input file in same directory as source.py")
args = parser.parse_args()
# Reading the matrices from the file
matrices = read_matrices_from_file(args.input)
# Initializing dicts To record processing time
time_normal = {}
time_strassen = {}
# Writing the results to output file
with open(args.output, 'w') as f:
# Computing multiplications for each set in the input file and writing the results to output file
# Iterating over each set in the list of matrix and saving the results
for i, (A, B) in enumerate(matrices):
f.write("\n########\n")
f.write("\nComparing Brute Force (Ordinary) and Strassen Multiplication for Matrix Order "+str(len(A))+"\n")
f.write("\n########\n")
f.write("\nMatrix Multiplication Method: Strassen")
st = time.time()
C,count = strassen(A,B)
time_strassen[len(A)] = time.time()-st
f.write("\nNo. of Multiplications: "+str(count))
f.write('\nTime taken to compute: ' +str(time_strassen[len(A)]))
f.write('\nResult:\n')
for row in C:
f.write(str(row)+'\n')
f.write("\n------\n")
f.write("\n------\n")
f.write("Matrix Multiplication Method: Ordinary")
st = time.time()
C,count = brut_force(A,B)
time_normal[len(A)] = time.time()-st
f.write("\nNo. of Multiplications: "+str(count))
f.write('\nTime taken to compute: ' +str(time_normal[len(A)]))
f.write('\nResult:\n')
for row in C:
f.write(str(row)+'\n')
f.close()
print(time_strassen, time_normal)