scml.std.rl =========== .. py:module:: scml.std.rl Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/scml/std/rl/action/index /autoapi/scml/std/rl/agent/index /autoapi/scml/std/rl/common/index /autoapi/scml/std/rl/env/index /autoapi/scml/std/rl/observation/index /autoapi/scml/std/rl/policies/index /autoapi/scml/std/rl/reward/index Attributes ---------- .. autoapisummary:: scml.std.rl.DefaultActionManager scml.std.rl.StdRLAgent scml.std.rl.RLState scml.std.rl.RLAction scml.std.rl.RLModel scml.std.rl.DefaultObservationManager scml.std.rl.__all__ Classes ------- .. autoapisummary:: scml.std.rl.ActionManager scml.std.rl.FlexibleActionManager scml.std.rl.StdEnv scml.std.rl.ObservationManager scml.std.rl.FlexibleObservationManager scml.std.rl.RewardFunction scml.std.rl.DefaultRewardFunction Functions --------- .. autoapisummary:: scml.std.rl.model_wrapper scml.std.rl.random_action scml.std.rl.random_policy scml.std.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:data:: StdRLAgent .. 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:: StdEnv(action_manager: scml.oneshot.rl.action.ActionManager, observation_manager: scml.oneshot.rl.observation.ObservationManager, reward_function: scml.oneshot.rl.reward.RewardFunction = DefaultRewardFunction(), render_mode=None, context: scml.oneshot.context.GeneralContext = FixedPartnerNumbersStdContext(), agent_type: type[scml.std.agent.StdAgent] = StdPlaceholder, agent_params: dict[str, Any] | None = None, extra_checks: bool = True, skip_after_negotiations: bool = True) Bases: :py:obj:`scml.oneshot.rl.env.OneShotEnv` 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:class:: ObservationManager Bases: :py:obj:`Protocol` Manages the observations of an agent in an RL environment .. py:property:: context :type: scml.oneshot.context.BaseContext .. py:method:: make_space() -> 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__