❓ Help Pa help Python code about numerical methods

holtnari

Enthusiast
Can u help me modify my code that the output would be the predicted csv?
Its about divided difference interpolation and extrapolation.

python code
import csv
from tkinter import Tk, Label, Button, Entry, filedialog, Text, Scrollbar, VERTICAL, RIGHT, Y, Listbox
from datetime import datetime, timedelta

def read_data(file_path):
"""Read historical weather data from a CSV file."""
data = []
with open(file_path, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
data.append({
"date": datetime.strptime(row["date"], "%Y-%m-%d"),
"temperature": float(row["temperature"]),
"humidity": float(row["humidity"]),
"rainfall": float(row["rainfall"])
})
return data

def divided_difference(x_values, y_values):
"""Calculate coefficients for the Divided Difference Method."""
n = len(y_values)
coef = [y for y in y_values]
for j in range(1, n):
for i in range(n - j):
coef = (coef[i + 1] - coef) / (x_values[i + j] - x_values)
return coef

def interpolate(date, historical_data, degree):
"""Interpolate or extrapolate weather data for a given date using a polynomial of specified degree."""
if degree + 1 > len(historical_data):
raise ValueError("Not enough data points to create the specified degree polynomial.")

x_values = [(d["date"] - historical_data[0]["date"]).days for d in historical_data[:degree + 1]]
predictions = {}
for key in ["temperature", "humidity", "rainfall"]:
y_values = [d[key] for d in historical_data[:degree + 1]]
coef = divided_difference(x_values, y_values)

# Polynomial evaluation
days = (date - historical_data[0]["date"]).days
prediction = coef[0]
for i in range(1, len(coef)):
term = coef
for j in range(i):
term *= (days - x_values[j])
prediction += term

# Clamp predictions to realistic ranges
if key == "temperature":
prediction = max(min(prediction, 50), -30) # Temperature between -30°C and 50°C
elif key == "humidity":
prediction = max(min(prediction, 100), 0) # Humidity between 0% and 100%
elif key == "rainfall":
prediction = max(prediction, 0) # Rainfall cannot be negative

predictions[key] = prediction
return predictions

class WeatherApp:
def init(self, master):
self.master = master
master.title("Weather Prediction System")

# File selection
self.label = Label(master, text="Select CSV File:")
self.label.pack()

self.select_file_button = Button(master, text="Browse", command=self.load_file)
self.select_file_button.pack()

self.file_label = Label(master, text="")
self.file_label.pack()

# Input fields
self.start_date_label = Label(master, text="Enter Start Date (YYYY-MM-DD):")
self.start_date_label.pack()

self.start_date_entry = Entry(master)
self.start_date_entry.pack()

self.num_days_label = Label(master, text="Enter Number of Predictions:")
self.num_days_label.pack()

self.num_days_entry = Entry(master)
self.num_days_entry.pack()

# Predict button
self.predict_button = Button(master, text="Predict", command=self.predict_weather)
self.predict_button.pack()

# Results display
self.results_label = Label(master, text="Predictions:")
self.results_label.pack()

self.results_listbox = Listbox(master, height=15, width=100)
self.results_listbox.pack(side="left", fill="y")

self.scrollbar = Scrollbar(master, orient=VERTICAL, command=self.results_listbox.yview)
self.scrollbar.pack(side=RIGHT, fill=Y)

self.results_listbox.config(yscrollcommand=self.scrollbar.set)

self.historical_data = []

def load_file(self):
"""Load CSV file and display file name."""
file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])
if file_path:
self.file_label.config(text=f"File Loaded: {file_path}")
self.historical_data = read_data(file_path)

def predict_weather(self):
"""Predict weather based on user inputs."""
if not self.historical_data:
self.results_listbox.insert("end", "No file loaded! Please load a CSV file first.")
return

start_date_str = self.start_date_entry.get()
try:
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
except ValueError:
self.results_listbox.insert("end", "Invalid date format. Use YYYY-MM-DD.")
return

try:
num_predictions = int(self.num_days_entry.get())
if num_predictions < 1:
self.results_listbox.insert("end", "Number of predictions must be at least 1.")
return
except ValueError:
self.results_listbox.insert("end", "Invalid number of predictions. Please enter a valid integer.")
return

# Determine degree
degree = 4 if start_date >= self.historical_data[0]["date"] and start_date <= self.historical_data[-1]["date"] else 2

self.results_listbox.delete(0, "end") # Clear previous results

for i in range(num_predictions):
current_date = start_date + timedelta(days=i)
try:
predictions = interpolate(current_date, self.historical_data, degree)
self.results_listbox.insert(
"end",
f"{current_date.strftime('%Y-%m-%d')}: Temp: {predictions['temperature']:.2f} °C, "
f"Humidity: {predictions['humidity']:.2f} %, Rainfall: {predictions['rainfall']:.2f} mm"
)
except ValueError as e:
self.results_listbox.insert("end", str(e))
return

# Run the application
root = Tk()
weather_app = WeatherApp(root)
root.mainloop()


csv file
date,temperature,humidity,rainfall
2024-01-01,25.3,60,5.0
2024-01-02,26.1,63,7.0
2024-01-03,24.8,59,6.5
2024-01-04,23.9,58,4.0
2024-01-05,24.2,60,4.5
 
To modify your code so that it outputs the predictions to a CSV file instead of just displaying them in the GUI, you can follow these steps. I will guide you through adding functionality to write the output predictions to a CSV file after they are generated.

### Step 1: Add a Function to Write Predictions to a CSV

Add a new method to the WeatherApp class that handles writing predictions to a CSV file:

Python:
def write_predictions_to_csv(self, predictions):
    """Write the weather predictions to a CSV file."""
    with open('predicted_weather.csv', 'w', newline='') as file:
        fieldnames = ['date', 'temperature', 'humidity', 'rainfall']
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        for prediction in predictions:
            writer.writerow(prediction)

### Step 2: Modify the predict_weather Method

Modify the predict_weather method to collect all predictions in a list, which will then be passed to the newly created method for writing to a CSV file.

Python:
def predict_weather(self):
    """Predict weather based on user inputs and write to CSV."""
    if not self.historical_data:
        self.results_listbox.insert("end", "No file loaded! Please load a CSV file first.")
        return

    start_date_str = self.start_date_entry.get()
    try:
        start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
    except ValueError:
        self.results_listbox.insert("end", "Invalid date format. Use YYYY-MM-DD.")
        return

    try:
        num_predictions = int(self.num_days_entry.get())
        if num_predictions < 1:
            self.results_listbox.insert("end", "Number of predictions must be at least 1.")
            return
    except ValueError:
        self.results_listbox.insert("end", "Invalid number of predictions. Please enter a valid integer.")
        return

    # Determine degree
    degree = 4 if start_date >= self.historical_data[0]["date"] and start_date <= self.historical_data[-1]["date"] else 2

    self.results_listbox.delete(0, "end")  # Clear previous results

    predictions = []
    for i in range(num_predictions):
        current_date = start_date + timedelta(days=i)
        try:
            prediction = interpolate(current_date, self.historical_data, degree)
            formatted_prediction = {
                "date": current_date.strftime('%Y-%m-%d'),
                "temperature": prediction['temperature'],
                "humidity": prediction['humidity'],
                "rainfall": prediction['rainfall']
            }
            predictions.append(formatted_prediction)
            self.results_listbox.insert(
                "end",
                f"{formatted_prediction['date']}: Temp: {formatted_prediction['temperature']:.2f} °C, "
                f"Humidity: {formatted_prediction['humidity']:.2f} %, Rainfall: {formatted_prediction['rainfall']:.2f} mm"
            )
        except ValueError as e:
            self.results_listbox.insert("end", str(e))
            return

    # Write predictions to CSV
    self.write_predictions_to_csv(predictions)

### Explanation

  • Collecting Predictions: All predictions are collected in a list of dictionaries. Each dictionary corresponds to a day's prediction with keys matching the CSV field names.
  • Writing to CSV: After collecting all predictions, the method write_predictions_to_csv is called with the list of prediction dictionaries. This method writes the predictions into a CSV file named predicted_weather.csv.

This modification should enable your application to not only display the predictions in the GUI but also save them to a CSV file, which can be used for further analysis or reporting. Make sure to test the application to ensure that the predictions are correctly written to the CSV file.
 

About this Thread

  • 1
    Replies
  • 340
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
1,059
Guests online
1,185
Total visitors
2,244

Forum statistics

Threads
2,269,101
Posts
28,926,516
Members
1,242,252
Latest member
zeroplays
Back
Top