示例#1
0
def get_trajectory_regularised(params, ampl_mdl_path, hide_solver_output=True):
    ampl = AMPL()
    ampl.read(ampl_mdl_path)

    for lbl, val in params.items():
        _ampl_set_param(ampl, lbl, val)

    _ampl_set_param(ampl, 'reg', 0)  # no regularisation
    _ampl_solve(ampl, hide_solver_output)

    optimal_sol_found = _ampl_optimal_sol_found(ampl)

    traj = None
    objective = None
    optimal_sol_found_reg = False
    if optimal_sol_found:
        _ampl_set_param(ampl, 'reg', 1)  # regularisation
        _ampl_solve(ampl, hide_solver_output)
        optimal_sol_found_reg = _ampl_optimal_sol_found(ampl)

        if optimal_sol_found_reg:
            traj = _extract_trajectory_from_solver(ampl)
            objective = ampl.getObjective('myobjective').value()

    ampl.close()
    return optimal_sol_found_reg, traj, objective
def compute_defense(att_stg,
                    prod_dist,
                    num_of_hp=args.fix_honeypots,
                    rationality=args.fix_rationality):
    # production ports and attacker"s strategy
    df = DataFrame('P')
    ports = getRelPorts(att_stg, prod_dist, num=25)
    df.setColumn('P', list(ports))

    #ports = getAllPorts(att_stg, prod_dist)
    #print(('Considered ports are: ', ports))
    att = [att_stg.get(x, 0) for x in ports]
    prod = [prod_dist.get(x, 0) for x in ports]
    #print(('Attack ports: ', att, len(att)))
    #print(('Dist ports: ', prod, len(prod)))

    df.addColumn('s', prod)
    df.addColumn('p', att)

    ampl = AMPL(Environment(args.ampl))
    ampl.setOption('solver', args.solver)
    # ampl.setOption('verbosity', 'terse')
    # Read the model file
    ampl.read(args.model)

    # Assign data to s
    ampl.setData(df, 'P')
    ampl.eval('let L :=  {}; let rat := {};'.format(num_of_hp, rationality))

    #print(df)
    # Solve the model
    with suppress_stdout():
        ampl.solve()
    reward = ampl.getObjective("reward").value()

    hp_stg = ampl.getData("{j in P} h[j]")
    output = dict()
    stg_json = list()
    for k, v in hp_stg.toDict().items():
        stg_json.append({"port": int(k), "prob": v})

    output.update({"stg": stg_json})
    output.update({"reward": reward})
    output.update({"rationality": rationality})
    output.update({"num_of_hp": num_of_hp})
    output.update({"used_hps": ampl.getData("tot").toDict().popitem()[1]})

    ampl.close()
    return output
示例#3
0
 def testEnvironment(self):
     from amplpy import Environment, AMPL
     env1 = Environment()
     env2 = Environment(os.curdir)
     self.assertEqual(env2.getBinDir(), os.curdir)
     env1.setBinDir(env2.getBinDir())
     self.assertEqual(env1.getBinDir(), env1.getBinDir())
     self.assertEqual(len(dict(env1)), len(list(env1)))
     self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1)))
     env1['MyEnvVar'] = 'TEST'
     self.assertEqual(env1['MyEnvVar'], 'TEST')
     self.assertEqual(env2['MyEnvVar'], None)
     d = dict(env1)
     self.assertEqual(d['MyEnvVar'], 'TEST')
     ampl = AMPL(Environment())
     ampl.close()
示例#4
0
    def test_environment(self):
        from amplpy import Environment, AMPL

        env1 = Environment()
        env2 = Environment(os.curdir)
        self.assertEqual(env2.get_bin_dir(), os.curdir)
        env1.set_bin_dir(env2.get_bin_dir())
        self.assertEqual(env1.get_bin_dir(), env1.get_bin_dir())
        self.assertEqual(len(dict(env1)), len(list(env1)))
        self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1)))
        env1["MyEnvVar"] = "TEST"
        self.assertEqual(env1["MyEnvVar"], "TEST")
        self.assertEqual(env2["MyEnvVar"], None)
        d = dict(env1)
        self.assertEqual(d["MyEnvVar"], "TEST")
        ampl = AMPL(Environment())
        ampl.close()
示例#5
0
def get_trajectory(params, ampl_mdl_path, hide_solver_output=True):
    ampl = AMPL(
    )  # ampl installation directory should be in system search path
    # .mod file
    ampl.read(ampl_mdl_path)

    # set parameter values
    for lbl, val in params.items():
        _ampl_set_param(ampl, lbl, val)

    _ampl_solve(ampl, hide_solver_output)
    optimal_sol_found = _ampl_optimal_sol_found(ampl)

    traj = None
    objective = None
    if optimal_sol_found:
        traj = _extract_trajectory_from_solver(ampl)
        objective = ampl.getObjective('myobjective').value()

    ampl.close()
    return optimal_sol_found, traj, objective
示例#6
0
def prodalloc(RID, SID, shared_ns=None, f_out=None, f_log=None):
    from amplpy import AMPL, DataFrame

    if shared_ns == None:
        (df_demand, wup_12mavg, ppp_sum12, df_scenario, sw_avail, df_penfunc,
         df_relcost) = pull_data(RID, SID)

    # =======================================
    # instantiate AMPL class and set AMPL options
    ampl = AMPL()

    # set options
    ampl.setOption('presolve', False)
    ampl.setOption('solver', 'gurobi_ampl')
    # ampl.setOption('solver', 'cbc')
    ampl.setOption('gurobi_options',
                   'iisfind=1 iismethod=1 lpmethod=4 mipgap=1e-6 warmstart=1')
    ampl.setOption('reset_initial_guesses', True)
    ampl.setOption('solver_msg', True)

    # real model from model file
    d_cur = os.getcwd()
    f_model = os.path.join(d_cur, 'model.amp')
    ampl.read(f_model)

    if shared_ns != None:
        df_demand = shared_ns.df_demand.query(
            f'RealizationID == {RID}').loc[:, ['wpda', 'dates', 'Demand']]
    dates = df_demand.loc[:, ['dates']].values
    df_demand.loc[:, 'dates'] = [
        pd.to_datetime(d).strftime('%Y-%b') for d in dates
    ]
    df_demand.set_index(keys=['wpda', 'dates'], inplace=True)
    wpda = sorted(list(set([w for (w, m) in df_demand.index])))
    monyr = df_demand.loc[('COT', ), ].index.values
    nyears = int(len(monyr) / 12.0)

    # lambda for determine number of days in a month
    dates = dates[0:(12 * nyears)]
    f_ndays_mo = lambda aday: (aday + dt.timedelta(days=32)).replace(day=1
                                                                     ) - aday
    ndays_mo = map(f_ndays_mo, [pd.to_datetime(d[0]) for d in dates])
    ndays_mo = [i.days for i in ndays_mo]

    # add data to sets -- Demand
    ampl.getParameter('nyears').value = nyears
    ampl.getSet('monyr').setValues(monyr)
    ampl.getSet('wpda').setValues(wpda)
    ampl.getParameter('demand').setValues(DataFrame.fromPandas(df_demand))
    ampl.getParameter('ndays_mo').setValues(ndays_mo)

    # index to year number
    yearno = [(i // 12) + 1 for i in range(len(dates))]
    ampl.getParameter('yearno').setValues(np.asarray(yearno))
    monthno = [pd.to_datetime(d[0]).month for d in dates]
    ampl.getParameter('monthno').setValues(np.asarray(monthno))

    # ---------------------------------------
    # WUP and preferred ranges
    if shared_ns != None:
        wup_12mavg = shared_ns.wup_12mavg
    ampl.getParameter('wup_12mavg').setValues(
        DataFrame.fromPandas(wup_12mavg.loc[:, ['wup_12mavg']]))
    ampl.getParameter('prod_range_lo').setValues(
        DataFrame.fromPandas(wup_12mavg.loc[:, ['prod_range_lo']]))
    ampl.getParameter('prod_range_hi').setValues(
        DataFrame.fromPandas(wup_12mavg.loc[:, ['prod_range_hi']]))

    # add ppp_sum12
    if shared_ns != None:
        ppp_sum12 = shared_ns.ppp_sum12
    ppp_sum12.loc[:, 'monyr'] = [i for i in range(1, 12)] * 3
    ppp_sum12.set_index(keys=['WF', 'monyr'], inplace=True)
    ampl.getParameter('ppp_sum12').setValues(DataFrame.fromPandas(ppp_sum12))

    # Relative cost of water per a million gallon
    if shared_ns != None:
        df_relcost = shared_ns.df_relcost
    ampl.getParameter('relcost').setValues(DataFrame.fromPandas(df_relcost))

    # ---------------------------------------
    # Scenario's data
    if shared_ns != None:
        df_scenario = shared_ns.df_scenario.query(
            f'ScenarioID=={SID}').loc[:, ['ParameterName', 'MonthNo', 'Value']]
    AVAIL_PCTILE = df_scenario.query(f"ParameterName == 'AVAIL_PCTILE'")
    AVAIL_PCTILE = AVAIL_PCTILE.loc[AVAIL_PCTILE.index, 'Value'].values[0]
    RES_INIT = df_scenario.query(f"ParameterName == 'RES_INIT'")
    RES_INIT = RES_INIT.loc[RES_INIT.index, 'Value'].values[0]
    # Surface Water Availability Data by month repeated for nyears
    ampl.getParameter('avail_pctile').value = AVAIL_PCTILE
    if shared_ns != None:
        sw_avail = shared_ns.sw_avail.query(
            f'Percentile == {AVAIL_PCTILE}'
        ).loc[:, ['source', 'monthno', 'value']]
    # sw_avail = temp.copy()
    # if nyears > 1:
    #     for i in range(1, nyears):
    #         sw_avail = sw_avail.append(temp)
    # srcs = sw_avail.loc[:, 'source'].unique()
    # for j in srcs:
    #     sw_avail.loc[sw_avail['source']==j,'monthno'] = [i+1 for i in range(len(monyr))]
    # sw_avail.set_index(keys=['source', 'monthno'], inplace=True)
    # ampl.getParameter('ngw_avail').setValues(DataFrame.fromPandas(sw_avail))
    sw_avail.set_index(keys=['source', 'monthno'], inplace=True)
    ampl.getParameter('ngw_avail').setValues(DataFrame.fromPandas(sw_avail))

    # ---------------------------------------
    # Penalty functions for under utilization
    if shared_ns != None:
        df_penfunc = shared_ns.df_penfunc
    ampl.getParameter('penfunc_x').setValues(
        DataFrame.fromPandas(df_penfunc.loc[:, ['under_limit']]))
    ampl.getParameter('penfunc_r').setValues(
        DataFrame.fromPandas(df_penfunc.loc[:, ['penalty_rate']]))
    '''
    # =======================================
    # Read fixed allocation from spreadsheet
    # f_excel = os.path.join(
    #     d_cur, 'WY 2019 monthly delivery and supply for budget InitialDraft.xlsx')
    sheet_names = ['WY 2019','WY 2020','WY 2021','WY 2022','WY 2023','WY 2024']
    # ch_poc: Central Hills delivery (row 16)
    # reg_lithia: Regional to Lithia (row 20)
    # reg_cot: Regional to City of Tampa (row 26)
    # reg_thic: THIC intertie purchase (row 37)
    # crw_prod: Carrollwood WF production (row 40)
    # eag_prod: Production for Eagle Well (row 41)

    # row index is zero based, minus one header row = -2
    row_offset = -2
    ch_poc, reg_lithia, reg_cot, reg_thic, crw_prod, eag_prod = [], [], [], [], [], []
    # These DV is fixed or receives values from other optimizer
    bud_fix, ds_fix, swtp_fix=[], [], []
    for i in range(nyears):
        df_excel = pd.read_excel(f_excel, sheet_names[i], usecols='C:N', nrows=41)
        ch_poc    .extend(list(df_excel.loc[16 + row_offset, :].values))
        reg_lithia.extend(list(df_excel.loc[20 + row_offset, :].values))
        reg_cot   .extend(list(df_excel.loc[26 + row_offset, :].values))
        reg_thic  .extend(list(df_excel.loc[37 + row_offset, :].values))
        crw_prod  .extend(list(df_excel.loc[40 + row_offset, :].values))
        eag_prod  .extend(list(df_excel.loc[41 + row_offset, :].values))
        
        bud_fix .extend(list(df_excel.loc[22 + row_offset, :].values))
        ds_fix  .extend(list(df_excel.loc[36 + row_offset, :].values))
        swtp_fix.extend(list(df_excel.loc[38 + row_offset, :].values))
    '''
    ch_poc = df_scenario[df_scenario.ParameterName == 'ch_poc'].Value
    reg_lithia = df_scenario[df_scenario.ParameterName == 'reg_lithia'].Value
    reg_cot = df_scenario[df_scenario.ParameterName == 'reg_cot'].Value
    reg_thic = df_scenario[df_scenario.ParameterName == 'reg_thic'].Value
    crw_prod = df_scenario[df_scenario.ParameterName == 'crw_prod'].Value
    eag_prod = df_scenario[df_scenario.ParameterName == 'eag_prod'].Value

    ampl.getParameter('ch_poc').setValues(np.asarray(ch_poc, dtype=np.float32))
    ampl.getParameter('reg_lithia').setValues(
        np.asarray(reg_lithia, dtype=np.float32))
    ampl.getParameter('reg_cot').setValues(
        np.asarray(reg_cot, dtype=np.float32))
    ampl.getParameter('reg_thic').setValues(
        np.asarray(reg_thic, dtype=np.float32))
    ampl.getParameter('crw_prod').setValues(
        np.asarray(crw_prod, dtype=np.float32))
    ampl.getParameter('eag_prod').setValues(
        np.asarray(eag_prod, dtype=np.float32))

    # overloaded function 'VariableInstance_fix' need float64
    bud_fix = np.asarray(
        df_scenario[df_scenario.ParameterName == 'bud_fix'].Value,
        dtype=np.float64)
    ds_fix = np.asarray(
        df_scenario[df_scenario.ParameterName == 'ds_fix'].Value,
        dtype=np.float64)
    swtp_fix = np.asarray(
        df_scenario[df_scenario.ParameterName == 'swtp_fix'].Value,
        dtype=np.float64)
    ampl.getParameter('bud_fix').setValues(
        np.asarray(bud_fix, dtype=np.float32))
    ampl.getParameter('ds_fix').setValues(np.asarray(ds_fix, dtype=np.float32))
    ampl.getParameter('swtp_fix').setValues(
        np.asarray(swtp_fix, dtype=np.float32))

    # ---------------------------------------
    # initialize/fix variable values
    ampl.getParameter('res_init').value = RES_INIT
    res_vol = ampl.getVariable('res_vol')
    res_vol[0].fix(RES_INIT)

    gw_prod = ampl.getVariable('gw_prod')
    bud_prod = [
        gw_prod[j, i] for ((j, i), k) in gw_prod.instances() if j == 'BUD'
    ]
    for i in range(len(bud_prod)):
        bud_prod[i].fix(bud_fix[i])

    ds_prod = ampl.getVariable('ds_prod')
    for i in range(ds_prod.numInstances()):
        ds_prod[i + 1].fix(ds_fix[i])

    swtp_prod = ampl.getVariable('swtp_prod')
    for i in range(swtp_prod.numInstances()):
        swtp_prod[i + 1].fix(swtp_fix[i])

    # ---------------------------------------
    # dump data
    with open('dump.dat', 'w') as f:
        with stdout_redirected(f):
            ampl.display('wpda,monyr')
            ampl.display('demand')
            ampl.display('nyears')
            ampl.display('ndays_mo,yearno,monthno')
            # ampl.display('years')
            # ampl.display('dem_total')
            ampl.display(
                'ch_poc,reg_lithia,reg_cot,reg_thic,crw_prod,eag_prod,bud_fix,ds_fix'
            )
            ampl.display('wup_12mavg')
            ampl.display('ppp_sum12')
            ampl.display('ngw_avail')
            ampl.display('prod_range_lo,prod_range_hi')
            ampl.display('relcost')
            ampl.display('penfunc_x,penfunc_r')

    # =======================================
    # silence solver
    with open('nul', 'w') as f:
        with stdout_redirected(f):
            ampl.solve()

    if f_out != None:
        with open(f_out, 'w') as f:
            print(r'# *** SOURCE ALLOCATION MODEL ****', file=f)
            print(r'# Monthly Delivery and Supply for Budgeting', file=f)
            print('\n# Objective: {}'.format(
                ampl.getObjective('mip_obj').value()),
                  file=f)

    if (f_log != None) & (ampl.getObjective('mip_obj').result() == 'solved'):
        with open(f_log, "w") as f:
            print('\n\nDump Variable and Constraint Values', file=f)
            with stdout_redirected(f):
                write_log(ampl)

    if ampl.getObjective('mip_obj').result() == 'infeasible':
        if f_log != None:
            with open(f_log, "w") as f:
                with stdout_redirected(f):
                    write_iis(ampl)
        else:
            write_iis(ampl)

    # =======================================
    # print output
    # groundwater production
    temp = ampl.getVariable('gw_prod').getValues().toPandas().join(
        ampl.getVariable('gw_under').getValues().toPandas()).join(
            ampl.getVariable('gw_over').getValues().toPandas())
    temp.columns = [i.replace('.val', '') for i in temp.columns]

    # pivoting df by source
    cwup_prod = temp.loc[[i for i in temp.index if i[0] == 'CWUP'], :].assign(
        index=monyr).set_index('index').rename(columns={
            'gw_prod': 'cwup_prod',
            'gw_under': 'cwup_under',
            'gw_over': 'cwup_over'
        })
    bud_prod = temp.loc[[i for i in temp.index if i[0] == 'BUD'], :].assign(
        index=monyr).set_index('index').rename(columns={
            'gw_prod': 'bud_prod',
            'gw_under': 'bud_under',
            'gw_over': 'bud_over'
        })
    sch_prod = temp.loc[[i for i in temp.index if i[0] == 'SCH'], :].assign(
        index=monyr).set_index('index').rename(columns={
            'gw_prod': 'sch_prod',
            'gw_under': 'sch_under',
            'gw_over': 'sch_over'
        })
    temp = cwup_prod.join(sch_prod.join(bud_prod))
    gw_results = temp

    temp_avg = temp.groupby(by=yearno).mean().reset_index()
    temp_avg = temp_avg.loc[:,
                            [i for i in temp_avg.columns[1:temp_avg.shape[1]]]]

    if f_out != None:
        with open(f_out, 'a') as f:
            # print heading
            print('\n\n# Monthly Groudwater Production', file=f)
            for l in range(len(temp)):
                if (l % 12) == 0:
                    print(('\n%10s' % 'Yr-Month') +
                          ('%11s' * len(temp.columns) % tuple(temp.columns)),
                          file=f)
                print(('%10s' % monyr[l]) + ('%11.3f' * len(temp.columns) %
                                             tuple(temp.iloc[l, :].values)),
                      file=f)
                if (l + 1) % 12 == 0:
                    print(('%10s' % 'Average') +
                          ('%11.3f' * len(temp_avg.columns) %
                           tuple(temp_avg.iloc[l // 12, :].values)),
                          file=f)
            print(
                ('\n%10s' % 'Total Avg') + ('%11.3f' * len(temp_avg.columns) %
                                            tuple(temp_avg.mean().values)),
                file=f)

    # ---------------------------------------
    # SWTP Production
    to_swtp = ampl.getVariable('to_swtp').getValues().toPandas()
    to_res = ampl.getVariable('to_res').getValues().toPandas()
    idx = to_swtp.index
    temp = ampl.getVariable('swtp_prod').getValues().toPandas()
    temp = temp.assign(tbc_swtp=to_swtp.loc[[i for i in idx
                                             if i[0] == 'TBC']].values)
    temp = temp.assign(
        alf_swtp=to_swtp.loc[[i for i in idx if i[0] == 'Alafia']].values)
    temp = temp.join(ampl.getVariable('res_eff').getValues().toPandas())
    temp = temp.assign(tbc_res=to_res.loc[[i for i in idx
                                           if i[0] == 'TBC']].values)
    temp = temp.assign(alf_res=to_res.loc[[i for i in idx
                                           if i[0] == 'Alafia']].values)
    temp = temp.join(ampl.getVariable('res_inf').getValues().toPandas()).join(
        ampl.getVariable('res_vol').getValues().toPandas())

    # Add availability columns
    temp = temp.assign(tbc_avail=sw_avail.loc[[('TBC', i) for i in monthno],
                                              ['value']].values)
    temp = temp.assign(alf_avail=sw_avail.loc[[('Alafia', i) for i in monthno],
                                              ['value']].values)

    # Add SW withdraws
    df1 = ampl.getVariable('sw_withdraw').getValues().toPandas()
    idx = temp.index
    temp = temp.assign(tbc_wthdr=df1.loc[[('TBC', i) for i in idx], :].values)
    temp = temp.assign(alf_wthdr=df1.loc[[('Alafia', i)
                                          for i in idx], :].values)
    temp.columns = [i.replace('.val', '') for i in temp.columns]
    sw_results = temp

    # Compute annual average
    temp_avg = temp.groupby(by=yearno).mean().reset_index()
    temp_avg = temp_avg.loc[:,
                            [i for i in temp_avg.columns[1:temp_avg.shape[1]]]]

    if f_out != None:
        with open(f_out, 'a') as f:
            # print heading
            print('\n\n# Monthly Surface Water Production', file=f)
            for l in range(len(temp)):
                if (l % 12) == 0:
                    print(('\n%10s' % 'Yr-Month') +
                          ('%10s' * len(temp.columns) % tuple(temp.columns)),
                          file=f)
                print(('%10s' % monyr[l]) + ('%10.3f' * len(temp.columns) %
                                             tuple(temp.loc[float(l + 1), :])),
                      file=f)
                if ((l + 1) % 12) == 0:
                    print(('%10s' % 'Average') +
                          ('%10.3f' * len(temp_avg.columns) %
                           tuple(temp_avg.loc[l // 12, :])),
                          file=f)
            print(
                ('\n%10s' % 'Total Avg') + ('%10.3f' * len(temp_avg.columns) %
                                            tuple(temp_avg.mean().values)),
                file=f)

    # ---------------------------------------
    # print multi objective values
    temp = ampl.getVariable('prodcost_avg').getValues().toPandas()
    idx = [i for i in temp.index]
    temp = temp.assign(
        prod_avg=temp.loc[:, 'prodcost_avg.val'] * 1e-3 /
        np.asarray([df_relcost.loc[i[0], 'relcost'] for i in idx]))

    temp = temp.join(
        ampl.getVariable('uu_penalty').getValues().toPandas()).join(
            ampl.getVariable('uu_avg').getValues().toPandas())
    temp.columns = [i.replace('.val', '') for i in temp.columns]
    temp_avg = temp.groupby([i[0] for i in temp.index]).mean().reset_index()

    if f_out != None:
        with open(f_out, 'a') as f:
            print(
                '\n\n# Annual Production and Under Utilization (Opportunity) Costs',
                file=f)
            for l in range(len(temp)):
                if (l % nyears) == 0:
                    print(('\n%10s%10s' % ('YearNo', 'Source')) +
                          ('%15s' * len(temp.columns) % tuple(temp.columns)),
                          file=f)
                print(('%10d%10s' % (idx[l][1], idx[l][0])) +
                      ('%15.3f' * len(temp.columns) %
                       tuple(temp.loc[[idx[l]], :].values[0])),
                      file=f)
                if ((l + 1) % nyears) == 0:
                    print(('%10s' % 'Average') +
                          (('%10s' + '%15.3f' * len(temp.columns)) %
                           tuple(temp_avg.iloc[l // nyears, :])),
                          file=f)

    ampl.close()

    # prepare data for ploting
    if f_out != None:
        df_plotdata = df_demand.groupby(level=1).sum().join(df_demand.loc[(
            'COT',
        ), ['Demand']].rename(columns={'Demand': 'COT'})).assign(
            TBW_Demand=lambda x: x.Demand - x.COT).loc[:, ['TBW_Demand']].join(
                gw_results.join(sw_results.set_index(gw_results.index)))
        monyr = [pd.Timestamp(i + '-01') for i in df_plotdata.index]
        df_plotdata = df_plotdata.assign(
            Dates=monyr).set_index('Dates').sort_index()
        df_plotdata = df_plotdata.assign(ndays_mo=ndays_mo)

        plot_results(SID, AVAIL_PCTILE, df_plotdata, f_out)
示例#7
0
    def fix_create_run(self, nest_tuple, cost_list):

        effective_lv = list(self.level_list)
        fix_dict = {
            'L0Tb': 1,
            'L0Tx': 1,
            'L0Ty': self.numAB[0],
            'L0Tf': self.numAB[1],
            'L0Tc': 1,
            'L0Tw': 1,
            'L0Th': 1,
            'L1Tw': self.pbsize_dict['w'],
            'L1Th': self.pbsize_dict['h']
        }
        cost_score = []
        bottleneck_list = []

        all_tiles = {}
        while len(effective_lv) > 0:
            best_target_cost = [
                -1, math.inf, {}
            ]  # best lv, best lv cost, tile names fixed by best lv
            for target_lv in effective_lv:
                try:
                    ampl = AMPL()
                    ampl.setOption('solver', 'ipopt')
                    modfile_name, cost_expr_list = self.create_modfile(
                        nest_tuple, cost_list, target_lv, effective_lv)
                    ampl.read(modfile_name)

                    fixed_vars = []
                    for fixtile_name in fix_dict.keys():
                        print(fixtile_name)
                        fixvar = ampl.getVariable(name=fixtile_name)
                        fixvar.fix(value=fix_dict.get(fixtile_name))
                        fixed_vars.append(fixvar)

                    ampl.solve()
                    maxcost = ampl.getObjective('maxcost')
                    tofix_tiles = {}
                    target_expr = cost_expr_list[self.level_list.index(
                        target_lv)]
                    for tofix_t in target_expr.free_symbols:
                        fixvar = ampl.getVariable(str(tofix_t))
                        tofix_tiles[str(tofix_t)] = math.floor(fixvar.value())

                    if maxcost.value(
                    ) < best_target_cost[1] and maxcost.exitcode(
                    ) == 0 and 'Optimal Solution Found' in maxcost.message():
                        best_target_cost[0] = target_lv
                        best_target_cost[1] = maxcost.value()
                        best_target_cost[2] = dict(tofix_tiles)
                        if len(effective_lv) == 1:
                            for lv in list(self.level_list) + list(
                                    self.parallel_list):
                                for idx in self.idx_list:
                                    Tx_name = str(
                                        self.pool.get_sym(idx=idx, tlv=lv))
                                    Tx_var = ampl.getVariable(name=Tx_name)
                                    Tx_value = math.floor(Tx_var.value())
                                    all_tiles[Tx_name] = Tx_value

                    ampl.close()
                except Exception as e:
                    print(e)
                    raise

            if (best_target_cost[0] < 0):
                return 'invalid'
            delete_lv = best_target_cost[0]
            bottle_cost = best_target_cost[1]
            print('lv', delete_lv, 'is bottleneck ', bottle_cost)
            tofix_tile_dict = best_target_cost[2]
            cost_score.append(best_target_cost[1])
            bottleneck_list.append(best_target_cost[0])

            popidx = effective_lv.index(delete_lv)
            effective_lv.pop(popidx)
            for tofix in tofix_tile_dict.keys():
                if fix_dict.get(tofix) == None:
                    fix_dict[tofix] = tofix_tile_dict.get(tofix)

        for fkey in fix_dict.keys():
            pblv = 'L' + str(self.level_list[-1] + 1)
            if pblv in fkey:
                continue
            fv = fix_dict.get(fkey)
            av = all_tiles.get(fkey)
            if (fv != av):
                print('fkey fv av:', fkey, fv, av)
                assert (av == fv)
        return cost_score, bottleneck_list, all_tiles, nest_tuple