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 copy_to_ampl(self, pan_dat, field_renamings = None, excluded_tables = None): """ copies the pan_dat object into a new pan_dat object populated with amplpy.DataFrame objects performs a deep copy :param pan_dat: a PanDat object :param field_renamings: dict or None. If fields are to be renamed in the copy, then a mapping from (table_name, field_name) -> new_field_name If a data field is to be omitted, then new_field can be falsey table_name cannot refer to an excluded table. (see below) field_name doesn't have to refer to a field to an element of self.data_fields[t], but it doesn't have to refer to a column in the pan_dat.table_name DataFrame :param excluded_tables: If truthy, a list of tables to be excluded from the copy. Tables without primary key fields are always excluded. :return: a deep copy of the tic_dat argument into amplpy.DataFrames """ verify(amplpy, "amplpy needs to be installed in order to enable AMPL functionality") msg = [] verify(self.good_pan_dat_object(pan_dat, msg.append), "pan_dat not a good object for this factory : %s"%"\n".join(msg)) verify(not excluded_tables or (containerish(excluded_tables) and set(excluded_tables).issubset(self.all_tables)), "bad excluded_tables argument") copy_tables = {t for t in self.all_tables if self.primary_key_fields[t]}.\ difference(excluded_tables or []) field_renamings = field_renamings or {} verify(dictish(field_renamings), "invalid field_renamings argument") for k,v in field_renamings.items(): verify(containerish(k) and len(k) == 2 and k[0] in copy_tables and k[1] in getattr(pan_dat, k[0]).columns and ((v and utils.stringish(v)) or (not bool(v) and k[1] not in self.primary_key_fields[k[0]])), "invalid field_renamings argument %s:%s"%(k,v)) class AmplPanDat(object): def __repr__(self): return "td:" + tuple(copy_tables).__repr__() rtn = AmplPanDat() for t in copy_tables: rename = lambda f : field_renamings.get((t, f), f) df_ampl = amplpy.DataFrame(index=tuple(map(rename, self.primary_key_fields[t]))) for f in self.primary_key_fields[t]: df_ampl.setColumn(rename(f), list(getattr(pan_dat, t)[f])) for f in {f for _t,f in field_renamings if _t == t}.union(self.data_fields[t]): if rename(f): df_ampl.addColumn(rename(f), list(getattr(pan_dat, t)[f])) setattr(rtn, t, df_ampl) return rtn
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