File size: 19,974 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import numpy as np
import pandas as pd
import math
import random
import warnings
import os
from langchain_openai import ChatOpenAI
import gurobipy as gp
from gurobipy import GRB
import re 
import scipy as sp
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits import create_sql_agent
from langchain_core.runnables import Runnable, RunnableLambda, RunnablePassthrough
from operator import itemgetter
import traceback
from langchain_core.tools import tool
from langchain import PromptTemplate
import time
from langchain_core.messages import AIMessage, HumanMessage
import sys
def add_new_obj(new_model_path, text, w1, w2,unselected,target_variable_values,parameterize,indicator):
    import gurobipy as gp
    model = gp.Model()
    I = list(range(55))
    K = [0, 1, 2]
    soc = [0, 1, 2]
    N = 60
    z = [0, 0, 50]
    k_0 = 0
    k_1 = 1
    k_2 = 2
    C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40]
    v = np.zeros((55, 3))
    random.seed(0)

    for i in range(len(I)):
        for j in range(len(K)):
            v[i, j] = random.randint(j * 5, j * 5 + 10)  
    for i in range(len(I)):
        for k in range(len(K)):
            model.addVar(name=f"u_{i}_{k}")
            model.addVar(name=f"x_{i}_dispatch_{k}")
    for i in range(len(I)):
        for k in range(len(K)-1):
            model.addVar(name=f"x_{i}_exchange_{k}")

    model.update()

    exec(text, {'model': model, 'gp': gp, "GRB": gp.GRB, "k_0":k_0, "k_1":k_1, "k_2":k_2, 'I': I, 'K': K, 'N':N, 'z':z, 'v':v, 'C':C})
    model.update()

    new_obj = model.getObjective()
    #print('extra_obj:',new_obj)

    new_model = gp.read(new_model_path)
    new_model.update()
    origin_obj = new_model.getObjective()
    new_obj_expr = gp.LinExpr()
    if isinstance(new_obj, gp.QuadExpr):
        #print('QuadExpr')
        w = new_model.addVar(vtype=GRB.CONTINUOUS, name="w")
        new_model.update()
        new_obj_expr.addTerms(1,w)
        new_model.update()
        if indicator == 'utilize':
            if parameterize is True:
                total_expression = gp.QuadExpr()
                for i in I:
                    for k in K:
                        sum_expression = gp.LinExpr()
                        var_name = f"u_{i}_{k}"
                        if i in unselected and var_name in target_variable_values:
                            #print(var_name,'will be replaced with ',target_variable_values[var_name])
                            new_model.addConstr(new_model.getVarByName(f'x_{i}_dispatch_{k}') == int(target_variable_values[f'x_{i}_dispatch_{k}']))
                            new_model.update()
                    for k in [0,1]:
                        if i in unselected and var_name in target_variable_values:
                            new_model.addConstr(new_model.getVarByName(f'x_{i}_exchange_{k}') == int(target_variable_values[f'x_{i}_exchange_{k}']))
                            new_model.update()
                        sum_expression = gp.LinExpr()
                        var_name = f"u_{i}_{k}"
                        if i in unselected and var_name in target_variable_values:
                            new_model.update()
                            sum_expression.addConstant(int(target_variable_values[var_name]))
                            #total_expression += (target_variable_values[var_name] - C[i])**2
                        else:
                            sum_expression.addTerms(1,new_model.getVarByName(f'u_{i}_{k}'))   
                    # print(total_expression)
                    ###
                    ###
                    ###
                        total_expression += (sum_expression - C[i])**2
                    ###
                    ###
                    ###
            else:
                    ###
                    ###
                    ###
                total_expression = gp.quicksum((gp.quicksum(new_model.getVarByName(f'u_{i}_{k}') for k in K) - C[i])**2 for i in I)
                    ###
                    ###
                    ###
        else:
            if parameterize is True:
                total_expression = gp.QuadExpr()
                for i in I:
                    for k in [1,2]:
                        var_name = f"x_{i}_dispatch_{k}"
                        if i in unselected and var_name in target_variable_values:
                        #print(var_name,'will be replaced with ',target_variable_values[var_name])
                            total_expression.addConstant(int(target_variable_values[f"x_{i}_dispatch_{k}"])**2)
                        else:
                            total_expression.addTerms(1,new_model.getVarByName(f"x_{i}_dispatch_{k}"),new_model.getVarByName(f"x_{i}_dispatch_{k}"))   
                for i in I:
                    for k in K:
                        if i in unselected and var_name in target_variable_values:
                            #print(var_name,'will be replaced with ',target_variable_values[var_name])
                            new_model.addConstr(new_model.getVarByName(f'x_{i}_dispatch_{k}') == int(target_variable_values[f'x_{i}_dispatch_{k}']))
                            new_model.update()
                    for k in [0,1]:
                        if i in unselected and var_name in target_variable_values:
                            new_model.addConstr(new_model.getVarByName(f'x_{i}_exchange_{k}') == int(target_variable_values[f'x_{i}_exchange_{k}']))
                            new_model.update()
            else:
                total_expression = gp.quicksum((new_model.getVarByName(f"x_{i}_dispatch_{k}"))**2 for k in [1,2] for i in I)
        new_model.addConstr(w == total_expression,'nonlinear')
        new_model.update()

    pattern = r'GRB\.(MAXIMIZE|MINIMIZE)'
    match = re.search(pattern, str(text))
    if match:
        new_model.setObjectiveN(w2 * origin_obj, index=0, priority=5, name='obj_tree')
        new_model.modelSense = GRB.MINIMIZE
    if match.group(1) == 'MAXIMIZE':
        new_model.setObjectiveN(-w1 * new_obj_expr,index=1, priority=1, name='obj_indicator')
    elif match.group(1) == 'MINIMIZE':
        new_model.setObjectiveN(w1 * new_obj_expr,index=1, priority=1, name='obj_indicator')
    new_model.update()

    #print(new_model.getObjective())
    return new_model

def select_random_keys(dictionary, k):
    random.seed(int(time.time()))
    return random.sample(list(dictionary.keys()), k)

def variables_values(variables, csv_path):
    """
    Convert variable names to their generalized form and assign means from a CSV file.

    Parameters:
    - variables: A list of variable names in string format.
    - csv_path: Path to the CSV file.

    Returns:
    - A dictionary with the original variable names as keys and their calculated means as values.
    """
    data = pd.read_csv(csv_path)
    result = {}

    for var in variables:
        # Extract indices from the variable name
        indices = re.findall(r'\d+', var)

        # Determine the type of variable and build column name for the CSV
        if 'exchange' in var:
            var_type = 'exchange'
        elif 'dispatch' in var:
            var_type = 'dispatch'
        elif 'u' in var:
            var_type = 'I'

        if var_type and len(indices) >= 2:
            i, k = indices[0], indices[1]
            column_name = f"{i}_{var_type}_{k}"
            # Calculate the mean value from the CSV data
            if column_name in data.columns:
                mean_value = int(data[column_name].mean())
                result[var] = mean_value
            else:
                result[var] = None  # If the column does not exist in the data
        else:
            result[var] = None  # If not enough indices or unrecognized type
    return result

def capture_gurobi_output(log_filename,model):

    if os.path.exists(log_filename):
        os.remove(log_filename)
    model.setParam(GRB.Param.Presolve, 0)  
    model.setParam(GRB.Param.Cuts, 0) 
    model.setParam(GRB.Param.TimeLimit, 3600)
    #model.setParam(GRB.Param.TimeLimit, 5)

    model.setParam(GRB.Param.NonConvex, 2)
    model.setParam(GRB.Param.DisplayInterval, 60)
    #model.setParam('LogToConsole', 0)
    model.setParam('LogFile', log_filename)
    start_time = time.time()
    model.optimize()
    end_time = time.time()    
    optimize_time = end_time - start_time
    
    var_values = extract_specific_vars_values(model)


    with open(log_filename, 'r') as log_file:
        log_contents = log_file.read()
    
    best_objective = [float(num) for num in re.findall(r'Best objective ([\d\.e\+\-]+)', log_contents)]
    best_bound = [float(num) for num in re.findall(r'best bound ([\d\.e\+\-]+)', log_contents)]
    gap = [float(num) for num in re.findall(r'gap ([\d\.e\+\-]+)%', log_contents)]

    return optimize_time,best_objective,best_bound,gap,var_values

def evaluate_expression(model, expression,selected):
    I = list(range(55))
    K = [0, 1, 2]
    soc = [0, 1, 2]
    N = 60
    z = [0, 0, 50]
    k_0 = 0
    k_1 = 1
    k_2 = 2
    C = [43,36,37,39,44]
         

    #C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40]
    v = np.zeros((55, 3))
    random.seed(0)

    for i in range(len(I)):
        for j in range(len(K)):
            v[i, j] = random.randint(j * 5, j * 5 + 10)  

    expression = re.sub(r'gp\.quicksum', 'sum', expression)
    expression = re.sub(r'model.getVarByName\((.*?)\)', r'model.getVarByName(\1).X', expression)
    expression = re.sub(r'I', str(selected), expression, count=1)
    expression = re.sub(r'model.setObjective\((.*?), GRB.(MINIMIZE|MAXIMIZE)\)', r'\1', expression)
    print(expression)
    total_value = eval(expression,{'model': model, 'gp': gp, "GRB": gp.GRB, "k_0":k_0, "k_1":k_1, "k_2":k_2, 'I': I, 'K': K, 'N':N, 'z':z, 'v':v, 'C':C})
    print(expression)
    return total_value

def extract_specific_vars_values(model):
    """
    Extract variable values for variables whose names contain 'x' or 'u' from a solved Gurobi model.

    Parameters:
    model (gurobipy.Model): The Gurobi model after it has been optimized.

    Returns:
    dict: A dictionary with variable names as keys and their solution values as values.
    """
    var_values = {}
    for var in model.getVars():
        if 'x' in var.VarName or 'u' in var.VarName:
            var_values[var.VarName] = var.X  # X attribute gives the solution value of the variable
    return var_values

def his_score(csv_path,indicator):
    I = list(range(55))
    K = [0, 1, 2]
    soc = [0, 1, 2]
    N = 60
    z = [0, 0, 50]
    k_0 = 0
    k_1 = 1
    k_2 = 2

    C = [43,36,37,39,44,39,39,39,37,39,36,36,32,42,40,35,43,37,43,37,41,40,37,32,37,31,43,32,44,42,42,31,38,40,41,39,41,40,31,39,40,35,38,39,46,37,41,38,36,41,38,31,43,38,40]
    v = np.zeros((55, 3))
    random.seed(0)

    for i in range(len(I)):
        for j in range(len(K)):
            v[i, j] = random.randint(j * 5, j * 5 + 10)  

    data = pd.read_csv(csv_path)
    data = data.rename(columns={f"{i}_I_{k}": f"u_{i}_{k}" for i in range(55) for k in range(3)})
    data = data.rename(columns={f"{i}_exchange_{k}": f"x_{i}_exchange_{k}" for i in range(55) for k in range(2)})
    data = data.rename(columns={f"{i}_dispatch_{k}": f"x_{i}_dispatch_{k}" for i in range(55) for k in range(2)})

    mean_data = data.mean(axis=0)[7:].to_dict()
    #print(mean_data)
    if indicator == 'utilize':
        ###
        ###
        ###
        score = sum((sum(mean_data[f'u_{i}_{k}'] for k in K) - C[i])**2 for i in I)
        ###
        ###
        ###
    else:
        score = sum((mean_data[f'x_{i}_dispatch_{k}'])**2 for k in [1,2] for i in I)
    #print(score)
    return score

if __name__ == "__main__":
    indicators = ['utilize','rate']
    ###!!!personalized!!!###
    csv_path = 'train_data_4.csv'
    percentage = 0
    times = 1
    for t in range(0,times):
        indicator = indicators[0]
    ###!!!personalized!!!###
        if t % 3 == 0:
            percentage += 0.2

        print('\n')
        print('\n')
        print('第',t,'次')
        print('\n')
        print('\n')


        spot_num = 55*round(percentage,1)
        spots = {
            0: '3rd Ave & Broad St', 1: '2nd Ave & Blanchard St', 2: '6th Ave & Blanchard St', 3: '2nd Ave & Blanchard St',
            4: '7th Ave & Union St', 5: 'Union St & 4th Ave', 6: '1st Ave & Marion St', 7: '2nd Ave & Spring St',
            8: 'City Hall / 4th Ave & James St', 9: '2nd Ave & Pine St', 10: '12th Ave & E Yesler Way', 11: 'Summit Ave & E Denny Way',
            12: 'E Harrison St & Broadway Ave E', 13: 'Summit Ave E & E Republican St', 14: '15th Ave E & E Thomas St',
            15: '12th Ave & E Denny Way', 16: 'E Pine St & 16th Ave', 17: 'Cal Anderson Park / 11th Ave & Pine St',
            18: 'Harvard Ave & E Pine St', 19: 'Bellevue Ave & E Pine St', 20: '12th Ave & E Mercer St', 21: '9th Ave N & Mercer St',
            22: "Children's Hospital / Sandpoint Way NE & 40th Ave NE",
            23: 'Fred Hutchinson Cancer Research Center / Fairview Ave N & Ward St',
            24: 'E Blaine St & Fairview Ave E', 25: 'Eastlake Ave E & E Allison St',
            26: 'Frye Art Museum / Terry Ave & Columbia St', 27: 'Seattle University / E Columbia St & 12th Ave',
            28: '6th Ave S & S King St', 29: 'Occidental Park / Occidental Ave S & S Washington St',
            30: 'King Street Station Plaza / 2nd Ave Extension S & S Jackson St', 31: 'REI / Yale Ave N & John St',
            32: 'Dexter Ave N & Aloha St', 33: 'Republican St & Westlake Ave N', 34: 'PATH / 9th Ave & Westlake Ave',
            35: 'Westlake Ave & 6th Ave', 36: 'Pine St & 9th Ave', 37: 'Lake Union Park / Valley St & Boren Ave N',
            38: 'Dexter Ave & Denny Way', 39: 'Key Arena / 1st Ave N & Harrison St', 40: 'Terry Ave & Stewart St',
            41: 'Mercer St & 9th Ave N', 42: 'Burke-Gilman Trail / NE Blakeley St & 24th Ave NE',
            43: 'NE 42nd St & University Way NE', 44: '12th Ave & NE Campus Pkwy', 45: 'NE 47th St & 12th Ave NE',
            46: 'UW McCarty Hall / Whitman Ct', 47: 'Burke Museum / E Stevens Way NE & Memorial Way NE',
            48: '15th Ave NE & NE 40th St', 49: 'UW Engineering Library / E Stevens Way NE & Jefferson Rd',
            50: 'UW Intramural Activities Building', 51: 'UW Magnuson Health Sciences Center Rotunda / Columbia Rd & San Juan Rd',
            52: 'Pier 69 / Alaskan Way & Clay St', 53: 'Seattle Aquarium / Alaskan Way S & Elliott Bay Trail',
            54: 'Broadway and E Denny Way'
        }
        selected = select_random_keys(spots, int(spot_num))
        print(selected)
       
        unselected_spots = {key: value for key, value in spots.items() if key not in selected}
        unselected = []
        for key, value in unselected_spots.items():
            unselected.append(key)
        print(unselected)

        target_variable_values = {}

        i_range = list(range(55))
        k_range = [0, 1, 2]
        vars = []
        for i in i_range:
            for k in k_range:
                var_name = f"u_{i}_{k}"
                vars.append(var_name)
                var_name = f"x_{i}_dispatch_{k}"
                vars.append(var_name)
            for k in [0,1]:
                var_name = f"x_{i}_exchange_{k}"
                vars.append(var_name)
        target_variable_values = variables_values(vars,csv_path)

        if indicator == 'utilize':
            ###
            ###
            ###
            text = "model.setObjective(gp.quicksum((gp.quicksum(model.getVarByName(f'u_{i}_{k}') for k in K) - C[i])**2 for i in I), GRB.MAXIMIZE)"
            ###
            ###
            ###
        else:
            #min \sum_i \sum_{k\in {k1,k2}} (x_ik)^2
            text = "model.setObjective(gp.quicksum(model.getVarByName(f'x_{i}_dispatch_{k}')**2 for k in [1,2] for i in I), GRB.MINIMIZE)"


        parameterize_model = add_new_obj('ebike_data/model04.mps', text, 1, 1, unselected, target_variable_values,True,indicator)
        # parameterize_model.write('exper4_para.lp')
        # parameterize_model.write('exper4_para.mps')
        tnow = time.time()
        log_path = 'result_extra_exper4/log_files/new_LEO_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow)
        LEO_optimize_time,LEO_obj_value,LEO_bound,LEO_gap,LEO_var_values = capture_gurobi_output(log_path,parameterize_model)
        LEO_qs = evaluate_expression(parameterize_model, text, selected)
        print(LEO_optimize_time,LEO_obj_value,LEO_bound,LEO_gap)
        parameterize_model.dispose()




        base_model = add_new_obj('ebike_data/model04.mps', text, 1, 1, unselected, target_variable_values,False,indicator)
        # base_model.write('exper4_base.lp')
        # base_model.write('exper4_base.mps') 
        log_path = 'result_extra_exper4/log_files/new_base_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow)
        base_optimize_time,base_obj_value,base_bound,base_gap,base_var_values = capture_gurobi_output(log_path,base_model)
        base_qs = evaluate_expression(base_model, text, selected)
        print(base_optimize_time,base_obj_value,base_bound,base_gap)
        base_model.dispose()

        if indicator == 'utilize':
            qs = (LEO_qs-base_qs)/(0.01+base_qs)
        else:
            qs = -1*(LEO_qs-base_qs)/(0.01+base_qs)

        result_gap_1 = (abs(abs(LEO_obj_value[0]) - abs(base_obj_value[0])) / abs(0.00001+LEO_obj_value[0]))*100
        result_gap_2 = (abs(abs(LEO_obj_value[1]) - abs(base_obj_value[1])) / abs(0.00001+LEO_obj_value[1]))*100

        file_path = 'result_extra_exper4/results/new_{}_scale{}_{}.txt'.format(indicator,round(percentage,1), tnow)
        f = open(file_path, 'w')

        print('LEO_optimize_time:', LEO_optimize_time)
        f.write('LEO_optimize_time:{}'.format(LEO_optimize_time))
        f.write('\n')
        print('LEO_result:', LEO_obj_value)
        f.write('LEO_result:{}'.format(LEO_obj_value))
        f.write('\n')
        print('LEO_bound', LEO_bound)
        f.write('LEO_bound:{}'.format(LEO_bound))
        f.write('\n')
        print('LEO_gap_1', LEO_gap[0])
        print('LEO_gap_2', LEO_gap[1])
        f.write('LEO_gap_1:{}'.format(LEO_gap[0]))
        f.write('\n')
        f.write('LEO_gap_2:{}'.format(LEO_gap[1]))
        f.write('\n')
        f.write('LEO_qs:{}'.format(LEO_qs))
        f.write('\n')
        f.write('LEO_var_values:{}'.format(LEO_var_values))
        f.write('\n')


        print('base_optimize_time:', base_optimize_time)
        f.write('base_optimize_time:{}'.format(base_optimize_time))
        f.write('\n')
        print('base_result:', base_obj_value)
        f.write('base_result:{}'.format(base_obj_value))
        f.write('\n')
        print('base_bound', base_bound)
        f.write('base_bound:{}'.format(base_bound))
        f.write('\n')
        print('base_gap_1', base_gap[0])
        print('base_gap_2', base_gap[1])
        f.write('base_gap_1:{}'.format(base_gap[0]))
        f.write('\n')
        f.write('base_gap_2:{}'.format(base_gap[1]))
        f.write('\n')
        f.write('base_qs:{}'.format(base_qs))
        f.write('\n')
        f.write('base_var_values:{}'.format(base_var_values))
        f.write('\n')

        print('selected station IDs:', selected)
        f.write('selected station IDs:{}'.format(selected))
        f.write('\n')
        print('result_gap_1', result_gap_1)
        print('result_gap_2', result_gap_2)
        f.write('result_gap_1:{}'.format(result_gap_1))
        f.write('\n')
        f.write('result_gap_2:{}'.format(result_gap_2))
        f.write('\n')
        print('qs:',qs)
        f.write('qs:{}'.format(qs))
        f.write('\n')
        f.close()