TypeError: Невозможно вычислить значение массива параметров

Я создал простую абстрактную модель и хотел предварительно решить ее. Вот моя модель:

from __future__ import division 

from pyomo.environ import *
from pyomo.opt import SolverFactory

model=AbstractModel()

opt=SolverFactory('ipopt')

#Sets
model.i=Set(initialize=['conv','effic','hybrid','elec'],ordered=True,doc='car  types')
model.iter=RangeSet(0,1000)
model.ir=Set(within=model.iter,ordered=True)
model.j=Set(initialize=model.i) 

#Parameter initialize

def lamda_init(model):
    return model.lamdalo

def mu_init(model):
    return model.mulo

def shares_init(model,i):
    return model.base[i]

def cost_init(model,i):
    return model.pr[i]+ model.lamda*model.em[i]+ model.mu(1-model.type[i])

#Parameters
model.pr=Param(model.i,initialize=    {'conv':12,'effic':15,'hybrid':25,'elec':45},mutable=True,doc='levelized cost of     car EUR per 100km')
model.base=Param(model.i,initialize= {'conv':0.80,'effic':0.07,'hybrid':0.10,'elec':0.03},mutable=True,doc='shares of car types in base year')
model.em=Param(model.i,initialize={'conv':10,'effic':5,'hybrid':1,'elec':0},mutable=True,doc='emissions kgCO2 per 100km')
model.type=Param(model.i,initialize={'conv':0,'effic':0,'hybrid':0,'elec':1},mutable=True,doc='compliance with promoted car type')
model.gamma=Param(initialize=-2.5,mutable=True,doc='exponent of discrete choice')
model.lamdalo=Param(initialize=0,mutable=True,doc='min dual value of emission constraint measured as additional cost')
model.lamda=Param(initialize=lamda_init,mutable=True,doc='dual value of emission constraint measured as additional cost')
model.lamdaup=Param(initialize=1000,mutable=True,doc='max dual value of emission constraint measured as additional cost')
model.mulo=Param(initialize=0,mutable=True,doc='dual value of desired car type measured as additional cost')
model.mu=Param(initialize=mu_init,mutable=True,doc='dual value of desired car type measured as additional cost')
model.muup=Param(initialize=1000,mutable=True,doc='dual value of desired car type measured as additional cost')
model.CO2goal=Param(initialize=0.9,mutable=True,doc='target of emissions')
model.cargoal=Param(initialize=0.50,mutable=True,doc='target of share of promoted car type')
model.CO2perf=Param(mutable=True,doc='performance for emissions')
model.carperf=Param(mutable=True,doc='performance in terms of share of promoted car type')
model.count=Param(mutable=True,doc='counter of model runs -iterations')
model.count1=Param(mutable=True)
model.count2=Param(mutable=True)
model.conv=Param(mutable=True,doc='convergence criterion')
model.tolerance=Param(initialize=10**-3,mutable=True,doc='tolerance of convergence')
model.maxiter=Param(initialize=200,mutable=True)
model.report=dict()

#Variables
model.shares=Var(model.i,initialize=shares_init,within=NonNegativeReals,doc='shares of technologies')
model.cost=Var(model.i,initialize=cost_init,within=NonNegativeReals,doc='generalized unit cost')


def eqobj_rule(model):
    return 0
model.obj=Objective(rule=eqobj_rule,doc='dummy objective')

def eq1_rule(model,i):
    return model.shares[i]==model.base[i]*model.cost[i]**model.gamma/sum(model.base[j]*model.cost[j]**model.gamma for j in model.j)

model.eq1=Constraint(model.i,rule=eq1_rule)

def eq2_rule(model,i):
    return model.cost[i]==model.pr[i]+model.lamda*model.em[i]+model.mu*(1-model.type[i])
model.eq2=Constraint(model.i,rule=eq2_rule)

model.count=0
model.conv=1000
instance=model.create_instance()

for i in instance.iter:
    if i==instance.count:
        instance.ir.add(i)
    else:
        pass

results= opt.solve(instance)

Но когда я запускаю его, возникает следующая ошибка:

TypeError                                 Traceback (most recent call last)
<ipython-input-92-5dc9cea3a41f> in <module>()
     75 display(instance)
     76 
---> 77 results= opt.solve(instance)
     78 
     79 def twocarpolicies_sub(model):

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\opt\base\solvers.pyc in     solve(self, *args, **kwds)
    579             initial_time = time.time()
    580 
--> 581             self._presolve(*args, **kwds)
    582 
    583             presolve_completion_time = time.time()

C:\Users\irini\Anaconda2\lib\site-     packages\pyomo\solvers\plugins\solvers\ASL.pyc in _presolve(self, *args, **kwds)
    176             self._instance = args[0]
    177             xfrm = TransformationFactory('mpec.nl')
--> 178             xfrm.apply_to(self._instance)
    179             if     len(self._instance._transformation_data['mpec.nl'].compl_cuids) == 0:
    180                 # There were no complementarity conditions

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\core\base\plugin.pyc in apply_to(self, model, **kwds)
    328         if not hasattr(model, '_transformation_data'):
    329             model._transformation_data = TransformationData()
--> 330         self._apply_to(model, **kwds)
    331 
    332     def create_using(self, model, **kwds):

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\mpec\plugins\mpec4.pyc in     _apply_to(self, instance, **kwds)
     42         free_vars = {}
     43         id_list = []
---> 44         for vdata in instance.component_data_objects(Var,     active=True, sort=SortComponents.deterministic):
     45             id_list.append( id(vdata) )
     46             free_vars[id(vdata)] = vdata

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\core\base\block.pyc in      component_data_objects(self, ctype, active, sort, descend_into, descent_order)
   1198                 sort=sort,
   1199                 descend_into=descend_into,
-> 1200                 descent_order=descent_order)
   1201         else:
   1202             block_generator = (self,)

 C:\Users\irini\Anaconda2\lib\site-packages\pyomo\core\base\block.pyc in    block_data_objects(self, active, sort, descend_into, descent_order)
   1269                                    active=active,
   1270                                    sort=sort,
-> 1271                                    traversal=descent_order)
   1272 
   1273     def _tree_iterator(self,

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\core\base\block.pyc in _tree_iterator(self, ctype, active, sort, traversal)
   1289         if active is not None and self.active != active:
   1290             return ().__iter__()
-> 1291         if self.parent_component().type() not in ctype:
   1292             return ().__iter__()
   1293 

C:\Users\irini\Anaconda2\lib\site-packages\pyomo\core\base\param.pyc in   __call__(self, exception)
    927         if exception:
    928         msg = 'Cannot compute the value of an array of parameters'
--> 929         raise TypeError(msg)
    930 
    931 register_component(Param, "Parameter data that is used to define a model instance.")

TypeError: Cannot compute the value of an array of parameters

Я не уверен, к какой части модели это относится. Кто-нибудь знает, почему это так?


person iriniapid    schedule 16.03.2017    source источник
comment
Можете ли вы включить всю трассировку стека и соответствующую часть модели? Ошибка, скорее всего, в одном из ваших правил.   -  person jsiirola    schedule 16.03.2017
comment
Вот и все! Большое спасибо   -  person iriniapid    schedule 16.03.2017
comment
Спасибо. Похоже, ошибка возникает внутри преобразования MPEC. Можете ли вы включить всю модель, и я могу попытаться воспроизвести ошибку?   -  person jsiirola    schedule 16.03.2017
comment
Я включил модель, которую хочу предварительно решить. Есть некоторые параметры, которые будут инициализированы позже в модели, но не используются в моих ограничениях или целях. Спасибо.   -  person iriniapid    schedule 17.03.2017


Ответы (1)


Это тонкий момент: type оказывается стандартным методом для всех компонентов Pyomo (включая AbstractModel). Когда вы объявляете параметр type:

model.type=Param(model.i,initialize={'conv':0,'effic':0,'hybrid':0,'elec':1},mutable=True,doc='compliance with promoted car type')

вы неявно заменяете этот метод своим Param. Это, в свою очередь, вызывает проблемы, когда последующий код использует модель, предполагая, что все обычные методы существуют.

Решение состоит в том, чтобы не объявлять компонент модели type.

Для полноты текущий список методов, определенных для модели (или блока), которые вам следует избегать переопределения:

['PseudoMap', '_DEFAULT_INDEX_CHECKING_ENABLED', '__class__', '__contains__', '__deepcopy__',
'__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__',
'__getstate__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__',
'__pickle_slots__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__',
'__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_active',
'_add_temporary_set', '_bfs_iterator', '_component', '_component_data_iter',
'_component_typemap', '_construct_temporary_set', '_constructed', '_ctypes', '_data',
'_decl', '_decl_order', '_default', '_flag_vars_as_stale', '_implicit_subsets', '_index',
'_initialize_component', '_load_model_data', '_name', '_options', '_parent',
'_postfix_dfs_iterator', '_pprint', '_prefix_dfs_iterator', '_processUnhashableIndex',
'_rule', '_suppress_ctypes', '_tree_iterator', '_tuplize', '_type', 'activate', 'active',
'active_blocks', 'active_component_data', 'active_components', 'add_component', 'all_blocks',
'all_component_data', 'all_components', 'block_data_objects', 'clear', 'clear_suffix_value',
'clone', 'cname', 'collect_ctypes', 'component', 'component_data_iterindex',
'component_data_objects', 'component_map', 'component_objects', 'compute_statistics',
'config', 'construct', 'contains_component', 'create', 'create_instance', 'deactivate',
'del_component', 'dim', 'display', 'doc', 'find_component', 'fix_all_vars',
'get_suffix_value', 'getname', 'id_index_map', 'index', 'index_set', 'is_constructed',
'is_indexed', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'local_name',
'model', 'name', 'nconstraints', 'nobjectives', 'nvariables', 'parent_block',
'parent_component', 'pprint', 'preprocess', 'preprocessor_ep', 'reclassify_component_type',
'reconstruct', 'root_block', 'set_suffix_value', 'set_value', 'solutions', 'statistics',
'to_dense_data', 'to_string', 'transform', 'type', 'unfix_all_vars', 'valid_model_component',
'valid_problem_types', 'values', 'write']
person jsiirola    schedule 17.03.2017