DSA-Assignments

Log | Files | Refs | README

problem1_generatePlot.py (1867B)


      1 import os
      2 import matplotlib.pyplot as plt
      3 import numpy as np
      4 from scipy.optimize import curve_fit
      5 
      6 # Function to read measurements from a file
      7 def read_measurements(filename):
      8     measurements = []
      9     with open(filename, 'r') as file:
     10         for line in file:
     11             parts = line.strip().split(',')
     12             if len(parts) == 3 and int(parts[0]) == 1000:  # Check if the first value is 1000
     13                 measurements.append((int(parts[1]), float(parts[2])))  # Ignore the first value
     14     return measurements
     15 
     16 # Function for exponential model
     17 def exponential_model(x, a, b, c):
     18     return a * np.exp(b * x) + c
     19 
     20 # Get the current directory and construct the file path
     21 current_dir = os.getcwd()
     22 file_path = os.path.join(current_dir, 'problem1_data_insertionSort.txt')
     23 
     24 # Read measurements from file
     25 measurements = read_measurements(file_path)
     26 
     27 # Unpacking the measurements
     28 array_sizes, times = zip(*measurements)
     29 
     30 # Convert to numpy arrays for easier handling
     31 array_sizes = np.array(array_sizes)
     32 times = np.array(times)
     33 
     34 # Fit the exponential model to the data
     35 params, covariance = curve_fit(exponential_model, array_sizes, times)
     36 
     37 # Create the 2D plot
     38 plt.figure(figsize=(16, 12))
     39 
     40 # Plotting the original data
     41 plt.scatter(array_sizes, times, c='blue', marker='o', label='Original Data')
     42 
     43 # Plotting the regression curve
     44 array_sizes_fit = np.linspace(min(array_sizes), max(array_sizes), 400)
     45 times_fit = exponential_model(array_sizes_fit, *params)
     46 plt.plot(array_sizes_fit, times_fit, color='red', label='Fitted Curve')
     47 
     48 # Adding labels, title, and legend
     49 plt.xlabel('Array Length')
     50 plt.ylabel('Time (seconds)')
     51 plt.title('Array Length vs Time with Exponential Regression')
     52 plt.legend()
     53 
     54 plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
     55 plt.savefig(os.path.join(current_dir, '2d_plot_with_regression.png'), dpi=500)
     56 
     57 # Show the plot
     58 plt.show()