scml.oneshot.rl =============== .. py:module:: scml.oneshot.rl Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/scml/oneshot/rl/action/index /autoapi/scml/oneshot/rl/agent/index /autoapi/scml/oneshot/rl/common/index /autoapi/scml/oneshot/rl/env/index /autoapi/scml/oneshot/rl/helpers/index /autoapi/scml/oneshot/rl/observation/index /autoapi/scml/oneshot/rl/policies/index /autoapi/scml/oneshot/rl/reward/index Attributes ---------- .. autoapisummary:: scml.oneshot.rl.DefaultActionManager scml.oneshot.rl.RLState scml.oneshot.rl.RLAction scml.oneshot.rl.RLModel scml.oneshot.rl.DefaultObservationManager scml.oneshot.rl.__all__ Classes ------- .. autoapisummary:: scml.oneshot.rl.ActionManager scml.oneshot.rl.FlexibleActionManager scml.oneshot.rl.OneShotRLAgent scml.oneshot.rl.OneShotEnv scml.oneshot.rl.ObservationManager scml.oneshot.rl.FlexibleObservationManager scml.oneshot.rl.RewardFunction scml.oneshot.rl.DefaultRewardFunction Functions --------- .. autoapisummary:: scml.oneshot.rl.model_wrapper scml.oneshot.rl.random_action scml.oneshot.rl.random_policy scml.oneshot.rl.greedy_policy Package Contents ---------------- .. py:class:: ActionManager Bases: :py:obj:`abc.ABC` Manges actions of an agent in an RL environment. .. py:attribute:: context :type: scml.oneshot.context.BaseContext .. py:attribute:: continuous :type: bool :value: False .. py:attribute:: n_suppliers :type: int .. py:attribute:: n_consumers :type: int .. py:attribute:: n_partners :type: int .. py:method:: make_space() -> gymnasium.Space :abstractmethod: Creates the action space .. py:method:: decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) -> dict[str, negmas.sao.common.SAOResponse] :abstractmethod: Decodes an action from an array to a `PurchaseOrder` and a `CounterMessage`. .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) -> numpy.ndarray Encodes an action as an array. This is only used for testing so it is optional .. py:class:: FlexibleActionManager Bases: :py:obj:`ActionManager` An action manager that matches any context. :param n_prices: Number of distinct prices allowed in the action. :param max_quantity: Maximum allowed quantity to offer in any negotiation. The number of quantities is one plus that because zero is allowed to model ending negotiation. :param n_partners: Maximum of partners allowed in the action. Remarks: - This action manager will always generate offers that are within the price and quantity limits given in its parameters. Wen decoding them, it will scale them up so that the maximum corresponds to the actual value in the world it finds itself. For example, if `n_prices` is 10 and the world has only two prices currently in the price issue, it will use any value less than 5 as the minimum price and any value above 5 as the maximum price. If on the other hand the current price issue has 20 values, then it will scale by multiplying the number given in the encoded action (ranging from 0 to 9) by 19/9 which makes it range from 0 to 19 which is what is expected by the world. - This action manager will adjust offers for different number of partners as follows: - If the true number of partners is larger than `n_partners` used by this action manager, it will simply use `n_partners` of them and always end negotiations with the rest of them. - If the true number of partners is smaller than `n_partners`, it will use the first `n_partners` values in the encoded action and increase the quantities of any counter offers (i.e. ones in which the response is REJECT_OFFER) by the amount missing from the ignored partners in the encoded action up to the maximum quantities allowed by the current negotiation context. For example, if `n_partneers` is 4 and we have only 2 partners in reality, and the received quantities from partners were [4, 3] while the maximum quantity allowed is 10 and the encoded action was [2, *, 3, *, 2, *, 1, *] (where we ignored prices), then the encoded action will be converted to [(Reject, 5, *), (Accept, 3, *)] where the 3 extra units that were supposed to be offered to the last two partners are moved to the first partner. If the maximum quantity allowed was 4 in that example, the result will be [(Reject, 4, *), (Accept, 3, *)]. .. py:attribute:: capacity_multiplier :type: int :value: 1 .. py:attribute:: n_prices :type: int :value: 2 .. py:attribute:: max_group_size :type: int :value: 2 .. py:attribute:: reduce_space_size :type: bool :value: True .. py:attribute:: extra_checks :type: bool :value: False .. py:attribute:: max_quantity :type: int .. py:method:: __attrs_post_init__() .. py:method:: make_space() -> gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box Creates the action space .. py:method:: decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) -> dict[str, negmas.sao.common.SAOResponse] Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a `dict[str, SAOResponse]` .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) -> numpy.ndarray Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing. .. py:data:: DefaultActionManager The default action manager .. py:class:: OneShotRLAgent(*args, models: list[scml.oneshot.rl.common.RLModel] | tuple[scml.oneshot.rl.common.RLModel, Ellipsis] = tuple(), observation_managers: list[scml.oneshot.rl.observation.ObservationManager] | tuple[scml.oneshot.rl.observation.ObservationManager, Ellipsis] = tuple(), action_managers: list[scml.oneshot.rl.action.ActionManager] | tuple[scml.oneshot.rl.action.ActionManager, Ellipsis] | None = None, fallback_type: type[scml.oneshot.agent.OneShotAgent] | None = GreedyOneShotAgent, fallback_params: dict[str, Any] | None = None, dynamic_context_switching: bool = False, randomize_test_order: bool = False, **kwargs) Bases: :py:obj:`scml.oneshot.policy.OneShotPolicy` A oneshot agent that can execute trained RL models in appropriate worlds. It falls back to the given agent type otherwise :param models: List of models to choose from. :param observation_managers: List of observation managers. Must be the same length as `models` :param action_managers: List of action managers of the same length as `models` or `None` to use the default action manager. :param fallback_type: A `OneShotAgent` type to use as a fall-back if the current world is not compatible with any observation/action managers :param fallback_params: Parameters of the `fallback_type` :param dynamic_context_switching: If `True`, the world is tested each step (instead of only at init) to find the appropriate model :param randomize_test_order: If `True`, the order at which the observation/action managers are checked for compatibility with the current world is randomized. :param \*\*kwargs: Any other OneShotPolicy parameters .. py:attribute:: _models :value: () .. py:attribute:: _action_managers :value: None .. py:attribute:: _obs_managers :value: () .. py:attribute:: _fallback_type .. py:attribute:: _dynamic_context_switching :value: False .. py:attribute:: _randomize_test_order :value: False .. py:attribute:: _fallback_params :value: None .. py:attribute:: _valid_context :type: scml.oneshot.context.Context :value: None .. py:attribute:: _valid_action_manager :type: scml.oneshot.rl.action.ActionManager :value: None .. py:attribute:: _valid_obs_manager :type: scml.oneshot.rl.observation.ObservationManager :value: None .. py:attribute:: _valid_index :type: int :value: -1 .. py:attribute:: _fallback_agent :type: scml.oneshot.agent.OneShotAgent :value: None .. py:method:: setup_fallback() .. py:method:: has_no_valid_model() .. py:method:: context_switch() .. py:method:: init() Called once after the AWI is set. Remarks: - Use this for any proactive initialization code. .. py:method:: encode_state(mechanism_states: dict[str, negmas.sao.common.SAOState]) -> scml.oneshot.rl.common.RLState Called to generate a state to be passed to the act() method. The default is all of `awi` of type `OneShotState` .. py:method:: decode_action(action: scml.oneshot.rl.common.RLAction) -> dict[str, negmas.sao.common.SAOResponse] Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a `dict[str, SAOResponse]` .. py:method:: act(state: scml.oneshot.rl.common.RLState) -> scml.oneshot.rl.common.RLAction The main policy. Generates an action given a state .. py:method:: propose(*args, **kwargs) -> negmas.outcomes.Outcome | None Called when the agent is asking to propose in one negotiation .. py:method:: respond(*args, **kwargs) -> negmas.gb.common.ResponseType Called when the agent is asked to respond to an offer .. py:method:: before_step() Called at at the BEGINNING of every production step (day) .. py:method:: step() Called at at the END of every production step (day) .. py:method:: on_negotiation_failure(*args, **kwargs) -> None Called when a negotiation the agent is a party of ends without agreement .. py:method:: on_negotiation_success(*args, **kwargs) -> None Called when a negotiation the agent is a party of ends with agreement .. py:data:: RLState We assume that RL states are numpy arrays .. py:data:: RLAction We assume that RL actions are numpy arrays .. py:data:: RLModel A policy is a callable that receives a state and returns an action .. py:function:: model_wrapper(model, deterministic: bool = False) -> RLModel Wraps a stable_baselines3 model as an RL model .. py:class:: OneShotEnv(action_manager: scml.oneshot.rl.action.ActionManager, observation_manager: scml.oneshot.rl.observation.ObservationManager, reward_function: scml.oneshot.rl.reward.RewardFunction = DefaultRewardFunction(), context: scml.oneshot.context.BaseContext = FixedPartnerNumbersOneShotContext(), agent_type: type[scml.oneshot.agent.OneShotAgent] = Placeholder, agent_params: dict[str, Any] | None = None, extra_checks: bool = True, skip_after_negotiations: bool = True, render_mode=None, debug=False) Bases: :py:obj:`gymnasium.Env` The main Gymnasium class for implementing Reinforcement Learning Agents environments. The class encapsulates an environment with arbitrary behind-the-scenes dynamics through the :meth:`step` and :meth:`reset` functions. An environment can be partially or fully observed by single agents. For multi-agent environments, see PettingZoo. The main API methods that users of this class need to know are: - :meth:`step` - Updates an environment with actions returning the next agent observation, the reward for taking that actions, if the environment has terminated or truncated due to the latest action and information from the environment about the step, i.e. metrics, debug info. - :meth:`reset` - Resets the environment to an initial state, required before calling step. Returns the first agent observation for an episode and information, i.e. metrics, debug info. - :meth:`render` - Renders the environments to help visualise what the agent see, examples modes are "human", "rgb_array", "ansi" for text. - :meth:`close` - Closes the environment, important when external software is used, i.e. pygame for rendering, databases Environments have additional attributes for users to understand the implementation - :attr:`action_space` - The Space object corresponding to valid actions, all valid actions should be contained within the space. - :attr:`observation_space` - The Space object corresponding to valid observations, all valid observations should be contained within the space. - :attr:`spec` - An environment spec that contains the information used to initialize the environment from :meth:`gymnasium.make` - :attr:`metadata` - The metadata of the environment, e.g. `{"render_modes": ["rgb_array", "human"], "render_fps": 30}`. For Jax or Torch, this can be indicated to users with `"jax"=True` or `"torch"=True`. - :attr:`np_random` - The random number generator for the environment. This is automatically assigned during ``super().reset(seed=seed)`` and when assessing :attr:`np_random`. .. seealso:: For modifying or extending environments use the :class:`gymnasium.Wrapper` class .. note:: To get reproducible sampling of actions, a seed can be set with ``env.action_space.seed(123)``. .. note:: For strict type checking (e.g. mypy or pyright), :class:`Env` is a generic class with two parameterized types: ``ObsType`` and ``ActType``. The ``ObsType`` and ``ActType`` are the expected types of the observations and actions used in :meth:`reset` and :meth:`step`. The environment's :attr:`observation_space` and :attr:`action_space` should have type ``Space[ObsType]`` and ``Space[ActType]``, see a space's implementation to find its parameterized type. .. py:attribute:: _skip_after_negotiations :value: True .. py:attribute:: _extra_checks :value: True .. py:attribute:: _reward_function .. py:attribute:: _world :type: scml.oneshot.world.SCMLBaseWorld :value: None .. py:attribute:: _agent_type .. py:attribute:: _agent_params :value: None .. py:attribute:: _agent_id :type: str :value: '' .. py:attribute:: _agent :type: scml.oneshot.agent.OneShotAgent :value: None .. py:attribute:: _obs_manager .. py:attribute:: _action_manager .. py:attribute:: _context .. py:attribute:: action_space .. py:attribute:: observation_space .. py:attribute:: render_mode :value: None .. py:method:: _get_obs() .. py:method:: calc_info() Calculates info to be returned from `step()`. .. py:method:: _render_frame() Used for rendering. Override with your rendering code .. py:method:: close() After the user has finished using the environment, close contains the code necessary to "clean up" the environment. This is critical for closing rendering windows, database or HTTP connections. Calling ``close`` on an already closed environment has no effect and won't raise an error. .. py:method:: render() Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment. The environment's :attr:`metadata` render modes (`env.metadata["render_modes"]`) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through `gymnasium.make` which automatically applies a wrapper to collect rendered frames. .. note:: As the :attr:`render_mode` is known during ``__init__``, the objects used to render the environment state should be initialised in ``__init__``. By convention, if the :attr:`render_mode` is: - None (default): no render is computed. - "human": The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during :meth:`step` and :meth:`render` doesn't need to be called. Returns ``None``. - "rgb_array": Return a single frame representing the current state of the environment. A frame is a ``np.ndarray`` with shape ``(x, y, 3)`` representing RGB values for an x-by-y pixel image. - "ansi": Return a strings (``str``) or ``StringIO.StringIO`` containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors). - "rgb_array_list" and "ansi_list": List based version of render modes are possible (except Human) through the wrapper, :py:class:`gymnasium.wrappers.RenderCollection` that is automatically applied during ``gymnasium.make(..., render_mode="rgb_array_list")``. The frames collected are popped after :meth:`render` is called or :meth:`reset`. .. note:: Make sure that your class's :attr:`metadata` ``"render_modes"`` key includes the list of supported modes. .. versionchanged:: 0.25.0 The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., ``gymnasium.make("CartPole-v1", render_mode="human")`` .. py:method:: reset(*, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[Any, dict[str, Any]] Resets the environment to an initial internal state, returning an initial observation and info. This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the ``seed`` parameter otherwise if the environment already has a random number generator and :meth:`reset` is called with ``seed=None``, the RNG is not reset. Therefore, :meth:`reset` should (in the typical use case) be called with a seed right after initialization and then never again. For Custom environments, the first line of :meth:`reset` should be ``super().reset(seed=seed)`` which implements the seeding correctly. .. versionchanged:: v0.25 The ``return_info`` parameter was removed and now info is expected to be returned. :param seed: The seed that is used to initialize the environment's PRNG (`np_random`) and the read-only attribute `np_random_seed`. If the environment does not already have a PRNG and ``seed=None`` (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and ``seed=None`` is passed, the PRNG will *not* be reset and the env's :attr:`np_random_seed` will *not* be altered. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer *right after the environment has been initialized and then never again*. Please refer to the minimal example above to see this paradigm in action. :type seed: optional int :param options: Additional information to specify how the environment is reset (optional, depending on the specific environment) :type options: optional dict :returns: Observation of the initial state. This will be an element of :attr:`observation_space` (typically a numpy array) and is analogous to the observation returned by :meth:`step`. info (dictionary): This dictionary contains auxiliary information complementing ``observation``. It should be analogous to the ``info`` returned by :meth:`step`. :rtype: observation (ObsType) .. py:method:: step(action) Run one timestep of the environment's dynamics using the agent actions. When the end of an episode is reached (``terminated or truncated``), it is necessary to call :meth:`reset` to reset this environment's state for the next episode. .. versionchanged:: 0.26 The Step API was changed removing ``done`` in favor of ``terminated`` and ``truncated`` to make it clearer to users when the environment had terminated or truncated which is critical for reinforcement learning bootstrapping algorithms. :param action: an action provided by the agent to update the environment state. :type action: ActType :returns: An element of the environment's :attr:`observation_space` as the next observation due to the agent actions. An example is a numpy array containing the positions and velocities of the pole in CartPole. reward (SupportsFloat): The reward as a result of taking the action. terminated (bool): Whether the agent reaches the terminal state (as defined under the MDP of the task) which can be positive or negative. An example is reaching the goal state or moving into the lava from the Sutton and Barto Gridworld. If true, the user needs to call :meth:`reset`. truncated (bool): Whether the truncation condition outside the scope of the MDP is satisfied. Typically, this is a timelimit, but could also be used to indicate an agent physically going out of bounds. Can be used to end the episode prematurely before a terminal state is reached. If true, the user needs to call :meth:`reset`. info (dict): Contains auxiliary diagnostic information (helpful for debugging, learning, and logging). This might, for instance, contain: metrics that describe the agent's performance state, variables that are hidden from observations, or individual reward terms that are combined to produce the total reward. In OpenAI Gym gymnasium.spaces.Space Creates the observation space .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Encodes an observation from the agent's awi .. py:method:: make_first_observation(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Creates the initial observation (returned from gym's reset()) .. py:method:: get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) -> dict[str, negmas.outcomes.Outcome | None] Gets the offers from an encoded awi .. py:class:: FlexibleObservationManager Bases: :py:obj:`BaseObservationManager` An observation manager that can be used with any SCML world. :param capacity_multiplier: A factor to multiply by the number of lines to give the maximum quantity allowed in offers :param exogenous_multiplier: A factor to multiply maximum production capacity with when encoding exogenous quantities :param continuous: If given the observation space will be a Box otherwise it will be a MultiDiscrete :param n_prices: The number of prices to use for encoding the unit price (if not `continuous`) :param max_production_cost: The limit for production cost. Anything above that will be mapped to this max :param max_group_size: Maximum size used for grouping observations from multiple partners. This will be used in the number of partners in the simulation is larger than the number used for training. :param n_past_received_offers: Number of past received offers to add to the observation. :param n_bins: N. bins to use for discretization (if not `continuous`) :param n_sigmas: The number of sigmas used for limiting the range of randomly distributed variables :param extra_checks: If given, extra checks are applied to make sure encoding and decoding make sense Remarks: ... .. py:attribute:: capacity_multiplier :type: int :value: 1 .. py:attribute:: n_prices :type: int :value: 2 .. py:attribute:: max_group_size :type: int :value: 2 .. py:attribute:: reduce_space_size :type: bool :value: True .. py:attribute:: n_past_received_offers :type: int :value: 1 .. py:attribute:: extra_checks :type: bool :value: False .. py:attribute:: n_bins :type: int :value: 40 .. py:attribute:: n_sigmas :type: int :value: 2 .. py:attribute:: max_production_cost :type: int :value: 10 .. py:attribute:: exogenous_multiplier :type: int :value: 1 .. py:attribute:: max_quantity :type: int .. py:attribute:: _chosen_partner_indices :type: list[int] | None .. py:attribute:: _previous_offers :type: collections.deque .. py:attribute:: _dims :type: list[int] | None .. py:method:: __attrs_post_init__() .. py:method:: get_dims() -> list[int] Get the sizes of all dimensions in the observation space. Used if not continuous. .. py:method:: make_space() -> gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box Creates the action space .. py:method:: make_first_observation(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Creates the initial observation (returned from gym's reset()) .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Encodes the awi as an array .. py:method:: extra_obs(awi: scml.oneshot.awi.OneShotAWI) -> list[tuple[float, int] | float] The observation values other than offers and previous offers. :returns: A list of tuples. Each is some observation variable as a real number between zero and one and a number of bins to use for discrediting this variable. If a single value, the number of bins will be self.n_bin .. py:method:: get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) -> dict[str, negmas.outcomes.Outcome | None] Gets offers from an encoded awi. .. py:data:: DefaultObservationManager The default observation manager .. py:function:: random_action(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv) -> numpy.ndarray Samples a random action from the action space of the .. py:function:: random_policy(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv, pend: float = 0.05, paccept: float = 0.15) -> numpy.ndarray Ends the negotiation or accepts with a predefined probability or samples a random response. .. py:function:: greedy_policy(obs: numpy.ndarray, awi: scml.oneshot.awi.OneShotAWI, obs_manager: scml.oneshot.rl.observation.ObservationManager, action_manager: scml.oneshot.rl.action.ActionManager = FlexibleActionManager(ANACOneShotContext()), debug=False, distributor: Callable[[int, int], list[int]] = all_but_concentrated) -> numpy.ndarray A simple greedy policy. :param obs: The current observation :param awi: The AWI of the agent running the policy :param obs_manager: The observation manager used to encode the observation :param action_manager: The action manager to be used to encode the action :param debug: If True, extra assertions are tested :param distributor: A callable that receives a total quantity to be distributed over n partners and returns a list of n values that sum to this total quantity Remarks: - Accepts the subset of offers with maximum total quantity under current needs. - The remaining quantity is distributed over the remaining partners using the distributor function - Prices are set to the worst for the agent if the price range is small else they are set randomly .. py:class:: RewardFunction Bases: :py:obj:`Protocol` Represents a reward function. Remarks: - `before_action` is called before the action is executed for initialization and should return info to be passed to the call - `__call__` is called with the awi (to get the state), action and info and should return the reward .. py:method:: before_action(awi: scml.oneshot.awi.OneShotAWI) -> Any Called before executing the action from the RL agent to save any required information for calculating the reward in its return Remarks: The returned value will be passed as `info` to `__call__()` when it is time to calculate the reward. .. py:method:: __call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: Any) -> float Called to calculate the reward to be given to the agent at the end of a step. :param awi: `OneShotAWI` to access the agent's state :param action: The action (decoded) as a mapping from partner ID to responses to their last offer. :param info: Information generated from `before_action()`. You an use this to store baselines for calculating the reward :returns: The reward (a number) to be given to the agent at the end of the step. .. py:class:: DefaultRewardFunction Bases: :py:obj:`RewardFunction` The default reward function of SCML Remarks: - The reward is the difference between the balance before the action and after it. .. py:method:: before_action(awi: scml.oneshot.awi.OneShotAWI) -> float Called before executing the action from the RL agent to save any required information for calculating the reward in its return Remarks: The returned value will be passed as `info` to `__call__()` when it is time to calculate the reward. .. py:method:: __call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: float) Called to calculate the reward to be given to the agent at the end of a step. :param awi: `OneShotAWI` to access the agent's state :param action: The action (decoded) as a mapping from partner ID to responses to their last offer. :param info: Information generated from `before_action()`. You an use this to store baselines for calculating the reward :returns: The reward (a number) to be given to the agent at the end of the step. .. py:data:: __all__