|
| 1 | +""" |
| 2 | +Implementation of Strassen's matrix multiplication algorithm. |
| 3 | +https://en.wikipedia.org/wiki/Strassen_algorithm |
| 4 | +
|
| 5 | +This is a divide-and-conquer algorithm that is asymptotically faster |
| 6 | +than the standard O(n^3) matrix multiplication for large matrices. |
| 7 | +
|
| 8 | +Note: In Python, due to the overhead of recursion and list slicing, |
| 9 | +this implementation will be *slower* than the iterative version |
| 10 | +for small or medium-sized matrices (like 4x4). |
| 11 | +""" |
| 12 | + |
| 13 | +# type Matrix = list[list[int]] # psf/black currently fails on this line |
| 14 | +Matrix = list[list[int]] |
| 15 | + |
| 16 | +# --- Test Matrices (reused from other files) --- |
| 17 | +matrix_1_to_4 = [ |
| 18 | + [1, 2], |
| 19 | + [3, 4], |
| 20 | +] |
| 21 | + |
| 22 | +matrix_5_to_8 = [ |
| 23 | + [5, 6], |
| 24 | + [7, 8], |
| 25 | +] |
| 26 | + |
| 27 | +matrix_count_up = [ |
| 28 | + [1, 2, 3, 4], |
| 29 | + [5, 6, 7, 8], |
| 30 | + [9, 10, 11, 12], |
| 31 | + [13, 14, 15, 16], |
| 32 | +] |
| 33 | + |
| 34 | +matrix_unordered = [ |
| 35 | + [5, 8, 1, 2], |
| 36 | + [6, 7, 3, 0], |
| 37 | + [4, 5, 9, 1], |
| 38 | + [2, 6, 10, 14], |
| 39 | +] |
| 40 | + |
| 41 | +matrix_non_square = [ |
| 42 | + [1, 2, 3], |
| 43 | + [4, 5, 6], |
| 44 | +] |
| 45 | + |
| 46 | + |
| 47 | +# --- Helper function from matrix_multiplication_recursion.py --- |
| 48 | +def is_square(matrix: Matrix) -> bool: |
| 49 | + """ |
| 50 | + Checks if a matrix is square. |
| 51 | + >>> is_square(matrix_1_to_4) |
| 52 | + True |
| 53 | + >>> is_square(matrix_non_square) |
| 54 | + False |
| 55 | + """ |
| 56 | + len_matrix = len(matrix) |
| 57 | + return all(len(row) == len_matrix for row in matrix) |
| 58 | + |
| 59 | + |
| 60 | +# --- Helper function for benchmarking --- |
| 61 | +def matrix_multiply(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: |
| 62 | + """ |
| 63 | + Standard iterative matrix multiplication for comparison. |
| 64 | + >>> matrix_multiply(matrix_1_to_4, matrix_5_to_8) |
| 65 | + [[19, 22], [43, 50]] |
| 66 | + """ |
| 67 | + return [ |
| 68 | + [sum(a * b for a, b in zip(row, col)) for col in zip(*matrix_b)] |
| 69 | + for row in matrix_a |
| 70 | + ] |
| 71 | + |
| 72 | + |
| 73 | +# --- Helper functions for Strassen's Algorithm --- |
| 74 | + |
| 75 | + |
| 76 | +def matrix_add(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: |
| 77 | + """ |
| 78 | + Adds two matrices element-wise. |
| 79 | + >>> matrix_add(matrix_1_to_4, matrix_5_to_8) |
| 80 | + [[6, 8], [10, 12]] |
| 81 | + """ |
| 82 | + return [ |
| 83 | + [matrix_a[i][j] + matrix_b[i][j] for j in range(len(matrix_a[0]))] |
| 84 | + for i in range(len(matrix_a)) |
| 85 | + ] |
| 86 | + |
| 87 | + |
| 88 | +def matrix_subtract(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: |
| 89 | + """ |
| 90 | + Subtracts matrix_b from matrix_a element-wise. |
| 91 | + >>> matrix_subtract(matrix_5_to_8, matrix_1_to_4) |
| 92 | + [[4, 4], [4, 4]] |
| 93 | + """ |
| 94 | + return [ |
| 95 | + [matrix_a[i][j] - matrix_b[i][j] for j in range(len(matrix_a[0]))] |
| 96 | + for i in range(len(matrix_a)) |
| 97 | + ] |
| 98 | + |
| 99 | + |
| 100 | +def split_matrix(matrix: Matrix) -> tuple[Matrix, Matrix, Matrix, Matrix]: |
| 101 | + """ |
| 102 | + Splits a given matrix into four equal quadrants. |
| 103 | + >>> a, b, c, d = split_matrix(matrix_count_up) |
| 104 | + >>> a |
| 105 | + [[1, 2], [5, 6]] |
| 106 | + >>> b |
| 107 | + [[3, 4], [7, 8]] |
| 108 | + >>> c |
| 109 | + [[9, 10], [13, 14]] |
| 110 | + >>> d |
| 111 | + [[11, 12], [15, 16]] |
| 112 | + """ |
| 113 | + n = len(matrix) // 2 |
| 114 | + a11 = [row[:n] for row in matrix[:n]] |
| 115 | + a12 = [row[n:] for row in matrix[:n]] |
| 116 | + a21 = [row[:n] for row in matrix[n:]] |
| 117 | + a22 = [row[n:] for row in matrix[n:]] |
| 118 | + return a11, a12, a21, a22 |
| 119 | + |
| 120 | + |
| 121 | +def combine_matrices( |
| 122 | + c11: Matrix, c12: Matrix, c21: Matrix, c22: Matrix |
| 123 | +) -> Matrix: |
| 124 | + """ |
| 125 | + Combines four quadrants into a single matrix. |
| 126 | + >>> a, b, c, d = split_matrix(matrix_count_up) |
| 127 | + >>> combine_matrices(a, b, c, d) == matrix_count_up |
| 128 | + True |
| 129 | + """ |
| 130 | + n = len(c11) |
| 131 | + result = [] |
| 132 | + for i in range(n): |
| 133 | + result.append(c11[i] + c12[i]) |
| 134 | + for i in range(n): |
| 135 | + result.append(c21[i] + c22[i]) |
| 136 | + return result |
| 137 | + |
| 138 | + |
| 139 | +def pad_matrix(matrix: Matrix, target_size: int) -> Matrix: |
| 140 | + """Pads a matrix with zeros to reach the target_size.""" |
| 141 | + n = len(matrix) |
| 142 | + if n == target_size: |
| 143 | + return matrix |
| 144 | + |
| 145 | + padded_matrix = [[0] * target_size for _ in range(target_size)] |
| 146 | + for i in range(n): |
| 147 | + for j in range(len(matrix[i])): |
| 148 | + padded_matrix[i][j] = matrix[i][j] |
| 149 | + return padded_matrix |
| 150 | + |
| 151 | + |
| 152 | +def unpad_matrix(matrix: Matrix, original_size: int) -> Matrix: |
| 153 | + """Removes padding to return to the original_size.""" |
| 154 | + if len(matrix) == original_size: |
| 155 | + return matrix |
| 156 | + return [row[:original_size] for row in matrix[:original_size]] |
| 157 | + |
| 158 | + |
| 159 | +# --- Main Strassen Function --- |
| 160 | + |
| 161 | + |
| 162 | +def strassen(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: |
| 163 | + """ |
| 164 | + :param matrix_a: A square Matrix. |
| 165 | + :param matrix_b: Another square Matrix with the same dimensions as matrix_a. |
| 166 | + :return: Result of matrix_a * matrix_b. |
| 167 | + :raises ValueError: If the matrices cannot be multiplied. |
| 168 | +
|
| 169 | + >>> strassen([], []) |
| 170 | + [] |
| 171 | + >>> strassen(matrix_1_to_4, matrix_5_to_8) |
| 172 | + [[19, 22], [43, 50]] |
| 173 | + >>> strassen(matrix_count_up, matrix_unordered) |
| 174 | + [[37, 61, 74, 61], [105, 165, 166, 129], [173, 269, 258, 197], [241, 373, 350, 265]] |
| 175 | + >>> strassen(matrix_1_to_4, matrix_non_square) |
| 176 | + Traceback (most recent call last): |
| 177 | + ... |
| 178 | + ValueError: Matrices must be square and of the same dimensions |
| 179 | + >>> strassen(matrix_1_to_4, matrix_count_up) |
| 180 | + Traceback (most recent call last): |
| 181 | + ... |
| 182 | + ValueError: Matrices must be square and of the same dimensions |
| 183 | + """ |
| 184 | + if not matrix_a or not matrix_b: |
| 185 | + return [] |
| 186 | + |
| 187 | + if not ( |
| 188 | + len(matrix_a) == len(matrix_b) |
| 189 | + and is_square(matrix_a) |
| 190 | + and is_square(matrix_b) |
| 191 | + ): |
| 192 | + raise ValueError("Matrices must be square and of the same dimensions") |
| 193 | + |
| 194 | + original_size = len(matrix_a) |
| 195 | + |
| 196 | + # Base case |
| 197 | + if original_size == 1: |
| 198 | + return [[matrix_a[0][0] * matrix_b[0][0]]] |
| 199 | + |
| 200 | + # Pad matrix to the next power of 2 |
| 201 | + n = original_size |
| 202 | + if n & (n - 1) != 0: |
| 203 | + next_power_of_2 = 1 << n.bit_length() |
| 204 | + a = pad_matrix(matrix_a, next_power_of_2) |
| 205 | + b = pad_matrix(matrix_b, next_power_of_2) |
| 206 | + n = next_power_of_2 |
| 207 | + else: |
| 208 | + a = matrix_a |
| 209 | + b = matrix_b |
| 210 | + |
| 211 | + # Split matrices into quadrants |
| 212 | + a11, a12, a21, a22 = split_matrix(a) |
| 213 | + b11, b12, b21, b22 = split_matrix(b) |
| 214 | + |
| 215 | + # Calculate the 7 Strassen products recursively |
| 216 | + p1 = strassen(a11, matrix_subtract(b12, b22)) |
| 217 | + p2 = strassen(matrix_add(a11, a12), b22) |
| 218 | + p3 = strassen(matrix_add(a21, a22), b11) |
| 219 | + p4 = strassen(a22, matrix_subtract(b21, b11)) |
| 220 | + p5 = strassen(matrix_add(a11, a22), matrix_add(b11, b22)) |
| 221 | + p6 = strassen(matrix_subtract(a12, a22), matrix_add(b21, b22)) |
| 222 | + p7 = strassen(matrix_subtract(a11, a21), matrix_add(b11, b12)) |
| 223 | + |
| 224 | + # Calculate result quadrants |
| 225 | + c11 = matrix_add(matrix_subtract(matrix_add(p5, p4), p2), p6) |
| 226 | + c12 = matrix_add(p1, p2) |
| 227 | + c21 = matrix_add(p3, p4) |
| 228 | + c22 = matrix_subtract(matrix_subtract(matrix_add(p5, p1), p3), p7) |
| 229 | + |
| 230 | + # Combine result quadrants |
| 231 | + result = combine_matrices(c11, c12, c21, c22) |
| 232 | + |
| 233 | + # Unpad the result to match original dimensions |
| 234 | + return unpad_matrix(result, original_size) |
| 235 | + |
| 236 | + |
| 237 | +if __name__ == "__main__": |
| 238 | + from doctest import testmod |
| 239 | + |
| 240 | + failure_count, test_count = testmod() |
| 241 | + if not failure_count: |
| 242 | + print("\nBenchmark (Note: Strassen has high overhead in Python):") |
| 243 | + from functools import partial |
| 244 | + from timeit import timeit |
| 245 | + |
| 246 | + # Run fewer iterations as Strassen is slower for small matrices in Python |
| 247 | + mytimeit = partial(timeit, globals=globals(), number=10_0DENIED) |
| 248 | + for func in ("matrix_multiply", "strassen"): |
| 249 | + print( |
| 250 | + f"{func:>25}(): " |
| 251 | + f"{mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}" |
| 252 | + ) |
0 commit comments