File size: 29,147 Bytes
266eb7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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 re
from collections import Counter
import Levenshtein
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from jellyfish import jaro_winkler_similarity
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 indicator(Target,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]
        #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())
            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))
                prompt2 = PromptTemplate(input_variables=["formulation","answer"],template=template2)
                gurobi_code = prompt2.format(formulation=Python_formulation,answer=groundtruth)
                result2 = llm1.invoke(gurobi_code)
                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)                
                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 (<string>, 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
    return Gurobi_formulation

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 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 remove_backslashes_from_getvar(input_string):
    pattern = r'getVarByName\((.*?)\)'
    result = re.sub(pattern, lambda m: "getVarByName(" + m.group(1).replace("\\", "") + ")", input_string)
    
    return result
if __name__ == "__main__":
     ###!!!personalized!!!###
    user_input = "order cancellation rate"  
    index = '订单取消率'  
    In_sample = True  
    randseed = 0 
    groundtruth_sample_num = 6  
    times = 1
    ###!!!personalized!!!###
    for t in range(times):
        print('\n')
        print('\n')
        print('第',t,'次')
        print('\n')
        print('\n')

        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 [1, 2]), 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]), GRB.MINIMIZE)",
            '平均换电次数':"model.setObjective(gp.quicksum(model.getVarByName(f'x_{i}_exchange_{k}') for i in range(55) for k in [0, 1]), GRB.MINIMIZE)",
            '市场占有率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '订单取消率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '市场渗透率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '投诉率': "model.setObjective(gp.quicksum(k*gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55)) for k in [1, 2]), GRB.MAXIMIZE)",
            '服务水平': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '用户满意度': "model.setObjective(gp.quicksum((k+1) * model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '平均成功骑行次数': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), 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(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [0, 1, 2]), GRB.MAXIMIZE)",
            '用户增长率': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [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)",
            '覆盖用户数': "model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE)",
            '覆盖区域面积':"model.setObjective(gp.quicksum(model.getVarByName(f'u_{i}_{k}') for i in range(55) for k in [1, 2]), GRB.MAXIMIZE) "
        }
        groundtruth = sample_expressions(groundtruth_sample_num*2, In_sample, index, expression_dict)
        tnow = time.time()
        if In_sample:
            file_path = 'similarity_exper_new/insample/index{}_sample{}_{}.txt'.format(index, groundtruth_sample_num, tnow)
        else:
            file_path = 'similarity_exper_new/outsample/index{}_sample{}_{}.txt'.format(index, groundtruth_sample_num, tnow)
        f = open(file_path, 'w')
        f.write('temp_text:{}'.format(indicator(user_input,groundtruth)))
        f.write('\n')
        f.close()