I am trying to use PuLP with Python to optimise a schedule where the goal is to run a generator whenever the electricity prices are the highest. One of my constraints is to limit the number of times the generator turns on or off. I am stuck with trying to write this out. I define a dictionary with 12 values, each representing if the generator is on in that hour.
hours = range(12) # length of schedule
generator_on = LpVariable.dicts("Generator_On", hours, cat="Binary") # Binary variable (1 if on, 0 if off)
And adding a constraint for the switch time like this, but it is not working for me.
# add 1 in list if previous hours state is not equal to his one and sum to get total number of state changes
prob += lpSum([1 if generator_on[i].value() != generator_on[i-1].value() else 0 for i in range(1, len(hours))]) <= max_state_changes, "Max_switch_time"
Is linear programming the right tool for this problem? Later I hope to add constraints that allow for a fuel tank to be considered as well, where fuel is constantly added to it and it must not be fully emptied or overfilled.
Full code:
from pulp import LpProblem, LpVariable, lpSum, LpMaximize
prob = LpProblem("GeneratorScheduling", LpMaximize) # maximize profit from generating electricity
# Decision variables
hours = range(12) # length of schedule
generator_on = LpVariable.dicts("Generator_On", hours, cat="Binary") # Binary variable (1 if on, 0 if off)
electricity_prices = [10, 8, 12, 7, 15, 9, 11, 14, 10, 8, 13, 10] # Example: hourly electricity prices
max_state_changes = 2 # Maximum allowed state changes
max_on_time = 6 # Maximum allowed consecutive on time
# Objective function: Maximize profit
prob += lpSum(electricity_prices[i] * generator_on[i] for i in hours), "Total_Profit"
# Constraints
prob += lpSum(generator_on[j] for j in range(12)) <= max_on_time, f"Max_On_Time"
prob += lpSum([1 if generator_on[i].value() != generator_on[i-1].value() else 0 for i in range(1, len(hours))]) <= max_state_changes, "Max_switch_time"
print(prob)
prob.solve()
print("Optimal Schedule:")
for i in hours:
print(f"Hour {i + 1}: {'On' if generator_on[i].value() == 1 else 'Off'}")
print("Total Profit:", round(prob.objective.value(), 2))