Here is the full test.py script that fulfills your requirements:
from solar_calculator import calculate_sunrise_sunset, format_time
from solar_calculator_v0 import calculate_sunrise_sunset as calculate_sunrise_sunset_v0
from testbed import calculate_sunrise_sunset_astral
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import numpy as np
def format_time(time_in_hours, seconds=True):
"""
Format time from decimal hours to HH:MM:SS AM/PM format.
"""
hour = int(time_in_hours)
remainder = time_in_hours - hour
minute = int(remainder * 60)
remainder = remainder * 60 - minute
second = int(round(remainder * 60))
if second >= 60:
second -= 60
minute += 1
if minute >= 60:
minute -= 60
hour += 1
hour %= 24
# Determine AM or PM
meridiem = "AM" if hour < 12 else "PM"
# Convert to 12-hour format
hour_display = hour % 12
if hour_display == 0:
hour_display = 12
if seconds:
return f"{hour_display}:{minute:02d}:{second:02d} {meridiem}"
else:
if second >= 30:
minute += 1
if minute >= 60:
minute -= 60
hour += 1
hour %= 24
meridiem = "AM" if hour < 12 else "PM"
hour_display = hour % 12
if hour_display == 0:
hour_display = 12
return f"{hour_display}:{minute:02d} {meridiem}"
if __name__ == "__main__":
# Location coordinates
latitude = 13.0326372542501 # Latitude in degrees (positive for north)
longitude = 77.5755860908572 # Longitude in degrees (positive for east)
# Date and timezone information
timezone_offset = 0 # UTC offset in hours (e.g., IST is UTC+5.5)
timezone = 'UTC'
# Lists to store errors
dates = []
sunrise_errors_v1 = []
sunset_errors_v1 = []
sunrise_errors_v0 = []
sunset_errors_v0 = []
sunrise_errors_v1_v0 = []
sunset_errors_v1_v0 = []
# Loop over the date range
start_date = datetime(2023, 1, 1)
end_date = datetime(2024, 12, 31)
delta = timedelta(days=1)
current_date = start_date
count = 0 # To keep track of the number of data points
while current_date <= end_date:
year = current_date.year
month = current_date.month
day = current_date.day
dates.append(current_date)
print(f"{'-' * 50}")
print(f"Date: {current_date.strftime('%Y-%m-%d')}")
# Calculate sunrise and sunset times
sunrise_v1, sunset_v1 = calculate_sunrise_sunset(latitude, longitude, year, month, day, timezone_offset)
sunrise_v0, sunset_v0 = calculate_sunrise_sunset_v0(latitude, longitude, year, month, day, timezone_offset)
sunrise_astral, sunset_astral = calculate_sunrise_sunset_astral(latitude, longitude, timezone, current_date)
sunrise_astral_dec = sunrise_astral.hour + sunrise_astral.minute/60 + sunrise_astral.second/3600
sunset_astral_dec = sunset_astral.hour + sunset_astral.minute/60 + sunset_astral.second/3600
# Adjust for timezone_offset
sunrise_astral_dec += timezone_offset
sunset_astral_dec += timezone_offset
sunrise_astral_str = sunrise_astral.strftime("%dth %B %Y %I:%M:%S %p")
sunset_astral_str = sunset_astral.strftime("%dth %B %Y %I:%M:%S %p")
if sunrise_v1 is not None and sunset_v1 is not None and sunrise_v0 is not None and sunset_v0 is not None:
# Format and display the results
print(f"Sunrise Custom V1: {format_time(sunrise_v1)}")
print(f"Sunset Custom V1: {format_time(sunset_v1)}")
print(f"Sunrise Custom V0: {format_time(sunrise_v0)}")
print(f"Sunset Custom V0: {format_time(sunset_v0)}")
else:
# Handle cases where sunrise or sunset does not occur
print("Sunrise and sunset times not available for this location on the given date.")
# Skip to next date
current_date += delta
continue
print(f"Sunrise Astral: {sunrise_astral_str}")
print(f"Sunset Astral: {sunset_astral_str}")
# Compute errors in seconds
error_sunrise_v1 = (sunrise_v1 - sunrise_astral_dec) * 3600 # error in seconds
error_sunset_v1 = (sunset_v1 - sunset_astral_dec) * 3600
error_sunrise_v0 = (sunrise_v0 - sunrise_astral_dec) * 3600 # error in seconds
error_sunset_v0 = (sunset_v0 - sunset_astral_dec) * 3600
error_sunrise_v1_v0 = (sunrise_v1 - sunrise_v0) * 3600 # error between v1 and v0
error_sunset_v1_v0 = (sunset_v1 - sunset_v0) * 3600
print(f"Error Sunrise V1 vs Astral: {error_sunrise_v1:.2f} seconds")
print(f"Error Sunset V1 vs Astral: {error_sunset_v1:.2f} seconds")
print(f"Error Sunrise V0 vs Astral: {error_sunrise_v0:.2f} seconds")
print(f"Error Sunset V0 vs Astral: {error_sunset_v0:.2f} seconds")
print(f"Error Sunrise V1 vs V0: {error_sunrise_v1_v0:.2f} seconds")
print(f"Error Sunset V1 vs V0: {error_sunset_v1_v0:.2f} seconds")
print(f"{'-' * 50}")
# Append errors to lists
sunrise_errors_v1.append(error_sunrise_v1)
sunset_errors_v1.append(error_sunset_v1)
sunrise_errors_v0.append(error_sunrise_v0)
sunset_errors_v0.append(error_sunset_v0)
sunrise_errors_v1_v0.append(error_sunrise_v1_v0)
sunset_errors_v1_v0.append(error_sunset_v1_v0)
current_date += delta
count += 1
# Convert lists to numpy arrays
sunrise_errors_v1 = np.array(sunrise_errors_v1)
sunset_errors_v1 = np.array(sunset_errors_v1)
sunrise_errors_v0 = np.array(sunrise_errors_v0)
sunset_errors_v0 = np.array(sunset_errors_v0)
sunrise_errors_v1_v0 = np.array(sunrise_errors_v1_v0)
sunset_errors_v1_v0 = np.array(sunset_errors_v1_v0)
# Compute metrics
def compute_metrics(errors):
mae = np.mean(np.abs(errors))
rmse = np.sqrt(np.mean(errors**2))
bias = np.mean(errors)
std_dev = np.std(errors)
max_error = np.max(errors)
min_error = np.min(errors)
return mae, rmse, bias, std_dev, max_error, min_error
print("\nMetrics for Sunrise V1 vs Astral:")
mae_sunrise_v1, rmse_sunrise_v1, bias_sunrise_v1, std_sunrise_v1, max_err_sunrise_v1, min_err_sunrise_v1 = compute_metrics(sunrise_errors_v1)
print(f"MAE: {mae_sunrise_v1:.2f} seconds")
print(f"RMSE: {rmse_sunrise_v1:.2f} seconds")
print(f"Bias: {bias_sunrise_v1:.2f} seconds")
print(f"Standard Deviation: {std_sunrise_v1:.2f} seconds")
print(f"Maximum Error: {max_err_sunrise_v1:.2f} seconds")
print(f"Minimum Error: {min_err_sunrise_v1:.2f} seconds")
print("\nMetrics for Sunset V1 vs Astral:")
mae_sunset_v1, rmse_sunset_v1, bias_sunset_v1, std_sunset_v1, max_err_sunset_v1, min_err_sunset_v1 = compute_metrics(sunset_errors_v1)
print(f"MAE: {mae_sunset_v1:.2f} seconds")
print(f"RMSE: {rmse_sunset_v1:.2f} seconds")
print(f"Bias: {bias_sunset_v1:.2f} seconds")
print(f"Standard Deviation: {std_sunset_v1:.2f} seconds")
print(f"Maximum Error: {max_err_sunset_v1:.2f} seconds")
print(f"Minimum Error: {min_err_sunset_v1:.2f} seconds")
print("\nMetrics for Sunrise V0 vs Astral:")
mae_sunrise_v0, rmse_sunrise_v0, bias_sunrise_v0, std_sunrise_v0, max_err_sunrise_v0, min_err_sunrise_v0 = compute_metrics(sunrise_errors_v0)
print(f"MAE: {mae_sunrise_v0:.2f} seconds")
print(f"RMSE: {rmse_sunrise_v0:.2f} seconds")
print(f"Bias: {bias_sunrise_v0:.2f} seconds")
print(f"Standard Deviation: {std_sunrise_v0:.2f} seconds")
print(f"Maximum Error: {max_err_sunrise_v0:.2f} seconds")
print(f"Minimum Error: {min_err_sunrise_v0:.2f} seconds")
print("\nMetrics for Sunset V0 vs Astral:")
mae_sunset_v0, rmse_sunset_v0, bias_sunset_v0, std_sunset_v0, max_err_sunset_v0, min_err_sunset_v0 = compute_metrics(sunset_errors_v0)
print(f"MAE: {mae_sunset_v0:.2f} seconds")
print(f"RMSE: {rmse_sunset_v0:.2f} seconds")
print(f"Bias: {bias_sunset_v0:.2f} seconds")
print(f"Standard Deviation: {std_sunset_v0:.2f} seconds")
print(f"Maximum Error: {max_err_sunset_v0:.2f} seconds")
print(f"Minimum Error: {min_err_sunset_v0:.2f} seconds")
print("\nMetrics for Sunrise V1 vs V0:")
mae_sunrise_v1_v0, rmse_sunrise_v1_v0, bias_sunrise_v1_v0, std_sunrise_v1_v0, max_err_sunrise_v1_v0, min_err_sunrise_v1_v0 = compute_metrics(sunrise_errors_v1_v0)
print(f"MAE: {mae_sunrise_v1_v0:.2f} seconds")
print(f"RMSE: {rmse_sunrise_v1_v0:.2f} seconds")
print(f"Bias: {bias_sunrise_v1_v0:.2f} seconds")
print(f"Standard Deviation: {std_sunrise_v1_v0:.2f} seconds")
print(f"Maximum Error: {max_err_sunrise_v1_v0:.2f} seconds")
print(f"Minimum Error: {min_err_sunrise_v1_v0:.2f} seconds")
print("\nMetrics for Sunset V1 vs V0:")
mae_sunset_v1_v0, rmse_sunset_v1_v0, bias_sunset_v1_v0, std_sunset_v1_v0, max_err_sunset_v1_v0, min_err_sunset_v1_v0 = compute_metrics(sunset_errors_v1_v0)
print(f"MAE: {mae_sunset_v1_v0:.2f} seconds")
print(f"RMSE: {rmse_sunset_v1_v0:.2f} seconds")
print(f"Bias: {bias_sunset_v1_v0:.2f} seconds")
print(f"Standard Deviation: {std_sunset_v1_v0:.2f} seconds")
print(f"Maximum Error: {max_err_sunset_v1_v0:.2f} seconds")
print(f"Minimum Error: {min_err_sunset_v1_v0:.2f} seconds")
# Determine which version is better (v1 or v0)
# We can use the MAE or RMSE to determine
total_mae_v1 = mae_sunrise_v1 + mae_sunset_v1
total_mae_v0 = mae_sunrise_v0 + mae_sunset_v0
if total_mae_v1 < total_mae_v0:
print("\nVersion V1 has better accuracy overall.")
else:
print("\nVersion V0 has better accuracy overall.")
# Plotting the errors
# Convert dates to matplotlib date numbers for plotting
import matplotlib.dates as mdates
dates_mpl = mdates.date2num(dates)
# Plot Sunrise Errors V1 vs Astral and V0 vs Astral
plt.figure(figsize=(12,6))
plt.plot_date(dates_mpl, sunrise_errors_v1, '-', label='Sunrise Error V1 vs Astral')
plt.plot_date(dates_mpl, sunrise_errors_v0, '-', label='Sunrise Error V0 vs Astral')
plt.xlabel('Date')
plt.ylabel('Error in seconds')
plt.title('Sunrise Errors')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Plot Sunset Errors V1 vs Astral and V0 vs Astral
plt.figure(figsize=(12,6))
plt.plot_date(dates_mpl, sunset_errors_v1, '-', label='Sunset Error V1 vs Astral')
plt.plot_date(dates_mpl, sunset_errors_v0, '-', label='Sunset Error V0 vs Astral')
plt.xlabel('Date')
plt.ylabel('Error in seconds')
plt.title('Sunset Errors')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Plot Sunrise Errors V1 vs V0
plt.figure(figsize=(12,6))
plt.plot_date(dates_mpl, sunrise_errors_v1_v0, '-', label='Sunrise Error V1 vs V0')
plt.xlabel('Date')
plt.ylabel('Error in seconds')
plt.title('Sunrise Error V1 vs V0')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Plot Sunset Errors V1 vs V0
plt.figure(figsize=(12,6))
plt.plot_date(dates_mpl, sunset_errors_v1_v0, '-', label='Sunset Error V1 vs V0')
plt.xlabel('Date')
plt.ylabel('Error in seconds')
plt.title('Sunset Error V1 vs V0')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Explanation:
Notes:
- Make sure all the modules (
solar_calculator, solar_calculator_v0, testbed) and their functions are correctly implemented and accessible.
- Ensure that the
timezone_offset is correctly applied to match the astral results.
- You might need to adjust the code slightly if the function signatures or outputs differ.
- The plots will help visualize how the errors vary over time and can highlight any patterns or anomalies.
- The metrics provide a quantitative analysis of the performance of each version.
This script should provide a comprehensive comparison of your V1 and V0 implementations against the astral library, helping you determine which version offers better accuracy for sunrise and sunset calculations.