Python Forum
Linear Programming (PuLP) - loop for constraints
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linear Programming (PuLP) - loop for constraints
#1
Hi,

I am new to Python and am trying to get it to solve an optimisation problem. I know how to use Excel to do this, but my problem is too big (too many decision variables and too many constraints) for Excel to manage. So I am trying to teach myself a bit of Python to solve the problem.

Basically I am trying to maximise the profit made across up to 2444 transactions throughout a year (attached to a date and hour of purchase - buy_date and buy_hour, as well as a date and hour of resale - sell_date and sell_hour). In each transaction I can purchase between 0 and 3 units (doesn't even have to be an integer value) and later sell between 0 and 3 units to make a profit. But in each of the 8760 hours in the year I can only store up to 5 units. So obviously I have 2444 decision variables which must be between 0 and 3, and 8760 constraints which must be between 0 and 5.

Please note, the 'constraints' list I have created is just a list of 1's to be used for the lpSum to be used when creating the loop for the 8760 constraints.

This is the code I have written which works:

#import data and store in lists

import csv

filename = 'OneDay3MWBattery5MWhStorage.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    ID = []
    buy_date = []
    buy_hour = []
    sell_date = []
    sell_hour = []
    profit_unit = []
        
    from datetime import datetime

    for row in reader:
        ID.append(row[0])
        buy_date.append(datetime.strptime(row[1], "%d-%m-%y"))
        buy_hour.append(int(row[2]))
        sell_date.append(datetime.strptime(row[3], "%d-%m-%y"))
        sell_hour.append(int(row[4]))
        profit_unit.append(float(row[5]))
        
filename = 'dates2018.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    
    date_solver = []
    time_solver = []
    constraints = []
    
    from datetime import datetime

    for row in reader:
        date_solver.append(datetime.strptime(row[0], "%d-%m-%y"))
        time_solver.append(int(row[1]))
        constraints.append(int(row[2]))
  
#store lists in dictionaries

buy_date_dict = {ID[i]: buy_date[i] for i in range(len(ID))} 
buy_hour_dict = {ID[i]: buy_hour[i] for i in range(len(ID))} 
sell_date_dict = {ID[i]: sell_date[i] for i in range(len(ID))} 
sell_hour_dict = {ID[i]: sell_hour[i] for i in range(len(ID))} 
profit_unit_dict = {ID[i]: profit_unit[i] for i in range(len(ID))} 

#set up linear programming problem

prob = LpProblem("Battery One Day",LpMaximize)

ID_vars = LpVariable.dicts("ID",ID,lowBound=0,upBound=3,cat='Continuous')

prob += lpSum([profit_unit_dict[i]*ID_vars[i] for i in ID])
       
This is the code which crashes:

#set up constraints


for j in range(len(date_solver)):
    for i in range(len(ID)):
        if buy_date[i] <= date_solver[j] <= sell_date[i] and buy_hour[i] <= time_solver[j] <= sell_hour[i]:
            prob += lpSum(constraints[j]*ID_vars[i]) >= 0
            prob += lpSum(constraints[j]*ID_vars[i]) <= 5
This is the error message I am getting:

Error:
KeyError Traceback (most recent call last) <ipython-input-84-c4a318de252e> in <module> 5 for i in range(len(ID)): 6 if buy_date[i] <= date_solver[j] <= sell_date[i] and buy_hour[i] <= time_solver[j] <= sell_hour[i]: ----> 7 prob += lpSum(constraints[j]*ID_vars[i]) >= 0 8 prob += lpSum(constraints[j]*ID_vars[i]) <= 5 KeyError: 1665
Is there anyone who can please advise me on if, and how, this problem can maybe be fixed?

Thank you very much.
Reply
#2
I have solved this myself. Turns out that the IDs were strings and not integers, so I converted them into integers when adding to the list. There were other problems in my code but I have fixed all the problems and the code seems to be doing what I wanted it to do. Yay!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Linear Programming Problem Axel_LF 0 699 Feb-23-2023, 11:03 PM
Last Post: Axel_LF
  How to solve equations, with groups of variables and or constraints? ThemePark 0 1,645 Oct-05-2020, 07:22 PM
Last Post: ThemePark
  New to programming, loop question tomyan 1 1,590 Sep-25-2020, 04:32 PM
Last Post: Larz60+
  Linear programming optimization PuLP new_in_python 0 22,370 Jul-17-2019, 04:56 PM
Last Post: new_in_python
  Linear programming PySou 1 2,226 May-26-2019, 05:24 PM
Last Post: heiner55
  Rigid Body Simulation in 3D with constraints FumingElephant 1 2,625 Jul-11-2018, 02:16 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020