0

I'm trying to output the model variables after solving the optimization. I however would like only the variables values to go into the output file as opposed to the whole model. (It's a very large model with many large constraints and I would do better cutting down to just what I need)

I've tried:

(1) one shot print call:

model.component_objects(Var, descend_into=True).pprint(filename='fin_soln.txt')

(2) iterative printing (with appending .txt files being the next step)

f = open("fin_soln_2.txt","a+")
for v in model.component_objects(Var, descend_into=True):
    print("FOUND VAR:" + v.name)
    f.write("FOUND VAR:" + v.name + "\n")
    v.pprint(filename=(v.name +'.txt'))
f.close()

As there are dozens of variables and the model is still being developed I would like something which is flexible and I don't have to keep updating as i add/delete variables from the model.

Thank you for your help.

mike h
  • 1
  • 2
  • Looks like pprint with variables doesn't have filename as an option based on https://buildmedia.readthedocs.org/media/pdf/pyomo/stable/pyomo.pdf. So i think that's why approaches don't currently work. At this point im guessing my best bet is to output the whoile thing and then write python code to delete the unwanted bits. – mike h Aug 15 '19 at 20:41

1 Answers1

0

Maybe something like this would work:

textbuffer = StringIO()
for v in model.component_objects(Var, descend_into=True):
    v.pprint(textbuffer)
    textbuffer.write('\n')

with open('filename.txt', 'w') as outputfile:
    outputfile.write(textbuffer.getvalue())
Qi Chen
  • 1,648
  • 1
  • 10
  • 19