baselines算法库common/vec_env/vec_env.py模块分析
common/vec_env/vec_env.py模块内容:
import contextlib
import os
from abc import ABC, abstractmethod from baselines.common.tile_images import tile_images class AlreadySteppingError(Exception):
"""
Raised when an asynchronous step is running while
step_async() is called again.
""" def __init__(self):
msg = 'already running an async step'
Exception.__init__(self, msg) class NotSteppingError(Exception):
"""
Raised when an asynchronous step is not running but
step_wait() is called.
""" def __init__(self):
msg = 'not running an async step'
Exception.__init__(self, msg) class VecEnv(ABC):
"""
An abstract asynchronous, vectorized environment.
Used to batch data from multiple copies of an environment, so that
each observation becomes an batch of observations, and expected action is a batch of actions to
be applied per-environment.
"""
closed = False
viewer = None metadata = {
'render.modes': ['human', 'rgb_array']
} def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = action_space @abstractmethod
def reset(self):
"""
Reset all the environments and return an array of
observations, or a dict of observation arrays. If step_async is still doing work, that work will
be cancelled and step_wait() should not be called
until step_async() is invoked again.
"""
pass @abstractmethod
def step_async(self, actions):
"""
Tell all the environments to start taking a step
with the given actions.
Call step_wait() to get the results of the step. You should not call this if a step_async run is
already pending.
"""
pass @abstractmethod
def step_wait(self):
"""
Wait for the step taken with step_async(). Returns (obs, rews, dones, infos):
- obs: an array of observations, or a dict of
arrays of observations.
- rews: an array of rewards
- dones: an array of "episode done" booleans
- infos: a sequence of info objects
"""
pass def close_extras(self):
"""
Clean up the extra resources, beyond what's in this base class.
Only runs when not self.closed.
"""
pass def close(self):
if self.closed:
return
if self.viewer is not None:
self.viewer.close()
self.close_extras()
self.closed = True def step(self, actions):
"""
Step the environments synchronously. This is available for backwards compatibility.
"""
self.step_async(actions)
return self.step_wait() def render(self, mode='human'):
imgs = self.get_images()
bigimg = tile_images(imgs)
if mode == 'human':
self.get_viewer().imshow(bigimg)
return self.get_viewer().isopen
elif mode == 'rgb_array':
return bigimg
else:
raise NotImplementedError def get_images(self):
"""
Return RGB images from each environment
"""
raise NotImplementedError @property
def unwrapped(self):
if isinstance(self, VecEnvWrapper):
return self.venv.unwrapped
else:
return self def get_viewer(self):
if self.viewer is None:
from gym.envs.classic_control import rendering
self.viewer = rendering.SimpleImageViewer()
return self.viewer class VecEnvWrapper(VecEnv):
"""
An environment wrapper that applies to an entire batch
of environments at once.
""" def __init__(self, venv, observation_space=None, action_space=None):
self.venv = venv
super().__init__(num_envs=venv.num_envs,
observation_space=observation_space or venv.observation_space,
action_space=action_space or venv.action_space) def step_async(self, actions):
self.venv.step_async(actions) @abstractmethod
def reset(self):
pass @abstractmethod
def step_wait(self):
pass def close(self):
return self.venv.close() def render(self, mode='human'):
return self.venv.render(mode=mode) def get_images(self):
return self.venv.get_images() def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError("attempted to get missing private attribute '{}'".format(name))
return getattr(self.venv, name) class VecEnvObservationWrapper(VecEnvWrapper):
@abstractmethod
def process(self, obs):
pass def reset(self):
obs = self.venv.reset()
return self.process(obs) def step_wait(self):
obs, rews, dones, infos = self.venv.step_wait()
return self.process(obs), rews, dones, infos class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
""" def __init__(self, x):
self.x = x def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x) def __setstate__(self, ob):
import pickle
self.x = pickle.loads(ob) @contextlib.contextmanager
def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment variables temporarily such as when we are starting multiprocessing
Processes.
"""
removed_environment = {}
for k, v in list(os.environ.items()):
for prefix in ['OMPI_', 'PMI_']:
if k.startswith(prefix):
removed_environment[k] = v
del os.environ[k]
try:
yield
finally:
os.environ.update(removed_environment)
类
class AlreadySteppingError(Exception):
class NotSteppingError(Exception):
作为异常类不过多介绍。
class VecEnv(ABC): 作为抽象类是对gym的环境进行进一步的包装,该类的作用就是进行多环境env的并行操作,也就是并行与环境进行交互和采样。
继承并实现该类进行初始化的时候需要设置并行的环境数和环境的状态空间和动作空间。
该类的主要操作为 reset, step, render , 这三个操作的含义和gym的设定相同,不同的是并行操作部分:
step函数中调用 self.step_async(actions) 保证多个环境都可以并行的收到下步的动作,self.step_wait() 可以视作阻塞操作用来同步多进程下多个环境的step同步,并将多个环境返回的:
Returns (obs, rews, dones, infos):
- obs: an array of observations, or a dict of
arrays of observations.
- rews: an array of rewards
- dones: an array of "episode done" booleans
- infos: a sequence of info object
obs,rews,dones,infos 向上级返回。
render函数为绘图动作,该函数将多个环境的当前状态的图片进行拼接,在'human'模式下将拼接后的图片进行绘图操作,在'rgb_array'模式下对拼接后的图片的np.array形式数据进行返回。
多环境当前状态图片的拼接参见: https://www.cnblogs.com/devilmaycry812839668/p/16025513.html
close函数关闭绘图对象self.viewer并调用close_extras关闭其他资源。
函数get_viewer生成绘图对象self.viewer,绘图对象self.viewer为调用gym的rendering模块生成的。
函数unwrapped判断实现VecEnv类的子类是否属于VecEnvWrapper类,如果是则调用self.venv.unwrapped,大致可以理解为该函数是要返回最原始的为包装过的env而不是VecEnv 。
类:
class VecEnvWrapper(VecEnv):
class VecEnvObservationWrapper(VecEnvWrapper):
均为抽象类,主要实现的函数:
def close(self):
return self.venv.close() def render(self, mode='human'):
return self.venv.render(mode=mode) def get_images(self):
return self.venv.get_images()
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError("attempted to get missing private attribute '{}'".format(name))
return getattr(self.venv, name)
@abstractmethod
def process(self, obs):
pass def reset(self):
obs = self.venv.reset()
return self.process(obs) def step_wait(self):
obs, rews, dones, infos = self.venv.step_wait()
return self.process(obs), rews, dones, infos
可以看出这几个抽象类的最后都是通过调用self.env来实现的,比如:
step函数则是调用:
self.venv.step_async(actions)
obs, rews, dones, infos = self.venv.step_wait()
return self.process(obs), rews, dones, infos
来实现的。
而reset则是:
def reset(self):
obs = self.venv.reset()
return self.process(obs)
可以看出self.env的env.reset()函数、env.step_wait()函数、venv.render(mode=mode)函数比较重要。
在类VecEnv及子类中比较有意思的函数:
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError("attempted to get missing private attribute '{}'".format(name))
return getattr(self.venv, name)
该函数的含义是调用类对象的成员变量时如果是私有变量则报错,对其他的变量都是返回self.env中对应的同名变量。
------------------------------------------------
class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
""" def __init__(self, x):
self.x = x def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x) def __setstate__(self, ob):
import pickle
self.x = pickle.loads(ob)
这个类是实现调用pickle实现序列化时内部是先调用cloudpickle模块实现raw byte类型,该模块可以将变量及函数都转为raw byte类型从而可以调用pickle进行序列化,可以实现多进程间传递python函数等。
-------------------------------------------------------
@contextlib.contextmanager
def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment variables temporarily such as when we are starting multiprocessing
Processes.
"""
removed_environment = {}
for k, v in list(os.environ.items()):
for prefix in ['OMPI_', 'PMI_']:
if k.startswith(prefix):
removed_environment[k] = v
del os.environ[k]
try:
yield
finally:
os.environ.update(removed_environment)
该函数的作用注释说的已经很清楚,这里在多解释下:
因为baseline模块会调用mpi4py函数,
from mpi4py import MPI
只要引入了mpi4py包就会自动设置环境变量,而引入mpi4py后在调用multiprocessing函数生成多个子进程时mpi4py模块会导致子进程挂起,这时如果我们已经引入了mpi4py后还想要调用multiprocessing模块生成多个进程则需要设置环境变量将mpi的环境变量删除,这样话就不会识别到已经引入的mpi4py,在生成多进程执行完操作后再将删除的mpi环境变量加回到环境变量中。
================================================
baselines算法库common/vec_env/vec_env.py模块分析的更多相关文章
- 图像滤镜艺术---ZPhotoEngine超级算法库
原文:图像滤镜艺术---ZPhotoEngine超级算法库 一直以来,都有个想法,想要做一个属于自己的图像算法库,这个想法,在经过了几个月的努力之后,终于诞生了,这就是ZPhotoEngine算法库. ...
- scikit-learn 支持向量机算法库使用小结
之前通过一个系列对支持向量机(以下简称SVM)算法的原理做了一个总结,本文从实践的角度对scikit-learn SVM算法库的使用做一个小结.scikit-learn SVM算法库封装了libsvm ...
- 【Python】【Web.py】详细解读Python的web.py框架下的application.py模块
详细解读Python的web.py框架下的application.py模块 这篇文章主要介绍了Python的web.py框架下的application.py模块,作者深入分析了web.py的源码, ...
- 第三百零六节,Django框架,models.py模块,数据库操作——创建表、数据类型、索引、admin后台,补充Django目录说明以及全局配置文件配置
Django框架,models.py模块,数据库操作——创建表.数据类型.索引.admin后台,补充Django目录说明以及全局配置文件配置 数据库配置 django默认支持sqlite,mysql, ...
- 使用织梦开源的分词算法库编写的YII获取分词扩展
在编辑文章中,很多时候都需要自动根据文章内容获取关键字的功能,因此,本文主要是说明如何在yii中使用织梦开源的分词算法编写一个独立的扩展,可以在不同的模块中使用,步骤如下: 1 到这里下载其他朋友整理 ...
- 四 Django框架,models.py模块,数据库操作——创建表、数据类型、索引、admin后台,补充Django目录说明以及全局配置文件配置
Django框架,models.py模块,数据库操作——创建表.数据类型.索引.admin后台,补充Django目录说明以及全局配置文件配置 数据库配置 django默认支持sqlite,mysql, ...
- mahout算法库(四)
mahout算法库 分为三大块 1.聚类算法 2.协同过滤算法(一般用于推荐) 协同过滤算法也可以称为推荐算法!!! 3.分类算法 算法类 算法名 中文名 分类算法 Log ...
- 操作MySQL-数据库的安装及Pycharm模块的导入
操作MySQL-数据库的安装及Pycharm模块的导入 1.基于pyCharm开发环境,在CMD控制台输入依次输入以下步骤: (1)pip3 install PyMySQL < 安装 PyMy ...
- 痞子衡嵌入式:对比MbedTLS算法库纯软件实现与i.MXRT上DCP,CAAM硬件加速器实现性能差异
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是MbedTLS算法库纯软件实现与i.MXRT上DCP,CAAM硬件加速器实现性能差异. 近期有 i.MXRT 客户在集成 OTA SBL ...
- snowland-smx密码算法库
snowland-smx密码算法库 一.snowland-smx密码算法库的介绍 snowland-smx是python实现的国密套件,对标python实现的gmssl,包含国密SM2,SM3,SM4 ...
随机推荐
- 解析Html Canvas的卓越性能与高效渲染策略
一.什么是Canvas 想必学习前端的同学们对Canvas 都不陌生,它是 HTML5 新增的"画布"元素,可以使用JavaScript来绘制图形. Canvas元素是在HTML5 ...
- 前端学习之nvm
接手了新的项目 需要使用nodejs,但是版本又不同如何解决呢 如果自己下载配置环境变量也太复杂了 下载nvm https://nvm.uihtm.com/download.html 使用nvm 下载 ...
- 12-Python数据库访问
在CentOS7上安装Mariadb https://blog.csdn.net/NetRookieX/article/details/104734181 常用的增删改查 show databases ...
- C# pythonnet(2)_傅里叶变换(FFT)
Python代码如下 import pandas as pd import numpy as np import matplotlib.pyplot as plt # 读取数据 data = pd.r ...
- QT学习:05 元对象系统
--- title: framework-cpp-qt-05-元对象系统 EntryName: framework-cpp-qt-05-mos date: 2020-04-09 17:11:44 ca ...
- 200 行 ,一个PYQT 窗口 + 后台 AIOHTTP 服务 , 例子
直接上代码 import sys from typing import Dict, List from aiohttp import web import asyncio from functools ...
- 关于Precision,Recall,ROC曲线,KS,Lift等模型评价指标的介绍
1.Precision, Recall 准确率 \(Accuracy = \frac{TP+TN}{TP+TN+FP+FN}\) 精确率(或命中率) \(Precision = \frac{TP}{T ...
- 云服务器从阿里云迁移到华为云,FTP服务器的一些设置处理
由于一些特殊原因,计划从阿里云上把ECS服务器的相关资源资源迁移到华为云上,为了保险起见,先申请一个月的华为云ECS服务器进行测试,首先就是搭建FTP服务器进行文件的上传处理,在使用FileZilla ...
- yolov5 损失函数代码详解
前言 模型的损失计算包括3个方面,分别是: 定位损失 分类损失 置信度损失 损失的计算公式如下: 损失计算的代码流程也是按照这三大块来计算的.本篇主要讲解yolov5中损失计算的实现,包括损失的逻辑实 ...
- [oeasy]python0133_变量名_标识符_identifier_id_locals
变量名 回忆上次内容 上次讲了 什么是变量 变量变量 能变的量 就是变量 各种系统.游戏就是由变量所组成的 添加图片注释,不超过 140 字(可选) 声明了变量 并且 定义了变量 ...