Untitled

mail@pastecode.io avatar
unknown
python
7 months ago
8.1 kB
2
Indexable
Never
from datetime import datetime
import pvlib
import tkinter.messagebox
from pvlib.modelchain import ModelChain
from pvlib.location import Location
from pvlib.pvsystem import PVSystem
from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk


window = tk.Tk()
window.title("App")
ppkwff_var = tk.StringVar()
ppkwff_var.set("0")
app_var = tk.StringVar()
app_var.set("0")
ipp_var = tk.StringVar()
ipp_var.set("0")

available_modules = list(pvlib.pvsystem.retrieve_sam('SandiaMod').columns)
available_inverters = list(pvlib.pvsystem.retrieve_sam('CECInverter').columns)

#  User Inputs (Safe Defaults)
user_latitude = 10
user_longitude = 10
user_slope = 45
user_azimuth = 180
user_peakpower = 1
user_startpriod = "2012-01-01"
user_endperiod = "2012-01-01"
user_startyear = 2012
user_endyear = 2012
if user_startyear == user_endyear:
     specified_year = user_startyear

modules_db = pvlib.pvsystem.retrieve_sam("SandiaMod")
inverters_db = pvlib.pvsystem.retrieve_sam("CECInverter")
modules_list = list(pvlib.pvsystem.retrieve_sam('SandiaMod').columns)
inverters_list = list(pvlib.pvsystem.retrieve_sam('CECInverter').columns)
selected_module = modules_list[0]
selected_inverter = inverters_list[0]

def main_func():
    
    user_latitude = float(entry_latitude.get())
    user_longitude = float(entry_longitude.get())
    user_slope = int(entry_slope.get())
    user_azimuth = int(entry_azimuth.get())
    user_peakpower = float(entry_peakpower.get())
    user_startperiod = str(entry_start_date.get())
    user_endperiod = str(entry_end_date.get())
    
    # Year or Date
    if year_or_date.get() == "Year":
        user_startyear = int(entry_year.get())
        user_endyear = user_startyear
    else:
        user_startyear = entry_start_date.get()
        user_endyear = entry_end_date.get()
    
    try:
        plt.title(f"Seasonal Energy Production for {user_startyear}", size=13, weight="bold", color="black")
        
    except Exception as e:
        print(f"Error: {e}")


    poa_data, meta, inputs= pvlib.iotools.get_pvgis_hourly(latitude = user_latitude, longitude = user_longitude,
                                                                    start = user_startyear, end = user_endyear,
                                                                    raddatabase = "PVGIS-SARAH2",
                                                                    peakpower=user_peakpower,
                                                                    components=True, pvcalculation=True,
                                                                    surface_tilt = user_slope,
                                                                    surface_azimuth = user_azimuth,
                                                                    url = "https://re.jrc.ec.europa.eu/api/v5_2/")
    

    
    
    poa_data["poa_diffuse"] = poa_data["poa_sky_diffuse"]+poa_data["poa_ground_diffuse"]
    poa_data["poa_global"] = poa_data["poa_diffuse"]+poa_data["poa_direct"]
    
    
    # location = Location(latitude=user_latitude,longitude=user_longitude,
    #                     tz="Europe/Helsinki", altitude=0, name="name")

    # module = selected_module
    # inverter = selected_inverter
    # temperature_parameters = TEMPERATURE_MODEL_PARAMETERS["sapm"]["open_rack_glass_glass"]
    
    
    # system = PVSystem(surface_tilt=user_slope, surface_azimuth=user_azimuth, module_parameters=module,
    #                   inverter_parameters=inverter, temperature_model_parameters=temperature_parameters,
    #                   modules_per_string=1, strings_per_inverter=1)
    # modelchain = ModelChain(system, location)
    # poa_data.index = pd.to_datetime(poa_data.index)
    # modelchain.run_model_from_poa(poa_data)
    
        
    start_date = datetime.strptime(user_startperiod, "%Y-%m-%d")
    end_date = datetime.strptime(user_endperiod, "%Y-%m-%d")

    system_power = poa_data["P"].sum()

    if year_or_date.get() == "Date Range":
        tk.Label(window, text="Total Energy Produced (Wh):").grid(row=13, column=0)
        tk.Label(window, text=int(system_power), width=20).grid(row=13, column=1)

    if user_startyear == user_endyear:
        seasons = {
            'Winter': [12, 1, 2],
            'Spring': [3, 4, 5],
            'Summer': [6, 7, 8],
            'Fall': [9, 10, 11]
        }
        
        seasonal_energy_data = {season: 0 for season in seasons}
        
        poa_data['season'] = poa_data.index.month.map(
            lambda x: next(season for season, months in seasons.items() if x in months)
        )
        seasonal_energy_data = poa_data.groupby('season')['poa_global'].sum()
        
        fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(aspect="equal"))
        wedges, texts, autotexts = ax.pie(
            seasonal_energy_data,
            labels=seasonal_energy_data.index,
            autopct='%1.1f%%',
            startangle=90
        )
        plt.setp(texts, size=10, weight="bold", color="black")
        plt.setp(autotexts, size=10, weight="bold", color="white")
        plt.title(f"Seasonal Energy Production for {user_startyear}", size=13, weight="bold", color="black")
    for widget in plot_frame.winfo_children():
        widget.destroy()

    if user_startyear == user_endyear:
        fig_canvas = FigureCanvasTkAgg(fig, master=plot_frame)
        fig_canvas.draw()
        fig_canvas.get_tk_widget().grid(row=8, columnspan=4)
    else:
        pass



def toggle_inputs():
    if year_or_date.get() == "Year":
        label_year.grid(row=2, column=0)
        entry_year.grid(row=2, column=1)
        label_start_date.grid_remove()
        entry_start_date.grid_remove()
        label_end_date.grid_remove()
        entry_end_date.grid_remove()
    else:
        label_year.grid_remove()
        entry_year.grid_remove()
        label_start_date.grid(row=3, column=0)
        entry_start_date.grid(row=3, column=1)
        label_end_date.grid(row=4, column=0)
        entry_end_date.grid(row=4, column=1)



    # Radio buttons
year_or_date = tk.StringVar(value="Year")
tk.Radiobutton(window, text="Year", variable=year_or_date, value="Year", command=toggle_inputs).grid(row=0, column=0, sticky="w")
tk.Radiobutton(window, text="Date", variable=year_or_date, value="Date Range", command=toggle_inputs).grid(row=1, column=0, sticky="w")


    # Labels and entries
label_year = tk.Label(window, text="Year:")
entry_year = tk.Entry(window)
entry_year.insert(0, 2012)
label_start_date = tk.Label(window, text="Start:")
entry_start_date = tk.Entry(window)
entry_start_date.insert(0, "2012-01-01")
label_end_date = tk.Label(window, text="End:")
entry_end_date = tk.Entry(window)
entry_end_date.insert(0, "2012-01-02")

    # Latitude input
tk.Label(window, text="Latitude:").grid(row=5, column=0)
entry_latitude = tk.Entry(window)
entry_latitude.grid(row=5, column=1)

    # Longitude input
tk.Label(window, text="Longitude:").grid(row=6, column=0)
entry_longitude = tk.Entry(window)
entry_longitude.grid(row=6, column=1)

    # Slope input
tk.Label(window, text="Slope:").grid(row=7, column=0)
entry_slope = tk.Entry(window)
entry_slope.grid(row=7, column=1)

    # Azimuth input
tk.Label(window, text="Azimuth:").grid(row=8, column=0)
entry_azimuth = tk.Entry(window)
entry_azimuth.grid(row=8, column=1)

    #Peak power
tk.Label(window, text="Peak power:").grid(row=9, column=0)
entry_peakpower = tk.Entry(window)
entry_peakpower.grid(row=9, column=1)

run_button = tk.Button(window, text="Apply", command=main_func)
run_button.grid(row=10, column=0, columnspan=2)

    # Plot frame
plot_frame = tk.Frame(window)
plot_frame.grid(row=11, column=0, columnspan=4)


toggle_inputs()
window.mainloop()
Leave a Comment