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 getpass #os.environ["OPENAI_API_KEY"] = getpass.getpass() os.environ["OPENAI_API_KEY"] = '' llm1 = ChatOpenAI(model="gpt-4o",temperature=0.8) # model='gpt-4' llm2 = ChatOpenAI(model="gpt-3.5-turbo",temperature=0.8) def random_pick_from_dict(dictionary, k): selected_values = random.sample(list(dictionary.values()), k) return ', '.join(selected_values) def create_partial_variables(model, dimension_feature2decision, decision_list, empirical_data): '''partial decision variables creating''' x = {} dimensions = dimension_feature2decision total_indices = 1 for dim in dimensions: total_indices *= dim index_combinations = [[]] for dim in reversed(dimensions): index_combinations = [[i] + rest for i in range(1, dim + 1) for rest in index_combinations] #print(index_combinations) for indices in index_combinations: if tuple(indices) not in decision_list: x[tuple(indices)] = empirical_data else: x[tuple(indices)] = model.addVar(vtype=GRB.CONTINUOUS, name="x_" + "_".join(map(str, indices))) # model.update() # for var in model.getVars(): print('decision_variable:', var.varName) return model, x def remove_variable_from_objective(model, target_variable_name): """ Remove a variable from the objective function of a Gurobi model. Parameters: - model: The Gurobi model from which the variable will be removed. - target_variable_name: The name of the variable to remove from the objective. """ obj_expr = model.getObjective() new_obj_expr = gp.LinExpr() for i in range(obj_expr.size()): var = obj_expr.getVar(i) coeff = obj_expr.getCoeff(i) if var.VarName != target_variable_name: new_obj_expr.addTerms(coeff, var) model.setObjective(new_obj_expr) model.update() return model def add_new_obj(new_model_path, text, w1, w2): 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)) global randseed random.seed(randseed) for i in range(55): for j in range(3): 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.LinExpr): #print('LinExpr') for i in range(new_obj.size()): coeff = new_obj.getCoeff(i) var_name = new_obj.getVar(i).VarName new_var = new_model.getVarByName(var_name) try: new_var = new_model.getVarByName(var_name) new_obj_expr.addTerms(coeff, new_var) except gp.GurobiError as e: continue new_obj_expr.addConstant(new_obj.getConstant()) elif isinstance(new_obj, gp.QuadExpr): new_obj_expr = gp.QuadExpr() #print('QuadExpr') for i in range(new_obj.size()): coeff = new_obj.getCoeff(i) var1_name = new_obj.getVar1(i).VarName var2_name = new_obj.getVar2(i).VarName #print(var1_name,var2_name) new_var1 = new_model.getVarByName(var1_name) new_var2 = new_model.getVarByName(var2_name) new_obj_expr.addTerms(coeff, new_var1, new_var2) lin_expr = new_obj.getLinExpr() for i in range(lin_expr.size()): coeff = lin_expr.getCoeff(i) var_name = lin_expr.getVar(i).VarName new_var = new_model.getVarByName(var_name) new_obj_expr.addTerms(coeff, new_var) 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 replace_variable_in_objective(model, selected_variables, csv_path): """ Replace selected variables in the model's objective function with constants from a value map. Args: - model: The Gurobi model from which variables will be replaced in the objective with constants. - selected_variables: A string containing specific variable names separated by commas, e.g., "u_1_1, x_0_exchange_1". """ variables = [var.strip() for var in selected_variables.split(',')] obj_expr = model.getObjective() new_obj_expr = gp.LinExpr() data = pd.read_csv(csv_path) for i in range(obj_expr.size()): var = obj_expr.getVar(i) coeff = obj_expr.getCoeff(i) if var.VarName in variables: result = {} indices = re.findall(r'\d+', str(var.VarName)) # Determine the type of variable and build column name for the CSV if 'exchange' in str(var.VarName): var_type = 'exchange' elif 'dispatch' in str(var.VarName): var_type = 'dispatch' 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 = data[column_name].mean() result[var] = mean_value constant_value = result[var] * coeff new_obj_expr.addConstant(constant_value) print(f"替换目标函数中的 {var.VarName} 为常数 {constant_value}") new_obj_expr.addTerms(coeff, var) model.setObjective(new_obj_expr) model.update() return model def add_equal_constr(model, target_variable_name, target_variable_value): model.addConstr(model.getVarByName(target_variable_name) == target_variable_value) print(target_variable_name, '==', target_variable_value) return model def replace_constraint(model,target_variable_name, target_variable_value): """rewrite constraint base on input""" print('target_variable_name',target_variable_name) constr_pos = model.getCol(model.getVarByName(target_variable_name)) pattern_string = str(constr_pos) print('\n variable',target_variable_name,'constraint',pattern_string) matches = re.findall(r'R\d+', pattern_string) for name in matches: print('constr name',name) constr = model.getConstrByName(name) expr = model.getRow(constr) matches = re.findall(r'\b\w+\b', str(expr)) #print('matches',matches) sense = constr.sense+str('=') rhs = constr.rhs origin_constr = str(expr)+str(sense)+str(rhs) print('origin_constr',origin_constr) for i in range(expr.size()): var = expr.getVar(i) if var.VarName == target_variable_name: coeff = expr.getCoeff(i) expr.remove(model.getVarByName(target_variable_name)) expr.addConstant(float(coeff)*target_variable_value) new_constr = str(expr)+str(sense)+str(rhs) print('new_constr',new_constr) model.addConstr(expr, sense, rhs, name=f"{name}") model.update() model.remove(constr) model.update() model.write('RF+SEB new.lp') model.write('RF+SEB new.mps') return model def convert_variable_names(variables, value_map): """ Convert variable names based on specific patterns and update values based on value_map. Parameters: - variables: A list of variable names in string format. - value_map: A dictionary with generalized variable names as keys and their corresponding values. Returns: - A dictionary with the converted variable names as keys and the updated values as values. """ result = {} for var in variables: # Extract indices from the variable name indices = re.findall(r'\d+', var) # Build the generic variable name pattern if 'exchange' in var: generic_var = f'x_i_exchange_k' elif 'dispatch' in var: generic_var = f'x_i_dispatch_k' elif 'u_' in var: generic_var = f'u_i_k' else: generic_var = None # Map the specific variable to its generic form and assign the value if generic_var and generic_var in value_map: result[var] = value_map[generic_var] else: result[var] = None # If no matching generic name, set value to None or keep original return result 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' else: var_type = None 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 process_constraints(user_input, model, csv_path): """ Process and replace constraints based on the decision variables extracted from the text content. Parameters: - text_content: The text containing the decision variables enclosed in 「」. - model: The Gurobi model where constraints will be replaced. Returns: - The updated model after replacing the constraints. """ # Extract decision variables from the text content # Split the string by commas that are not inside square brackets decision_variables = variables_obtain(user_input,model) # Convert variable names and get values converted_variables = variables_values(decision_variables, csv_path) # Replace constraints in the model based on the converted variable names and their values for variable, value in converted_variables.items(): #model = replace_constraint(model, variable, value) model = add_equal_constr(model, variable, value) return model def variables_obtain(spot_id,model): #print('spot_id',spot_id) indices = [int(num) for num in spot_id.split(',')] decision_variables = [] for var in model.getVars(): var_name = var.VarName for i in indices: if f"x_{i}_dispatch" in var_name or f"x_{i}_exchange" in var_name: decision_variables.append(var_name) return decision_variables def name2id(format_output): matches = re.findall(r'「(.*?)」', format_output) #def station_name2station_id(): spot_names_to_numbers = {0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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_spot_names_str = matches[0] if matches else '' selected_spot_names = [name.strip() for name in selected_spot_names_str.split(",")] spot_numbers = [] if all(name.strip().isdigit() for name in selected_spot_names): spot_numbers = [','.join(selected_spot_names)] else: pattern = re.compile(r"[a-zA-Z0-9&/'. ]{3,}") for name in selected_spot_names: if pattern.search(name): matched_number = next((str(num) for num, spot_name in spot_names_to_numbers.items() if spot_name == name), None) if matched_number: spot_numbers.append(matched_number) if spot_numbers: spot_numbers = [','.join(spot_numbers)] #print(spot_numbers) return spot_numbers def parsing_text(re_search): if re_search: objective = 'MINIMIZE' if 'MINIMIZE' in re_search.group() else 'MAXIMIZE' new_result = f'model.setObjective({re_search.group(1)} GRB.{objective})' new_result = f'「{new_result}」' else: new_result = None #print(new_result) matches2 = re.findall(r'「(.*?)」', str(new_result)) for match in matches2: print(match) temp_text = str(match) return temp_text def get_optimal_values(model): return {var.name: var.value() for var in model.variables()} def capture_model_variables(model): variables_info = [] for var in model.getVars(): if 'u' in var.VarName or 'x' in var.VarName: variables_info.append((var.VarName, var.X)) return variables_info def evaluate_expression(model, expression_dict, key): 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)) global randseed, expression random.seed(randseed) for i in range(55): for j in range(3): v[i, j] = random.randint(j * 5, j * 5 + 10) expression = expression_dict[key] expression = re.sub(r'gp\.quicksum', 'sum', expression) expression = re.sub(r'model.getVarByName\((.*?)\)', r'model.getVarByName(\1).X', expression) expression = re.sub(r'model.setObjective\((.*?), GRB.(MINIMIZE|MAXIMIZE)\)', r'\1', expression) print(expression) total_value = eval(expression,{'model': model, "k_0":k_0, "k_1":k_1, "k_2":k_2, 'I': I, 'K': K, 'N':N, 'z':z, 'v':v, 'C':C}) return total_value def sample_expressions(n_samples, include_mandatory, mandatory_key, expression_dict): """ Sample expressions from a dictionary, either ensuring the inclusion or exclusion of a specified mandatory item. Args: n_samples (int): Number of items to sample from the dictionary. include_mandatory (bool): If True, include the mandatory item; if False, exclude it. mandatory_key (str): The key of the item to include or exclude. expression_dict (dict): The dictionary from which to sample. seed (int): Random seed for reproducibility. Returns: dict: A dictionary containing sampled expressions. """ keys = list(expression_dict.keys()) sampled_dict = {} if n_samples == 0: return 'None' if include_mandatory: # Ensure the mandatory item is included if specified if mandatory_key in keys: sampled_dict[mandatory_key] = expression_dict[mandatory_key] keys.remove(mandatory_key) n_samples -= 1 # Reduce the number of items to sample since one is already included else: # Ensure the mandatory key is excluded if mandatory_key in keys: keys.remove(mandatory_key) # Randomly sample the remaining number of keys from the list sampled_keys = random.sample(keys, min(n_samples, len(keys))) # Add the sampled items to the dictionary for key in sampled_keys: sampled_dict[key] = expression_dict[key] return sampled_dict def remove_backslashes_from_getvar(input_string): pattern = r'getVarByName\((.*?)\)' result = re.sub(pattern, lambda m: "getVarByName(" + m.group(1).replace("\\", "") + ")", input_string) return result from langchain_core.tools import tool from langchain import PromptTemplate import re #Create tools #[domain, target, target description,target code,partial variable,] @tool def recognizer(user_input:str) -> list: """这个工具用于提取出用户想要作用的领域和想要实现的指标。输入的是用户的需求字符串格式,最终返回一个列表,输出列表中包含作用领域和指标的提取结果""" template = """Based on the {input}, you need to extract the user's domain of activity and the goals they want to achieve. The response format must be exactly as follows: domain:「」, target:「」, with no alterations. Here, "domain" describes the real-world area of application, and "target" describes the specific metrics or objectives they wish to improve. Pay close attention to the details of the user's goals, extracting the information directly without any summarization. For example:domain:「shared E-bike」,target:「improve revenue at site named '3rd Ave & Broad St'」.You should pay special attention to the user's location requirements in your identification results and truthfully record them. """ prompt = PromptTemplate(input_variables=["input"],template=template) prompt_intent = prompt.format(input=user_input) #print(prompt_intent) response = llm2.invoke(prompt_intent) print(response) matches = re.findall(r'「(.*?)」', str(response)) global Domain, Target Domain = matches[0] Target = matches[1] return matches @tool def indicator(user_target:list)-> list: """这个工具基用于结合后端的优化模型获取指标的可能公式构成,并通过LLM确保该公式的gurobi表述能够正常运行。输入是包含用户需求的列表,最终返回一个列表,输出列表中用户需求以及指标公式构成""" global groundtruth template = '''You are an assistant to a professor of operations research, possessing a strong foundation in mathematics and operations research. You need to complete tasks according to requirements, while ensuring the output format meets the specified standards. The requirements are as follows: Now, the following descriptions are provided, including sets, parameters, and decision variables. Sets symbols, descriptions, and definitions are as follows: --- $$I$$: Set of parking spots; $$K$$: Set of discrete electric charge levels for shared e-bikes; Defined respectively as: I = list(range(55)), with each spot i and its corresponding name: {{0: '3rd Ave & Broad St', 1: '2nd Ave & Vine 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'}}; K = [0,1,2] --- Parameters --- $$v[i][k]$$: Number of bikes at initial parking spot i with charge level k; $$z[k]$$: Number of fully charged bikes initially on the transport vehicle; $$k_0$$: The minimum charge level threshold for e-bikes to be serviceable, below which they cannot be used by customers; $$C[i]$$: Capacity of parking spot i; $$B$$: Maximum number of batteries that the battery exchange transport can accommodate; $$N$$: Capacity of the transport vehicle; Defined respectively as: N = 60; z = [0, 0, 50]; "k_0":k_0, "k_1":k_1, "k_2":k_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)) --- Decision variables symbols, descriptions, and definitions are as follows: --- $$x_i_exchange_k$$: Number of batteries with charge level k taken from parking spot i and replaced with the same number of fully charged batteries, for this variable, k can only take values from [0,1]; $$x_i_dispatch_k$$: Number of e-bikes with charge level k deployed (+) or removed (−) at parking spot i; $$u_i_k$$: Number of e-bikes with charge level k at parking spot i after scheduling and battery exchange; If you need to use a decision variable, follow this form: model.addVar(name=f"u_{{i}}_{{k}}"); model.addVar(name=f"x_{{i}}_dispatch_{{k}}"); model.addVar(name=f"x_{{i}}_exchange_{{k}}"). Note that when you use the variable x_i_exchange_k, its k can only take values from [0,1]. For example, in the case of summation, you need to represent it as: model.getVarByName(f'x_{{i}}_exchange_{{k}}') if k < 2 else 0 --- Based on the above parameters, you are required to construct an expression to depict this {target}, which must be sensible, containing the mentioned parameters and decision variables without creation of additional elements, and the formula must be convex. Do not use quadratic terms(**2,^2) in fomula. Must not use the maximum value (max/min) or absolute value (abs) in the formula. Must not contain any line continuation character. The output must contain the following two points, and the format must adhere to the following: 1. Start with an explanation of the formula, explaining why it is set up this way, and be sure to enclose the formula explanation in “「」”; 2. Then provide the corresponding python statement for the formula, ensuring it is enclosed in “「」” and only includes the previously mentioned sets, parameters, and decision variables in the format provided; For example:Formula explanation: “「The meaning of the formula is:」”, python representation: “「」”. Now I will give you some groundtruth formulation, If the content I provide you is similar to the goal, you can refer to it. {answer} The output format must follow the example above, enclosed in “「」”, but the content is for you to decide, the formula should not be complex, just reasonable. Python code mast not contain special symbols such as line breaks({{\n}}). Make sure the output standard is followed, and the representation of variables, parameters, and subscripts conforms to the defined method, with no latex representation in the content. Take a deep breath and solve the problem step by step.''' prompt = PromptTemplate(input_variables=["target","answer"],template=template) prompt_scope_down = prompt.format(target=Target,answer=groundtruth) result = llm1.invoke(prompt_scope_down) matches = re.findall(r'「(.*?)」', str(result)) global Formulation_explanation, Python_formulation Formulation_explanation = matches[0] Python_formulation = matches[1] for match in matches: user_target.append(str(match)) #print(match) template2 = """ The current {formulation} consists of the following sets, parameters, and decision variables: Sets --- $$I$$: Set of parking spots; $$K$$: Set of discrete electric charge levels for shared e-bikes; Defined respectively as: I = list(range(55)), with each spot i and its corresponding name:{{0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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'}}; K = [0,1,2] --- Parameters --- $$v[i][k]$$: Number of bikes at initial parking spot i with charge level k; $$z[k]$$: Number of fully charged bikes initially on the transport vehicle; $$k_0$$: The minimum charge level threshold for e-bikes to be serviceable, below which they cannot be used by customers; $$C[i]$$: Capacity of parking spot i; $$B$$: Maximum number of batteries that the battery exchange transport can accommodate; $$N$$: Capacity of the transport vehicle; Defined respectively as: N = 60; z = [0, 0, 50]; "k_0":k_0, "k_1":k_1, "k_2":k_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)) --- Decision Variables --- $$x_i_exchange_k$$: Number of SOC level k batteries removed from parking spot i and replaced with the same number of fully charged batteries, for this variable, k can only take values from[0,1]; $$x_i_dispatch_k$$: Number of SOC level k e-bikes deployed (+) or removed (−) at parking spot i; $$u_i_k$$: Number of e-bikes with charge level k at parking spot i after scheduling and battery exchange; If you need to use a decision variable, follow this form: model.addVar(name=f"u_{{i}}_{{k}}"); model.addVar(name=f"x_{{i}}_dispatch_{{k}}"); model.addVar(name=f"x_{{i}}_exchange_{{k}}") --- You need to rewrite {formulation} as the objective function code for gurobi (model.setObjective()). You must ensure that your gurobi code is complete, containing decision variable identification (getVarByName), summing (sum/quicksum), the objective function keyword (model.setObjective()), and the sense of the objective function must in (GRB.MAXIMIZE or GRB.MINIMIZE). Now I will give you some groundtruth formulation, If the content I provide you is similar to the goal, you can refer to it. {answer} When you attempt to use getVarByName to fetch a decision variable, you must ensure the object being used is indeed a decision variable, and only decision variables should use getVarByName, while the rest are treated as parameters. Your expression of variables must follow the format given below, without any additional form of expression: $$x_i_exchange_k$$; $$x_i_dispatch_k$$; $$u_i_k$$. Note that when you use the variable x_i_exchange_k, its k can only take values from [0,1]. For example, in the case of summation, you need to represent it as: model.getVarByName(f'x_{{i}}_exchange_{{k}}') if k < 2 else 0 The content in the code must conform to their definitions, the output must be in gurobi syntax. Mustn't contain any line continuation character and the format must comply with: gurobi code is: “「」” For example: gurobi code is: "「“”“model.setObjective(gp.quicksum(model.getVarByName(f'x_{{i}}_exchange_{{k}}') for i in I for k in K-1), GRB.MAXIMIZE)“”“」" The output format must follow the example above, enclosed in “「」” and it cannot be the same as the example I gave, fill in the sentences you translated. Gurobi code mast not contain special symbols such as line breaks({{\n}}). Take a deep breath and solve the problem step by step. """ prompt2 = PromptTemplate(input_variables=["formulation","answer"],template=template2) gurobi_code = prompt2.format(formulation=Python_formulation,answer=groundtruth) result2 = llm1.invoke(gurobi_code) print(result2.content) pattern = r'model.setObjective\((.*?)\s*GRB\.(MINIMIZE|MAXIMIZE)' match = re.search(pattern,str(result2)) global temp_text temp_text = parsing_text(match) temp_text = remove_backslashes_from_getvar(temp_text) invoke_count = 0 while True: 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)) global randseed random.seed(randseed) for i in range(55): for j in range(3): v[i, j] = random.randint(j * 5, j * 5 + 10) for i in range(55): for k in range(3): model.addVar(name=f"u_{i}_{k}") model.addVar(name=f"x_{i}_dispatch_{k}") for i in range(55): for k in range(2): model.addVar(name=f"x_{i}_exchange_{k}") model.update() try: print('global obj:',temp_text) exec(temp_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() print("执行成功,目标函数可行。",model.getObjective()) user_target.append(str(temp_text)) break except Exception as e: # print('current obj:',temp_text) print(e) # ##### error_traceback = traceback.format_exc() invoke_count += 1 if invoke_count > 2: print('错误修改失败,重新生成新的formulation') temp_text = '' new_prompt = """The previously generated code has an issue. You need to regenerate it and do not refer to the previous information at all.""" result = llm1.invoke(new_prompt+prompt_scope_down) pattern = r'model.setObjective\((.*?)\s*GRB\.(MINIMIZE|MAXIMIZE)' match = re.search(pattern,str(result2)) temp_text = parsing_text(match) temp_text = remove_backslashes_from_getvar(temp_text) matches = re.findall(r'「(.*?)」', str(result)) for match in matches: user_target.append(str(match)) #print(match) prompt2 = PromptTemplate(input_variables=["formulation","answer"],template=template2) gurobi_code = prompt2.format(formulation=Python_formulation,answer=groundtruth) result2 = llm1.invoke(gurobi_code) #print(result2.content) pattern = r'model.setObjective\((.*?)\s*GRB\.(MINIMIZE|MAXIMIZE)' match = re.search(pattern,str(result2)) #global temp_text temp_text = parsing_text(match) temp_text = remove_backslashes_from_getvar(temp_text) invoke_count = 0 continue else: print("正在重新调试目标函数。") template3 = """You are a programmer specializing in operations research, meticulous and proficient in Gurobi and Python syntax. You are now required to correct the erroneous code. The current Gurobi code: {gurobi_code} has an error, with the detailed error information as follows: {error_traceback}. You need to modify the Gurobi code to address the errors specifically, ensuring it can run properly without altering its overall structure. The output must comply with the format requirements. Here are some common errors and their modifications: 1. TypeError: 'int' object is not iterable Modification: This usually happens when the object iterated in a sum or quicksum loop is not iterable. For example, you might need to change it to: for i in range(I) or for i in range I 2. TypeError: unsupported operand type(s) for +=: 'gurobipy.LinExpr' and 'NoneType' Modification: This often occurs due to a variable matching issue. You should pay extra attention to the naming of decision variables, for example: if the naming convention is u_i_k, then you should use model.getVarByName(f'u_{{i}}_{{k}}') instead of other forms 3. Syntaxerror: unexpected character after line continuation character (, line 1) Modification: This situation indicates that your expression contains special symbols, such as line breaks or the presence of'{{\}}' in function (getVarByName()).So remove these special symbols. Do not use conversion characters in the getVarByName() function. Now I will give you some groundtruth formulation, If the content I provide you is similar to the goal, you can refer to it. {answer} The current parameters and decision variables are as follows: Sets: $$I$$: Parking spot set; with each spot i and its corresponding name:{{0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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'}} $$K$$: Discrete electric charge level set for shared e-bikes; Parameters: $$v[i,k]$$: Number of bikes at initial parking spot i with charge level k; $$z[k]$$: Number of fully charged bikes initially on the transport vehicle; $$k_0$$: The minimum charge level threshold for e-bikes to be serviceable, below which they cannot be used by customers; $$C[i]$$: Capacity of parking spot i; $$B$$: Maximum number of batteries that the battery exchange transport can accommodate; $$N$$: Capacity of the transport vehicle; Decision Variables: $$x_i_exchange_k$$: Number of SOC level k batteries removed from parking spot i and replaced with the same number of fully charged batteries, for this variable, k can only take values from [0,1]; $$x_i_dispatch_k$$: Number of SOC level k e-bikes deployed (+) or removed (−) at parking spot i; $$u_i_k$$: Number of e-bikes with charge level k at parking spot i after scheduling and battery exchange; Note that the decision variables are only x_i_exchange_k, x_i_dispatch_k, u_i_k, so model.getVarByName() should only be used for these variables, others are treated as parameters and should not use this function. Note that when you use the variable x_i_exchange_k, its k can only take values from [0,1]. For example, in the case of summation, you need to represent it as: model.getVarByName(f'x_{{i}}_exchange_{{k}}') if k < 2 else 0 Finally, you must reply according to the format requirements, enclosing the Python Gurobi code in “「」” symbols. If the formula involves fractions, be aware that the denominator should only contain parameters, not variables. Your reply should be formatted as follows: (YOU MUST STICK TO THIS FORMAT ONLY!) Modified Gurobi code is: “「」” The output format must follow the above requirements, enclosing your modified Gurobi code in “「」” symbols. Take a deep breath and solve the problem step by step. """ prompt3 = PromptTemplate(input_variables=["gurobi_code","error_traceback","answer"],template=template3) gurobi_prompt = prompt3.format(gurobi_code=temp_text, error_traceback=error_traceback,answer=groundtruth) result3 = llm2.invoke(gurobi_prompt) #print(result3) match = re.search(pattern,str(result3)) temp_text = parsing_text(match) temp_text = remove_backslashes_from_getvar(temp_text) print('corrector obj',temp_text) global Gurobi_formulation Gurobi_formulation = temp_text user_target_indicator = user_target return user_target_indicator @tool def sampler(user_target_indicator:list) -> list: """这个工具基于用户的目标,结合后端数据库中记录的数据,筛选出对用户目标影响不大的变量,将其参数化。输入的是一个包含用户需求以及指标公式的列表,最终返回一个列表,输出列表包括用户需求、指标公式以及参数化的变量""" database = SQLDatabase.from_uri("mysql+pymysql://root:Zhy15810886562!@127.0.0.1/SEB") agent_executor = create_sql_agent(llm2, db=database, agent_type="openai-tools", verbose=True) error_text = "" template = '''You are a database administrator and an expert in operations research. You need to perform cross-analysis on three existing tables in the database and ultimately provide me with some station names and why you selected these station. Attention! wrap station names with special symbols'「」'. Below are the three tables and the meanings of each column in them: 1. The 'OD' table contains trip records for some e-bike users, including the following fields: trip_id: order number; starttime: order start time; stoptime: order end time; bikeid: ride vehicle id; tripduration: ride duration; from_station_name: departure station name;to_station_name: arrival station name; from_station_id: departure station id; to_station_id: arrival station id; usertype: user type; gender: gender; birthyear: birth year. 2. The 'station' table records information about e-bike charging stations, including the following fields: station_id: station ID; name: station name; lat: station longitude; long: station latitude; install_date: construction date;install_dockcount: number of charging spots constructed; modification_date: repair date; current_dockcount: current number of charging spots; decommission_date: decommissioning time. 3. The 'tree_features' table contains some environmental information, start_hour: statistical start time; day_of_week: day of the week; Mean_Temperature_F: Fahrenheit; Mean_Humidity: average humidity; Mean_Visibility_Miles: average visibility; Mean_Wind_Speed_MPH: average wind speed; Precipitation_In: precipitation;x_{{i}}_dispatch_{{k}}: Number of SOC level k e-bikes deployed (+) or removed (−) at parking spot i; x_{{i}} _exchange_{{k}}:Number of SOC level k batteries removed from parking spot i and replaced with the same number of fully charged batteries;{{i}}_I_{{k}}:Number of e-bikes with charge level k at parking spot i after scheduling and battery exchange. Based on the database information provided, you need to tell me which stations' decisions have little impact on {target}, meaning it's unnecessary to make decisions, then all decision variables involved (decision variables with subscript i equal to that station's number) must be transformed from decisions to parameters. The current target formula is: {formulation} The existing sets are described as follows: Sets symbols, descriptions, and definitions are as follows: --- $$I$$: Set of parking stations; $$K$$: Set of discrete electric charge levels for shared e-bikes; Defined respectively as: I = list(range(55)), with station IDs i and its corresponding names: {{0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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'}}; K = [0,1,2] —-- Decision Variables are as follows: --- $$x_i_exchange_k$$: Number of SOC level k batteries removed from station i and replaced with the same number of fully charged batteries, for this variable, k can only take values from [0,1]; $$x_i_dispatch_k$$: Number of SOC level k e-bikes deployed (+) or removed (−) at station i; --- For example, you can analyze the travel data of some orders by querying the trip information in the database. Here are a example of output formats for reference: Answer: “「Reason」” so let all variables with station names 「3rd Ave & Broad St,2nd Ave & Vine St」 be parameterized. This is just a format example so your answer cannot be exactly the same. So you need to replace the station names contained by the symbol '「」' based on your thinking. You must and can only choose station names from station names I have provided before. Make sure to include the station names which need to be parameterized with the “「」” symbol. Format as shown in the example before. Each of your SQL query statements should not be too general. So make all query code you used more precise strictly! You must select station names satisfy the following: 1. You must select at least 3 station names and a maximum of 10 station names. 2. Finally provide me with all the station names to be parameterized for subsequent conversion into parameters. Be mindful that your database query statement and the statement's return results should not be too lengthy. You mustn't use SQL code like 'select * from' or other general code, these code is too general and will make system shutdown. Make all query code you used more precise. Anyway you need to give me an answer. Finally, you must reply following the format requirements (encapsulate the reason for parameterization and selected variables with “「」” symbols), and the changed station names must be defined in the preceding text. you must fulfill the requirements. Take a deep breath and solve the problem step by step. ''' success = False while not success: try: prompt = PromptTemplate(input_variables=["target", "formulation"],template=error_text+template) prompt_sample = prompt.format(formulation = Python_formulation,target=Target) database_result = agent_executor.invoke(prompt_sample) success = True except Exception as e: error_text = str(e) continue parameters_text = database_result['output'] print(parameters_text) # database_result = agent_executor.invoke(prompt_sample) # parameters_text = database_result['output'] # print(parameters_text) ## template2 = """The content from {parameters_text} is based on a database search to select station names for parameterization, but it often does not meet my expected output format. You must extract its content into two parts, each enclosed with "「」" symbols. The first part should explain the reason for selecting the station names, and the second part should list the selected station names contained by '「」' symbol. You need to refer to the dictionary format comparison relationship I provided below. {{0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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'}} You need to check the format and content. The final output should be a string. Here is an example format for reference: Reason explanation: "「The reason for variable selection is」", selected station names are: "「3rd Ave & Broad St,2nd Ave & Vine St」.This is just a format example so your answer cannot be exactly the same. Anyway, you must provide a station selection that is different from the example I provided, according to the format requirements!""" prompt2 = PromptTemplate(input_variables=["parameters_text"],template=template2) prompt_sample2 = prompt2.format(parameters_text = parameters_text) format_output = llm1.invoke(prompt_sample2) matches = re.findall(r'「.*?」', str(format_output)) global Selected_reason, Selected_spot_numbers Selected_reason = matches[0] Selected_spot_numbers = matches[1] print(Selected_reason) print(Selected_spot_numbers) user_target_indicator = [] for s in matches: user_target_indicator.append(s) ## return user_target_indicator @tool def solver(user_target_indicator_sample:list) -> dict: """这个工具用于得到变量化参数设定后求解使用。输入的是包含用户需求、指标公式以及参数化的变量列表,最终返回一个字典,字典中包含用户需求、指标公式、参数化的变量、模型的最优目标函数取值和决策变量的取值等""" global partial_spot_numbers, LEO_optimize_time, solve_result, csv_path model_add_newobj = add_new_obj('model04.mps', Gurobi_formulation, w1=1, w2=1) partial_spot_numbers = '' # matches = re.findall(r'「(.*?)」', Selected_spot_numbers) # if matches: # for partial in matches: # partial_spot_numbers = partial matches = name2id(Selected_spot_numbers) if matches: for partial in matches: partial_spot_numbers = partial # model_replaceobj = replace_variable_in_objective(model_add_newobj, partial_variable, csv_path) # print('-----Objective function processing finished!-----') model_process_constr = process_constraints(partial_spot_numbers, model_add_newobj, csv_path) print('-----Constraint processing finished!-----') model_process_constr.write('RF+SEB LEO.lp') model_process_constr.write('RF+SEB LEO.mps') print('-----model writing finished!-----') # model_process_constr.setParam(GRB.Param.Presolve, 0) # 关闭预处理 # model_process_constr.setParam(GRB.Param.Cuts, 0) # 关闭割平面操作 # model_process_constr.setParam(GRB.Param.MIPGap, 0.005) # 关闭割平面操作 start_time = time.time() # 执行优化 model_process_constr.optimize() # 记录结束时间 end_time = time.time() # 计算并打印执行时间 LEO_optimize_time = end_time - start_time print(f"模型求解 {LEO_optimize_time} 秒") indicator_description = user_target_indicator_sample[2] indicator_python = user_target_indicator_sample[3] solve_result = {} solve_result['indicator_description'] = indicator_description solve_result['indicator_python'] = indicator_python solve_result['optimal_obj'] = model_process_constr.ObjVal for var in model_process_constr.getVars(): solve_result[var.VarName] = var.X return solve_result tools=[recognizer,indicator,sampler] def agent_prompt(): #Create prompt from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser #create prompt from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder global chat_history prompt = ChatPromptTemplate.from_messages( [ ("system","You are a very capable assistant, and you need to fulfill my requirements based on the tools I provide to you."), MessagesPlaceholder(variable_name="chat_history"), ("user","{input}"), MessagesPlaceholder(variable_name="agent_scratchpad") ] ) # bind tool from langchain_community.tools.convert_to_openai import format_tool_to_openai_function llm_tools=llm1.bind(functions=[format_tool_to_openai_function(t) for t in tools]) #create agent chat_history = [] from langchain.agents.format_scratchpad import format_to_openai_function_messages agent=( { "input": lambda x: x["input"], "agent_scratchpad": lambda x: format_to_openai_function_messages( x["intermediate_steps"] ), "chat_history": lambda x: x["chat_history"] } |prompt |llm_tools |OpenAIFunctionsAgentOutputParser() ) # initial prompt #prompt.pretty_print() return agent if __name__ == "__main__": # init definition from langchain.agents import AgentExecutor, create_openai_tools_agent global csv_path stations= {0: '3rd Ave & Broad St',1: '2nd Ave & Vine 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'} ###!!!personalized!!!### csv_path = 'train_data_4.csv' locality = 0.2 station_sample = random_pick_from_dict(stations, int(55*locality)) user_input = f"increase the proportion of available shared E-bikes at the site named '{station_sample}'" index = '可用车辆比率' In_sample = False randseed = 0 groundtruth_sample_num = 6 times = 1 for t in range(times): ###!!!personalized!!!### expression_dict = { '低电量单车占比': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_0') for i in range(55)), GRB.MINIMIZE)", '单车利用率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in range(1,3)), GRB.MAXIMIZE)", '充电成本': "model.setObjective(gp.quicksum(model.getVarByName(f'x_{i}_exchange_{k}') * (2 - k) for i in range(55) for k in [0, 1, 2]), GRB.MINIMIZE)", '平均换电次数':"model.setObjective(gp.quicksum(model.getVarByName(f'x_{i}_exchange_{k}') for i in range(55) for k in [0, 1, 2]), GRB.MINIMIZE)", '市场占有率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in range(1, 3)), GRB.MAXIMIZE)", '平均骑行距离': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}')*k for i in range(55) for k in [0, 1, 2]), GRB.MAXIMIZE)", '可用车辆比率': "model.setObjective((gp.quicksum(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for k in K if k > k_0)/ C[i] for i in I)) , GRB.MAXIMIZE)", '超投率': "model.setObjective(gp.quicksum(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for k in K) / C[i] for i in I) / len(I), GRB.MINIMIZE)", '降低碳排放量': "model.setObjective(gp.quicksum((2-k) * model.getVarByName(f'x_{i}_exchange_{k}') for i in range(55) for k in [0, 1]), GRB.MAXIMIZE)" } global groundtruth groundtruth = sample_expressions(groundtruth_sample_num, In_sample, index, expression_dict) # Create agent agent = agent_prompt() agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) input_target = '「' + str(user_input) + '」' input_prompt = """ The text within "「」" marks my goal, which should include the domain of application and the metrics I am concerned with. You need to use the tool to accomplish the following tasks sequentially: 1. You need to extract the domain of action and the desired metrics based on 「{input}」, returning them as per the tool's requirements. 2. Based on the extracted metrics, obtain possible formulation and iterate to test these formulation until it is feasible, returning results as per the tool's requirements. 3. Based on the extracted metrics, and using data recorded in the backend database, identify station IDs that have little impact on the metrics and parameterize them, returning results as per the tool's requirements. finally, you just answer me 'All agent task has been done!'.without any further explanation. """ input_combine = input_target + input_prompt global global_parameters, global_obj_history, global_evaluator_history, model_statie, expression global_obj_history = 0 global_evaluator_history = 0 result = agent_executor.invoke({"input": input_combine, "chat_history": chat_history}) chat_history.extend([HumanMessage(content=input_combine), AIMessage(content=result["output"]) ]) ### global partial_spot_numbers, LEO_optimize_time, solve_result model_add_newobj = add_new_obj('model04.mps', Gurobi_formulation, w1=1, w2=1) partial_spot_numbers = '' matches = name2id(Selected_spot_numbers) if matches: for partial in matches: partial_spot_numbers = partial print("partial_spot_numbers:", partial_spot_numbers) # model_replaceobj = replace_variable_in_objective(model_add_newobj, partial_variable, csv_path) # print('-----Objective function processing finished!-----') model_process_constr = process_constraints(partial_spot_numbers, model_add_newobj, csv_path) # print('-----Constraint processing finished!-----') model_process_constr.write('RF+SEB LEO.lp') model_process_constr.write('RF+SEB LEO.mps') # print('-----model writing finished!-----') model_process_constr.setParam(GRB.Param.Presolve, 0) model_process_constr.setParam(GRB.Param.Cuts, 0) # model_process_constr.setParam(GRB.Param.MIPGap, 0.005) start_time = time.time() # 执行优化 model_process_constr.optimize() # 记录结束时间 end_time = time.time() # 计算并打印执行时间 LEO_optimize_time = end_time - start_time # print(f"LEO模型求解 {LEO_optimize_time} 秒") leo_model_vars = capture_model_variables(model_process_constr) qs_value_LEO = evaluate_expression(model_process_constr, expression_dict, index) LEO_obj_value=[] for i in range(model_process_constr.NumObj): model_process_constr.setParam(GRB.Param.ObjNumber, i) print(f"Obj {i + 1} = {model_process_constr.ObjNVal}") LEO_obj_value.append(model_process_constr.ObjNVal) model_process_constr.dispose() ### MIP solving basemodel_add_newobj = add_new_obj('model04.mps', Gurobi_formulation, w1=1, w2=1) # print('-----Constraint processing finished!-----') basemodel_add_newobj.write('RF+SEB base.lp') basemodel_add_newobj.write('RF+SEB base.mps') # print('-----model writing finished!-----') basemodel_add_newobj.setParam(GRB.Param.Presolve, 0) basemodel_add_newobj.setParam(GRB.Param.Cuts, 0) # basemodel_add_newobj.setParam(GRB.Param.MIPGap, 0.005) start_time = time.time() # 执行优化 basemodel_add_newobj.optimize() # 记录结束时间 end_time = time.time() # 计算并打印执行时间 base_optimize_time = end_time - start_time # print(f"base模型求解 {base_optimize_time} 秒") base_model_vars = capture_model_variables(basemodel_add_newobj) qs_value_base = evaluate_expression(basemodel_add_newobj, expression_dict, index) ### base_obj_value=[] for i in range(basemodel_add_newobj.NumObj): basemodel_add_newobj.setParam(GRB.Param.ObjNumber, i) print(f"Obj {i + 1} = {basemodel_add_newobj.ObjNVal}") base_obj_value.append(basemodel_add_newobj.ObjNVal) basemodel_add_newobj.dispose() origin_model = gp.read('model04.mps') origin_model.setParam('OutputFlag', 0) origin_model.optimize() qs_value_origin = evaluate_expression(origin_model, expression_dict, index) origin_model.dispose() tnow = time.time() if In_sample: file_path = 'result_exper2/insample/index{}_sample{}_{}.txt'.format(index, groundtruth_sample_num, tnow) else: file_path = 'result_exper2/outsample/index{}_sample{}_{}.txt'.format(index, groundtruth_sample_num, tnow) f = open(file_path, 'w') print('selected station IDs:', partial_spot_numbers) f.write('selected station IDs:{}'.format(partial_spot_numbers)) f.write('\n') print('Formulation_explanation:', Formulation_explanation) f.write('Formulation_explanation:{}'.format(Formulation_explanation)) f.write('\n') # print('Python_formulation:', Python_formulation) 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('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('Optimization gap',abs(float(base_optimize_time)-float(LEO_optimize_time))/float(base_optimize_time)) optimization_gap = [abs(abs(float(base_obj_value[i]))-abs(float(LEO_obj_value[i])))/(0.00001+abs(float(base_obj_value[i]))) for i in range(len(base_obj_value))] print(f'Optimization gap 1: {optimization_gap[0] * 100:.2f}%') print(f'Optimization gap 2: {optimization_gap[1] * 100:.2f}%') f.write(f'Optimization gap 1: {optimization_gap[0] * 100:.2f}%') f.write('\n') f.write(f'Optimization gap 2: {optimization_gap[1] * 100:.2f}%') f.write('\n') qs_LEO = abs(abs(qs_value_origin) - abs(qs_value_LEO)) / abs(qs_value_origin) qs_base = abs(abs(qs_value_origin) - abs(qs_value_base)) / abs(qs_value_origin) print(qs_value_LEO) print(qs_value_origin) print(qs_value_base) f.write(f'Query value LEO: {qs_value_LEO}') f.write('\n') f.write(f'Query value origin: {qs_value_origin}') f.write('\n') f.write(f'Query value base: {qs_value_base}') f.write('\n') print(f'Query satisfication LEO: {qs_LEO * 100:.2f}%') f.write(f'Query satisfication LEO: {qs_LEO * 100:.2f}%') f.write('\n') print(f'Query satisfication base: {qs_base * 100:.2f}%') f.write(f'Query satisfication base: {qs_base * 100:.2f}%') f.write('\n') f.write(f'caculate expression: {expression}') f.write('\n') # Write LEO Model Variables and Values f.write("LEO Model Variables and Values:\n") for var_name, var_value in leo_model_vars: f.write(f"{var_name} = {var_value}\n") f.write("Base Model Variables and Values:\n") for var_name, var_value in base_model_vars: f.write(f"{var_name} = {var_value}\n") f.close()