Download case study code/experiment4.py from BTBUzhy/JOC: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/datasets/BTBUzhy/JOC/resolve/main/case%20study%20code/experiment4.py
- Command line
-
hf download 'hf://datasets/BTBUzhy/JOC/case study code/experiment4.py'
-
curl -L -o experiment4.py https://huggingface.co/datasets/BTBUzhy/JOC/resolve/main/case%20study%20code/experiment4.py
20 kB
| import numpy as np | |
| import pandas as pd | |
| import math | |
| import random | |
| import warnings | |
| import os | |
| from langchain_openai import ChatOpenAI | |
| import gurobipy as gp | |
| from gurobipy import GRB | |
| import re | |
| import scipy as sp | |
| from langchain_community.utilities import SQLDatabase | |
| from langchain_community.agent_toolkits import create_sql_agent | |
| from langchain_core.runnables import Runnable, RunnableLambda, RunnablePassthrough | |
| from operator import itemgetter | |
| import traceback | |
| from langchain_core.tools import tool | |
| from langchain import PromptTemplate | |
| import time | |
| from langchain_core.messages import AIMessage, HumanMessage | |
| import sys | |
| def add_new_obj(new_model_path, text, w1, w2,unselected,target_variable_values,parameterize,indicator): | |
| import gurobipy as gp | |
| model = gp.Model() | |
| I = list(range(55)) | |
| K = [0, 1, 2] | |
| soc = [0, 1, 2] | |
| N = 60 | |
| z = [0, 0, 50] | |
| k_0 = 0 | |
| k_1 = 1 | |
| k_2 = 2 | |
| C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40] | |
| v = np.zeros((55, 3)) | |
| random.seed(0) | |
| for i in range(len(I)): | |
| for j in range(len(K)): | |
| v[i, j] = random.randint(j * 5, j * 5 + 10) | |
| for i in range(len(I)): | |
| for k in range(len(K)): | |
| model.addVar(name=f"u_{i}_{k}") | |
| model.addVar(name=f"x_{i}_dispatch_{k}") | |
| for i in range(len(I)): | |
| for k in range(len(K)-1): | |
| model.addVar(name=f"x_{i}_exchange_{k}") | |
| model.update() | |
| exec(text, {'model': model, 'gp': gp, "GRB": gp.GRB, "k_0":k_0, "k_1":k_1, "k_2":k_2, 'I': I, 'K': K, 'N':N, 'z':z, 'v':v, 'C':C}) | |
| model.update() | |
| new_obj = model.getObjective() | |
| #print('extra_obj:',new_obj) | |
| new_model = gp.read(new_model_path) | |
| new_model.update() | |
| origin_obj = new_model.getObjective() | |
| new_obj_expr = gp.LinExpr() | |
| if isinstance(new_obj, gp.QuadExpr): | |
| #print('QuadExpr') | |
| w = new_model.addVar(vtype=GRB.CONTINUOUS, name="w") | |
| new_model.update() | |
| new_obj_expr.addTerms(1,w) | |
| new_model.update() | |
| if indicator == 'utilize': | |
| if parameterize is True: | |
| total_expression = gp.QuadExpr() | |
| for i in I: | |
| for k in K: | |
| sum_expression = gp.LinExpr() | |
| var_name = f"u_{i}_{k}" | |
| if i in unselected and var_name in target_variable_values: | |
| #print(var_name,'will be replaced with ',target_variable_values[var_name]) | |
| new_model.addConstr(new_model.getVarByName(f'x_{i}_dispatch_{k}') == int(target_variable_values[f'x_{i}_dispatch_{k}'])) | |
| new_model.update() | |
| for k in [0,1]: | |
| if i in unselected and var_name in target_variable_values: | |
| new_model.addConstr(new_model.getVarByName(f'x_{i}_exchange_{k}') == int(target_variable_values[f'x_{i}_exchange_{k}'])) | |
| new_model.update() | |
| sum_expression = gp.LinExpr() | |
| var_name = f"u_{i}_{k}" | |
| if i in unselected and var_name in target_variable_values: | |
| new_model.update() | |
| sum_expression.addConstant(int(target_variable_values[var_name])) | |
| #total_expression += (target_variable_values[var_name] - C[i])**2 | |
| else: | |
| sum_expression.addTerms(1,new_model.getVarByName(f'u_{i}_{k}')) | |
| # print(total_expression) | |
| ### | |
| ### | |
| ### | |
| total_expression += (sum_expression - C[i])**2 | |
| ### | |
| ### | |
| ### | |
| else: | |
| ### | |
| ### | |
| ### | |
| total_expression = gp.quicksum((gp.quicksum(new_model.getVarByName(f'u_{i}_{k}') for k in K) - C[i])**2 for i in I) | |
| ### | |
| ### | |
| ### | |
| else: | |
| if parameterize is True: | |
| total_expression = gp.QuadExpr() | |
| for i in I: | |
| for k in [1,2]: | |
| var_name = f"x_{i}_dispatch_{k}" | |
| if i in unselected and var_name in target_variable_values: | |
| #print(var_name,'will be replaced with ',target_variable_values[var_name]) | |
| total_expression.addConstant(int(target_variable_values[f"x_{i}_dispatch_{k}"])**2) | |
| else: | |
| total_expression.addTerms(1,new_model.getVarByName(f"x_{i}_dispatch_{k}"),new_model.getVarByName(f"x_{i}_dispatch_{k}")) | |
| for i in I: | |
| for k in K: | |
| if i in unselected and var_name in target_variable_values: | |
| #print(var_name,'will be replaced with ',target_variable_values[var_name]) | |
| new_model.addConstr(new_model.getVarByName(f'x_{i}_dispatch_{k}') == int(target_variable_values[f'x_{i}_dispatch_{k}'])) | |
| new_model.update() | |
| for k in [0,1]: | |
| if i in unselected and var_name in target_variable_values: | |
| new_model.addConstr(new_model.getVarByName(f'x_{i}_exchange_{k}') == int(target_variable_values[f'x_{i}_exchange_{k}'])) | |
| new_model.update() | |
| else: | |
| total_expression = gp.quicksum((new_model.getVarByName(f"x_{i}_dispatch_{k}"))**2 for k in [1,2] for i in I) | |
| new_model.addConstr(w == total_expression,'nonlinear') | |
| new_model.update() | |
| pattern = r'GRB\.(MAXIMIZE|MINIMIZE)' | |
| match = re.search(pattern, str(text)) | |
| if match: | |
| new_model.setObjectiveN(w2 * origin_obj, index=0, priority=5, name='obj_tree') | |
| new_model.modelSense = GRB.MINIMIZE | |
| if match.group(1) == 'MAXIMIZE': | |
| new_model.setObjectiveN(-w1 * new_obj_expr,index=1, priority=1, name='obj_indicator') | |
| elif match.group(1) == 'MINIMIZE': | |
| new_model.setObjectiveN(w1 * new_obj_expr,index=1, priority=1, name='obj_indicator') | |
| new_model.update() | |
| #print(new_model.getObjective()) | |
| return new_model | |
| def select_random_keys(dictionary, k): | |
| random.seed(int(time.time())) | |
| return random.sample(list(dictionary.keys()), k) | |
| def variables_values(variables, csv_path): | |
| """ | |
| Convert variable names to their generalized form and assign means from a CSV file. | |
| Parameters: | |
| - variables: A list of variable names in string format. | |
| - csv_path: Path to the CSV file. | |
| Returns: | |
| - A dictionary with the original variable names as keys and their calculated means as values. | |
| """ | |
| data = pd.read_csv(csv_path) | |
| result = {} | |
| for var in variables: | |
| # Extract indices from the variable name | |
| indices = re.findall(r'\d+', var) | |
| # Determine the type of variable and build column name for the CSV | |
| if 'exchange' in var: | |
| var_type = 'exchange' | |
| elif 'dispatch' in var: | |
| var_type = 'dispatch' | |
| elif 'u' in var: | |
| var_type = 'I' | |
| if var_type and len(indices) >= 2: | |
| i, k = indices[0], indices[1] | |
| column_name = f"{i}_{var_type}_{k}" | |
| # Calculate the mean value from the CSV data | |
| if column_name in data.columns: | |
| mean_value = int(data[column_name].mean()) | |
| result[var] = mean_value | |
| else: | |
| result[var] = None # If the column does not exist in the data | |
| else: | |
| result[var] = None # If not enough indices or unrecognized type | |
| return result | |
| def capture_gurobi_output(log_filename,model): | |
| if os.path.exists(log_filename): | |
| os.remove(log_filename) | |
| model.setParam(GRB.Param.Presolve, 0) | |
| model.setParam(GRB.Param.Cuts, 0) | |
| model.setParam(GRB.Param.TimeLimit, 3600) | |
| #model.setParam(GRB.Param.TimeLimit, 5) | |
| model.setParam(GRB.Param.NonConvex, 2) | |
| model.setParam(GRB.Param.DisplayInterval, 60) | |
| #model.setParam('LogToConsole', 0) | |
| model.setParam('LogFile', log_filename) | |
| start_time = time.time() | |
| model.optimize() | |
| end_time = time.time() | |
| optimize_time = end_time - start_time | |
| var_values = extract_specific_vars_values(model) | |
| with open(log_filename, 'r') as log_file: | |
| log_contents = log_file.read() | |
| best_objective = [float(num) for num in re.findall(r'Best objective ([\d\.e\+\-]+)', log_contents)] | |
| best_bound = [float(num) for num in re.findall(r'best bound ([\d\.e\+\-]+)', log_contents)] | |
| gap = [float(num) for num in re.findall(r'gap ([\d\.e\+\-]+)%', log_contents)] | |
| return optimize_time,best_objective,best_bound,gap,var_values | |
| def evaluate_expression(model, expression,selected): | |
| I = list(range(55)) | |
| K = [0, 1, 2] | |
| soc = [0, 1, 2] | |
| N = 60 | |
| z = [0, 0, 50] | |
| k_0 = 0 | |
| k_1 = 1 | |
| k_2 = 2 | |
| C = [43,36,37,39,44] | |
| #C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40] | |
| v = np.zeros((55, 3)) | |
| random.seed(0) | |
| for i in range(len(I)): | |
| for j in range(len(K)): | |
| v[i, j] = random.randint(j * 5, j * 5 + 10) | |
| expression = re.sub(r'gp\.quicksum', 'sum', expression) | |
| expression = re.sub(r'model.getVarByName\((.*?)\)', r'model.getVarByName(\1).X', expression) | |
| expression = re.sub(r'I', str(selected), expression, count=1) | |
| expression = re.sub(r'model.setObjective\((.*?), GRB.(MINIMIZE|MAXIMIZE)\)', r'\1', expression) | |
| print(expression) | |
| total_value = eval(expression,{'model': model, 'gp': gp, "GRB": gp.GRB, "k_0":k_0, "k_1":k_1, "k_2":k_2, 'I': I, 'K': K, 'N':N, 'z':z, 'v':v, 'C':C}) | |
| print(expression) | |
| return total_value | |
| def extract_specific_vars_values(model): | |
| """ | |
| Extract variable values for variables whose names contain 'x' or 'u' from a solved Gurobi model. | |
| Parameters: | |
| model (gurobipy.Model): The Gurobi model after it has been optimized. | |
| Returns: | |
| dict: A dictionary with variable names as keys and their solution values as values. | |
| """ | |
| var_values = {} | |
| for var in model.getVars(): | |
| if 'x' in var.VarName or 'u' in var.VarName: | |
| var_values[var.VarName] = var.X # X attribute gives the solution value of the variable | |
| return var_values | |
| def his_score(csv_path,indicator): | |
| I = list(range(55)) | |
| K = [0, 1, 2] | |
| soc = [0, 1, 2] | |
| N = 60 | |
| z = [0, 0, 50] | |
| k_0 = 0 | |
| k_1 = 1 | |
| k_2 = 2 | |
| C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40] | |
| v = np.zeros((55, 3)) | |
| random.seed(0) | |
| for i in range(len(I)): | |
| for j in range(len(K)): | |
| v[i, j] = random.randint(j * 5, j * 5 + 10) | |
| data = pd.read_csv(csv_path) | |
| data = data.rename(columns={f"{i}_I_{k}": f"u_{i}_{k}" for i in range(55) for k in range(3)}) | |
| data = data.rename(columns={f"{i}_exchange_{k}": f"x_{i}_exchange_{k}" for i in range(55) for k in range(2)}) | |
| data = data.rename(columns={f"{i}_dispatch_{k}": f"x_{i}_dispatch_{k}" for i in range(55) for k in range(2)}) | |
| mean_data = data.mean(axis=0)[7:].to_dict() | |
| #print(mean_data) | |
| if indicator == 'utilize': | |
| ### | |
| ### | |
| ### | |
| score = sum((sum(mean_data[f'u_{i}_{k}'] for k in K) - C[i])**2 for i in I) | |
| ### | |
| ### | |
| ### | |
| else: | |
| score = sum((mean_data[f'x_{i}_dispatch_{k}'])**2 for k in [1,2] for i in I) | |
| #print(score) | |
| return score | |
| if __name__ == "__main__": | |
| indicators = ['utilize','rate'] | |
| ###!!!personalized!!!### | |
| csv_path = 'train_data_4.csv' | |
| percentage = 0 | |
| times = 1 | |
| for t in range(0,times): | |
| indicator = indicators[0] | |
| ###!!!personalized!!!### | |
| if t % 3 == 0: | |
| percentage += 0.2 | |
| print('\n') | |
| print('\n') | |
| print('第',t,'次') | |
| print('\n') | |
| print('\n') | |
| spot_num = 55*round(percentage,1) | |
| spots = { | |
| 0: '3rd Ave & Broad St', 1: '2nd Ave & Blanchard St', 2: '6th Ave & Blanchard St', 3: '2nd Ave & Blanchard St', | |
| 4: '7th Ave & Union St', 5: 'Union St & 4th Ave', 6: '1st Ave & Marion St', 7: '2nd Ave & Spring St', | |
| 8: 'City Hall / 4th Ave & James St', 9: '2nd Ave & Pine St', 10: '12th Ave & E Yesler Way', 11: 'Summit Ave & E Denny Way', | |
| 12: 'E Harrison St & Broadway Ave E', 13: 'Summit Ave E & E Republican St', 14: '15th Ave E & E Thomas St', | |
| 15: '12th Ave & E Denny Way', 16: 'E Pine St & 16th Ave', 17: 'Cal Anderson Park / 11th Ave & Pine St', | |
| 18: 'Harvard Ave & E Pine St', 19: 'Bellevue Ave & E Pine St', 20: '12th Ave & E Mercer St', 21: '9th Ave N & Mercer St', | |
| 22: "Children's Hospital / Sandpoint Way NE & 40th Ave NE", | |
| 23: 'Fred Hutchinson Cancer Research Center / Fairview Ave N & Ward St', | |
| 24: 'E Blaine St & Fairview Ave E', 25: 'Eastlake Ave E & E Allison St', | |
| 26: 'Frye Art Museum / Terry Ave & Columbia St', 27: 'Seattle University / E Columbia St & 12th Ave', | |
| 28: '6th Ave S & S King St', 29: 'Occidental Park / Occidental Ave S & S Washington St', | |
| 30: 'King Street Station Plaza / 2nd Ave Extension S & S Jackson St', 31: 'REI / Yale Ave N & John St', | |
| 32: 'Dexter Ave N & Aloha St', 33: 'Republican St & Westlake Ave N', 34: 'PATH / 9th Ave & Westlake Ave', | |
| 35: 'Westlake Ave & 6th Ave', 36: 'Pine St & 9th Ave', 37: 'Lake Union Park / Valley St & Boren Ave N', | |
| 38: 'Dexter Ave & Denny Way', 39: 'Key Arena / 1st Ave N & Harrison St', 40: 'Terry Ave & Stewart St', | |
| 41: 'Mercer St & 9th Ave N', 42: 'Burke-Gilman Trail / NE Blakeley St & 24th Ave NE', | |
| 43: 'NE 42nd St & University Way NE', 44: '12th Ave & NE Campus Pkwy', 45: 'NE 47th St & 12th Ave NE', | |
| 46: 'UW McCarty Hall / Whitman Ct', 47: 'Burke Museum / E Stevens Way NE & Memorial Way NE', | |
| 48: '15th Ave NE & NE 40th St', 49: 'UW Engineering Library / E Stevens Way NE & Jefferson Rd', | |
| 50: 'UW Intramural Activities Building', 51: 'UW Magnuson Health Sciences Center Rotunda / Columbia Rd & San Juan Rd', | |
| 52: 'Pier 69 / Alaskan Way & Clay St', 53: 'Seattle Aquarium / Alaskan Way S & Elliott Bay Trail', | |
| 54: 'Broadway and E Denny Way' | |
| } | |
| selected = select_random_keys(spots, int(spot_num)) | |
| print(selected) | |
| unselected_spots = {key: value for key, value in spots.items() if key not in selected} | |
| unselected = [] | |
| for key, value in unselected_spots.items(): | |
| unselected.append(key) | |
| print(unselected) | |
| target_variable_values = {} | |
| i_range = list(range(55)) | |
| k_range = [0, 1, 2] | |
| vars = [] | |
| for i in i_range: | |
| for k in k_range: | |
| var_name = f"u_{i}_{k}" | |
| vars.append(var_name) | |
| var_name = f"x_{i}_dispatch_{k}" | |
| vars.append(var_name) | |
| for k in [0,1]: | |
| var_name = f"x_{i}_exchange_{k}" | |
| vars.append(var_name) | |
| target_variable_values = variables_values(vars,csv_path) | |
| if indicator == 'utilize': | |
| ### | |
| ### | |
| ### | |
| text = "model.setObjective(gp.quicksum((gp.quicksum(model.getVarByName(f'u_{i}_{k}') for k in K) - C[i])**2 for i in I), GRB.MAXIMIZE)" | |
| ### | |
| ### | |
| ### | |
| else: | |
| #min \sum_i \sum_{k\in {k1,k2}} (x_ik)^2 | |
| text = "model.setObjective(gp.quicksum(model.getVarByName(f'x_{i}_dispatch_{k}')**2 for k in [1,2] for i in I), GRB.MINIMIZE)" | |
| parameterize_model = add_new_obj('ebike_data/model04.mps', text, 1, 1, unselected, target_variable_values,True,indicator) | |
| # parameterize_model.write('exper4_para.lp') | |
| # parameterize_model.write('exper4_para.mps') | |
| tnow = time.time() | |
| log_path = 'result_extra_exper4/log_files/new_LEO_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow) | |
| LEO_optimize_time,LEO_obj_value,LEO_bound,LEO_gap,LEO_var_values = capture_gurobi_output(log_path,parameterize_model) | |
| LEO_qs = evaluate_expression(parameterize_model, text, selected) | |
| print(LEO_optimize_time,LEO_obj_value,LEO_bound,LEO_gap) | |
| parameterize_model.dispose() | |
| base_model = add_new_obj('ebike_data/model04.mps', text, 1, 1, unselected, target_variable_values,False,indicator) | |
| # base_model.write('exper4_base.lp') | |
| # base_model.write('exper4_base.mps') | |
| log_path = 'result_extra_exper4/log_files/new_base_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow) | |
| base_optimize_time,base_obj_value,base_bound,base_gap,base_var_values = capture_gurobi_output(log_path,base_model) | |
| base_qs = evaluate_expression(base_model, text, selected) | |
| print(base_optimize_time,base_obj_value,base_bound,base_gap) | |
| base_model.dispose() | |
| if indicator == 'utilize': | |
| qs = (LEO_qs-base_qs)/(0.01+base_qs) | |
| else: | |
| qs = -1*(LEO_qs-base_qs)/(0.01+base_qs) | |
| result_gap_1 = (abs(abs(LEO_obj_value[0]) - abs(base_obj_value[0])) / abs(0.00001+LEO_obj_value[0]))*100 | |
| result_gap_2 = (abs(abs(LEO_obj_value[1]) - abs(base_obj_value[1])) / abs(0.00001+LEO_obj_value[1]))*100 | |
| file_path = 'result_extra_exper4/results/new_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow) | |
| f = open(file_path, 'w') | |
| print('LEO_optimize_time:', LEO_optimize_time) | |
| f.write('LEO_optimize_time:{}'.format(LEO_optimize_time)) | |
| f.write('\n') | |
| print('LEO_result:', LEO_obj_value) | |
| f.write('LEO_result:{}'.format(LEO_obj_value)) | |
| f.write('\n') | |
| print('LEO_bound', LEO_bound) | |
| f.write('LEO_bound:{}'.format(LEO_bound)) | |
| f.write('\n') | |
| print('LEO_gap_1', LEO_gap[0]) | |
| print('LEO_gap_2', LEO_gap[1]) | |
| f.write('LEO_gap_1:{}'.format(LEO_gap[0])) | |
| f.write('\n') | |
| f.write('LEO_gap_2:{}'.format(LEO_gap[1])) | |
| f.write('\n') | |
| f.write('LEO_qs:{}'.format(LEO_qs)) | |
| f.write('\n') | |
| f.write('LEO_var_values:{}'.format(LEO_var_values)) | |
| f.write('\n') | |
| print('base_optimize_time:', base_optimize_time) | |
| f.write('base_optimize_time:{}'.format(base_optimize_time)) | |
| f.write('\n') | |
| print('base_result:', base_obj_value) | |
| f.write('base_result:{}'.format(base_obj_value)) | |
| f.write('\n') | |
| print('base_bound', base_bound) | |
| f.write('base_bound:{}'.format(base_bound)) | |
| f.write('\n') | |
| print('base_gap_1', base_gap[0]) | |
| print('base_gap_2', base_gap[1]) | |
| f.write('base_gap_1:{}'.format(base_gap[0])) | |
| f.write('\n') | |
| f.write('base_gap_2:{}'.format(base_gap[1])) | |
| f.write('\n') | |
| f.write('base_qs:{}'.format(base_qs)) | |
| f.write('\n') | |
| f.write('base_var_values:{}'.format(base_var_values)) | |
| f.write('\n') | |
| print('selected station IDs:', selected) | |
| f.write('selected station IDs:{}'.format(selected)) | |
| f.write('\n') | |
| print('result_gap_1', result_gap_1) | |
| print('result_gap_2', result_gap_2) | |
| f.write('result_gap_1:{}'.format(result_gap_1)) | |
| f.write('\n') | |
| f.write('result_gap_2:{}'.format(result_gap_2)) | |
| f.write('\n') | |
| print('qs:',qs) | |
| f.write('qs:{}'.format(qs)) | |
| f.write('\n') | |
| f.close() | |