0% found this document useful (0 votes)
2 views

Assignment of Electrical

This document outlines a laboratory work assignment for the Numerical Computations course at COMSATS University Islamabad, focusing on data interpolation using Python and Tkinter. It includes code for loading CSV data, performing linear and Lagrange interpolation, and visualizing the results. Additionally, it provides a justification for the choice of interpolation methods based on data characteristics.

Uploaded by

ahmedraza786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment of Electrical

This document outlines a laboratory work assignment for the Numerical Computations course at COMSATS University Islamabad, focusing on data interpolation using Python and Tkinter. It includes code for loading CSV data, performing linear and Lagrange interpolation, and visualizing the results. Additionally, it provides a justification for the choice of interpolation methods based on data characteristics.

Uploaded by

ahmedraza786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

COMSATS University Islamabad (CUI), Wah Campus

Numerical Computations MTH375


Laboratory Work - 2024

Program/Class: BEE-5/A Date: 25th DEC,2024


Subject: NUMERICAL COMPUTATION Instructor: Dr. KAWAL SAEED
Student Name: MUHAMMAD AHMAD Registration #: FA22-BEE-017

OPEN ENDED LAB CODE

import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.interpolate import lagrange
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Function to load data from a CSV file


def load_data():
global x, y
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
if file_path:
try:
data = np.genfromtxt(file_path, delimiter=",", skip_header=1)
x, y = data[:, 0], data[:, 1] # Assuming first column is x, second is y
messagebox.showinfo("Success", "Data loaded successfully!")
except Exception as e:

1|Page
COMSATS University Islamabad (CUI), Wah Campus
Numerical Computations MTH375
Laboratory Work - 2024

messagebox.showerror("Error", f"Failed to load data: {e}")

# Function to interpolate and plot the data


def plot_interpolation():
if x is None or y is None:
messagebox.showerror("Error", "No data loaded!")
return

method = method_var.get()
xp = np.linspace(min(x), max(x), 500) # Generate fine x points for smooth plot

try:
if method == "Linear":
interpolator = interp1d(x, y, kind="linear")
yp = interpolator(xp)
elif method == "Lagrange":
poly = lagrange(x, y)
yp = poly(xp)
else:
messagebox.showerror("Error", "Invalid interpolation method selected!")
return

# Plot the data and interpolation


ax.clear()
ax.plot(x, y, 'o', label='Data Points')
ax.plot(xp, yp, '-', label=f'{method} Interpolation')

2|Page
COMSATS University Islamabad (CUI), Wah Campus
Numerical Computations MTH375
Laboratory Work - 2024

ax.set_title(f'{method} Interpolation')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
canvas.draw()
except Exception as e:
messagebox.showerror("Error", f"Failed to interpolate: {e}")

# Function to justify the method selection


def justify_method():
justification = (
"Method Selection Justification:\n"
"- Linear Interpolation: Best for sparse or linearly varying data.\n"
"- Lagrange Interpolation: Useful for polynomial fitting, but may oscillate for large
datasets.\n\n"
"Analyze the plot visually to determine which method suits the dataset best."
)
messagebox.showinfo("Justification", justification)

# Initialize main Tkinter window


root = tk.Tk()
root.title("Interpolation Viewer")

# Variables for storing x and y data


x, y = None, None

3|Page
COMSATS University Islamabad (CUI), Wah Campus
Numerical Computations MTH375
Laboratory Work - 2024

# Frame for controls


frame = tk.Frame(root)
frame.pack(pady=10)

# Load Data Button


load_button = tk.Button(frame, text="Load Data", command=load_data)
load_button.grid(row=0, column=0, padx=5)

# Interpolation Method Dropdown


method_var = tk.StringVar()
method_var.set("Linear") # Default method
method_menu = ttk.OptionMenu(frame, method_var, "Linear", "Linear", "Lagrange")
method_menu.grid(row=0, column=1, padx=5)

# Plot Button
plot_button = tk.Button(frame, text="Plot", command=plot_interpolation)
plot_button.grid(row=0, column=2, padx=5)

# Justification Button
justify_button = tk.Button(frame, text="Justify Method", command=justify_method)
justify_button.grid(row=0, column=3, padx=5)

# Matplotlib Figure
fig, ax = plt.subplots(figsize=(6, 4))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()

4|Page
COMSATS University Islamabad (CUI), Wah Campus
Numerical Computations MTH375
Laboratory Work - 2024

canvas_widget.pack()

# Run the Tkinter event loop


root.mainloop()

5|Page

You might also like