- Posts: 2
PVWatts + Battery - Single day execution failing on Battwatts
- Trinity
- Topic Author
Less
More
11 Jun 2025 14:38 #14110
by Trinity
PVWatts + Battery - Single day execution failing on Battwatts was created by Trinity
Hi there,
My code is at the bottom.
I'm trying to do a work around to simulate a single day for the PVWatts + Battery model by changing the input load and weather file to only contain data for 24 hours (1 hour increments). I created the model in the desktop app then generated the JSON files using "PySAM JSON". I changed the load in the battwatts.json to only have 24 values and sliced the weather file after reading it into the code.
In doing some troubleshooting, it's clear that code is failing while trying to execute battwatts but not actually throwing an error. The code runs perfectly when using a year dataset so maybe my logic is faulty somewhere? Any help would be great!
Cheers
# Using PVWatts-Battery – Commercial Owner
import json
# import each module being used
import PySAM.Pvwattsv8 as Pvwatts # detailed PV system model
import PySAM.Battwatts as Battwatts # simbple battery model
import PySAM.Grid as Grid # electric grid model
import PySAM.Utilityrate5 as UtilityRate # retail electricity bill calculator
import PySAM.Cashloan as CashLoan
# plotting and saving
import matplotlib.pyplot as plt
import pandas as pd
# create new instance of the pvsamv1 module + use from_existing() for the
# subsequent modules so that all of the compute modules share the same data.
pv = Pvwatts.new()
batt = Battwatts.from_existing(pv)
grid = Grid.from_existing(pv)
ur = UtilityRate.from_existing(pv)
cl = CashLoan.from_existing(pv)
# get the inputs from the JSON file from SAM desktop "PySAM JSON"
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts SAM PySAM JSON - ONE DAY" + "\\"
file_names = ["Battwatts_pvwattsv8","Battwatts_battwatts", "Battwatts_grid", "Battwatts_utilityrate5", "Battwatts_cashloan"]
modules = [pv, batt, grid, ur, cl]
# Loop through each module for inputs
for f, m in zip(file_names, modules):
with open(directory + f + ".json", 'r') as file:
data = json.load(file)
# iterate through the input key-value pairs and set the module inputs
for k, v in data.items():
if k != "number_inputs":
m.value(k, v)
# --- Override Time-Series Data for One-Day Simulation ---
# 1. Adapt Solar Resource Data
# Get the annual weather file path that was loaded from the JSON
solar_file = pv.SolarResource.solar_resource_file
weather_df = pd.read_csv(solar_file, skiprows=2)
#create the data dictionary for PySAM from the first 24 rows
solar_data_dict = {
'lat': 33.45,
'lon': -111.98,
'tz': -7,
'elev': 358,
'dn': weather_df.iloc[0:24].tolist(),
'df': weather_df.iloc[0:24].tolist(),
'gh': weather_df.iloc[0:24].tolist(),
'wspd': weather_df.iloc[0:24].tolist(),
'tdry': weather_df.iloc[0:24].tolist(),
}
# manually set solar resource data to ensure its using my 24 window
pv.SolarResource.solar_resource_data = {'0':'0'}
pv.SolarResource.solar_resource_data = solar_data_dict
# run each model in the correct order
i = 0
for m in modules:
print('On module:', file_names)
m.execute()
print('Done module:', file_names)
i += 1
#Results
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts-PySAMfiles - ONEDAY" + '\\'
current = pd.Series(batt.Outputs.batt_I[0:24])
current.to_csv(directory + 'Current.csv')
plt.plot(range(0,24,1), batt.Outputs.batt_SOC[0:24])
plt.xlabel('Hour of year')
plt.ylabel('Battery SOC (%)')
plt.savefig(directory + 'SOC.png')
plt.show()
My code is at the bottom.
I'm trying to do a work around to simulate a single day for the PVWatts + Battery model by changing the input load and weather file to only contain data for 24 hours (1 hour increments). I created the model in the desktop app then generated the JSON files using "PySAM JSON". I changed the load in the battwatts.json to only have 24 values and sliced the weather file after reading it into the code.
In doing some troubleshooting, it's clear that code is failing while trying to execute battwatts but not actually throwing an error. The code runs perfectly when using a year dataset so maybe my logic is faulty somewhere? Any help would be great!
Cheers
# Using PVWatts-Battery – Commercial Owner
import json
# import each module being used
import PySAM.Pvwattsv8 as Pvwatts # detailed PV system model
import PySAM.Battwatts as Battwatts # simbple battery model
import PySAM.Grid as Grid # electric grid model
import PySAM.Utilityrate5 as UtilityRate # retail electricity bill calculator
import PySAM.Cashloan as CashLoan
# plotting and saving
import matplotlib.pyplot as plt
import pandas as pd
# create new instance of the pvsamv1 module + use from_existing() for the
# subsequent modules so that all of the compute modules share the same data.
pv = Pvwatts.new()
batt = Battwatts.from_existing(pv)
grid = Grid.from_existing(pv)
ur = UtilityRate.from_existing(pv)
cl = CashLoan.from_existing(pv)
# get the inputs from the JSON file from SAM desktop "PySAM JSON"
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts SAM PySAM JSON - ONE DAY" + "\\"
file_names = ["Battwatts_pvwattsv8","Battwatts_battwatts", "Battwatts_grid", "Battwatts_utilityrate5", "Battwatts_cashloan"]
modules = [pv, batt, grid, ur, cl]
# Loop through each module for inputs
for f, m in zip(file_names, modules):
with open(directory + f + ".json", 'r') as file:
data = json.load(file)
# iterate through the input key-value pairs and set the module inputs
for k, v in data.items():
if k != "number_inputs":
m.value(k, v)
# --- Override Time-Series Data for One-Day Simulation ---
# 1. Adapt Solar Resource Data
# Get the annual weather file path that was loaded from the JSON
solar_file = pv.SolarResource.solar_resource_file
weather_df = pd.read_csv(solar_file, skiprows=2)
#create the data dictionary for PySAM from the first 24 rows
solar_data_dict = {
'lat': 33.45,
'lon': -111.98,
'tz': -7,
'elev': 358,
'dn': weather_df.iloc[0:24].tolist(),
'df': weather_df.iloc[0:24].tolist(),
'gh': weather_df.iloc[0:24].tolist(),
'wspd': weather_df.iloc[0:24].tolist(),
'tdry': weather_df.iloc[0:24].tolist(),
}
# manually set solar resource data to ensure its using my 24 window
pv.SolarResource.solar_resource_data = {'0':'0'}
pv.SolarResource.solar_resource_data = solar_data_dict
# run each model in the correct order
i = 0
for m in modules:
print('On module:', file_names)
m.execute()
print('Done module:', file_names)
i += 1
#Results
directory = r"C:\Users\Trinity\Desktop\Testing PySAM\Battwatts-PySAMfiles - ONEDAY" + '\\'
current = pd.Series(batt.Outputs.batt_I[0:24])
current.to_csv(directory + 'Current.csv')
plt.plot(range(0,24,1), batt.Outputs.batt_SOC[0:24])
plt.xlabel('Hour of year')
plt.ylabel('Battery SOC (%)')
plt.savefig(directory + 'SOC.png')
plt.show()
Attachments:
Please Log in or Create an account to join the conversation.
- Paul Gilman
Less
More
- Posts: 5574
12 Jun 2025 09:34 - 12 Jun 2025 09:35 #14112
by Paul Gilman
Replied by Paul Gilman on topic PVWatts + Battery - Single day execution failing on Battwatts
Hi Trinity,
I ran your script using JSON input files that I generated from the default PVWatts / Commercial case in SAM. I had to make modifications to your script to get it to work:
1. Unassign the 'solar_resource_file' variable. This ensures that the value of 'solar_resource_data' from the JSON input file is discarded. Without this step, if both 'solar_resource_data' and 'solar_resource_file' are assigned and have valid values, Pvwattsv8 will read weather data from the weather file.
2. Add the required time stamp columns (year, month, day, hour, minute) to 'solar_resource_data':
After making these changes, I get the following error: "Exception: battwatts execution error. compute fail(battwatts): single_year_to_lifetime_interpolated error: Calculated step_per_hour was 0."
PySAM generates this error because the Battwatts module requires at least one year of data. This is because the battery model degradation calculations do not work over shorter periods.
Best regards,
Paul.
I ran your script using JSON input files that I generated from the default PVWatts / Commercial case in SAM. I had to make modifications to your script to get it to work:
1. Unassign the 'solar_resource_file' variable. This ensures that the value of 'solar_resource_data' from the JSON input file is discarded. Without this step, if both 'solar_resource_data' and 'solar_resource_file' are assigned and have valid values, Pvwattsv8 will read weather data from the weather file.
Code:
# manually set solar resource data to ensure its using my 24 window
pv.unassign('solar_resource_file')
pv.SolarResource.solar_resource_data = {'0':'0'}
pv.SolarResource.solar_resource_data = solar_data_dict
2. Add the required time stamp columns (year, month, day, hour, minute) to 'solar_resource_data':
Code:
#create the data dictionary for PySAM from the first 24 rows
solar_data_dict = {
'lat': 33.45,
'lon': -111.98,
'tz': -7,
'elev': 358,
'year': weather_df['Year'].iloc[0:24].tolist(),
'month': weather_df['Month'].iloc[0:24].tolist(),
'day': weather_df['Day'].iloc[0:24].tolist(),
'hour': weather_df['Hour'].iloc[0:24].tolist(),
'minute': weather_df['Minute'].iloc[0:24].tolist(),
'dn': weather_df['DNI'].iloc[0:24].tolist(),
'df': weather_df['DHI'].iloc[0:24].tolist(),
'gh': weather_df['GHI'].iloc[0:24].tolist(),
'wspd': weather_df['Wind Speed'].iloc[0:24].tolist(),
'tdry': weather_df['Temperature'].iloc[0:24].tolist(),
}
After making these changes, I get the following error: "Exception: battwatts execution error. compute fail(battwatts): single_year_to_lifetime_interpolated error: Calculated step_per_hour was 0."
PySAM generates this error because the Battwatts module requires at least one year of data. This is because the battery model degradation calculations do not work over shorter periods.
Best regards,
Paul.
Last edit: 12 Jun 2025 09:35 by Paul Gilman.
Please Log in or Create an account to join the conversation.
Moderators: Paul Gilman