Exemple #1
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 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
Exemple #3
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())
Exemple #4
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
Exemple #5
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
Exemple #6
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
Exemple #7
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
Exemple #8
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()
Exemple #9
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()
Exemple #10
0
def amplSubTourElimination(ampl: AMPL):
    # Add the constraint and the needed parameters
    subToursAMPL = """param nSubtours >= 0 integer, default 0;
  set SUB {1..nSubtours} within NODES;

  subject to Subtour_Elimination {k in 1..nSubtours}:
  sum {i in SUB[k], j in NODES diff SUB[k]} 
  if (i,j) in PAIRS then X[i,j] else X[j,i] >= 2;"""
    ampl.eval(subToursAMPL)

    AMPLnSubtours = ampl.getParameter("nSubtours")
    AMPLSubtours = ampl.getSet("SUB")

    allsubtours = list()

    while True:  # Repeat until the solution contains only one tour
        ampl.solve()
        # Get solution
        ARCS = ampl.getData("{(i,j) in PAIRS : X[i,j]>0} X[i,j];")
        ARCS = set([(i, j) for (i, j, k) in ARCS.toList()])
        nodes = NODES.copy()
        subtours = findSubTours(ARCS, nodes)

        # If we have only one tour, the solution is valid
        if len(subtours) <= 1:
            break
        if PLOTSUBTOURS:
            plotTours(subtours, CPOINTS)
        # Else add the current tours to the list of subtours
        allsubtours.extend(subtours)
        # And add those to the constraints by assigning the values to
        # the parameter and the set
        AMPLnSubtours.set(len(allsubtours))
        for (i, tour) in enumerate(allsubtours):
            AMPLSubtours[i + 1].setValues(tour)
Exemple #11
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
Exemple #12
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()
Exemple #13
0
def solverSubTourElimination(ampl: AMPL, solver):
    global xvars, xinverse, vertices
    # Export the model using ampls
    model = ampl.exportModel(solver)
    model.enableLazyConstraints()

    # Get the global maps between solver vars and AMPL entities
    varMap = model.getVarMapFiltered("X")
    inverse = model.getVarMapInverse()
    xvars = {index: var2tuple(var)[1:] for var, index in varMap.items()}
    xinverse = {var2tuple(var)[1:]: index for index, var in inverse.items()}
    vertices = list(
        sorted(
            set([x[0]
                 for x in xvars.values()] + [x[1] for x in xvars.values()])))

    # Assign the callback
    callback = MyCallback()
    model.setCallback(callback)
    # Start the optimization
    model.optimize()
    # Import the solution back to AMPL
    ampl.importSolution(model)
Exemple #14
0
def main(argc, argv):
    # You can install amplpy with "python -m pip install amplpy"
    from amplpy import AMPL

    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'))
    """

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

    # Set the value to false (maps to 0)
    ampl.set_option("presolve", False)

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

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

    # Check again, this time failing
    value = ampl.get_option("s_o_l_v_e_r")
    if value is None:
        print("Option s_o_l_v_e_r does not exist!")
Exemple #15
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
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)
    ampl.reset()
    ampl.read('/Users/jonathan/Desktop/169projectPEnvy.mod')
    ampl.readData(
        "/Users/jonathan/Desktop/random_data/{}ppl{}obj_heuristic.dat".format(
            ppl, obj))
    ampl.setOption('solver', 'cplex')
    start_time = time.time()
    ampl.solve()
    finish_time = time.time()
    p_envy = ampl.getObjective('p_envy').value()

    return p_envy, finish_time - start_time


ampl = AMPL(
    Environment(
        "/Users/jonathan/Documents/files/amplide.macosx64/amplide.macosx64"))

with open('part4.csv', 'a', newline='') as csvfile:
    fieldnames = [
        'Number of People', 'Number of Items', 'Optimal P-Envy',
        'Wall Clock Time'
    ]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i in range(1, 11):
        for j in range(1, 11):
            for _ in range(30):
                p_envy, run_time = run_one_experiment(ampl, i, j)
                out = {
                    'Number of People': j,
Exemple #18
0
def main(argc, argv):
    from amplpy import AMPL, DataFrame
    import amplpy
    from time import time
    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.setOption('reset_initial_guesses', True)
        ampl.setOption('send_statuses', False)
        ampl.setOption('relax_integrality', True)

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

        # Load the AMPL model from file
        modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models')
        ampl.read(os.path.join(modelDirectory, 'qpmv/qpmv.mod'))
        ampl.read(os.path.join(modelDirectory, 'qpmv/qpmvbit.run'))

        # Set tables directory (parameter used in the script above)
        ampl.getParameter('data_dir').set(os.path.join(modelDirectory, 'qpmv'))
        # Read tables
        ampl.readTable('assetstable')
        ampl.readTable('astrets')

        # Set the output handler to accumulate the output messages
        class MyOutputHandler(amplpy.OutputHandler):
            """
            Class used as an output handler. It only prints the solver output.
            Must implement :class:`amplpy.OutputHandler`.
            """
            def output(self, kind, msg):
                if kind == amplpy.Kind.SOLVE:
                    assert ampl.isBusy()
                    print('Solver: {}'.format(msg))

        class MyErrorHandler(amplpy.ErrorHandler):
            def error(self, exception):
                print('Error:', exception.getMessage())

            def warning(self, exception):
                print('Warning:', exception.getMessage())

        # Create an output handler
        outputHandler = MyOutputHandler()
        ampl.setOutputHandler(outputHandler)

        # Create an error handler
        errorHandler = MyErrorHandler()
        ampl.setErrorHandler(errorHandler)

        print("Main thread: Model setup complete. Solve on worker thread.")
        # Initiate the solution process asynchronously
        ampl.solveAsync()

        # Wait for the solution to complete
        print("Main thread: Waiting for solution to end...")
        start = time()

        # Wait for the async operation to finish
        ampl.wait()
        duration = time() - start

        print("Main thread: done waiting.")
        print("Main thread: waited for {} s".format(duration))

        # Print the objective value
        print("Main thread: cost: {}".format(ampl.getValue('cst')))
    except Exception as e:
        print(e, type(e))
        raise
Exemple #19
0
execute this, move to the root directory of this project and issue the
command below.

```
python3 src/main.py
```
"""

from amplpy import AMPL, DataFrame
import pandas as pd
import numpy as np
import os

## Load the ample model ##
# It might be great idea to separate configs to another file, e.g. JSON?
ampl           = AMPL()
modelDirectory = 'models'
modelName      = 'two_markets.mod'
mod_path       = os.path.join(modelDirectory, modelName)
dataDirectory  = 'data/balanced/'
ampl.read(mod_path)

## Assign set data ##
def assign_set_data(name,data):
    """Method to assign set data taking set name and a list as arguments"""
    df = DataFrame(name)
    df.setColumn(name,data)
    ampl.setData(df,name)

intervals = pd.read_csv(os.path.join(dataDirectory, 'intervals.csv'),
                        skipinitialspace=True)
Exemple #20
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_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)

    # build the AMPL math model
    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')

    ampl.eval("""
    set Workers;
    set Shifts;
    set Availability within {Workers,Shifts};

    param Pay{Workers};
    param Shift_Require{Shifts};

    var x{Availability} binary;
    var slack{Shifts}>=0;
    var totShifts{Workers};
    var totSlack;

    minimize Total_slack: totSlack;

    subject to reqCts{s in Shifts}: slack[s]+sum{(w,s) in Availability} x[w,s]== Shift_Require[s];
    subject to TotalSlack:totSlack==sum{s in Shifts}slack[s];
    subject to TotalShifts{w in Workers}:totShifts[w]==sum{(w,s) in Availability} x[w,s];
    """)

    # copy the tables to amplpy.DataFrame objects, renaming the data fields as needed
    dat = input_schema.copy_to_ampl(dat, field_renamings={
        ("shifts", "Requirement"): "Shift_Require",
        ("workers", "Payment"): "Pay"})
    # load the amplpy.DataFrame objects into the AMPL model, explicitly identifying how to populate the AMPL sets
    input_schema.set_ampl_data(dat, ampl, {"workers": "Workers", "shifts": "Shifts",
                                           "availability": "Availability"})

    ampl.solve()

    if ampl.getValue("solve_result") != "infeasible":
        # lexicographical solve 2 - minimize Total Payments while restricting Total Slack to be as small as possible
        totalSlack = ampl.getValue("totSlack")
        ampl.eval("""
        param maxSlack;
        subject to MaximumSlack: totSlack <= maxSlack;
        var totPayments;
        subject to TotalPayments: totPayments = sum{(w,s) in Availability}x[w,s]*Pay[w];
        minimize Total_payments: totPayments;
        objective Total_payments;
        """)
        ampl.param["maxSlack"] = totalSlack
        ampl.solve()
        if ampl.getValue("solve_result") != "infeasible":
            # lexicographical solve 2 - minimize imbalance among workers while restricting
            # Total Slack and Total Payments to be as small as possible
            totalPayments = ampl.getValue("Total_payments")
            ampl.eval("""
            param maxTotalPayments;
            subject to MaximumTotalPayments: totPayments <= maxTotalPayments;

            var avgShifts;
            var diffShifts{Workers};
            subject to avgShiftsC: card(Workers)*avgShifts==sum{w in Workers} totShifts[w];
            subject to Diff{w in Workers}: diffShifts[w]==totShifts[w]-avgShifts;

            minimize Total_Imbalance: sum{w in Workers}diffShifts[w] * diffShifts[w];
            objective Total_Imbalance;
            """)
            ampl.param["maxTotalPayments"] = totalPayments
            ampl.solve()
            if ampl.getValue("solve_result") != "infeasible":
                sln = solution_schema.copy_from_ampl_variables(
                        {('assignments' ,''): (ampl.getVariable("x"), lambda x: abs(x-1) < 1e-5),
                         ('slacks', 'Slack'): ampl.getVariable("slack"),
                         ('total_shifts', 'Total Number Of Shifts'): ampl.getVariable("totShifts")
                        })
                sln.parameters.loc[0] = ['Total Slack', ampl.getValue("Total_slack")]
                sln.parameters.loc[1] = ['Total Payments', ampl.getValue("Total_payments")]
                sln.parameters.loc[2] = ['Variance of Total Shifts', ampl.getValue("Total_Imbalance/card(Workers)")]
                return sln
training_dat = "phase2_training.dat"#input("What's the directory of your training .dat file?")
validating_dir = "Validation_Dataset.csv" #input("What's the directory of your validating set?")
model_dir = "phase2_lasso.mod" #input("What's the directory of your model?")
ampl_dir =  "/home/nub3ar/AMPL" #input("Where is ampl installed on your computer?") #"E:\ampl_mswin64"
validating_data = pd.read_csv(open(validating_dir))
#dimensions of the data
dv1,dv2 = validating_data.shape
print(dv1, dv2)
#column names
col_names_va = validating_data.columns.values
#x/y variable separation
y_va = validating_data.loc[0::,'Label'].values.tolist()
x_va = validating_data.loc[0::,'Item'::]

############AMPL#################
ampl = AMPL(Environment(ampl_dir))

index_list = []
Accuracy_list = []
for index in (range 1:1000)
    ampl.reset()
    tuning = ampl.getParameter("tuning")
    tuning.SetValues(0.00001*index)
    ampl.read(model_dir)
    ampl.readData(training_dat)
    ampl.solve()
    a = ampl.getVariable('a').getValues().toList()
    b = ampl.getVariable('b').value()

    #parsing the coefficients
    a_list = []
Exemple #22
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={("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
Exemple #23
0
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 17:20:23 2018

@author: donja
"""

from amplpy import AMPL, Environment

ampl = AMPL(Environment('D:\\amplide.mswin64\\amplide.mswin64'))
ampl.option['solver'] = 'cplexamp'
ampl.read('example.mod')  #read the model
ampl.eval('objective z; solve;')
ampl.display('z', 'roth', 'traditional', 'surplus')

pstring = """
objective function = {z}
bi-weekly roth contribution = ${roth}
bi-weekly traditional contribution = ${traditional}
surplus (amount left after optimal allocation) = ${surplus}
total (without surplus)  = ${total}
total (with surplus)  = ${totalS}
"""
z = ampl.getValue('z')
roth = ampl.getValue('roth')
traditional = ampl.getValue('traditional')
surplus = ampl.getValue('surplus')

annual_roth_amt = roth * 12 * 2
annual_traditional_amt = traditional * 12 * 2
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)
Exemple #25
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)

    # build the AMPL math model
    # 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 volume {COMMODITIES} > 0, < Infinity;
    param capacity {ARCS} >= 0;
    set SHIPMENT_OPTIONS within {COMMODITIES,ARCS};
    param cost {SHIPMENT_OPTIONS} >= 0, < Infinity;
    set INFLOW_INDEX within {COMMODITIES,NODES};
    param inflow {INFLOW_INDEX} > -Infinity, < Infinity;
    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] * volume[h] <= 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];
    """)
    # 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",
            "cost": "SHIPMENT_OPTIONS",
            "inflow": "INFLOW_INDEX"
        })
    # 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({
            ('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
Exemple #26
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'])
Exemple #27
0
def solve(dat):
    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)

    dat = input_schema.copy_to_ampl(dat, field_renamings={
            ("roster", "Grade"):"grade",
            ("positions", "Position Importance"): "position_importance",
            ("positions", "Position Group"): "position_group",
            ("player_ratings", "Rating"): "player_rating",
            ("innings", "Inning Group"): "inning_group",
            ("position_constraints", "Min Players"): "min_players",
            ("position_constraints", "Max Players"): "max_players"
        })

    ampl = AMPL()
    ampl.setOption('solver', 'gurobi')

    mod_str = """
    # Players and grades

    set PLAYERS;
    param grade {PLAYERS} symbolic;
    set GRADES = setof {pl in PLAYERS} grade[pl];
    set IN_GRADE {g in GRADES} = {pl in PLAYERS: grade[pl] = g};

    # Positions and position groups; player ratings

    set POSITIONS;
    param position_importance {POSITIONS};
    param position_group {POSITIONS} symbolic;
    set POSITION_GROUPS = setof {p in POSITIONS} position_group[p];
    set IN_POSITION_GROUP {pg in POSITION_GROUPS} = {p in POSITIONS: position_group[p] = pg};

    param player_rating {PLAYERS,POSITION_GROUPS};

    # Innings and inning groups; player limits

    set INNINGS;
    param inning_group {INNINGS} symbolic;
    set INNING_GROUPS = setof {i in INNINGS} inning_group[i];
    set IN_INNING_GROUP {ig in INNING_GROUPS} = {i in INNINGS: inning_group[i] = ig};

    set POSITION_CONSTRAINTS within {POSITION_GROUPS,INNING_GROUPS,GRADES};
    param min_players {POSITION_CONSTRAINTS};
    param max_players {POSITION_CONSTRAINTS};

    # Decision variables: 1 ==> assignment of a player to a position in an inning

    var Play {INNINGS,POSITIONS,PLAYERS} binary;

    # Objective function: Maximize desirability of the assignment

    maximize TotalImportance:
       sum {i in INNINGS, p in POSITIONS, pl in PLAYERS}
          position_importance[p] * player_rating[pl,position_group[p]] * Play[i,p,pl];

    # Exactly one player per position per inning

    subject to AllPositionsFilledPerInning {i in INNINGS, p in POSITIONS}:
       sum {pl in PLAYERS} Play[i,p,pl] = 1;

    # At most one possition per player per inning

    subject to AtMostOnePositionPerInning {i in INNINGS, pl in PLAYERS}:
       sum {p in POSITIONS} Play[i,p,pl] <= 1;

    # Total roster slots assigned, for listed combinations of
    # position group, inning group, and grade, must be within specified limits

    subject to MinMaxPlayers {(pg,ig,g) in POSITION_CONSTRAINTS}:
       min_players[pg,ig,g] <=
         sum {p in IN_POSITION_GROUP[pg], i in IN_INNING_GROUP[ig], pl in IN_GRADE[g]} Play[i,p,pl]
           <= max_players[pg,ig,g];
    """
    ampl.eval(mod_str)

    input_schema.set_ampl_data(dat, ampl, {"roster": "PLAYERS", "positions": "POSITIONS",
                                           "innings": "INNINGS", "position_constraints": "POSITION_CONSTRAINTS"})
    ampl.solve()

    if ampl.getValue("solve_result") != "infeasible":
        sln = solution_schema.TicDat()
        for (i,p,pl),x in ampl.getVariable("Play").getValues().toDict().items():
            if round(x[0]) > 0:
                sln.lineup[i,p] = pl
        sln.parameters["Total Cost"] = ampl.getObjective('TotalImportance').value()
        return sln
Exemple #28
0
def main(argc, argv):
    from amplpy import AMPL
    os.chdir(os.path.dirname(__file__) or os.curdir)
    try:
        ampl = AMPL()

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

        modelDirectory = os.path.join(
            argv[2] if argc == 3 else os.path.join('..', 'models'), 'tracking')

        # Load the AMPL model from file
        ampl.read(os.path.join(modelDirectory, 'tracking.mod'))
        # Read data
        ampl.readData(os.path.join(modelDirectory, 'tracking.dat'))
        # Read table declarations
        ampl.read(os.path.join(modelDirectory, 'trackingbit.run'))
        # Set tables directory (parameter used in the script above)
        ampl.getParameter('data_dir').set(modelDirectory)
        # Read tables
        ampl.readTable('assets')
        ampl.readTable('indret')
        ampl.readTable('returns')

        hold = ampl.getVariable('hold')
        ifinuniverse = ampl.getParameter('ifinuniverse')

        # Relax the integrality
        ampl.setOption('relax_integrality', True)
        # Solve the problem
        ampl.solve()
        objectives = list(obj for name, obj in ampl.getObjectives())
        assert objectives[0].value() == ampl.getObjective('cst').value()
        print("QP objective value", ampl.getObjective('cst').value())

        lowcutoff = 0.04
        highcutoff = 0.1

        # Get the variable representing the (relaxed) solution vector
        holdvalues = hold.getValues()
        toHold = []
        # For each asset, if it was held by more than the highcutoff,
        # forces it in the model, if less than lowcutoff, forces it out
        for value in holdvalues.getColumn('hold'):
            if value < lowcutoff:
                toHold.append(0)
            elif value > highcutoff:
                toHold.append(2)
            else:
                toHold.append(1)
        # uses those values for the parameter ifinuniverse, which controls
        # which
        # stock is included or not in the solution
        ifinuniverse.setValues(toHold)

        # Get back to the integer problem
        ampl.setOption('relax_integrality', False)
        # Solve the (integer) problem
        ampl.solve()
        print("QMIP objective value", ampl.getObjective('cst').value())
    except Exception as e:
        print(e)
        raise
Exemple #29
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)
Exemple #30
0
def main(argc, argv):
    # You can install amplpy with "python -m pip install amplpy"
    from amplpy import AMPL

    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'))
    """

    if argc > 1:
        ampl.set_option("solver", argv[1])

    model_directory = os.path.join(
        argv[2] if argc == 3 else os.path.join("..", "models"), "tracking")

    # Load the AMPL model from file
    ampl.read(os.path.join(model_directory, "tracking.mod"))
    # Read data
    ampl.read_data(os.path.join(model_directory, "tracking.dat"))
    # Read table declarations
    ampl.read(os.path.join(model_directory, "trackingbit.run"))
    # Set tables directory (parameter used in the script above)
    ampl.get_parameter("data_dir").set(model_directory)
    # Read tables
    ampl.read_table("assets")
    ampl.read_table("indret")
    ampl.read_table("returns")

    hold = ampl.get_variable("hold")
    ifinuniverse = ampl.get_parameter("ifinuniverse")

    # Relax the integrality
    ampl.set_option("relax_integrality", True)

    # Solve the problem
    ampl.solve()
    solve_result = ampl.get_value("solve_result")
    if solve_result != "solved":
        raise Exception(
            "Failed to solve (solve_result: {})".format(solve_result))

    objectives = list(obj for name, obj in ampl.get_objectives())
    assert objectives[0].value() == ampl.get_objective("cst").value()
    print("QP objective value", ampl.get_objective("cst").value())

    lowcutoff = 0.04
    highcutoff = 0.1

    # Get the variable representing the (relaxed) solution vector
    holdvalues = hold.get_values()
    to_hold = []
    # For each asset, if it was held by more than the highcutoff,
    # forces it in the model, if less than lowcutoff, forces it out
    for value in holdvalues.get_column("hold.val"):
        if value < lowcutoff:
            to_hold.append(0)
        elif value > highcutoff:
            to_hold.append(2)
        else:
            to_hold.append(1)
    # uses those values for the parameter ifinuniverse, which controls
    # which stock is included or not in the solution
    ifinuniverse.set_values(to_hold)

    # Get back to the integer problem
    ampl.set_option("relax_integrality", False)

    # Solve the (integer) problem
    ampl.solve()
    solve_result = ampl.get_value("solve_result")
    if solve_result != "solved":
        raise Exception(
            "Failed to solve (solve_result: {})".format(solve_result))

    print("QMIP objective value", ampl.get_objective("cst").value())