Hi support
I need your help. I want to save the iteration result in file txt but I don’t know how do it. I’m working in AMPL API Python. Would you help me.
Hi support
I need your help. I want to save the iteration result in file txt but I don’t know how do it. I’m working in AMPL API Python. Would you help me.
Hi @Oscar_Romero,
What do you mean by saving the iteration result? Do you want to save the current solution in a file?
You can for instance save the values for all variable in a csv file as follows:
ampl.get_data("_varname, _var").to_pandas().to_csv("solution.csv", index=False)
If you just want non-zeros, you can do that as follows:
ampl.get_data("{i in 1.._nvars: _var[i] != 0} (_varname[i], _var[i])").to_pandas().to_csv("nonzeros.csv", index=False)
Dear fdabrandao
I need only iteration like best bound, Gap, best integer, etc. In other words, all the information that appears on the console and that you can save in a file.
Hi @Oscar_Romero,
Would storing the solver output be enough? You can retrieve it with the latest version of amplpy as follows:
output = ampl.solve(return_output=True)
open("output.txt", "w").write(output)
In case you need specific information to be extracted you can either parse this output or use the options to returning solve information such as time and work which is available for some solvers such as Gurobi.
Thank fdabrandao for answer but I have a problem with the code.
I am trying to save the console information in a txt file and at the same time have the console information visible. I used your codes, but I think I put something wrong and I can’t find it. Can you help me, please?. These are the codes:
for i in numbers_to_include:
demanda_valor = {(1,1): i*1000, (1,2): i*1000, (2,1): i*1000, (2,2): i*1000}
csetup_valores = {1: 3370786, 2: 3932584}
cprod_valores = {(1,1): 38499, (1,2): 33804, (2,1): 34624, (2,2): 30402}
ck_valores = {(1,1): 1404494, (1,2): 1404494, (2,1): 1404494, (2,2): 1404494, (3,1): 1966292, (3,2): 1966292}
cinv_valores = {(1,1): 139, (1,2): 139, (2,1): 125, (2,2): 125}
configurar_parametros(ampl, csetup_valores, cprod_valores, ck_valores, cinv_valores, demanda_valor)
# Guardar la salida en un archivo y restaurar la salida estándar
try:
output = ampl.solve(return_output=True)
with open("output.txt", "w") as output_file:
output_file.write(output)
result = ampl.get_value("solve_result")
if result == "solved" or result == "limit":
print(result) # Esta información se imprimirá en la consola
# Asegurarse de que la solución final se guarda
guardar_resultados_en_excel(ampl, workbook, str(i * 1000), demanda_valor)
except Exception as e:
print(f"Error: {e}")
nombre_archivo = f"Resultado_K_{parametros['K']}_A_{parametros['A']}_S_{parametros['S']}_Dda_4.xls"
workbook.save(nombre_archivo)
ampl.close()
In relation to your query, I take this opportunity to ask, is it possible to capture the results after some time has passed while it continues iterating? As an example, I leave the following code that does not do what I expect, but you can understand that is what I am looking for. Also, mention that if 100 seconds have passed, capture the information and save it in a sheet, and then for 200 seconds do the same, and so on.
def main():
modelo_path = "C:\\Users\\oscar\\eclipse-workspace\\LastInstance\\Last_Model.mod"
datos_path = "C:\\Users\\oscar\\eclipse-workspace\\LastInstance\\LastData1y2.dat"
solver_path = "D:\\Software Respaldo\\AMPL_2023\\ampl_mswin64\\cplex.exe"
opciones_solver = f"timing=1 time={parametros['Timelimit']} NodeFile=3 mipdisplay=2 threads=0 return_mipgap=1"
ampl = inicializar_ampl(modelo_path, datos_path, solver_path, opciones_solver, parametros)
workbook = Workbook()
workbook.remove(workbook.active) # Eliminar la hoja predeterminada
numbers_to_include = [4]
intervalo_guardado = 100 # segundos
tiempo_inicial = time.time()
siguiente_guardado = intervalo_guardado
for i in numbers_to_include:
demanda_valor = {(1, 1): i * 1000, (1, 2): i * 1000, (2, 1): i * 1000, (2, 2): i * 1000}
csetup_valores = {1: 3370786, 2: 3932584}
cprod_valores = {(1, 1): 38499, (1, 2): 33804, (2, 1): 34624, (2, 2): 30402}
ck_valores = {(1, 1): 1404494, (1, 2): 1404494, (2, 1): 1404494, (2, 2): 1404494, (3, 1): 1966292,
(3, 2): 1966292}
cinv_valores = {(1, 1): 139, (1, 2): 139, (2, 1): 125, (2, 2): 125}
configurar_parametros(ampl, csetup_valores, cprod_valores, ck_valores, cinv_valores, demanda_valor)
ampl.solve() # Resolver el modelo
while True:
tiempo_transcurrido_ampl = ampl.get_total_solve_elapsed_time()
if tiempo_transcurrido_ampl >= siguiente_guardado:
guardar_resultados_en_excel(ampl, workbook, f"Resultados_{int(tiempo_transcurrido_ampl)}s",
demanda_valor)
siguiente_guardado += intervalo_guardado
# Salir del bucle si se alcanza el límite de tiempo
if tiempo_transcurrido_ampl >= {parametros['Timelimit']}:
break
time.sleep(1) # Esperar un segundo antes de volver a verificar
# Asegurarse de que la solución final se guarda
guardar_resultados_en_excel(ampl, workbook, f"Resultados_{int(tiempo_transcurrido_ampl)}s", demanda_valor)
nombre_archivo = f"Resultado_K_{parametros['K']}_A_{parametros['A']}_S_{parametros['S']}_Dda_4.xls"
workbook.save(nombre_archivo)
ampl.close()
if __name__ == "__main__":
main()
Thanks for asking, I am also facing same issue.
Hi @Oscar_Romero,
Sorry for the late reply. When you use ampl.solve(return_output=True)
, it only returns the output and does not display it. If you want to have it as a string and also display it you need to add a print(output)
line afterwards.
Hi @Oscar_Romero,
Do you mean storing the best solution obtained so far while still optimizing? It is possible using our solver interfaces with callbacks (available for Gurobi, CPLEX, Xpress, and COPT) as it would be necessary to access the solver object to extract the solution. You can see for instance at Example: callbacks_first — ampl::ampls-api 0.1 documentation. However, it may be a big switch if that is all you need to record. We can create a new example for this type of use case if that would help.
Hi @emilymoore,
Did any of my answers above, answer you question?