我需要在调用另一个类的方法的类中使用多处理技术。下面的解释。
我正在编写多代理策略。因此,我的代码分为 3 个类:
- 代理类
- 环境等级
- 主要的。
在代理类中,我正在运行一个返回决策变量字典的 MILP 问题:
class Agent:
def __init__():
....
def Optimisation():
.....
return decision_agent
类环境接收来自所有代理的输出以计算“社区”输出。由于每个代理都是一个独立的实体,代理将并行计算他们的优化问题。因此,我想在环境类中使用多处理来获取所有代理的决策
import Agent as Agent
class Env:
def __init__():
self.agents = #list of agents in my environment
def community_output():
#**start the part of code I want to multiprocess**
for agent in self.agents:
agents_output.append(agent.Optimisation)
#**end the part of code I want to multiprocess**
"""compute community_output based on agents_output """
return community_output
然后在 main 中调用方法community_output()
:
import Env as Env
if __name__ == '__main__':
env = Env()
result = env.community_output()
请问我该如何进行?
由于我有一个实例方法列表作为可迭代对象,因此我尝试了以下方法:
def job(instance):
instance.Optimisation()
return instance
if __name__ == '__main__':
pool = mp.Pool(processes=4)
agents_output= pool.map(job, agents)
pool.close()
pool.join()
这仅在我删除Env
类并将其所有处理放在之前的情况下才有效def job(instance)
。
当我将它集成到Env
课堂上时:
import Agent as Agent
class Env:
def __init__():
self.agents = #list of agents in my environment
def job(instance):
instance.Optimisation()
return instance
def community_output():
pool = mp.Pool(processes=4)
agents_output = pool.map(self.job, self.agents)
pool.close()
pool.join()
""" Compute community_output based on agents_output """
return community_output
Import Env as Env
if __name__ == '__main__':
env = Env()
result = env.community_output()
我得到了错误:
File "C:\Users\chaim\...\Env.py", line 576, in community_output
results = pool.map(self.job, self.agents)
File "C:\Users\chaim\anaconda3\envs\picos\lib\multiprocessing\pool.py", line 268, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Users\chaim\anaconda3\envs\picos\lib\multiprocessing\pool.py", line 657, in get
raise self._value
multiprocessing.pool.MaybeEncodingError: Error sending result: '[{'opt_prob': <Mixed-Integer Linear Program>, 'q_us_val': <190x1 matrix, tc='d'>, 'q_ds_val': 0.0, 'p_net_exp_val': <48x1 matrix, tc='d'>, 'q_sup_sell_val': <48x1 matrix, tc='d'>, 'q_sup_buy_val': <48x1 matrix, tc='d'>, 'p_es_ch_val': <48x1 matrix, tc='d'>, 'p_es_dis_val': <48x1 matrix, tc='d'>, 'q_ds_0': <1×1 Real Constant: 0>, 'q_us_0': <1×1 Real Constant: q_usᵀ·[190×1]>}]'. Reason: 'PicklingError("Can't pickle <function <lambda> at 0x000001B8B9C31288>: attribute lookup <lambda> on picos.modeling.options failed")'
我注意到:
{'opt_prob': <Mixed-Integer Linear Program>, '... q_usᵀ·[190×1]>}
是方法返回的字典agent.Optimisation
,picos
是使用的优化API。
任何线索我该如何解决这个问题?