예제 #1
0
def solve_sscfl_instance(mod_file, sscfl_instance, ampl_folder):
    print('### AMPL SOLUTION ###')
    if ampl_folder is None:
        primal_pl = AMPL()
    else:
        primal_pl = AMPL(Environment(ampl_folder))
    primal_pl.read('ampl_mod_files/' + mod_file)
    primal_pl.setOption('solver', 'cplex')
    primal_pl = write_ampl_sscfl_dat_file(primal_pl, sscfl_instance)
    primal_pl.solve()
    f = primal_pl.getObjective('f')
    print('\nZ = ', '%.5f' % (f.value()))
    return f.value()
예제 #2
0
def solve(dat):
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set NODES;
    set ARCS within {i in NODES, j in NODES: i <> j};
    set COMMODITIES;
    param volume {COMMODITIES} > 0, < Infinity;
    param capacity {ARCS} >= 0;
    param cost {COMMODITIES,ARCS} >= 0, < Infinity;
    param inflow {COMMODITIES,NODES} > -Infinity, < Infinity;
    var Flow {COMMODITIES,ARCS} >= 0;
    minimize TotalCost:
       sum {h in COMMODITIES, (i,j) in ARCS} cost[h,i,j] * Flow[h,i,j];
    subject to Capacity {(i,j) in ARCS}:
       sum {h in COMMODITIES} Flow[h,i,j] * volume[h] <= capacity[i,j];
    subject to Conservation {h in COMMODITIES, j in NODES}:
       sum {(i,j) in ARCS} Flow[h,i,j] + inflow[h,j] = sum {(j,i) in ARCS} Flow[h,j,i];
    """)

    # copy the tables to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat,
                                    field_renamings={
                                        ("commodities", "Volume"): "volume",
                                        ("arcs", "Capacity"): "capacity",
                                        ("cost", "Cost"): "cost",
                                        ("inflow", "Quantity"): "inflow"
                                    })

    # load the amplpy.DataFrame objects into the AMPL model, explicitly identifying how to populate the AMPL sets
    input_schema.set_ampl_data(dat, ampl, {
        "nodes": "NODES",
        "arcs": "ARCS",
        "commodities": "COMMODITIES"
    })
    ampl.solve()
    if ampl.getValue("solve_result") != "infeasible":
        # solution tables are populated by mapping solution (table, field) to AMPL variable
        sln = solution_schema.copy_from_ampl_variables({
            ('flow', 'Quantity'):
            ampl.getVariable("Flow")
        })
        # append the solution KPI results to the solution parameters table
        sln.parameters.loc[0] = [
            'Total Cost', ampl.getObjective('TotalCost').value()
        ]
        return sln
예제 #3
0
def main(argc, argv):
    from amplpy import AMPL, DataFrame
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        # Create an AMPL instance
        ampl = AMPL()

        """
        # If the AMPL installation directory is not in the system search path:
        from amplpy import Environment
        ampl = AMPL(
            Environment('full path to the AMPL installation directory'))
        """

        ampl.eval('set CITIES; set LINKS within (CITIES cross CITIES);')
        ampl.eval('param cost {LINKS} >= 0; param capacity {LINKS} >= 0;')
        ampl.eval('data; set CITIES := PITT NE SE BOS EWR BWI ATL MCO;')

        cost = [2.5, 3.5, 1.7, 0.7, 1.3, 1.3, 0.8, 0.2, 2.1]
        capacity = [250, 250, 100, 100, 100, 100, 100, 100, 100]
        LinksFrom = ['PITT', 'PITT', 'NE', 'NE', 'NE', 'SE', 'SE', 'SE', 'SE']
        LinksTo = ['NE', 'SE', 'BOS', 'EWR', 'BWI', 'EWR', 'BWI', 'ATL', 'MCO']

        df = DataFrame(('LINKSFrom', 'LINKSTo'), ('cost', 'capacity'))
        df.setColumn('LINKSFrom', LinksFrom)
        df.setColumn('LINKSTo', LinksTo)
        df.setColumn('cost', cost)
        df.setColumn('capacity', capacity)
        print(df)

        ampl.setData(df, 'LINKS')
    except Exception as e:
        print(e)
        raise
예제 #4
0
def main(argc, argv):
    from amplpy import AMPL
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        # Create an AMPL instance
        ampl = AMPL()

        # Get the value of the option presolve and print
        presolve = ampl.getOption('presolve')
        print("AMPL presolve is", presolve)

        # Set the value to false (maps to 0)
        ampl.setOption('presolve', False)

        # Get the value of the option presolve and print
        presolve = ampl.getOption('presolve')
        print("AMPL presolve is now", presolve)

        # Check whether an option with a specified name
        # exists
        value = ampl.getOption('solver')
        if value is not None:
            print("Option solver exists and has value:", value)

        # Check again, this time failing
        value = ampl.getOption('s_o_l_v_e_r')
        if value is None:
            print("Option s_o_l_v_e_r does not exist!")
    except Exception as e:
        print(e)
        raise
예제 #5
0
def main(argc, argv):
    ampl = AMPL(Environment(r'C:\Users\etjones\Desktop\AI OPS\AMPL\amplide.mswin64'))
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        if argc > 1:
            ampl.setOption('solver', argv[1])

        # Read the model and data files.
        #modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models')
        #ampl.read(os.path.join(modelDirectory, 'diet/diet.mod'))
        #ampl.readData(os.path.join(modelDirectory, 'diet/diet.dat'))
        ampl.read(r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.mod')
        ampl.readData(r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.dat')

        # Solve
        print('\n' + "AMPL MODEL:" + '\n')
        ampl.solve()
        totalcost = ampl.getObjective('Total_Cost')
        print("Minimum Cost:", totalcost.value())
        print('\n' + "Optimal Flow:")
        ampl.display('Trans')
        print('\n' + "Compare pdf flow to the above table to confirm optmial flows")
    except Exception as e:
        print(e)
        raise
예제 #6
0
def tsp_model(tsp_data, enable_mtz=True):
    from amplpy import AMPL
    from math import sqrt
    ampl = AMPL()
    ampl.eval('''
    param n;
    set V := 1..n;
    set A := {(i,j) in V cross V : i != j};
    param c{A} >= 0 default Infinity;

    var x{A}, binary;
    var u{V} >= 0;

    minimize total: sum{(i,j) in A} c[i,j] * x[i,j];
    s.t. enter{j in V}: sum{i in V: i != j} x[i, j] == 1;
    s.t. leave{i in V}: sum{j in V: j != i} x[i, j] == 1;
    ''')

    if enable_mtz:
        ampl.eval('''
        # subtour elimination Miller, Tucker and Zemlin (MTZ) (1960)
        subject to MTZ{(i,j) in A: i != 1}: u[i]-u[j] + (n-1)*x[i,j] <= n-2;
        ''')

    n, xs, ys = load_tsp_data(tsp_data)
    dist = {(i + 1, j + 1): sqrt((xs[j] - xs[i])**2 + (ys[j] - ys[i])**2)
            for i in range(n) for j in range(n) if i != j}
    ampl.param['n'] = n
    ampl.param['c'] = dist
    return ampl
예제 #7
0
def call_ampl(dat):
    ampl = AMPL()
    ampl.read('ComplementarMaxCovering.md')
    ampl.setOption('solver', 'cplex')

    ni = ampl.getParameter('ni')
    ni.set(dat['ni'])  # Envia a quantidade de clientes para o AMPL

    nj = ampl.getParameter('nj')
    nj.set(dat['nj'])  # Envia a quantidade de facilidades para o AMPL

    p = ampl.getParameter('p')
    p.set(dat['p']
          )  # Envia o valor da quantidade máxima de facilidades para o AMPL

    w = ampl.getParameter('w')
    w.setValues(dat['w'])  # Envia os pesos de cada cliente para o AMPL

    for i in range(dat['ni']):
        ampl.set['a'][i] = dat['a'][i]  # Envia a matriz A para o AMPL

    ampl.getOutput('solve;')  # Demonstra o resultado na tela do Python

    fo = ampl.getObjective('fo').value()
    x = ampl.getVariable('x')
    _x = [int(j) for j in range(dat['nj']) if x[j].value() > 0.9]
    y = ampl.getVariable('y')
    _y = [int(i) for i in range(dat['ni']) if y[i].value() > 0.9]

    return (fo, _x, _y)
예제 #8
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
예제 #9
0
def main(argc, argv):
    from amplpy import AMPL, DataFrame
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        ampl = AMPL()
        ampl.eval('set CITIES; set LINKS within (CITIES cross CITIES);')
        ampl.eval('param cost {LINKS} >= 0; param capacity {LINKS} >= 0;')
        ampl.eval('data; set CITIES := PITT NE SE BOS EWR BWI ATL MCO;')

        cost = [2.5, 3.5, 1.7, 0.7, 1.3, 1.3, 0.8, 0.2, 2.1]
        capacity = [250, 250, 100, 100, 100, 100, 100, 100, 100]
        LinksFrom = ['PITT', 'PITT', 'NE', 'NE', 'NE', 'SE', 'SE', 'SE', 'SE']
        LinksTo = ['NE', 'SE', 'BOS', 'EWR', 'BWI', 'EWR', 'BWI', 'ATL', 'MCO']

        df = DataFrame(('LINKSFrom', 'LINKSTo'), ('cost', 'capacity'))
        df.setColumn('LINKSFrom', LinksFrom)
        df.setColumn('LINKSTo', LinksTo)
        df.setColumn('cost', cost)
        df.setColumn('capacity', capacity)
        print(df)

        ampl.setData(df, 'LINKS')
    except Exception as e:
        print(e)
        raise
def call_ampl(dat):
    ampl = AMPL()
    ampl.read('Base.md')
    ampl.setOption('solver', 'cplex')

    n = ampl.getParameter('n')
    n.set(dat['n'])

    cx = ampl.getParameter('cx')
    cx.setValues(dat['cx'])

    cy = ampl.getParameter('cy')
    cy.setValues(dat['cy'])

    ampl.getOutput('solve;')

    fo = ampl.getObjective('fo').value()

    x = ampl.getVariable('x')

    rota = []
    for i in range(dat['n']):
        for j in range(dat['n']):
            if j != i:
                if x[i, j].value() > 0.9:
                    rota.append(j)
    return (fo, rota)
def call_ampl_normal(dat):
    ampl = AMPL()
    ampl.read('HierarquicoPMediana.md')
    ampl.setOption('solver', 'cplex')

    ni = ampl.getParameter('ni')
    ni.set(dat['ni'])

    nj = ampl.getParameter('nj')
    nj.set(dat['nj'])

    p = ampl.getParameter('p')
    p.set(dat['p'])

    q = ampl.getParameter('q')
    q.set(dat['q'])

    ampl.param['a'] = {(i, j) : dat['a'][i][j] for i in range(dat['ni']) for j in range(dat['nj'])}

    ampl.param['b'] = {(i, j) : dat['b'][i][j] for i in range(dat['ni']) for j in range(dat['nj'])}

    ampl.param['c'] = {(i, j) : dat['c'][i][j] for i in range(dat['ni']) for j in range(dat['nj'])}

    ampl.getOutput('solve;')

    fo = ampl.getObjective('fo').value()
    y = ampl.getVariable('y')
    _y = [int(j) for j in range(dat['nj']) if y[j].value() > 0.9]
    z = ampl.getVariable('z')
    _z = [int(j) for j in range(dat['nj']) if z[j].value() > 0.9]

    return (fo, _y, _z)
예제 #12
0
def main(argc, argv):
    from amplpy import AMPL
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        # Create an AMPL instance
        ampl = AMPL()
        """
        # If the AMPL installation directory is not in the system search path:
        from amplpy import Environment
        ampl = AMPL(
            Environment('full path to the AMPL installation directory'))
        """

        if argc > 1:
            ampl.setOption('solver', argv[1])

        # Read the model and data files.
        modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models')
        ampl.read(os.path.join(modelDirectory, 'diet/diet.mod'))
        ampl.readData(os.path.join(modelDirectory, 'diet/diet.dat'))

        # Solve
        ampl.solve()

        # Get objective entity by AMPL name
        totalcost = ampl.getObjective('Total_Cost')
        # Print it
        print("Objective is:", totalcost.value())

        # Reassign data - specific instances
        cost = ampl.getParameter('cost')
        cost.setValues({'BEEF': 5.01, 'HAM': 4.55})
        print("Increased costs of beef and ham.")

        # Resolve and display objective
        ampl.solve()
        print("New objective value:", totalcost.value())

        # Reassign data - all instances
        elements = [3, 5, 5, 6, 1, 2, 5.01, 4.55]
        cost.setValues(elements)
        print("Updated all costs.")

        # Resolve and display objective
        ampl.solve()
        print("New objective value:", totalcost.value())

        # Get the values of the variable Buy in a dataframe object
        buy = ampl.getVariable('Buy')
        df = buy.getValues()
        # Print them
        print(df)

        # Get the values of an expression into a DataFrame object
        df2 = ampl.getData('{j in FOOD} 100*Buy[j]/Buy[j].ub')
        # Print them
        print(df2)
    except Exception as e:
        print(e)
        raise
예제 #13
0
    def __init__(self):
        self._ampl = AMPL()
        """
        Use the CPLEX solver driver for linear programming problems.
        """
        self._ampl.setOption('solver', 'cplex')
        """
         Prevent using the current values as well as the statuses of the variables in
         constructing the starting point at the next solve.
        """
        self._ampl.setOption('reset_initial_guesses', True)
        """
        The major use of solver status values from an optimal basic solution is to provide a
        good starting point for the next optimization run. The option send_statuses, when set to True,
        instructs AMPL to include statuses with the information about variables sent to the solver at each solve.
        """
        self._ampl.setOption('send_statuses', True)

        self._n_iterations: int = 0
        """
        Add class that handles AMPL outputs
        """
        self._ampl.setOutputHandler(AMPLOutputHandler(self.set_n_iterations))
        """
        Add class that handles errors and warnings that may occur during the AMPL execution.
        """
        self._ampl.setErrorHandler(AMPLErrorHandler())
예제 #14
0
def solve(dat):
    """
    core solving routine
    :param dat: a good ticdat for the input_schema
    :return: a good ticdat for the solution_schema, or None
    """
    assert input_schema.good_tic_dat_object(dat)
    assert not input_schema.find_foreign_key_failures(dat)
    assert not input_schema.find_data_type_failures(dat)
    assert not input_schema.find_data_row_failures(dat)
    # use default parameters, unless they are overridden by user-supplied parameters
    full_parameters = dict(
        default_parameters,
        **{k: v["Value"]
           for k, v in dat.parameters.items()})

    sln = solution_schema.TicDat()  # create an empty solution'

    ampl_dat = input_schema.copy_to_ampl(
        dat,
        excluded_tables=set(input_schema.all_tables).difference(
            {"load_amounts"}))
    # solve a distinct MIP for each pair of (# of one-way-trips, amount leftover)
    for number_trips, amount_leftover in product(dat.number_of_one_way_trips,
                                                 dat.amount_leftover):

        ampl = AMPL()
        ampl.setOption('solver', 'gurobi')
        # use the ampl_format function for AMPL friendly key-named text substitutions
        ampl.eval(
            ampl_format("""
        set LOAD_AMTS;
        var Num_Visits {LOAD_AMTS} integer >= 0;
        var Amt_Leftover >= {{amount_leftover_lb}}, <= {{amount_leftover_ub}};
        minimize Total_Visits:
           sum {la in LOAD_AMTS} Num_Visits[la];
        subj to Set_Amt_Leftover:
           Amt_Leftover = sum {la in LOAD_AMTS} la * Num_Visits[la] - {{one_way_price}} * {{number_trips}};""",
                        number_trips=number_trips,
                        one_way_price=full_parameters["One Way Price"],
                        amount_leftover_lb=amount_leftover
                        if full_parameters["Amount Leftover Constraint"]
                        == "Equality" else 0,
                        amount_leftover_ub=amount_leftover))

        input_schema.set_ampl_data(ampl_dat, ampl,
                                   {"load_amounts": "LOAD_AMTS"})
        ampl.solve()

        if ampl.getValue("solve_result") != "infeasible":
            # store the results if and only if the model is feasible
            for la, x in ampl.getVariable(
                    "Num_Visits").getValues().toDict().items():
                if round(x) > 0:
                    sln.load_amount_details[number_trips, amount_leftover,
                                            la] = round(x)
                    sln.load_amount_summary[number_trips, amount_leftover]["Number Of Visits"]\
                       += round(x)
    return sln
예제 #15
0
def solver(alpha, n_intersections, C, g_i_inbound, g_i_outbound, delta, verbose=True):
    """
    Solves the linear problem for the given set of parameters
    :param alpha:
    :type alpha:
    :param n_intersections:
    :type n_intersections:
    :param C:
    :type C:
    :param g_i_inbound:
    :type g_i_inbound:
    :param g_i_outbound:
    :type g_i_outbound:
    :param delta:
    :type delta:
    :return:
    :rtype:
    """
    ampl = AMPL(Environment(path))

    # Set the solver
    ampl.setOption('solver', path + '/cplex')

    # Read the model file
    ampl.read('lp.mod')

    # Set parameters values
    ampl.param['alpha'] = alpha
    ampl.param['N'] = n_intersections
    ampl.param['C'] = C
    ampl.param['g_incoming'] = g_i_inbound
    ampl.param['g_outgoing'] = g_i_outbound
    ampl.param['delta'] = delta

    if verbose == True:
        print("alpha: {}".format(alpha))
        print("N: {}".format(n_intersections))
        print("C: {}".format(C))
        print("g_incoming: {}".format(g_i_inbound))
        print("g_outgoing: {}".format(g_i_outbound))
        print("delta: {}".format(delta))

    # Resolve and display objective
    ampl.solve()
    bandwidth = ampl.getObjective('bandwidth').value()

    # Display the variables
    b_incoming = ampl.getVariable('b_incoming').value()
    b_outgoing = ampl.getVariable('b_outgoing').value()
    wl = ampl.getVariable('w').getValues()

    if verbose == True:
        print("New objective value: {}".format(bandwidth))
        print("New offsets: {}".format(list(wl.toPandas()['w.val'])))
        print("Incoming bandwidth: {}".format(b_incoming))
        print("Outgoing bandwidth: {}".format(b_outgoing))

    # return bandwidths and offset values
    return b_incoming, b_outgoing, list(wl.toPandas()['w.val'])
def calculate(*args):
    try:
        ampl = AMPL(Environment('/Users/zintun/Downloads/amplide.macosx64')) ##path has to change accordingly
        ampl.setOption('solver', 'gurobi')

        ampl.read('Y3_Elementals.mod')
        ampl.readData('Y3_data.dat')

        day_val = int(day.get())
        print(day_val)

        T = ampl.getParameter('T')
        T.set(day_val)

        ampl.solve()

        v1 = ampl.getVariable('X').getValues()
            
        c = v1.toList()
        rows = [[int(column) for column in row] for row in c]

        org_mat = []
        dest_mat = []
        mod_mat = []
        value_mat = []
        for i in range(len(rows)):
            element = rows[i]
            origin = element[0]
            dest = element[1]
            mode = element[2]
            value = element[3]
            org_mat.append(origin)
            dest_mat.append(dest)
            mod_mat.append(mode)
            value_mat.append(value)

        N = ampl.getParameter('N').getValues()
        N1 = N.toList()
        N_rows = [[int(column) for column in row] for row in N1]
        count = 0
        exist = []
        while(count < len(N_rows)):
            if(N_rows[count][3] or N_rows[count+1][3] or N_rows[count+2][3] or N_rows[count+3][3]):
                exist.extend([1, 1, 1,1])
            else:
                exist.extend([0, 0, 0,0])
            count = count + 4

        
        cost = ampl.getObjective('Cost').value()

        drawGraph1(org_mat,dest_mat,mod_mat,value_mat,exist,cost)


    except ValueError:
        pass
예제 #17
0
def solve(dat):

    assert input_schema.good_tic_dat_object(dat)

    # copy the data over to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat,
                                    field_renamings={
                                        ("foods", "Cost"): "cost",
                                        ("categories", "Min Nutrition"):
                                        "n_min",
                                        ("categories", "Max Nutrition"):
                                        "n_max",
                                        ("nutrition_quantities", "Quantity"):
                                        "amt"
                                    })

    # create and AMPL object and load it with .mod code
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set CAT;
    set FOOD;

    param cost {FOOD} > 0;

    param n_min {CAT} >= 0;
    param n_max {i in CAT} >= n_min[i];

    param amt {FOOD, CAT} >= 0;

    var Buy {j in FOOD} >= 0;
    var Consume {i in CAT } >= n_min [i], <= n_max [i];

    minimize Total_Cost:  sum {j in FOOD} cost[j] * Buy[j];

    subject to Diet {i in CAT}:
       Consume[i] =  sum {j in FOOD} amt[j,i] * Buy[j];
    """)

    # set the AMPL object with the amplpy.DataFrame data and solve
    input_schema.set_ampl_data(dat, ampl, {
        "categories": "CAT",
        "foods": "FOOD"
    })
    ampl.solve()

    if ampl.getValue("solve_result") != "infeasible":
        sln = solution_schema.copy_from_ampl_variables({
            ("buy_food", "Quantity"):
            ampl.getVariable("Buy"),
            ("consume_nutrition", "Quantity"):
            ampl.getVariable("Consume")
        })
        sln.parameters['Total Cost'] = ampl.getObjective('Total_Cost').value()

        return sln
예제 #18
0
def solve(dat):
    """
    core solving routine
    :param dat: a good pandat for the input_schema
    :return: a good pandat for the solution_schema, or None
    """
    assert input_schema.good_pan_dat_object(dat)
    assert not input_schema.find_duplicates(dat)
    assert not input_schema.find_foreign_key_failures(dat)
    assert not input_schema.find_data_type_failures(dat)
    assert not input_schema.find_data_row_failures(dat)

    # build the AMPL math model
    if AMPL is None: # even if you don't have amplpy installed, you can still import this file for other uses
        print("*****\namplpy needs to be installed for this example code to solve!\n*****\n")
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set CAT;
    set FOOD;

    param cost {FOOD} >= 0, < Infinity;

    param n_min {CAT} >= 0, < Infinity;
    param n_max {i in CAT} >= n_min[i];

    param amt {FOOD, CAT} >= 0, < Infinity;

    var Buy {j in FOOD} >= 0;
    var Consume {i in CAT } >= n_min [i], <= n_max [i];

    minimize Total_Cost:  sum {j in FOOD} cost[j] * Buy[j];

    subject to Diet {i in CAT}:
       Consume[i] =  sum {j in FOOD} amt[j,i] * Buy[j];
    """)
    # copy the tables to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat, field_renamings={
            ("foods", "Cost"): "cost",
            ("categories", "Min Nutrition"): "n_min",
            ("categories", "Max Nutrition"): "n_max",
            ("nutrition_quantities", "Quantity"): "amt"})
    # load the amplpy.DataFrame objects into the AMPL model, explicitly identifying how to populate the AMPL sets
    input_schema.set_ampl_data(dat, ampl, {"categories": "CAT", "foods": "FOOD"})

    # solve and recover the solution if feasible
    ampl.solve()
    if ampl.getValue("solve_result") != "infeasible":
        # solution tables are populated by mapping solution (table, field) to AMPL variable
        sln = solution_schema.copy_from_ampl_variables(
            {("buy_food", "Quantity"): ampl.getVariable("Buy"),
            ("consume_nutrition", "Quantity"): ampl.getVariable("Consume")})
        # append the solution KPI results to the solution parameters table
        sln.parameters.loc[0] = ['Total Cost', ampl.getObjective('Total_Cost').value()]

        return sln
예제 #19
0
def main(argc, argv):
    from amplpy import AMPL, DataFrame
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        ampl = AMPL()

        if argc > 1:
            ampl.setOption('solver', argv[1])

        # Read the model file
        modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models')
        ampl.read(os.path.join(modelDirectory, 'diet/diet.mod'))

        foods = ['BEEF', 'CHK', 'FISH', 'HAM', 'MCH', 'MTL', 'SPG', 'TUR']
        costs = [3.59, 2.59, 2.29, 2.89, 1.89, 1.99, 1.99, 2.49]

        fmin = [2, 2, 2, 2, 2, 2, 2, 2]
        fmax = [10, 10, 10, 10, 10, 10, 10, 10]

        df = DataFrame('FOOD')
        df.setColumn('FOOD', foods)
        df.addColumn('cost', costs)
        df.addColumn('f_min', fmin)
        df.addColumn('f_max', fmax)
        ampl.setData(df, 'FOOD')

        nutrients = ['A', 'C', 'B1', 'B2', 'NA', 'CAL']
        nmin = [700, 700, 700, 700, 0, 16000]
        nmax = [20000, 20000, 20000, 20000, 50000, 24000]

        df = DataFrame('NUTR')
        df.setColumn('NUTR', nutrients)
        df.addColumn('n_min', nmin)
        df.addColumn('n_max', nmax)
        ampl.setData(df, 'NUTR')

        amounts = [[60, 8, 8, 40, 15, 70, 25, 60],
                   [20, 0, 10, 40, 35, 30, 50, 20],
                   [10, 20, 15, 35, 15, 15, 25, 15],
                   [15, 20, 10, 10, 15, 15, 15, 10],
                   [928, 2180, 945, 278, 1182, 896, 1329, 1397],
                   [295, 770, 440, 430, 315, 400, 379, 450]]

        df = DataFrame(('NUTR', 'FOOD'), 'amt')
        df.setValues({(nutrient, food): amounts[i][j]
                      for i, nutrient in enumerate(nutrients)
                      for j, food in enumerate(foods)})
        ampl.setData(df)

        ampl.solve()

        print('Objective: {}'.format(ampl.getObjective('total_cost').value()))
    except Exception as e:
        print(e)
        raise
예제 #20
0
def solver(alpha, n_intersections, C, g_i_inbound, g_i_outbound, delta, print_=True):
    """
    Solves the linear problem for the given set of parameters
    :param alpha:
    :type alpha:
    :param n_intersections:
    :type n_intersections:
    :param C:
    :type C:
    :param g_i_inbound:
    :type g_i_inbound:
    :param g_i_outbound:
    :type g_i_outbound:
    :param delta:
    :type delta:
    :return:
    :rtype:
    """
    ampl = AMPL(Environment(path))

    # Set the solver
    ampl.setOption('solver', path + '/cplex')

    # Read the model file
    ampl.read('lp.mod')

    # Set parameters values
    ampl.param['alpha'] = alpha
    ampl.param['N'] = n_intersections
    ampl.param['C'] = C
    ampl.param['g_incoming'] = g_i_inbound
    ampl.param['g_outgoing'] = g_i_outbound
    ampl.param['delta'] = delta

    # Resolve and display objective
    ampl.solve()
    bandwidth = ampl.getObjective('bandwidth').value()

    # Display the variables
    b_incoming = ampl.getVariable('b_incoming').value()
    b_outgoing = ampl.getVariable('b_outgoing').value()
    w_relative = ampl.getVariable('w').getValues()
    w_relative = [w[1] for w in w_relative]

    if print_ == True:
        print("New objective value: {}".format(bandwidth))
        print("Incoming bandwidth: {}".format(b_incoming))
        print("Outgoing bandwidth: {}".format(b_outgoing))
        print("Incoming offsets: {}".format(w_relative))

    # return bandwidths and offset values
    return b_incoming, b_outgoing, w_relative
예제 #21
0
    def run_ampl_model(self, data):
        # Intiialize AMPL choose solver and load model
        ampl = AMPL()
        ampl.eval('option solver cplex;')
        ampl.read('model/ampl/model.mod')

        # Generate and load temporary data file
        data_file = self.generate_temp_data_file(data)
        ampl.readData(data_file.name)
        data_file.close()

        ampl.solve()
        return ampl
예제 #22
0
def solve(dat):
    """
    core solving routine
    :param dat: a good ticdat for the input_schema
    :return: a good ticdat for the solution_schema, or None
    """
    assert input_schema.good_tic_dat_object(dat)
    assert not input_schema.find_foreign_key_failures(dat)
    assert not input_schema.find_data_type_failures(dat)

    # copy the data over to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat, field_renamings={("arcs", "Capacity"): "capacity",
            ("cost", "Cost"): "cost", ("inflow", "Quantity"): "inflow"})

    # for instructional purposes, the following code anticipates extreme sparsity and doesn't generate
    # conservation of flow records unless they are really needed
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set NODES;
    set ARCS within {i in NODES, j in NODES: i <> j};
    set COMMODITIES;
    param capacity {ARCS} >= 0;
    set SHIPMENT_OPTIONS within {COMMODITIES,ARCS};
    param cost {SHIPMENT_OPTIONS} > 0;
    set INFLOW_INDEX within {COMMODITIES,NODES};
    param inflow {INFLOW_INDEX};
    var Flow {SHIPMENT_OPTIONS} >= 0;
    minimize TotalCost:
       sum {(h,i,j) in SHIPMENT_OPTIONS} cost[h,i,j] * Flow[h,i,j];
    subject to Capacity {(i,j) in ARCS}:
       sum {(h,i,j) in SHIPMENT_OPTIONS} Flow[h,i,j] <= capacity[i,j];
    subject to Conservation {h in COMMODITIES, j in NODES:
         card {(h,i,j) in SHIPMENT_OPTIONS} > 0 or
         card {(h,j,i) in SHIPMENT_OPTIONS} > 0 or
         (h,j) in INFLOW_INDEX}:
       sum {(h,i,j) in SHIPMENT_OPTIONS} Flow[h,i,j] +
       (if (h,j) in INFLOW_INDEX then inflow[h,j]) =
       sum {(h,j,i) in SHIPMENT_OPTIONS} Flow[h,j,i];
    """)

    input_schema.set_ampl_data(dat, ampl, {"nodes": "NODES", "arcs": "ARCS",
                                           "commodities": "COMMODITIES", "cost":"SHIPMENT_OPTIONS",
                                            "inflow":"INFLOW_INDEX"})
    ampl.solve()

    if ampl.getValue("solve_result") != "infeasible":
        sln = solution_schema.copy_from_ampl_variables(
            {('flow' ,'Quantity'):ampl.getVariable("Flow")})
        sln.parameters["Total Cost"] = ampl.getObjective('TotalCost').value()
        return sln
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
예제 #24
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()
예제 #25
0
def run_ampl_model(data, minW=0.01, maxW=0.6, ex=0, K=3):
    dir = os.path.dirname(__file__)
    dir = 'C:\\Biblioteki\\AMPL\\ampl.mswin64'
    # dir=dir.replace('/','\\')

    # ampl = AMPL()
    ampl = AMPL(Environment(dir))

    if ex < 1:
        ampl.read('omg3.txt')
        data_file = generate_temp_data_file(data, minW=minW, maxW=maxW)
        ampl.setOption('solver', dir + '\minos.exe')
    elif ex == 2:

        ampl.read('omg_lmt.txt')

        data_file = generate_temp_data_file_lmt(data, minW=minW, maxW=maxW, K=K)
        ampl.setOption('solver', dir + '\cplex.exe')

    elif ex == 3:
        # ampl.read('omg_lmt.txt')
        ampl.read('omg4.txt')

        data_file = generate_temp_data_file_lmt(data, minW=minW, maxW=maxW, K=K)
        ampl.setOption('solver', dir + '\cplex.exe')

    else:
        ampl.read('eomg.txt')
        data_file = generate_temp_data_file_ex(data, minW=minW, maxW=maxW)
        ampl.setOption('solver', dir + '\minos.exe')

    # data_file=open('data_pattern.txt')
    ampl.readData(data_file.name)
    # ampl.readData('data_test.dat')
    data_file.close()
    ampl.solve()
    x = get_np_array_from_variable(ampl, 'x')
    # x=ampl.getVariable('x').getValues().toPandas()

    v0 = ampl.getVariable('v0').getValues().toPandas()

    sol = []

    for i in range(x.shape[1]):
        sol.append(x.iloc[0, i] / v0.iloc[0, 0])

    return sol
예제 #26
0
def solve(dat):
    """
    core solving routine
    :param dat: a good ticdat for the input_schema
    :return: a good ticdat for the solution_schema, or None
    """
    assert input_schema.good_tic_dat_object(dat)
    assert not input_schema.find_foreign_key_failures(dat)
    assert not input_schema.find_data_type_failures(dat)

    # copy the data over to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat, field_renamings={("arcs", "Capacity"): "capacity",
            ("cost", "Cost"): "cost", ("inflow", "Quantity"): "inflow"})

    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set NODES;
    set ARCS within {i in NODES, j in NODES: i <> j};
    set COMMODITIES;

    param capacity {ARCS} >= 0;
    param cost {COMMODITIES,ARCS} > 0;
    param inflow {COMMODITIES,NODES};

    var Flow {COMMODITIES,ARCS} >= 0;

    minimize TotalCost:
       sum {h in COMMODITIES, (i,j) in ARCS} cost[h,i,j] * Flow[h,i,j];

    subject to Capacity {(i,j) in ARCS}:
       sum {h in COMMODITIES} Flow[h,i,j] <= capacity[i,j];

    subject to Conservation {h in COMMODITIES, j in NODES}:
       sum {(i,j) in ARCS} Flow[h,i,j] + inflow[h,j] = sum {(j,i) in ARCS} Flow[h,j,i];
    """)

    input_schema.set_ampl_data(dat, ampl, {"nodes": "NODES", "arcs": "ARCS",
                                           "commodities": "COMMODITIES"})
    ampl.solve()

    if ampl.getValue("solve_result") != "infeasible":
        sln = solution_schema.copy_from_ampl_variables(
            {('flow' ,'Quantity'):ampl.getVariable("Flow")})
        sln.parameters["Total Cost"] = ampl.getObjective('TotalCost').value()
        return sln
예제 #27
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()
예제 #28
0
    def __init__(self, data, model_type, relax=False, time_limit=600):
        self.dat = data
        self.ampl = AMPL()        
        self.ampl.setOption('solver', 'cplex')
        self.ampl.setOption('cplex_options', 'timelimit={:d} return_mipgap=1 bestbound memoryemphasis=1'.format(time_limit))
        self.relax = relax
        if relax:
            self.ampl.setOption('relax_integrality', 1)

        if model_type == "pv":
            self.ampl.read('ampl_models/pos_variables.mod')
        elif model_type == "ct":
            self.ampl.read('ampl_models/conc_time.mod')
        else:
            print("Invalid model_type")
            return

        self.bind_data()
예제 #29
0
def main(argc, argv):
    from amplpy import AMPL, DataFrame

    os.chdir(os.path.dirname(__file__) or os.curdir)

    # Create an AMPL instance
    ampl = AMPL()
    """
    # If the AMPL installation directory is not in the system search path:
    from amplpy import Environment
    ampl = AMPL(
        Environment('full path to the AMPL installation directory'))
    """

    ampl.eval("set CITIES; set LINKS within (CITIES cross CITIES);")
    ampl.eval("param cost {LINKS} >= 0; param capacity {LINKS} >= 0;")
    ampl.eval("data; set CITIES := PITT NE SE BOS EWR BWI ATL MCO;")

    cost = [2.5, 3.5, 1.7, 0.7, 1.3, 1.3, 0.8, 0.2, 2.1]
    capacity = [250, 250, 100, 100, 100, 100, 100, 100, 100]
    links_from = ["PITT", "PITT", "NE", "NE", "NE", "SE", "SE", "SE", "SE"]
    links_to = ["NE", "SE", "BOS", "EWR", "BWI", "EWR", "BWI", "ATL", "MCO"]

    # Using amplpy.DataFrame
    df = DataFrame(("LINKSFrom", "LINKSTo"), ("cost", "capacity"))
    df.set_column("LINKSFrom", links_from)
    df.set_column("LINKSTo", links_to)
    df.set_column("cost", cost)
    df.set_column("capacity", capacity)
    print(df)

    ampl.set_data(df, "LINKS")
    ampl.display("LINKS")

    # Using pandas.DataFrame (recommended)
    df = pd.DataFrame(
        list(zip(links_from, links_to, cost, capacity)),
        columns=["LINKSFrom", "LINKSTo", "cost", "capacity"],
    ).set_index(["LINKSFrom", "LINKSTo"])
    print(df)

    ampl.eval("reset data LINKS;")
    ampl.set_data(df, "LINKS")
    ampl.display("LINKS")
예제 #30
0
def solve(dat):
    # build the AMPL math model
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')
    ampl.eval("""
    set CAT;
    set FOOD;

    param cost {FOOD} > 0, < Infinity;

    param n_min {CAT} >= 0, < Infinity;
    param n_max {i in CAT} >= n_min[i];

    param amt {FOOD, CAT} >= 0, < Infinity;

    var Buy {j in FOOD} >= 0;
    var Consume {i in CAT } >= n_min [i], <= n_max [i];

    minimize Total_Cost:  sum {j in FOOD} cost[j] * Buy[j];

    subject to Diet {i in CAT}:
       Consume[i] =  sum {j in FOOD} amt[j,i] * Buy[j];
    """)
    # copy the tables to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat, field_renamings={
            ("foods", "Cost"): "cost",
            ("categories", "Min Nutrition"): "n_min",
            ("categories", "Max Nutrition"): "n_max",
            ("nutrition_quantities", "Quantity"): "amt"})
    # load the amplpy.DataFrame objects into the AMPL model, explicitly identifying how to populate the AMPL sets
    input_schema.set_ampl_data(dat, ampl, {"categories": "CAT", "foods": "FOOD"})

    # solve and recover the solution if feasible
    ampl.solve()
    if ampl.getValue("solve_result") != "infeasible":
        # solution tables are populated by mapping solution (table, field) to AMPL variable
        sln = solution_schema.copy_from_ampl_variables(
            {("buy_food", "Quantity"): ampl.getVariable("Buy"),
            ("consume_nutrition", "Quantity"): ampl.getVariable("Consume")})
        # append the solution KPI results to the solution parameters table
        sln.parameters.loc[0] = ['Total Cost', ampl.getObjective('Total_Cost').value()]

        return sln