|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": 1, |
| 6 | + "id": "f03c3997-70f0-4196-b909-d84162d8c2c7", |
| 7 | + "metadata": {}, |
| 8 | + "outputs": [], |
| 9 | + "source": [ |
| 10 | + "import coding_club as cc\n", |
| 11 | + "\n", |
| 12 | + "import numpy as np\n", |
| 13 | + "import time\n", |
| 14 | + "import matplotlib.pyplot as plt" |
| 15 | + ] |
| 16 | + }, |
| 17 | + { |
| 18 | + "cell_type": "code", |
| 19 | + "execution_count": 2, |
| 20 | + "id": "220a9b52-0091-4b07-b926-5d8311844e5d", |
| 21 | + "metadata": {}, |
| 22 | + "outputs": [], |
| 23 | + "source": [ |
| 24 | + "def create_random_matrix(n: int):\n", |
| 25 | + " \"\"\"\n", |
| 26 | + " Initializes an n x n matrix with random numbers from 0 to 1.\n", |
| 27 | + "\n", |
| 28 | + " Args:\n", |
| 29 | + " n: The dimension of the square matrix (e.g., for an n x n matrix).\n", |
| 30 | + "\n", |
| 31 | + " Returns:\n", |
| 32 | + " A numpy array representing the n x n matrix with random numbers.\n", |
| 33 | + " \"\"\"\n", |
| 34 | + " matrix = np.random.rand(n, n)\n", |
| 35 | + " return matrix\n", |
| 36 | + "\n", |
| 37 | + "def manual_matrix_multiply(A: list[list[float]], B: list[list[float]]) -> list[list[float]]:\n", |
| 38 | + " \"\"\"\n", |
| 39 | + " Multiplies two matrices A and B using pure Python.\n", |
| 40 | + " Assumes inputs are well-formed (rectangular) lists of lists.\n", |
| 41 | + " \"\"\"\n", |
| 42 | + " # Get dimensions\n", |
| 43 | + " rows_A = len(A)\n", |
| 44 | + " cols_A = len(A[0])\n", |
| 45 | + " rows_B = len(B)\n", |
| 46 | + " cols_B = len(B[0])\n", |
| 47 | + "\n", |
| 48 | + " # Check if multiplication is possible\n", |
| 49 | + " if cols_A != rows_B:\n", |
| 50 | + " raise ValueError(f\"Cannot multiply matrices of shapes ({rows_A}, {cols_A}) and ({rows_B}, {cols_B}). Inner dimensions must match.\")\n", |
| 51 | + "\n", |
| 52 | + " # Initialize the result matrix C with zeros.\n", |
| 53 | + " # Dimensions of C will be (rows_A, cols_B)\n", |
| 54 | + " C = [[0 for _ in range(cols_B)] for _ in range(rows_A)]\n", |
| 55 | + "\n", |
| 56 | + " # Perform the multiplication\n", |
| 57 | + " # Iterate through each row of A\n", |
| 58 | + " for i in range(rows_A):\n", |
| 59 | + " # Iterate through each column of B\n", |
| 60 | + " for j in range(cols_B):\n", |
| 61 | + " # Calculate the dot product of A's row i and B's column j\n", |
| 62 | + " dot_product = 0\n", |
| 63 | + " for k in range(cols_A): # or range(rows_B)\n", |
| 64 | + " dot_product += A[i][k] * B[k][j]\n", |
| 65 | + " C[i][j] = dot_product\n", |
| 66 | + " \n", |
| 67 | + " return C\n", |
| 68 | + "\n", |
| 69 | + "def matrix_power(matrix: np.ndarray[np.ndarray], exponent: int, nrows: int):\n", |
| 70 | + " \"\"\"\n", |
| 71 | + " Multiplies two matrices using the manual Python matrix multiplication function\n", |
| 72 | + " \"\"\"\n", |
| 73 | + "\n", |
| 74 | + " result = np.eye(nrows, dtype = \"f8\")\n", |
| 75 | + " base = matrix\n", |
| 76 | + "\n", |
| 77 | + " while exponent > 0:\n", |
| 78 | + " if exponent % 2 == 1:\n", |
| 79 | + " result = manual_matrix_multiply(result, base)\n", |
| 80 | + " base = manual_matrix_multiply(base, base)\n", |
| 81 | + " exponent //= 2\n", |
| 82 | + " return result\n", |
| 83 | + "\n", |
| 84 | + "def np_matrix_power(matrix: np.ndarray[np.ndarray], exponent: int, nrows: int):\n", |
| 85 | + " \"\"\"\n", |
| 86 | + " Multiplies two matrices using the numpy.dot matrix multiplication function\n", |
| 87 | + " \"\"\"\n", |
| 88 | + "\n", |
| 89 | + " result = np.eye(nrows, dtype = \"f8\")\n", |
| 90 | + " base = matrix\n", |
| 91 | + "\n", |
| 92 | + " while exponent > 0:\n", |
| 93 | + " if exponent % 2 == 1:\n", |
| 94 | + " result = np.dot(result, base)\n", |
| 95 | + " base = np.dot(base, base)\n", |
| 96 | + " exponent //= 2\n", |
| 97 | + " return result" |
| 98 | + ] |
| 99 | + }, |
| 100 | + { |
| 101 | + "cell_type": "code", |
| 102 | + "execution_count": null, |
| 103 | + "id": "5019de12-010f-4d59-9b69-479a485d6b3a", |
| 104 | + "metadata": {}, |
| 105 | + "outputs": [], |
| 106 | + "source": [ |
| 107 | + "%%time\n", |
| 108 | + "\n", |
| 109 | + "python_times = np.array([])\n", |
| 110 | + "\n", |
| 111 | + "numpy_times = np.array([])\n", |
| 112 | + "\n", |
| 113 | + "py_numpy_times = np.array([])\n", |
| 114 | + "\n", |
| 115 | + "rust_python_times = np.array([])\n", |
| 116 | + "\n", |
| 117 | + "size = [5, 7, 10, 20, 50, 70, 100, 200, 500, 700]\n", |
| 118 | + "\n", |
| 119 | + "iterations = 10\n", |
| 120 | + "\n", |
| 121 | + "for i in size:\n", |
| 122 | + " matrix = create_random_matrix(i)\n", |
| 123 | + "\n", |
| 124 | + " s = time.process_time(); py_result = matrix_power(matrix, iterations, i); e = time.process_time();\n", |
| 125 | + " python_times = np.append(python_times, e-s)\n", |
| 126 | + "\n", |
| 127 | + "\n", |
| 128 | + " s = time.process_time(); numpy_result = np.linalg.matrix_power(matrix, iterations); e = time.process_time();\n", |
| 129 | + " numpy_times = np.append(numpy_times, e-s)\n", |
| 130 | + "\n", |
| 131 | + "\n", |
| 132 | + " s = time.process_time(); rust_result = cc.matrix_power(matrix, iterations); e = time.process_time();\n", |
| 133 | + " rust_python_times = np.append(rust_python_times, e-s)\n", |
| 134 | + "\n", |
| 135 | + " if np.all(np.isclose(py_result, numpy_result)) & np.all(np.isclose(numpy_result, rust_result)) & np.all(np.isclose(py_result, rust_result)):\n", |
| 136 | + " continue\n", |
| 137 | + " else: \n", |
| 138 | + " print(\"Results are inconsistent\")\n", |
| 139 | + " break\n" |
| 140 | + ] |
| 141 | + }, |
| 142 | + { |
| 143 | + "cell_type": "code", |
| 144 | + "execution_count": null, |
| 145 | + "id": "2123601b-fed4-418c-8107-c8b98db516be", |
| 146 | + "metadata": {}, |
| 147 | + "outputs": [], |
| 148 | + "source": [ |
| 149 | + "plt.plot(size, python_times, label = \"Python\")\n", |
| 150 | + "plt.plot(size, numpy_times, label = \"Numpy\")\n", |
| 151 | + "plt.plot(size, rust_python_times, label = \"Rust-Python\")\n", |
| 152 | + "plt.legend()\n", |
| 153 | + "plt.title(\"Runtime Performance on Matrix Benchmark\")\n", |
| 154 | + "plt.ylabel(\"Runtime (seconds)\")\n", |
| 155 | + "plt.xlabel(\"Matrix size\")" |
| 156 | + ] |
| 157 | + }, |
| 158 | + { |
| 159 | + "cell_type": "code", |
| 160 | + "execution_count": null, |
| 161 | + "id": "314bd286-0c80-45e4-9954-6c91fc93d578", |
| 162 | + "metadata": {}, |
| 163 | + "outputs": [], |
| 164 | + "source": [ |
| 165 | + "plt.plot(size, python_times, label = \"Python\")\n", |
| 166 | + "plt.plot(size, numpy_times, label = \"Numpy\")\n", |
| 167 | + "plt.plot(size, rust_python_times, label = \"Rust-Python\")\n", |
| 168 | + "plt.xscale(\"log\")\n", |
| 169 | + "plt.yscale(\"log\")\n", |
| 170 | + "plt.legend()\n", |
| 171 | + "plt.title(\"Runtime Performance on Matrix Benchmark (Log-Log)\")\n", |
| 172 | + "plt.ylabel(\"Runtime (Log(seconds))\")\n", |
| 173 | + "plt.xlabel(\"Log(Matrix size)\")\n", |
| 174 | + "plt.savefig('benchmark.png')" |
| 175 | + ] |
| 176 | + }, |
| 177 | + { |
| 178 | + "cell_type": "code", |
| 179 | + "execution_count": null, |
| 180 | + "id": "68a5392b-6bd0-4aa6-94db-763579611feb", |
| 181 | + "metadata": {}, |
| 182 | + "outputs": [], |
| 183 | + "source": [ |
| 184 | + "rust_python_times/numpy_times" |
| 185 | + ] |
| 186 | + }, |
| 187 | + { |
| 188 | + "cell_type": "code", |
| 189 | + "execution_count": null, |
| 190 | + "id": "c3c9b488-ff19-4d78-8606-2d91a4ab3c98", |
| 191 | + "metadata": {}, |
| 192 | + "outputs": [], |
| 193 | + "source": [ |
| 194 | + "python_times/rust_python_times" |
| 195 | + ] |
| 196 | + } |
| 197 | + ], |
| 198 | + "metadata": { |
| 199 | + "kernelspec": { |
| 200 | + "display_name": "Python 3 (ipykernel)", |
| 201 | + "language": "python", |
| 202 | + "name": "python3" |
| 203 | + }, |
| 204 | + "language_info": { |
| 205 | + "codemirror_mode": { |
| 206 | + "name": "ipython", |
| 207 | + "version": 3 |
| 208 | + }, |
| 209 | + "file_extension": ".py", |
| 210 | + "mimetype": "text/x-python", |
| 211 | + "name": "python", |
| 212 | + "nbconvert_exporter": "python", |
| 213 | + "pygments_lexer": "ipython3", |
| 214 | + "version": "3.13.4" |
| 215 | + } |
| 216 | + }, |
| 217 | + "nbformat": 4, |
| 218 | + "nbformat_minor": 5 |
| 219 | +} |
0 commit comments