code stringlengths 17 6.64M |
|---|
class MeterLogger(object):
' A class to package and print meters. '
def __init__(self, modes=('train', 'val')):
self.modes = list(modes)
self.meter = {}
self.logger = {}
for mode in modes:
self.meter[mode] = {}
self.logger[mode] = {}
self.timer ... |
class TensorboardMeterLogger(MeterLogger):
" A class to package and visualize meters.\n\n Args:\n log_dir: Directory to write events to (log_dir/env)\n env: Tensorboard environment to log to.\n plotstylecombined: Whether to plot curves in the same window.\n loggers: All modes: defau... |
class VisdomConnections(object):
'\n Keeps global track of connections to visdom. This prevents us from new connections each time we want to log a value.\n '
def __init__(self):
self.connections = {}
self.log_connections = {}
def add(self, server, port, log_to_filename):
... |
class BaseVisdomLogger(Logger):
'\n The base class for logging output to Visdom.\n\n ***THIS CLASS IS ABSTRACT AND MUST BE SUBCLASSED***\n\n Note that the Visdom server is designed to also handle a server architecture,\n and therefore the Visdom server must be running at all times. The... |
class VisdomSaver(object):
' Serialize the state of the Visdom server to disk.\n Unless you have a fancy schedule, where different are saved with different frequencies,\n you probably only need one of these.\n '
def __init__(self, envs=None, port=8097, server='localhost', log_to_filename=Non... |
class VisdomLogger(BaseVisdomLogger):
'\n A generic Visdom class that works with the majority of Visdom plot types.\n '
def __init__(self, plot_type, fields=None, win=None, env=None, opts={}, port=8097, server='localhost', log_to_filename=None):
"\n Args:\n fields:... |
class VisdomPlotLogger(BaseVisdomLogger):
def __init__(self, plot_type, fields=None, win=None, env=None, opts={}, port=8097, server='localhost', name=None, log_to_filename=None):
'\n Multiple lines can be added to the same plot with the "name" attribute (see example)\n Args:\n ... |
class VisdomTextLogger(BaseVisdomLogger):
'Creates a text window in visdom and logs output to it.\n\n The output can be formatted with fancy HTML, and it new output can\n be set to \'append\' or \'replace\' mode.\n\n Args:\n fields: Currently not used\n update_type: One of {\'REPLACE\', \'A... |
class VisdomMeterLogger(MeterLogger):
' A class to package and visualize meters.\n\n Args:\n server: The uri of the Visdom server\n env: Visdom environment to log to.\n port: Port of the visdom server.\n title: The title of the MeterLogger. This will be used as a prefix for all plot... |
class AUCMeter(meter.Meter):
'\n The AUCMeter measures the area under the receiver-operating characteristic\n (ROC) curve for binary classification problems. The area under the curve (AUC)\n can be interpreted as the probability that, given a randomly selected positive\n example and a randomly selecte... |
class AverageValueMeter(ValueSummaryMeter):
def __init__(self):
warnings.warn('AverageValueMeter is deprecated in favor of ValueSummaryMeter and will be removed in a future version', FutureWarning)
super(AverageValueMeter, self).__init__()
|
class mAPMeter(meter.Meter):
'\n The mAPMeter measures the mean average precision over all classes.\n\n The mAPMeter is designed to operate on `NxK` Tensors `output` and\n `target`, and optionally a `Nx1` Tensor weight where (1) the `output`\n contains model output scores for `N` examples and `K` clas... |
class Meter(object):
'Meters provide a way to keep track of important statistics in an online manner.\n\n This class is abstract, but provides a standard interface for all meters to follow.\n\n '
def reset(self):
'Resets the meter to default settings.'
pass
def add(self, value):
... |
class MovingAverageValueMeter(meter.Meter):
def __init__(self, windowsize):
super(MovingAverageValueMeter, self).__init__()
self.windowsize = windowsize
self.valuequeue = torch.Tensor(windowsize)
self.reset()
def reset(self):
self.sum = 0.0
self.n = 0
... |
class MSEMeter(meter.Meter):
def __init__(self, root=False):
super(MSEMeter, self).__init__()
self.reset()
self.root = root
def reset(self):
self.n = 0
self.sesum = 0.0
def add(self, output, target):
if ((not torch.is_tensor(output)) and (not torch.is_ten... |
class MultiValueSummaryMeter(ValueSummaryMeter):
def __init__(self, keys):
'\n Args:\n keys: An iterable of keys\n '
super(MultiValueSummaryMeter, self).__init__()
self.keys = list(keys)
|
class SingletonMeter(meter.Meter):
'Stores exactly one value which can be regurgitated'
def __init__(self, maxlen=1):
super(SingletonMeter, self).__init__()
self.__val = None
def reset(self):
'Resets the meter to default settings.'
old_val = self.__val
self.__val ... |
class TimeMeter(meter.Meter):
'\n <a name="TimeMeter">\n #### tnt.TimeMeter(@ARGP)\n @ARGT\n\n The `tnt.TimeMeter` is designed to measure the time between events and can be\n used to measure, for instance, the average processing time per batch of data.\n It is different from most other meters in... |
class ValueSummaryMeter(meter.Meter):
def __init__(self):
super(ValueSummaryMeter, self).__init__()
self.reset()
self.val = 0
def add(self, value, n=1):
self.val = value
self.sum += value
self.var += (value * value)
self.n += n
if (self.n == 0)... |
def compose(transforms):
assert isinstance(transforms, list)
for tr in transforms:
assert callable(tr), 'list of functions expected'
def composition(z):
for tr in transforms:
z = tr(z)
return z
return composition
|
def tablemergekeys():
def mergekeys(tbl):
mergetbl = {}
if isinstance(tbl, dict):
for (idx, elem) in tbl.items():
for (key, value) in elem.items():
if (key not in mergetbl):
mergetbl[key] = {}
mergetbl[key... |
def tableapply(f):
return (lambda d: dict(map((lambda kv: (kv[0], f(kv[1]))), iteritems(d))))
|
def makebatch(merge=None):
if merge:
makebatch = compose([tablemergekeys(), merge])
else:
makebatch = compose([tablemergekeys(), tableapply((lambda field: (mergetensor(field) if canmerge(field) else field)))])
return (lambda samples: makebatch(samples))
|
class MultiTaskDataLoader(object):
'Loads batches simultaneously from multiple datasets.\n\n The MultiTaskDataLoader is designed to make multi-task learning simpler. It is\n ideal for jointly training a model for multiple tasks or multiple datasets.\n MultiTaskDataLoader is initialzes with an iterable of... |
def zip_batches(*iterables, **kwargs):
use_all = kwargs.pop('use_all', False)
if use_all:
try:
from itertools import izip_longest as zip_longest
except ImportError:
from itertools import zip_longest
return zip_longest(*iterables, fillvalue=None)
else:
... |
def canmergetensor(tbl):
if (not isinstance(tbl, list)):
return False
if torch.is_tensor(tbl[0]):
sz = tbl[0].numel()
for v in tbl:
if (v.numel() != sz):
return False
return True
return False
|
def mergetensor(tbl):
sz = ([len(tbl)] + list(tbl[0].size()))
res = tbl[0].new(torch.Size(sz))
for (i, v) in enumerate(tbl):
res[i].copy_(v)
return res
|
def _get_version():
import phantom
return phantom.__version__
|
@ph.msg_payload()
class ImpressionRequest():
'\n The message indicating that a user is visiting a website and might be\n interested in an advertisement offer\n\n Attributes:\n -----------\n timestamp (int): the time of the impression\n user_id (int): the unique and anonymous identifier of t... |
@ph.msg_payload()
class Bid():
'\n The message sent by the advertiser to the exchange\n to win the impression\n\n Attributes:\n -----------\n bid (float): the cost charged to the advertiser\n theme (str): the theme of the ad that will be displayed\n user_id(str): the user identifier\n... |
@ph.msg_payload()
class AuctionResult():
"\n The message sent by the exchange to the advertiser\n to inform her of the auction's result\n\n Attributes:\n -----------\n cost (float): the cost charged to the advertiser\n winning_bid (float): the highest bid during this auction\n\n ... |
@ph.msg_payload()
class Ads():
'\n The message sent by an advertisers containing the ads to show to the user.\n For simplicity, it only contains a theme.\n\n Attributes:\n -----------\n advertiser_id (str): the theme of the ads\n theme (str): the theme of the ads\n user_id (int)... |
@ph.msg_payload()
class ImpressionResult():
'\n The result of the ad display. i.e whether or not the user clicked\n on the ad\n\n Attributes:\n -----------\n clicked (bool): whether or not the user clicked on the ad\n\n '
clicked: bool
|
class PublisherPolicy(ph.Policy):
def compute_action(self, obs: np.ndarray) -> np.ndarray:
return np.array([0])
|
class PublisherAgent(ph.Agent):
'\n A `PublisherAgent` generates `ImpressionRequest` which corresponds to\n real-estate on their website rented to advertisers to display their ads.\n\n Attributes:\n -----------\n _USER_CLICK_PROBABILITIES (dict): helper dictionary containing the probability\n ... |
class AdvertiserAgent(ph.StrategicAgent):
'\n An `AdvertiserAgent` learns to bid efficiently and within its budget limit, on an impression\n in order to maximize the number of clicks it gets.\n For this implementation an advertiser is associated with a `theme` which will impact the\n probability of a ... |
class AdExchangeAgent(ph.Agent):
"\n The `AdExchangeAgent` is actually just an actor who reacts to messages reveived.\n It doesn't perform any action on its own.\n "
@dataclass(frozen=True)
class AdExchangeView(ph.AgentView):
'\n The view is used to expose additional information t... |
class DigitalAdsEnv(ph.FiniteStateMachineEnv):
def __init__(self, num_steps=20, num_agents_theme=None, **kwargs):
self.exchange_id = 'ADX'
self.publisher_id = 'PUB'
USER_CLICK_PROBABILITIES = {1: {'sport': 0.0, 'travel': 1.0, 'science': 0.2, 'tech': 0.5}, 2: {'sport': 1.0, 'travel': 0.0, ... |
class AdvertiserBidUser(ph.metrics.Metric[float]):
def __init__(self, agent_id: str, user_id: int) -> None:
self.agent_id: str = agent_id
self.user_id: int = user_id
def extract(self, env: ph.PhantomEnv) -> float:
'@override\n Extracts the per-step value to track\n '
... |
class AdvertiserAverageHitRatioUser(ph.metrics.Metric[float]):
def __init__(self, agent_id: str, user_id: int) -> None:
self.agent_id: str = agent_id
self.user_id: int = user_id
def extract(self, env: ph.PhantomEnv) -> float:
'@override\n Extracts the per-step value to track\n... |
class AdvertiserAverageWinProbaUser(ph.metrics.Metric[float]):
def __init__(self, agent_id: str, user_id: int) -> None:
self.agent_id: str = agent_id
self.user_id: int = user_id
def extract(self, env: ph.PhantomEnv) -> float:
'@override\n Extracts the per-step value to track\n... |
class AdvertiserTotalRequests(ph.metrics.Metric[float]):
def __init__(self, agent_id: str, user_id: int) -> None:
self.agent_id: str = agent_id
self.user_id: int = user_id
def extract(self, env: ph.PhantomEnv) -> float:
return env[self.agent_id].total_requests[self.user_id]
def ... |
class AdvertiserTotalWins(ph.metrics.Metric[float]):
def __init__(self, agent_id: str, user_id: int) -> None:
self.agent_id: str = agent_id
self.user_id: int = user_id
def extract(self, env: ph.PhantomEnv) -> float:
return env[self.agent_id].total_wins[self.user_id]
def reduce(s... |
def BuyerPolicy(obs):
if (obs[1] and (obs[0] <= obs[2])):
action = obs[1]
else:
action = 0
return action
|
def SellerPolicy(obs):
action = np.random.uniform()
return action
|
def rollout(env):
(observations, _) = env.reset()
rewards = {}
while (env.current_step < env.num_steps):
print(env.current_step)
print('\nobservations:')
print(observations)
print('\nrewards:')
print(rewards)
actions = {}
for (aid, obs) in observatio... |
@dataclass(frozen=True)
class Leak():
victim_id: str
price: float
|
class MaybeSneakySeller(SellerAgent):
def __init__(self, agent_id: ph.AgentID, victim_id=None):
super().__init__(agent_id)
self.victim_id = victim_id
self.victims_price = 0
self.observation_space = Box(np.array([0, 0, 0]), np.array([np.Inf, 1, 1]))
def encode_observation(self... |
class MaybeLeakyBuyer(BuyerAgent):
def __init__(self, agent_id, demand_prob, supertype, victim_id=None, adv_id=None):
super().__init__(agent_id, demand_prob, supertype)
self.victim_id = victim_id
self.adv_id = adv_id
@ph.agents.msg_handler(Price)
def handle_price_message(self, ct... |
@dataclass(frozen=True)
class AdversarialSetup():
leaky_buyer: ph.AgentID
victim_seller: ph.AgentID
adv_seller: ph.AgentID
|
class LeakySimpleMarketEnv(SimpleMarketEnv):
def __init__(self, num_steps, network, adv_setup=None):
super().__init__(num_steps, network)
self.leaky = False
if adv_setup:
self.adversarial_setup(adv_setup.leaky_buyer, adv_setup.adv_seller, adv_setup.victim_seller)
def adve... |
@dataclass(frozen=True)
class Price(ph.MsgPayload):
price: float
|
@dataclass(frozen=True)
class Order(ph.MsgPayload):
vol: int
|
@dataclass
class BuyerSupertype(ph.Supertype):
value: float
|
class BuyerAgent(ph.StrategicAgent):
def __init__(self, agent_id, demand_prob, supertype):
super().__init__(agent_id, supertype=supertype)
self.seller_prices = {}
self.demand_prob = demand_prob
self.current_reward = 0
self.action_space = Discrete(2)
self.observatio... |
class SellerAgent(ph.StrategicAgent):
def __init__(self, agent_id: ph.AgentID):
super().__init__(agent_id)
self.current_price = 0
self.current_revenue = 0
self.current_tx = 0
self.action_space = Box(low=0, high=1, shape=(1,))
self.observation_space = Box(np.array([... |
class SimpleMarketEnv(ph.FiniteStateMachineEnv):
@dataclass(frozen=True)
class View(ph.fsm.FSMEnvView):
avg_price: float
def __init__(self, num_steps, network):
buyers = [aid for (aid, agent) in network.agents.items() if isinstance(agent, BuyerAgent)]
sellers = [aid for (aid, age... |
@ph.msg_payload('CustomerAgent', 'ShopAgent')
class OrderRequest():
size: int
|
@ph.msg_payload('ShopAgent', 'CustomerAgent')
class OrderResponse():
size: int
|
@ph.msg_payload('ShopAgent', 'FactoryAgent')
class StockRequest():
size: int
|
@ph.msg_payload('FactoryAgent', 'ShopAgent')
class StockResponse():
size: int
|
class FactoryAgent(ph.Agent):
def __init__(self, agent_id: str):
super().__init__(agent_id)
@ph.agents.msg_handler(StockRequest)
def handle_stock_request(self, ctx: ph.Context, message: ph.Message):
return [(message.sender_id, StockResponse(message.payload.size))]
|
class CustomerAgent(ph.Agent):
def __init__(self, agent_id: ph.AgentID, shop_id: ph.AgentID):
super().__init__(agent_id)
self.shop_id: str = shop_id
@ph.agents.msg_handler(OrderResponse)
def handle_order_response(self, ctx: ph.Context, message: ph.Message):
return
def genera... |
class ShopAgent(ph.StrategicAgent):
def __init__(self, agent_id: str, factory_id: str):
super().__init__(agent_id)
self.factory_id: str = factory_id
self.stock: int = 0
self.sales: int = 0
self.missed_sales: int = 0
self.observation_space = gym.spaces.Box(low=0.0, ... |
class SupplyChainEnv(ph.PhantomEnv):
def __init__(self):
factory_id = 'WAREHOUSE'
customer_ids = [f'CUST{(i + 1)}' for i in range(NUM_CUSTOMERS)]
shop_id = 'SHOP'
factory_agent = FactoryAgent(factory_id)
customer_agents = [CustomerAgent(cid, shop_id=shop_id) for cid in cus... |
class FixedCategorical(torch.distributions.Categorical):
def sample(self):
return super().sample().unsqueeze((- 1))
def log_probs(self, actions):
return super().log_prob(actions.squeeze((- 1))).view(actions.size(0), (- 1)).sum((- 1)).unsqueeze((- 1))
def mode(self):
return self.... |
class FixedNormal(torch.distributions.Normal):
def log_probs(self, actions):
return super().log_prob(actions).sum((- 1), keepdim=True)
def entropy(self):
return super().entropy().sum((- 1))
def mode(self):
return self.mean
|
class FixedBernoulli(torch.distributions.Bernoulli):
def log_probs(self, actions):
return super.log_prob(actions).view(actions.size(0), (- 1)).sum((- 1)).unsqueeze((- 1))
def entropy(self):
return super().entropy().sum((- 1))
def mode(self):
return torch.gt(self.probs, 0.5).floa... |
class Categorical(nn.Module):
def __init__(self, num_inputs: int, num_outputs: int) -> None:
super().__init__()
init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0)), gain=0.01))
self.linear = init_(nn.Linear(num_inputs, num_outputs))
def forward(self, x... |
class DiagGaussian(nn.Module):
def __init__(self, num_inputs: int, num_outputs: int) -> None:
super().__init__()
init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0))))
self.fc_mean = init_(nn.Linear(num_inputs, num_outputs))
self.logstd = AddBias(tor... |
class Bernoulli(nn.Module):
def __init__(self, num_inputs: int, num_outputs: int) -> None:
super().__init__()
init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0))))
self.linear = init_(nn.Linear(num_inputs, num_outputs))
def forward(self, x):
x ... |
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), (- 1))
|
class PPOPolicy(nn.Module, Policy):
def __init__(self, observation_space: gym.Space, action_space: gym.Space, base_type: Optional[Type['NNBase']]=None, base_kwargs: Optional[Dict[(str, Any)]]=None) -> None:
nn.Module.__init__(self)
Policy.__init__(self, observation_space, action_space)
ba... |
class NNBase(nn.Module):
def __init__(self, recurrent: bool, recurrent_input_size: int, hidden_size: int):
super().__init__()
self._hidden_size = hidden_size
self._recurrent = recurrent
if recurrent:
self.gru = nn.GRU(recurrent_input_size, hidden_size)
for ... |
class CNNBase(NNBase):
def __init__(self, num_inputs: int, recurrent: bool=False, hidden_size: int=512) -> None:
super().__init__(recurrent, hidden_size, hidden_size)
init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.constant_(x, 0)), nn.init.calculate_gain('relu')))
self... |
class MLPBase(NNBase):
def __init__(self, num_inputs: int, recurrent: bool=False, hidden_size: int=64) -> None:
super().__init__(recurrent, num_inputs, hidden_size)
if recurrent:
num_inputs = hidden_size
init_ = (lambda m: init(m, nn.init.orthogonal_, (lambda x: nn.init.consta... |
class PPOTrainer(Trainer):
'\n Proximal Policy Optimisation (PPO) algorithm implementation derived from\n https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail.\n\n For performance and stability reasons, it is recommended that the RLlib\n implementation is used using the :func:`utils.rllib.train` f... |
def init(module, weight_init, bias_init, gain=1):
weight_init(module.weight.data, gain=gain)
bias_init(module.bias.data)
return module
|
def get_vec_normalize(venv):
if isinstance(venv, VecNormalize):
return venv
if hasattr(venv, 'venv'):
return get_vec_normalize(venv.venv)
return None
|
class AddBias(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self._bias = torch.nn.Parameter(bias.unsqueeze(1))
def forward(self, x):
if (x.dim() == 2):
bias = self._bias.t().view(1, (- 1))
else:
bias = self._bias.t().view(1, (- 1), 1, ... |
def update_linear_schedule(optimizer, epoch, total_num_epochs, initial_lr):
'Decreases the learning rate linearly'
lr = (initial_lr - (initial_lr * (epoch / float(total_num_epochs))))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
|
class VecNormalize(VecNormalize_):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.training = True
def _obfilt(self, obs, update=True):
if self.obs_rms:
if (self.training and update):
self.obs_rms.update(obs)
obs = n... |
class QLearningPolicy(Policy):
'\n Simple QLearning policy implementation.\n\n Arguments:\n observation_space: Observation space of the policy.\n action_space: Action space of the policy.\n '
def __init__(self, observation_space: gym.spaces.Discrete, action_space: gym.spaces.Discrete) ... |
class QLearningTrainer(Trainer):
'\n Simple QLearning algorithm implementation.\n\n Arguments:\n alpha: Learning rate.\n gamma: Discount factor.\n epsilon: Exploration rate.\n tensorboard_log_dir: If provided, will save metrics to the given directory\n in a format that... |
class Agent(ABC):
"\n Representation of an agent in the network.\n\n Instances of :class:`phantom.Agent` occupy the nodes on the network graph.\n They are resonsible for storing and monitoring internal state, constructing\n :class:`View` instances and handling messages.\n\n Arguments:\n agen... |
class StrategicAgent(Agent):
"\n Representation of a behavioural agent in the network.\n\n Instances of :class:`phantom.Agent` occupy the nodes on the network graph.\n They are resonsible for storing and monitoring internal state, constructing\n :class:`View` instances and handling messages.\n\n Ar... |
def msg_handler(message_type: Type[MsgPayload]) -> Callable[([Handler], Handler)]:
def decorator(fn: Handler) -> Handler:
setattr(fn, '_message_type', message_type)
return fn
return decorator
|
@dataclass(frozen=True)
class Context():
"\n Representation of the local neighbourhood around a focal agent node.\n\n This class is designed to provide context about an agent's local neighbourhood. In\n principle this could be extended to something different to a star graph, but for now\n this is how ... |
class Decoder(Generic[Action], ABC):
'A trait for types that decode raw actions into packets.'
@property
@abstractmethod
def action_space(self) -> gym.Space:
'The action/input space of the decoder type.'
@abstractmethod
def decode(self, ctx: Context, action: Action) -> List[Tuple[(Ag... |
class EmptyDecoder(Decoder[Any]):
'Converts any actions into empty packets.'
@property
def action_space(self) -> gym.Space:
return gym.spaces.Box((- np.inf), np.inf, (0,))
def decode(self, _: Context, action: Action) -> List[Tuple[(AgentID, MsgPayload)]]:
return []
|
class ChainedDecoder(Decoder[Tuple]):
'Combines n decoders into a single decoder with a tuple action space.\n\n Attributes:\n decoders: An iterable collection of decoders which is flattened into a\n list.\n '
def __init__(self, decoders: Iterable[Decoder]):
self.decoders: List... |
class DictDecoder(Decoder[Dict[(str, Any)]]):
'Combines n decoders into a single decoder with a dict action space.\n\n Attributes:\n decoders: A mapping of decoder names to decoders.\n '
def __init__(self, decoders: Mapping[(str, Decoder)]):
self.decoders: Dict[(str, Decoder)] = dict(dec... |
class Encoder(Generic[Observation], ABC):
'A trait for types that encodes the context of an agent into an observation.'
@property
@abstractmethod
def observation_space(self) -> gym.Space:
'The output space of the encoder type.'
@abstractmethod
def encode(self, ctx: Context) -> Observ... |
class EmptyEncoder(Encoder[np.ndarray]):
'Generates an empty observation.'
@property
def observation_space(self) -> gym.spaces.Box:
return gym.spaces.Box((- np.inf), np.inf, (1,))
def encode(self, _: Context) -> np.ndarray:
return np.zeros((1,))
|
class ChainedEncoder(Encoder[Tuple]):
'Combines n encoders into a single encoder with a tuple action space.\n\n Attributes:\n encoders: An iterable collection of encoders which is flattened into a\n list.\n '
def __init__(self, encoders: Iterable[Encoder]):
self.encoders: List... |
class DictEncoder(Encoder[Dict[(str, Any)]]):
'Combines n encoders into a single encoder with a dict action space.\n\n Attributes:\n encoders: A mapping of encoder names to encoders.\n '
def __init__(self, encoders: Mapping[(str, Encoder)]):
self.encoders: Dict[(str, Encoder)] = dict(enc... |
class Constant(Encoder[np.ndarray]):
'Encoder that always returns a constant valued Box Space.\n\n Arguments:\n shape: Shape of the returned box.\n value: Value that the box is filled with.\n '
def __init__(self, shape: Tuple[int], value: float=0.0) -> None:
self._shape = shape
... |
class PhantomEnv(gym.Env):
'\n Base Phantom environment.\n\n Usage:\n >>> env = PhantomEnv({ ... })\n >>> env.reset()\n <Observation: dict>\n >>> env.step({ ... })\n <Step: 4-tuple>\n\n Attributes:\n num_steps: The maximum number of steps the environment allows p... |
class SingleAgentEnvAdapter(gym.Env):
'\n Wraps a :class:`PhantomEnv` instance or sub-class providing a fully compatible\n :class:`gym.Env` interface, from the perspective of a single agent.\n\n This can be used to test and experiment with Phantom environments using other\n single-agent only framework... |
class FSMValidationError(Exception):
'\n Error raised when validating the FSM when initialising the\n :class:`FiniteStateMachineEnv`.\n '
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.