def test_netflow_amplpy(self): dat = _netflow_input_pdf.copy_to_ampl(_netflow_dat, field_renamings={ ("arcs", "Capacity"): "capacity", ("cost", "Cost"): "cost", ("inflow", "Quantity"): "inflow" }) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_netflow_mod) _netflow_input_pdf.set_ampl_data(dat, ampl, { "nodes": "NODES", "arcs": "ARCS", "commodities": "COMMODITIES" }) ampl.solve() sln = _netflow_sln_pdf.copy_from_ampl_variables({ ('flow', 'Quantity'): ampl.getVariable("Flow") }) sln.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('TotalCost').value() ] self.assertTrue(_netflow_sln_pdf._same_data(sln, _netflow_sln_pandat)) sln2 = _netflow_sln_pdf.copy_from_ampl_variables({ ('flow', 'Quantity'): (ampl.getVariable("Flow"), lambda v: v > 30) }) sln3 = _netflow_sln_pdf.copy_from_ampl_variables({ ('flow', 'Quantity'): (ampl.getVariable("Flow"), lambda v: 0 < v <= 30) }) sln2.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('TotalCost').value() ] sln3.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('TotalCost').value() ] self.assertTrue(len(sln2.flow) and len(sln3.flow)) self.assertFalse(_netflow_sln_pdf._same_data(sln, sln2)) self.assertFalse(_netflow_sln_pdf._same_data(sln, sln2)) sln2.flow = sln2.flow.append(sln3.flow) self.assertTrue(_netflow_sln_pdf._same_data(sln, sln2))
def solve(self, prob=None): try: ampl_env = amplpy.Environment() ampl = amplpy.AMPL(ampl_env) ampl.setOption('solver', 'gurobi') model_dir = os.path.normpath('./ampl_models') ampl.read(os.path.join(model_dir, '/ampl_m.mod')) departs=['1','2','3','4'] arrivees=['1','2','3','4'] df = amplpy.DataFrame('depart') df.setColumn(self,'depart') ampl.setData(df, departs) df = amplpy.DataFrame('arrivee') df.setColumn(self,'arrivee') ampl.setData(df, arrivees) df = amplpy.DataFrame(('depart','arrivee'), 'dst') df.setValues({ (depart, arrivee): self.matrice[i][j] for i, depart in enumerate(departs) for j, arrivee in enumerate(arrivees)}) ampl.setData(self, df) ampl.solve() self.done = True print('Objective: {}'.format(ampl.getObjective('Total_Cost').value())) solution = ampl.getVariable('Buy').getValues() print('Solution retournée: \n' + str(solution)) except Exception as error: print(error) raise
def solve(self): #----------Initialisation de l'environnement----------# ampl_env = amplpy.Environment() ampl_path = os.path.normpath(emplacement_AMPL) ampl_env = amplpy.Environment(ampl_path) ampl = amplpy.AMPL(ampl_env) #--------------------Configuration--------------------# ampl.setOption('solver', 'cplex') #-------------------Lecture du .mod-------------------# model_dir = os.path.normpath(emplacement_AMPL) ampl.read(os.path.join(model_dir, model)) #----------------------Paramètre----------------------# """ Param n: Nombre de département """ df = ampl.getParameter('n') df.set(self.n) """ Param m: Nombre maximal de rangée """ df = ampl.getParameter('m') df.set(self.m) """ Param d: Largeur des rangées """ df = ampl.getParameter('d') df.set(self.d) """ Param L: Somme des longueurs de tous les département """ df = ampl.getParameter('L') df.set(self.L) """ Coût du déménagement d'un département de sa position actuelle => sa nouvelle position """ df = ampl.getParameter('cd') df.set(self.cd) """ Param Lon_u: Longueur MAX de l'usine """ df = ampl.getParameter('Lon_u') df.set(self.lon_u) """ Param Lar_u: Largeur MAX de l'usine """ df = ampl.getParameter('Lar_u') df.set(self.lar_u) """ Set K: Ensemble des département """ df = amplpy.DataFrame('K') df.setColumn('K', self.set_K) ampl.setData(df, 'K') """ Param lon: Longueur du département k """ df = amplpy.DataFrame("K", "lon") df.setValues({I: self.lon[i] for i, I in enumerate(self.set_K)}) ampl.setData(df) """ Position horizontale actuelle du département k """ df = amplpy.DataFrame("K", "Xa") df.setValues({I: self.Xa[i] for i, I in enumerate(self.set_K)}) ampl.setData(df) """ Position verticale actuelle du département k """ df = amplpy.DataFrame("K", "Ya") df.setValues({I: self.Ya[i] for i, I in enumerate(self.set_K)}) ampl.setData(df) """ Param c: Coût du déplacement de i => j """ df = amplpy.DataFrame(('I', 'J'), 'c') df.setValues({(I, J): self.poids[(len(self.set_K)) * i + j] for i, I in enumerate(self.set_K) for j, J in enumerate(self.set_K)}) ampl.setData(df) ampl.solve() #----------------------Variables----------------------# """ Var X: Position horizontale du département i """ X = ampl.getVariable('X') X_val = X.getValues() X_val_dic = X_val.toDict() """ Var Y: Position verticale du département i """ Y = ampl.getVariable('Y') Y_val = Y.getValues() Y_val_dic = Y_val.toDict() """ Var Aij: Position relative; =1 si i est dans la même rangée à la gauche de j, 0 sinon """ A = ampl.getVariable('Aij') A_val = A.getValues() A_val_dic = A_val.toDict() """ Var Bij: Position relative; =1 si i et j ne sont pas dans la même rangée et que i est en dessous de j, 0 sinon """ B = ampl.getVariable('Bij') B_val = B.getValues() B_val_dic = B_val.toDict() """ Var dx: Distance horizontale entre i et j """ dx = ampl.getVariable('dx') dx_val = dx.getValues() dx_val_dic = dx_val.toDict() """ Var dy: Distance verticale entre i et j """ dy = ampl.getVariable('dy') dy_val = dy.getValues() dy_val_dic = dy_val.toDict() """ Var ddx: Distance de déménagement horizontale """ ddx = ampl.getVariable('ddx') ddx_val = ddx.getValues() ddx_val_dic = ddx_val.toDict() """ Var dxy: Distance de déménagement verticale """ ddy = ampl.getVariable('ddy') ddy_val = ddy.getValues() ddy_val_dic = ddy_val.toDict() return (X_val_dic, Y_val_dic, A_val_dic, B_val_dic, dx_val_dic, dy_val_dic, ddx_val_dic, ddy_val_dic, X_val, Y_val, A_val, B_val, dx_val, dy_val, ddx_val, ddy_val, model)
def solve(racingdata): ampl_env = amplpy.Environment() ampl = amplpy.AMPL(ampl_env) ampl.setOption('solver', 'gurobi') ampl.setOption( 'gurobi_options', "mipfocus 1" "relax 0" "timelim 7200 " "tunetimelimit 60 ") model_dir = os.path.normpath('./ampl_models/Trend3D') ampl.read(os.path.join(model_dir, 'f1aiTyre.mod')) listlaps = list(range(1, racingdata.totalLaps + 1)) listwear = list( range(1, (min(len(racingdata.lapData[0]), len(racingdata.lapData[1]), len(racingdata.lapData[2])) + 1))) listtyres = racingdata.compounds.values() dftyres = amplpy.DataFrame('tyres') dftyres.setColumn('tyres', listtyres) ampl.setData(dftyres, 'tyres') dfwear = amplpy.DataFrame('stints') dfwear.setColumn('stints', listwear) ampl.setData(dfwear, 'stints') dflaps = amplpy.DataFrame('laps') dflaps.setColumn('laps', listlaps) ampl.setData(dflaps, 'laps') totallaps = ampl.getParameter('totalLaps') totallaps.set(racingdata.totalLaps) tyrelifespan = ampl.getParameter('tyreLifeSpan') tyrelifespan.set(len(listwear)) pittime = ampl.getParameter('pitTime') pittime.set(racingdata.pitTime) df = amplpy.DataFrame(('tyres', 'wear'), 'usage') df.setValues({(tyre, wear): racingdata.futureTyreUsageData[i][j] for i, tyre in enumerate(listtyres) for j, wear in enumerate(listwear)}) ampl.setData(df) df = amplpy.DataFrame('tyres', ['avg', 'coeff']) df.setValues(racingdata.trendlinedata()) ampl.setData(df) print(racingdata.futureTyreUsageData) ampl.solve() solution = Decision(racingdata) pit = ampl.getVariable('pit') dfpit = pit.getValues() chosen = {int(row[1]): row[0] for row in dfpit if row[2] == 1} solution.pitDecision = chosen compound = ampl.getVariable('compound') dfcompound = compound.getValues() chosen = { int(row[2]): [row[0], int(row[1])] for row in dfcompound if row[3] == 1 } solution.compoundStrategy = chosen time = ampl.getVariable('time') dftime = time.getValues() for row in dftime: for k, v in racingdata.compounds.items(): if v == row[0]: solution.lapTimes[k].append(row[2]) return solution
def test_diet_amplpy(self): dat = _diet_input_pdf.copy_to_ampl( _diet_dat, field_renamings={ ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "n_min", ("categories", "Max Nutrition"): "n_max", ("nutrition_quantities", "Quantity"): "amt", ("nutrition_quantities", "Other Quantity"): "other_amt" }) self.assertTrue({"n_min", "n_max"}.issubset(dat.categories.toPandas().columns)) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_diet_mod) _diet_input_pdf.set_ampl_data(dat, ampl, { "categories": "CAT", "foods": "FOOD" }) ampl.solve() sln = _diet_sln_pdf.copy_from_ampl_variables({ ("buy_food", "Quantity"): ampl.getVariable("Buy"), ("consume_nutrition", "Quantity"): ampl.getVariable("Consume") }) sln.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('Total_Cost').value() ] _missing_field_pdf = PanDatFactory( **{ t: [pks, (["Max Nutrition"] if t == "categories" else dfs)] for t, (pks, dfs) in _diet_input_pdf.schema().items() }) dat = _missing_field_pdf.copy_to_ampl( _diet_dat, field_renamings={ ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "n_min", ("categories", "Max Nutrition"): "n_max", ("nutrition_quantities", "Quantity"): "amt", ("nutrition_quantities", "Other Quantity"): "other_amt" }) self.assertTrue({"n_min", "n_max"}.issubset(dat.categories.toPandas().columns)) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_diet_mod) _diet_input_pdf.set_ampl_data(dat, ampl, { "categories": "CAT", "foods": "FOOD" }) ampl.solve() sln_2 = _diet_sln_pdf.copy_from_ampl_variables({ ("buy_food", "Quantity"): ampl.getVariable("Buy"), ("consume_nutrition", "Quantity"): ampl.getVariable("Consume") }) sln_2.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('Total_Cost').value() ] self.assertTrue(_diet_sln_pdf._same_data(sln, sln_2)) diet_dat_two = _diet_input_pdf.copy_to_tic_dat(_diet_dat) for r in diet_dat_two.nutrition_quantities.values(): r["Quantity"], r["Other Quantity"] = [0.5 * r["Quantity"]] * 2 diet_dat_two = pan_dat_maker(_diet_input_pdf.schema(), diet_dat_two) dat = _diet_input_pdf.copy_to_ampl( diet_dat_two, field_renamings={ ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "n_min", ("categories", "Max Nutrition"): "n_max", ("nutrition_quantities", "Quantity"): "amt", ("nutrition_quantities", "Other Quantity"): "other_amt" }) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_diet_mod) _diet_input_pdf.set_ampl_data(dat, ampl, { "categories": "CAT", "foods": "FOOD" }) ampl.solve() self.assertTrue("solved" == ampl.getValue("solve_result")) sln = _diet_sln_pdf.copy_from_ampl_variables({ ("buy_food", "Quantity"): ampl.getVariable("Buy"), ("consume_nutrition", "Quantity"): ampl.getVariable("Consume") }) sln.parameters.loc[0] = [ 'Total Cost', ampl.getObjective('Total_Cost').value() ] self.assertTrue( _diet_sln_pdf._same_data(sln, _diet_sln_pandat, epsilon=1e-5)) dat = _diet_input_pdf.copy_to_ampl( _diet_dat, { ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "", ("categories", "Max Nutrition"): "n_max" }, ["nutrition_quantities"]) self.assertFalse(hasattr(dat, "nutrition_quantities")) self.assertTrue({"n_min", "n_max"}.intersection( dat.categories.toPandas().columns) == {"n_max"}) sln_tdf_2 = PanDatFactory(buy_food=[["Food"], ["Quantity"]], consume_nutrition=[["Category"], []]) sln_tdf_2.set_default_value("buy_food", "Quantity", 1) sln_2 = sln_tdf_2.copy_from_ampl_variables({ ("buy_food", False): ampl.getVariable("Buy"), ("consume_nutrition", False): (ampl.getVariable("Consume"), lambda x: x < 100) }) self.assertTrue(set(sln_2.buy_food["Quantity"]) == {1}) self.assertTrue( set(sln_2.buy_food["Food"]) == set(sln.buy_food["Food"])) self.assertTrue(len(sln_2.consume_nutrition) > 0) self.assertTrue( set(sln_2.consume_nutrition["Category"]) == set(sln.consume_nutrition[sln.consume_nutrition["Quantity"] < 100] ["Category"])) diet_dat_two = _diet_input_pdf.copy_to_tic_dat(_diet_dat) diet_dat_two.categories["calories"] = [0, 200] diet_dat_two = pan_dat_maker(_diet_input_pdf.schema(), diet_dat_two) dat = _diet_input_pdf.copy_to_ampl( diet_dat_two, field_renamings={ ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "n_min", ("categories", "Max Nutrition"): "n_max", ("nutrition_quantities", "Quantity"): "amt", ("nutrition_quantities", "Other Quantity"): "other_amt" }) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_diet_mod) _diet_input_pdf.set_ampl_data(dat, ampl, { "categories": "CAT", "foods": "FOOD" }) ampl.solve() self.assertTrue("infeasible" == ampl.getValue("solve_result")) diet_dat_two = _diet_input_pdf.copy_to_tic_dat(_diet_dat) for v in diet_dat_two.categories.values(): v["Max Nutrition"] = float("inf") diet_dat_two.foods["hamburger"] = -1 diet_dat_two = pan_dat_maker(_diet_input_pdf.schema(), diet_dat_two) dat = _diet_input_pdf.copy_to_ampl( diet_dat_two, field_renamings={ ("foods", "Cost"): "cost", ("categories", "Min Nutrition"): "n_min", ("categories", "Max Nutrition"): "n_max", ("nutrition_quantities", "Quantity"): "amt", ("nutrition_quantities", "Other Quantity"): "other_amt" }) ampl = amplpy.AMPL() ampl.setOption('solver', 'gurobi') ampl.eval(_diet_mod) _diet_input_pdf.set_ampl_data(dat, ampl, { "categories": "CAT", "foods": "FOOD" }) ampl.solve() self.assertTrue("unbounded" == ampl.getValue("solve_result"))
import amplpy import pandas as pd import matplotlib as plt ampl = amplpy.AMPL( amplpy.Environment(r'C:\Users\diego\Documents\Diego_Aldunate\iPre\AMPL')) ampl.read( r'C:\Users\diego\Documents\Diego_Aldunate\iPre\CS_2020_2\Modelo_AMPL\modelo_nl_costo.mod' ) ampl.readData( r'C:\Users\diego\Documents\Diego_Aldunate\iPre\CS_2020_2\Modelo_AMPL\datos_precio_Fijo.dat' ) ampl.setOption('solver', 'knitro') #print(ampl.getOption('solver')) ampl.solve() fo = ampl.getObjective('FO') #print(fo) print("Valor de Funcion Objetivo es:" + str(fo.value())) produccion = ampl.getVariable('P') #indice k y t print(produccion.getValues()) produccion = ampl.var['P'].getValues() print(produccion) prod = list(produccion.getColumn('P.val')) print(prod) produccion = ampl.var['P'].getValues().toPandas() produccion.index = pd.MultiIndex.from_tuples(produccion.index)
import amplpy import pandas as pd import Modificar_Parametros import Generar_Dataframe import Variables import Graficar ampl = amplpy.AMPL(amplpy.Environment(r'C:\Program Files\AMPL')) #ampl = amplpy.AMPL(amplpy.Environment(r'C:\Users\diego\Documents\Diego_Aldunate\iPre\AMPL')) ampl.read( r'C:\Users\diego\Documents\Diego_Aldunate\iPre\CS_2020_2\Modelo_AMPL\modelo_nl_costo.mod' ) ampl.readData( r'C:\Users\diego\Documents\Diego_Aldunate\iPre\CS_2020_2\Modelo_AMPL\datos_precio_Fijo.dat' ) ampl.setOption('solver', 'knitro') #print(ampl.getOption('solver')) #### Definir Parametros ### hold = ampl.getParameter('hold').getValues().toPandas() hold_df = Generar_Dataframe.Generar(hold) alpha = ampl.getParameter('alfa').getValues().toPandas() alpha_df = Generar_Dataframe.Generar(alpha) beta = ampl.getParameter('beta').getValues().toPandas() beta_df = Generar_Dataframe.Generar(beta) # Iteracion 0# funcion_objetivo = [] ampl.solve()