Search code examples
pythonclassinstancepyomo

How can I acces to my results from a class solution with pyomo?


I just want to explain that I'm super new to python I want to acces the results from my problem:

I have this, and its running I just want to access my results so that I can compare the two types of batteries that I have How can I have the Results for B1 and for B2 that is being solved for?

Here is one of my variables declared:

model.ach = Var(model.t , domain=NonNegativeReals, bounds=(0,1)) #Rate of charging

Here is a dictonary to build the demand

demand = Jan[:24*4*5]
t = range(len(demand))
demand_dict = {}
for tt, dd in zip(t, demand):
demand_dict[tt] = dd

Here is declared fixed values:

 cosP = 12.34
 cosE=0.0606
 cosF=0.02673   

After my objective function is declared in my abstract model I use a class to have different kinds of Batteries:

class Battery:
      def __init__(self, n, Emax, Emin, cap):
      self.n=n
      self.Emax=Emax
      self.Emin=Emin
     self.cap=cap


B1=Battery(0.8,3800,400,500)
B2=Battery(0.8,7600,800,1000)
Batts=[B1,B2]

Now I'm interating through the two classes my model

Results=[]
Instance=[]
for b in Batts:
        data = {None: {'cosP': {None: cosP},
               't': {None: t},
               'cosE': {None: cosE},
               'cosF':{None:cosF},
               'n':{None: b.n},
               'Emax':{None:b.Emax}, #kWh max capacity
               'Emin':{None:b.Emin}, #kWh min capacity
               'cap':{None:b.cap},
               'dem': demand_dict
              }
        }
        instance=model.create_instance(data)
        opt=SolverFactory('glpk')
        results = opt.solve(instance)
Results.append(results)
Instance.append(instance)

I'm, trying to access for example a value previously delcared ach I tried this:

for t in instance.t:
    ach.append(instance.ach[t].value)

But that only gives me acces to the last runt i.e b2 in Battery. How do I access other values assuming I might have multiples b's


Solution

  • When you want to get the result of one of your variable, simply do

    print(instance.X[indice1, indice2].value) #for indexed var objects
    

    or

    print(instance.X.value) #for non-indexed var objects
    

    where indice1 and indice2 are the indices that is part of your variable index, and where X is the name of your variable.

    The use of print is only to show the result, and the value of your variable can be used in Python directly if you don't use print.

    Edit: If you want to access the value of all variables, I recommend you the following question: Pyomo: Access Solution From Python Code