diff --git a/PA003/Makefile b/PA003/Makefile index 48dad3d..866620c 100644 --- a/PA003/Makefile +++ b/PA003/Makefile @@ -1,33 +1,24 @@ -FLAGS = -O0 -Wextra -Wall -pedantic -c +FC = gfortran -std=gnu +SRC = gaussian_elimination.f90 +EXEC = gaussian_elimination +MODULE = mymodule.mod +MODF = mymodule.f90 +RM = rm -f -all: main_ada main_bash main_php main_perl +all: $(EXEC) -main_ada: main_ada.adb - # Running Ada Code - gcc -c main_ada.adb - gnatmake --GNATBIND=gnatbind --GNATLINK=gnatlink main_ada - ./main_ada - # ===================== +$(EXEC): $(SRC) $(MODULE) + $(FC) -c $(SRC) + gfortran mymodule.o gaussian_elimination.o -o gaussian_elimination + # $(FC) -o $(EXEC) $(SRC) + -main_bash: main_bash.sh - # Running Bash Code - bash main_bash.sh - # ===================== - -main_php: main_php.php - # Running PHP Code - php main_php.php - # ===================== -main_perl: main_perl.pl - # Running PHP Code - perl main_perl.pl - # ===================== +$(MODULE): $(MODF) + $(FC) -c $(MODF) clean: - rm -f main_ada main_ada.o main_ada.ali + $(RM) *.o *.mod -test: - make clean - make - - ./main +test: clean gaussian_elimination + # ./gaussian_elimination 3 4 1 2 3 4 5 6 7 8 9 10 11 12 + ./gaussian_elimination 3 4 "matrix.txt" diff --git a/PA003/compiled_vs_interpreted.ipynb b/PA003/compiled_vs_interpreted.ipynb index 419b2cd..3186f0a 100644 --- a/PA003/compiled_vs_interpreted.ipynb +++ b/PA003/compiled_vs_interpreted.ipynb @@ -1,11 +1,422 @@ { "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Comparing compiled vs interpreted language performance.\n", + "\n", + "#### Ziad Arafat - 2023-03-05\n", + "\n", + "The performance of compiled and interpreted languages has been a topic of interest in programming languages research for decades. While compiled languages are generally known for their faster runtime performance, interpreted languages offer advantages in terms of ease of use and portability. In this experiment, we aimed to explore the practical performance of compiled and interpreted languages in implementing Gaussian elimination with back substitution, a widely used numerical algorithm. We implemented the algorithm in Python and FORTRAN, and tested their runtime performance on matrices of varying size, with and without the use of numpy. The experiment provides insights into the practical trade-offs between compiled and interpreted languages in the context of numerical algorithms." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### These commands will clean and compile our fortran program so its ready to execute" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "rm -f gaussian_elimination\n", + "gfortran -std=gnu -c mymodule.f90\n", + "gfortran -std=gnu -c gaussian_elimination.f90\n", + "gfortran mymodule.o gaussian_elimination.o -o gaussian_elimination\n", + "# gfortran -std=gnu -o gaussian_elimination gaussian_elimination.f90\n" + ] + } + ], + "source": [ + "!make clean\n", + "!make" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python function to generate a random matrix of size nxn" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def generate_matrix_and_vector(n):\n", + " \"\"\"\n", + " This function generates a random square matrix of size n x n.\n", + " \n", + " Args:\n", + " n: the size of the square matrix\n", + " \n", + " Returns:\n", + " a list of lists representing the random square matrix\n", + " \n", + " \"\"\"\n", + " min_value = -2000.0\n", + " max_value = 2000.0\n", + " \n", + " matrix = []\n", + "\n", + " for row in range(n):\n", + " next_row = []\n", + " for column in range(n):\n", + " next_row.append(random.uniform(min_value, max_value))\n", + " matrix.append(next_row)\n", + " vector = [random.uniform(min_value, max_value) for number in range(n)]\n", + " \n", + " return matrix, vector" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python function to measure our runtime" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "\n", + "def measure_time(func, *args, **kwargs):\n", + " \"\"\"\n", + " This function measures the time it takes to run another function with a given set of arguments.\n", + " \n", + " Args:\n", + " func: the function to be measured\n", + " *args: the positional arguments for the function\n", + " **kwargs: the keyword arguments for the function\n", + " \n", + " Returns:\n", + " the runtime of the function in seconds\n", + " \n", + " \"\"\"\n", + " start_time = time.time()\n", + " func(*args, **kwargs)\n", + " end_time = time.time()\n", + " runtime = end_time - start_time\n", + " return runtime\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python without numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def gaussian_elimination(matrix, vector):\n", + " \"\"\"\n", + " This function performs Gaussian elimination with back substitution on a given square matrix A and vector b, \n", + " without partial pivoting or using numpy.\n", + " \n", + " Args:\n", + " A: a square matrix of size n x n\n", + " b: a vector of length n\n", + " \n", + " Returns:\n", + " x: a vector of length n that represents the solution to the linear system Ax = b\n", + " \n", + " \"\"\"\n", + " n = len(matrix)\n", + " \n", + " # Forward elimination\n", + " for i in range(n):\n", + " # Check if the diagonal element is zero\n", + " if matrix[i][i] == 0:\n", + " raise ValueError('Diagonal element is zero, cannot proceed with Gaussian elimination')\n", + " # Normalize the current row\n", + " for j in range(i + 1, n):\n", + " ratio = matrix[j][i] / matrix[i][i]\n", + " for k in range(i, n):\n", + " matrix[j][k] -= ratio * matrix[i][k]\n", + " vector[j] -= ratio * vector[i]\n", + " \n", + " # Back substitution\n", + " x = [0] * n\n", + " for i in range(n - 1, -1, -1):\n", + " x[i] = vector[i]\n", + " for j in range(i + 1, n):\n", + " x[i] -= matrix[i][j] * x[j]\n", + " x[i] /= matrix[i][i]\n", + " \n", + " return x\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python with numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import scipy\n", + "\n", + "def gaussian_elimination_lu(matrix, vector):\n", + " \"\"\"\n", + " This function performs Gaussian elimination with back substitution using LU decomposition with partial pivoting.\n", + " \n", + " Args:\n", + " n: the size of the square matrix\n", + " matrix: the square matrix as a list of lists\n", + " vector: the vector as a list\n", + " \n", + " Returns:\n", + " the solution vector as a NumPy array\n", + " \n", + " \"\"\"\n", + " # Convert the matrix and vector to NumPy arrays\n", + " \n", + "\n", + " # Perform LU decomposition with partial pivoting\n", + " pivoted, L, U = scipy.linalg.lu(matrix)\n", + "\n", + " # Solve the system using back substitution\n", + " y = np.linalg.solve(L, pivoted.dot(vector))\n", + " x = np.linalg.solve(U, y)\n", + "\n", + " return x\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python functions to run our fortran program" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Function to generate the command line args" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def generate_fortran_args(matrix, vector):\n", + " \"\"\"\n", + " This function generates command line arguments for a Fortran program.\n", + "\n", + " Args:\n", + " matrix: the square matrix as a list of lists\n", + " vector: the vector as a list\n", + "\n", + " Returns:\n", + " a list of command line arguments\n", + "\n", + " \"\"\"\n", + " # Create a new matrix with the vector appended as a new column\n", + " new_matrix = [row + [vector[index]] for index, row in enumerate(matrix)]\n", + " n = len(matrix)\n", + " \n", + " matrix_string = \" \".join([str(x) for row in new_matrix for x in row])\n", + " with open(\"matrix.txt\", \"w\") as file:\n", + " file.write(matrix_string)\n", + " # Flatten the matrix into a list of arguments and start with dimensions\n", + " \n", + " args = [str(n), str(n + 1)] + [\"matrix.txt\"]\n", + "\n", + " return args\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Function to execute the fortran command" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess\n", + "\n", + "def execute_fortran_program(args):\n", + " \"\"\"\n", + " This function executes a local Fortran program with given command line arguments.\n", + " \n", + " Args:\n", + " args: a list of command line arguments\n", + " \n", + " Returns:\n", + " the output of the Fortran program\n", + " \n", + " \"\"\"\n", + " \n", + " # Run the Fortran program with the given arguments using subprocess\n", + "# print(args)\n", + " output = subprocess.check_output(['./gaussian_elimination'] + args, universal_newlines=True)\n", + " \n", + " return output\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Function to execute the fortran with the generated args and measure the runtime" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[-1803.6614565526902, -1163.052031318744, 1204.954132164146, 865.0517943648642, -1880.9897725970268], [-1690.672041585398, -160.9356704378472, -1552.015898166367, -1222.2298544590058, 495.03252376841874], [-797.6153344221682, 764.018508951775, 196.1169544207596, 1726.7528355832578, 1472.4096241622078], [-901.3860003146635, 1051.9136245123414, 1957.2159110539815, 1113.3275403294206, 1357.670213072519], [-748.3247876376345, 224.30346685685345, -221.87982734355091, -453.7220777268508, 1637.7657211029768]]\n", + "(5, 5)\n", + "There are 3 ARGS\n", + "(250, 250) (250,)\n", + "There are 3 ARGS\n", + "(250, 250) (250,)\n", + "There are 3 ARGS\n", + "(250, 250) (250,)\n", + "There are 3 ARGS\n", + "(250, 250) (250,)\n", + "There are 3 ARGS\n", + "(250, 250) (250,)\n", + "There are 3 ARGS\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "\n", + "Program received signal SIGSEGV: Segmentation fault - invalid memory reference.\n", + "\n", + "Backtrace for this error:\n", + "#0 0x7f5579a1af4f in ???\n", + "#1 0x55af40d22864 in ???\n", + "#2 0x55af40d228d5 in ???\n", + "#3 0x7f5579a0578f in ???\n", + "#4 0x7f5579a05849 in ???\n", + "#5 0x55af40d21204 in ???\n", + "#6 0xffffffffffffffff in ???\n" + ] + }, + { + "ename": "CalledProcessError", + "evalue": "Command '['./gaussian_elimination', '200', '201', 'matrix.txt']' died with .", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mCalledProcessError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[0;32mIn[10], line 29\u001b[0m\n\u001b[1;32m 25\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mThere are\u001b[39m\u001b[39m\"\u001b[39m,\u001b[39mlen\u001b[39m(fortran_args), \u001b[39m\"\u001b[39m\u001b[39mARGS\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[1;32m 26\u001b[0m \u001b[39m# result_fortran = measure_time(execute_fortran_program,\u001b[39;00m\n\u001b[1;32m 27\u001b[0m \u001b[39m# fortran_args)\u001b[39;00m\n\u001b[1;32m 28\u001b[0m \u001b[39m# results[\"fortran\"][n_size].append(result_fortran)\u001b[39;00m\n\u001b[0;32m---> 29\u001b[0m execute_fortran_program(fortran_args)\n\u001b[1;32m 31\u001b[0m result_python \u001b[39m=\u001b[39m measure_time(gaussian_elimination, \n\u001b[1;32m 32\u001b[0m matrix, vector)\n\u001b[1;32m 33\u001b[0m results[\u001b[39m\"\u001b[39m\u001b[39mpython no numpy\u001b[39m\u001b[39m\"\u001b[39m][n_size]\u001b[39m.\u001b[39mappend(result_python)\n", + "Cell \u001b[0;32mIn[7], line 17\u001b[0m, in \u001b[0;36mexecute_fortran_program\u001b[0;34m(args)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[39m \u001b[39m\u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 5\u001b[0m \u001b[39m This function executes a local Fortran program with given command line arguments.\u001b[39;00m\n\u001b[1;32m 6\u001b[0m \u001b[39m \u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[39m \u001b[39;00m\n\u001b[1;32m 13\u001b[0m \u001b[39m \"\"\"\u001b[39;00m\n\u001b[1;32m 15\u001b[0m \u001b[39m# Run the Fortran program with the given arguments using subprocess\u001b[39;00m\n\u001b[1;32m 16\u001b[0m \u001b[39m# print(args)\u001b[39;00m\n\u001b[0;32m---> 17\u001b[0m output \u001b[39m=\u001b[39m subprocess\u001b[39m.\u001b[39;49mcheck_output([\u001b[39m'\u001b[39;49m\u001b[39m./gaussian_elimination\u001b[39;49m\u001b[39m'\u001b[39;49m] \u001b[39m+\u001b[39;49m args, universal_newlines\u001b[39m=\u001b[39;49m\u001b[39mTrue\u001b[39;49;00m)\n\u001b[1;32m 19\u001b[0m \u001b[39mreturn\u001b[39;00m output\n", + "File \u001b[0;32m/usr/lib/python3.10/subprocess.py:421\u001b[0m, in \u001b[0;36mcheck_output\u001b[0;34m(timeout, *popenargs, **kwargs)\u001b[0m\n\u001b[1;32m 418\u001b[0m empty \u001b[39m=\u001b[39m \u001b[39mb\u001b[39m\u001b[39m'\u001b[39m\u001b[39m'\u001b[39m\n\u001b[1;32m 419\u001b[0m kwargs[\u001b[39m'\u001b[39m\u001b[39minput\u001b[39m\u001b[39m'\u001b[39m] \u001b[39m=\u001b[39m empty\n\u001b[0;32m--> 421\u001b[0m \u001b[39mreturn\u001b[39;00m run(\u001b[39m*\u001b[39;49mpopenargs, stdout\u001b[39m=\u001b[39;49mPIPE, timeout\u001b[39m=\u001b[39;49mtimeout, check\u001b[39m=\u001b[39;49m\u001b[39mTrue\u001b[39;49;00m,\n\u001b[1;32m 422\u001b[0m \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\u001b[39m.\u001b[39mstdout\n", + "File \u001b[0;32m/usr/lib/python3.10/subprocess.py:526\u001b[0m, in \u001b[0;36mrun\u001b[0;34m(input, capture_output, timeout, check, *popenargs, **kwargs)\u001b[0m\n\u001b[1;32m 524\u001b[0m retcode \u001b[39m=\u001b[39m process\u001b[39m.\u001b[39mpoll()\n\u001b[1;32m 525\u001b[0m \u001b[39mif\u001b[39;00m check \u001b[39mand\u001b[39;00m retcode:\n\u001b[0;32m--> 526\u001b[0m \u001b[39mraise\u001b[39;00m CalledProcessError(retcode, process\u001b[39m.\u001b[39margs,\n\u001b[1;32m 527\u001b[0m output\u001b[39m=\u001b[39mstdout, stderr\u001b[39m=\u001b[39mstderr)\n\u001b[1;32m 528\u001b[0m \u001b[39mreturn\u001b[39;00m CompletedProcess(process\u001b[39m.\u001b[39margs, retcode, stdout, stderr)\n", + "\u001b[0;31mCalledProcessError\u001b[0m: Command '['./gaussian_elimination', '200', '201', 'matrix.txt']' died with ." + ] + } + ], + "source": [ + "def run_and_measure_fortran():\n", + " args = generate_fortran_args(10,\n", + " generate_matrix_and_vector(10),\n", + " [random.randint(0, 100) for _ in range(10)])\n", + " print(args)\n", + " execute_fortran_program(args)\n", + " \n", + "\n", + "\n", + "sample_size = 5\n", + "input_sizes = (250, 200)\n", + "algorithms = (\"fortran\", \"python no numpy\", \"python with numpy\")\n", + "results = dict(zip(algorithms, \n", + " [dict(zip(input_sizes, \n", + " [[] for item in input_sizes])) for _ in algorithms]))\n", + "matrix, vector = generate_matrix_and_vector(5)\n", + "print(matrix)\n", + "matrix_np = np.array(matrix, dtype=float)\n", + "vector_np = np.array(vector, dtype=float)\n", + "print(matrix_np.shape)\n", + "for n_size in input_sizes:\n", + " for sample in range(sample_size):\n", + " matrix, vector = generate_matrix_and_vector(n_size)\n", + " fortran_args = generate_fortran_args(matrix, vector)\n", + " # print(\"There are\",len(fortran_args), \"ARGS\")\n", + " \n", + " print(\"Executing Fortran with\", n_size, \"number\", sample+1)\n", + " result_fortran = measure_time(execute_fortran_program,\n", + " fortran_args)\n", + " results[\"fortran\"][n_size].append(result_fortran)\n", + " # execute_fortran_program(fortran_args)\n", + " \n", + " print(\"Executing python with\", n_size, \"number\", sample+1)\n", + " result_python = measure_time(gaussian_elimination, \n", + " matrix, vector)\n", + " results[\"python no numpy\"][n_size].append(result_python)\n", + " \n", + " print(\"Executing numpy with\", n_size, \"number\", sample+1)\n", + " matrix_np = np.array(matrix, dtype=float)\n", + " vector_np = np.array(vector, dtype=float)\n", + " print(matrix_np.shape, vector_np.shape)\n", + " result_python_numpy = measure_time(gaussian_elimination_lu,\n", + " matrix_np, vector_np)\n", + " results[\"python with numpy\"][n_size].append(result_python_numpy) " + ] + }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "print(results)" + ] } ], "metadata": { @@ -15,7 +426,15 @@ "name": "python3" }, "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", "version": "3.10.9" }, "orig_nbformat": 4, diff --git a/PA003/gaussian_elimination.f90 b/PA003/gaussian_elimination.f90 new file mode 100644 index 0000000..bbe2f5a --- /dev/null +++ b/PA003/gaussian_elimination.f90 @@ -0,0 +1,89 @@ +program read_matrix_from_args + use mymodule + implicit none + integer :: i, j, n, m, index_of_input, s + ! real :: next_argument_real + character (len=128):: nchar, mchar, next_argument + character (len=9999999):: input_array + character (len=2048) :: file_name + integer :: file_unit, file_size, status + real, dimension(:,:), allocatable :: matrix + real, dimension(:), allocatable :: input_list + REAL,DIMENSION(:), allocatable:: result_vector + + file_unit = 10 + ! Get the number of rows and columns from the command line + if (command_argument_count() < 3) then + print *, "Usage: read_matrix_from_args n m\n" + stop + endif + + call getarg(1, nchar) + call getarg(2, mchar) + + read(nchar, *) n + read(mchar, *) m + + call getarg(3, file_name) + + ! Open the file + open(newunit=file_unit, file=file_name, status='old', action='read', iostat=status) + if (status /= 0) then + write(*,*) "Error opening file: ", file_name + stop + end if + + ! Determine the size of the file + inquire(unit=file_unit, size=file_size) + ! Allocate memory for the file contents + ! allocate(input_array(file_size)) + + + ! Read the file into the string + read(file_unit, '(a)', iostat=status) input_array + + ! Allocate memory for the matrix + allocate(matrix(n,m)) + allocate(input_list(n*m)) + allocate(result_vector(n)) + + input_list = string_to_real_array(input_array, n*m) + + ! write (*, '(f20.5)') input_list(1) + + + + index_of_input = 1 + ! Read values from the file string into the matrix + do i = 1, n + do j = 1, m + matrix(i,j) = input_list(index_of_input) + ! write ( * , '(f20.5)', advance="no") matrix(i,j) + ! write ( * , '(f20.5)') input_list(index_of_input) + index_of_input = index_of_input + 1 + end do + end do + + ! gaussian elimination + + do j = 1,n + do i = j + 1, n + matrix(i, :) = matrix(i, :)-matrix(j, :) * matrix(i, j)/matrix(j, j) + end do + end do + + do i = n,1,-1 + s = matrix(i, n + 1) + do j = i + 1, n + s = s - matrix(i, j) * result_vector(j) + end do + result_vector(i) = s/matrix(i,i) + end do + +! ! Deallocate the matrix + ! deallocate(matrix) + ! close(file_unit) + ! deallocate(input_list) +end program read_matrix_from_args + + diff --git a/PA003/mymodule.f90 b/PA003/mymodule.f90 new file mode 100644 index 0000000..648edef --- /dev/null +++ b/PA003/mymodule.f90 @@ -0,0 +1,32 @@ +module mymodule + implicit none + + ! Define the string_to_real_array function + contains +pure function string_to_real_array(str, n) result(arr) + implicit none + character(len=*), intent(in) :: str + character(len=:), allocatable :: str_new + character(len=10) :: index_str + integer, intent(in) :: n + real, dimension(:), allocatable :: arr + integer :: i, status, index_int + str_new = str + ! Allocate memory for the real array + allocate(arr(n)) + + ! Read each real number from the string and store it in the array + i = 1 + do while (len_trim(str_new) > 0) + read(str_new, '(f2.20)', iostat=status) arr(i) + + i = i + 1 + index_int = index(str_new, ' ') + str_new = adjustl(str_new(index_int+1:)) + end do + +end function string_to_real_array + + +end module mymodule + diff --git a/PA003/requirements.txt b/PA003/requirements.txt new file mode 100644 index 0000000..d47e24c --- /dev/null +++ b/PA003/requirements.txt @@ -0,0 +1,2 @@ +numpy==1.24.2 +scipy==1.10.1