diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__init__.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af19c66a02e87a367cf58ed8117e4937369b9e1 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..907ff8dcbc1062e1f167a234af242d84d65bf5fb Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f32f9b185026001a17dcd1941ad01058eab1b638 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8c1a7a07fe0d530d753480d76a744f89c476039 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/clip.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..da7c8b97bf927bf4d97c7feed8285faa55ac89cf --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/clip.py @@ -0,0 +1,41 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.spaces.space_utils import clip_action, get_base_struct_from_space +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ClipActionsConnector(ActionConnector): + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + (clip_action(actions, self._action_space_struct), states, fetches), + ) + + def to_state(self): + return ClipActionsConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ClipActionsConnector(ctx) + + +register_connector(ClipActionsConnector.__name__, ClipActionsConnector) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/lambdas.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/lambdas.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf862dd834d57e8b77a677c5f6fa7df8755779e --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/lambdas.py @@ -0,0 +1,76 @@ +from typing import Any, Callable, Dict, Type + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + PolicyOutputType, + StateBatches, + TensorStructType, +) +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def register_lambda_action_connector( + name: str, fn: Callable[[TensorStructType, StateBatches, Dict], PolicyOutputType] +) -> Type[ActionConnector]: + """A util to register any function transforming PolicyOutputType as an ActionConnector. + + The only requirement is that fn should take actions, states, and fetches as input, + and return transformed actions, states, and fetches. + + Args: + name: Name of the resulting actor connector. + fn: The function that transforms PolicyOutputType. + + Returns: + A new ActionConnector class that transforms PolicyOutputType using fn. + """ + + class LambdaActionConnector(ActionConnector): + def transform( + self, ac_data: ActionConnectorDataType + ) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + fn(actions, states, fetches), + ) + + def to_state(self): + return name, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return LambdaActionConnector(ctx) + + LambdaActionConnector.__name__ = name + LambdaActionConnector.__qualname__ = name + + register_connector(name, LambdaActionConnector) + + return LambdaActionConnector + + +# Convert actions and states into numpy arrays if necessary. +ConvertToNumpyConnector = OldAPIStack( + register_lambda_action_connector( + "ConvertToNumpyConnector", + lambda actions, states, fetches: ( + convert_to_numpy(actions), + convert_to_numpy(states), + fetches, + ), + ), +) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/pipeline.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..b96296e7584227b79179faf6907753a616b0329f --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/action/pipeline.py @@ -0,0 +1,61 @@ +import logging +from typing import Any, List +from collections import defaultdict + +from ray.rllib.connectors.connector import ( + ActionConnector, + Connector, + ConnectorContext, + ConnectorPipeline, +) +from ray.rllib.connectors.registry import get_connector, register_connector +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.util.timer import _Timer + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class ActionConnectorPipeline(ConnectorPipeline, ActionConnector): + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + super().__init__(ctx, connectors) + self.timers = defaultdict(_Timer) + + def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + for c in self.connectors: + timer = self.timers[str(c)] + with timer: + ac_data = c(ac_data) + return ac_data + + def to_state(self): + children = [] + for c in self.connectors: + state = c.to_state() + assert isinstance(state, tuple) and len(state) == 2, ( + "Serialized connector state must be in the format of " + f"Tuple[name: str, params: Any]. Instead we got {state}" + f"for connector {c.__name__}." + ) + children.append(state) + return ActionConnectorPipeline.__name__, children + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + assert ( + type(params) == list + ), "ActionConnectorPipeline takes a list of connector params." + connectors = [] + for state in params: + try: + name, subparams = state + connectors.append(get_connector(name, ctx, subparams)) + except Exception as e: + logger.error(f"Failed to de-serialize connector state: {state}") + raise e + return ActionConnectorPipeline(ctx, connectors) + + +register_connector(ActionConnectorPipeline.__name__, ActionConnectorPipeline) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c10ace8780e1b746ec23c9e028120a762722dcf9 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9ddf64fc54d46195f731c662e87191467a60327 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e7b034f6702fdc63219eac620118b7bf7a69c3b Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9d55e4aea24ab16691aa61116dd76ac7e9a71608 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py @@ -0,0 +1,56 @@ +from typing import Any + +import numpy as np + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ClipRewardAgentConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, sign=False, limit=None): + super().__init__(ctx) + assert ( + not sign or not limit + ), "should not enable both sign and limit reward clipping." + self.sign = sign + self.limit = limit + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) == dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + if SampleBatch.REWARDS not in d: + # Nothing to clip. May happen for initial obs. + return ac_data + + if self.sign: + d[SampleBatch.REWARDS] = np.sign(d[SampleBatch.REWARDS]) + elif self.limit: + d[SampleBatch.REWARDS] = np.clip( + d[SampleBatch.REWARDS], + a_min=-self.limit, + a_max=self.limit, + ) + return ac_data + + def to_state(self): + return ClipRewardAgentConnector.__name__, { + "sign": self.sign, + "limit": self.limit, + } + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ClipRewardAgentConnector(ctx, **params) + + +register_connector(ClipRewardAgentConnector.__name__, ClipRewardAgentConnector) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py new file mode 100644 index 0000000000000000000000000000000000000000..05a714a0df982e36bce96c33ddfb6f6e9ce05188 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py @@ -0,0 +1,86 @@ +from typing import Any, Callable, Type + +import numpy as np +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentConnectorsOutput, +) +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def register_lambda_agent_connector( + name: str, fn: Callable[[Any], Any] +) -> Type[AgentConnector]: + """A util to register any simple transforming function as an AgentConnector + + The only requirement is that fn should take a single data object and return + a single data object. + + Args: + name: Name of the resulting actor connector. + fn: The function that transforms env / agent data. + + Returns: + A new AgentConnector class that transforms data using fn. + """ + + class LambdaAgentConnector(AgentConnector): + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + return AgentConnectorDataType( + ac_data.env_id, ac_data.agent_id, fn(ac_data.data) + ) + + def to_state(self): + return name, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return LambdaAgentConnector(ctx) + + LambdaAgentConnector.__name__ = name + LambdaAgentConnector.__qualname__ = name + + register_connector(name, LambdaAgentConnector) + + return LambdaAgentConnector + + +@OldAPIStack +def flatten_data(data: AgentConnectorsOutput): + assert isinstance( + data, AgentConnectorsOutput + ), "Single agent data must be of type AgentConnectorsOutput" + + raw_dict = data.raw_dict + sample_batch = data.sample_batch + + flattened = {} + for k, v in sample_batch.items(): + if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith("state_out_"): + # Do not flatten infos, actions, and state_out_ columns. + flattened[k] = v + continue + if v is None: + # Keep the same column shape. + flattened[k] = None + continue + flattened[k] = np.array(tree.flatten(v)) + flattened = SampleBatch(flattened, is_training=False) + + return AgentConnectorsOutput(raw_dict, flattened) + + +# Agent connector to build and return a flattened observation SampleBatch +# in addition to the original input dict. +FlattenDataAgentConnector = OldAPIStack( + register_lambda_agent_connector("FlattenDataAgentConnector", flatten_data) +) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..0113c1c45887a05ef480bbf3a34d6e60eb8edea7 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py @@ -0,0 +1,72 @@ +import logging +from typing import Any, List +from collections import defaultdict + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, + ConnectorPipeline, +) +from ray.rllib.connectors.registry import get_connector, register_connector +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack +from ray.util.timer import _Timer + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class AgentConnectorPipeline(ConnectorPipeline, AgentConnector): + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + super().__init__(ctx, connectors) + self.timers = defaultdict(_Timer) + + def reset(self, env_id: str): + for c in self.connectors: + c.reset(env_id) + + def on_policy_output(self, output: ActionConnectorDataType): + for c in self.connectors: + c.on_policy_output(output) + + def __call__( + self, acd_list: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + ret = acd_list + for c in self.connectors: + timer = self.timers[str(c)] + with timer: + ret = c(ret) + return ret + + def to_state(self): + children = [] + for c in self.connectors: + state = c.to_state() + assert isinstance(state, tuple) and len(state) == 2, ( + "Serialized connector state must be in the format of " + f"Tuple[name: str, params: Any]. Instead we got {state}" + f"for connector {c.__name__}." + ) + children.append(state) + return AgentConnectorPipeline.__name__, children + + @staticmethod + def from_state(ctx: ConnectorContext, params: List[Any]): + assert ( + type(params) == list + ), "AgentConnectorPipeline takes a list of connector params." + connectors = [] + for state in params: + try: + name, subparams = state + connectors.append(get_connector(name, ctx, subparams)) + except Exception as e: + logger.error(f"Failed to de-serialize connector state: {state}") + raise e + return AgentConnectorPipeline(ctx, connectors) + + +register_connector(AgentConnectorPipeline.__name__, AgentConnectorPipeline) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4516abd8bbe0ad47d6cc96baedb8909ff26b62fd --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py @@ -0,0 +1,120 @@ +from collections import defaultdict +import logging +import pickle +from typing import Any + +import numpy as np +from ray.rllib.utils.annotations import override +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, +) +from ray import cloudpickle +from ray.rllib.connectors.registry import register_connector +from ray.rllib.core.columns import Columns +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class StateBufferConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, states: Any = None): + super().__init__(ctx) + + self._initial_states = ctx.initial_states + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + self._states = defaultdict(lambda: defaultdict(lambda: (None, None, None))) + self._enable_new_api_stack = False + # TODO(jungong) : we would not need this if policies are never stashed + # during the rollout of a single episode. + if states: + try: + self._states = cloudpickle.loads(states) + except pickle.UnpicklingError: + # StateBufferConnector states are only needed for rare cases + # like stashing then restoring a policy during the rollout of + # a single episode. + # It is ok to ignore the error for most of the cases here. + logger.info( + "Can not restore StateBufferConnector states. This warning can " + "usually be ignore, unless it is from restoring a stashed policy." + ) + + @override(Connector) + def in_eval(self): + super().in_eval() + + def reset(self, env_id: str): + # States should not be carried over between episodes. + if env_id in self._states: + del self._states[env_id] + + def on_policy_output(self, ac_data: ActionConnectorDataType): + # Buffer latest output states for next input __call__. + self._states[ac_data.env_id][ac_data.agent_id] = ac_data.output + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + env_id = ac_data.env_id + agent_id = ac_data.agent_id + assert ( + env_id is not None and agent_id is not None + ), f"StateBufferConnector requires env_id(f{env_id}) and agent_id(f{agent_id})" + + action, states, fetches = self._states[env_id][agent_id] + + if action is not None: + d[SampleBatch.ACTIONS] = action # Last action + else: + # Default zero action. + d[SampleBatch.ACTIONS] = tree.map_structure( + lambda s: np.zeros_like(s.sample(), s.dtype) + if hasattr(s, "dtype") + else np.zeros_like(s.sample()), + self._action_space_struct, + ) + + if states is None: + states = self._initial_states + if self._enable_new_api_stack: + if states: + d[Columns.STATE_OUT] = states + else: + for i, v in enumerate(states): + d["state_out_{}".format(i)] = v + + # Also add extra fetches if available. + if fetches: + d.update(fetches) + + return ac_data + + def to_state(self): + # Note(jungong) : it is ok to use cloudpickle here for stats because: + # 1. self._states may contain arbitary data objects, and will be hard + # to serialize otherwise. + # 2. seriazlized states are only useful if a policy is stashed and + # restored during the rollout of a single episode. So it is ok to + # use cloudpickle for such non-persistent data bits. + states = cloudpickle.dumps(self._states) + return StateBufferConnector.__name__, states + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return StateBufferConnector(ctx, params) + + +register_connector(StateBufferConnector.__name__, StateBufferConnector) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..583825fb1d677f7f06c27ce4470c01fc53837e7d --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py @@ -0,0 +1,381 @@ +from collections import defaultdict +import logging +from typing import Any, Collection, Dict, List, Optional, Tuple, Type, Union + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.typing import EpisodeType, StateDict +from ray.util.annotations import PublicAPI +from ray.util.timer import _Timer + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class ConnectorPipelineV2(ConnectorV2): + """Utility class for quick manipulation of a connector pipeline.""" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.observation_space + + @override(ConnectorV2) + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.action_space + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + connectors: Optional[List[ConnectorV2]] = None, + **kwargs, + ): + """Initializes a ConnectorPipelineV2 instance. + + Args: + input_observation_space: The (optional) input observation space for this + connector piece. This is the space coming from a previous connector + piece in the (env-to-module or learner) pipeline or is directly + defined within the gym.Env. + input_action_space: The (optional) input action space for this connector + piece. This is the space coming from a previous connector piece in the + (module-to-env) pipeline or is directly defined within the gym.Env. + connectors: A list of individual ConnectorV2 pieces to be added to this + pipeline during construction. Note that you can always add (or remove) + more ConnectorV2 pieces later on the fly. + """ + self.connectors = [] + + for conn in connectors: + # If we have a `ConnectorV2` instance just append. + if isinstance(conn, ConnectorV2): + self.connectors.append(conn) + # If, we have a class with `args` and `kwargs`, build the instance. + # Note that this way of constructing a pipeline should only be + # used internally when restoring the pipeline state from a + # checkpoint. + elif isinstance(conn, tuple) and len(conn) == 3: + self.connectors.append(conn[0](*conn[1], **conn[2])) + + super().__init__(input_observation_space, input_action_space, **kwargs) + + self.timers = defaultdict(_Timer) + + def __len__(self): + return len(self.connectors) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + """In a pipeline, we simply call each of our connector pieces after each other. + + Each connector piece receives as input the output of the previous connector + piece in the pipeline. + """ + shared_data = shared_data if shared_data is not None else {} + # Loop through connector pieces and call each one with the output of the + # previous one. Thereby, time each connector piece's call. + for connector in self.connectors: + timer = self.timers[str(connector)] + with timer: + batch = connector( + rl_module=rl_module, + batch=batch, + episodes=episodes, + explore=explore, + shared_data=shared_data, + # Deprecated arg. + data=batch, + **kwargs, + ) + if not isinstance(batch, dict): + raise ValueError( + f"`data` returned by ConnectorV2 {connector} must be a dict! " + f"You returned {batch}. Check your (custom) connectors' " + f"`__call__()` method's return value and make sure you return " + f"the `data` arg passed in (either altered or unchanged)." + ) + return batch + + def remove(self, name_or_class: Union[str, Type]): + """Remove a single connector piece in this pipeline by its name or class. + + Args: + name: The name of the connector piece to be removed from the pipeline. + """ + idx = -1 + for i, c in enumerate(self.connectors): + if c.__class__.__name__ == name_or_class: + idx = i + break + if idx >= 0: + del self.connectors[idx] + self._fix_spaces(self.input_observation_space, self.input_action_space) + logger.info( + f"Removed connector {name_or_class} from {self.__class__.__name__}." + ) + else: + logger.warning( + f"Trying to remove a non-existent connector {name_or_class}." + ) + + def insert_before( + self, + name_or_class: Union[str, type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece before an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece before which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 before which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + next_connector = self.connectors[idx] + + self.connectors.insert(idx, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} before {name_or_class} " + f"to {self.__class__.__name__}." + ) + return next_connector + + def insert_after( + self, + name_or_class: Union[str, Type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece after an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece after which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 after which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + prev_connector = self.connectors[idx] + + self.connectors.insert(idx + 1, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} after {name_or_class} " + f"to {self.__class__.__name__}." + ) + + return prev_connector + + def prepend(self, connector: ConnectorV2) -> None: + """Prepend a new connector at the beginning of a connector pipeline. + + Args: + connector: The new connector piece to be prepended to this pipeline. + """ + self.connectors.insert(0, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the beginning of " + f"{self.__class__.__name__}." + ) + + def append(self, connector: ConnectorV2) -> None: + """Append a new connector at the end of a connector pipeline. + + Args: + connector: The new connector piece to be appended to this pipeline. + """ + self.connectors.append(connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the end of " + f"{self.__class__.__name__}." + ) + + @override(ConnectorV2) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = {} + for conn in self.connectors: + conn_name = type(conn).__name__ + if self._check_component(conn_name, components, not_components): + state[conn_name] = conn.get_state( + components=self._get_subcomponents(conn_name, components), + not_components=self._get_subcomponents(conn_name, not_components), + **kwargs, + ) + return state + + @override(ConnectorV2) + def set_state(self, state: Dict[str, Any]) -> None: + for conn in self.connectors: + conn_name = type(conn).__name__ + if conn_name in state: + conn.set_state(state[conn_name]) + + @override(Checkpointable) + def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: + return [(type(conn).__name__, conn) for conn in self.connectors] + + # Note that we don't have to override Checkpointable.get_ctor_args_and_kwargs and + # don't have to return the `connectors` c'tor kwarg from there. This is b/c all + # connector pieces in this pipeline are themselves Checkpointable components, + # so they will be properly written into this pipeline's checkpoint. + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (self.input_observation_space, self.input_action_space), # *args + { + "connectors": [ + (type(conn), *conn.get_ctor_args_and_kwargs()) + for conn in self.connectors + ] + }, + ) + + @override(ConnectorV2) + def reset_state(self) -> None: + for conn in self.connectors: + conn.reset_state() + + @override(ConnectorV2) + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + merged_states = {} + if not states: + return merged_states + for i, (key, item) in enumerate(states[0].items()): + state_list = [state[key] for state in states] + conn = self.connectors[i] + merged_states[key] = conn.merge_states(state_list) + return merged_states + + def __repr__(self, indentation: int = 0): + return "\n".join( + [" " * indentation + self.__class__.__name__] + + [c.__str__(indentation + 4) for c in self.connectors] + ) + + def __getitem__( + self, + key: Union[str, int, Type], + ) -> Union[ConnectorV2, List[ConnectorV2]]: + """Returns a single ConnectorV2 or list of ConnectorV2s that fit `key`. + + If key is an int, we return a single ConnectorV2 at that index in this pipeline. + If key is a ConnectorV2 type or a string matching the class name of a + ConnectorV2 in this pipeline, we return a list of all ConnectorV2s in this + pipeline matching the specified class. + + Args: + key: The key to find or to index by. + + Returns: + A single ConnectorV2 or a list of ConnectorV2s matching `key`. + """ + # Key is an int -> Index into pipeline and return. + if isinstance(key, int): + return self.connectors[key] + # Key is a class. + elif isinstance(key, type): + results = [] + for c in self.connectors: + if issubclass(c.__class__, key): + results.append(c) + return results + # Key is a string -> Find connector(s) by name. + elif isinstance(key, str): + results = [] + for c in self.connectors: + if c.name == key: + results.append(c) + return results + # Slicing not supported (yet). + elif isinstance(key, slice): + raise NotImplementedError( + "Slicing of ConnectorPipelineV2 is currently not supported!" + ) + else: + raise NotImplementedError( + f"Indexing ConnectorPipelineV2 by {type(key)} is currently not " + f"supported!" + ) + + @property + def observation_space(self): + if len(self) > 0: + return self.connectors[-1].observation_space + return self._observation_space + + @property + def action_space(self): + if len(self) > 0: + return self.connectors[-1].action_space + return self._action_space + + def _fix_spaces(self, input_observation_space, input_action_space): + if len(self) > 0: + # Fix each connector's input_observation- and input_action space in + # the pipeline. + obs_space = input_observation_space + act_space = input_action_space + for con in self.connectors: + con.input_action_space = act_space + con.input_observation_space = obs_space + obs_space = con.observation_space + act_space = con.action_space diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2873294ac694e5e426d1dd4d47a59d9b0d87f06c --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py @@ -0,0 +1,36 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.env_to_module.env_to_module_pipeline import ( + EnvToModulePipeline, +) +from ray.rllib.connectors.env_to_module.flatten_observations import ( + FlattenObservations, +) +from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter +from ray.rllib.connectors.env_to_module.prev_actions_prev_rewards import ( + PrevActionsPrevRewards, +) +from ray.rllib.connectors.env_to_module.write_observations_to_episodes import ( + WriteObservationsToEpisodes, +) + + +__all__ = [ + "AddObservationsFromEpisodesToBatch", + "AddStatesFromEpisodesToBatch", + "AgentToModuleMapping", + "BatchIndividualItems", + "EnvToModulePipeline", + "FlattenObservations", + "MeanStdFilter", + "NumpyToTensor", + "PrevActionsPrevRewards", + "WriteObservationsToEpisodes", +] diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d94f861fca67bcd9ce5da83156f2937903e2c630 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f2eac30ff0970525bff71531ec8b829064c7a00 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py new file mode 100644 index 0000000000000000000000000000000000000000..483b02aeb4a4e79e869afcc5a841ca5a0fb0ef46 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py @@ -0,0 +1,211 @@ +from typing import Any, Collection, Dict, List, Optional + +import gymnasium as gym +from gymnasium.spaces import Box +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import flatten_inputs_to_1d_tensor +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import AgentID, EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class FlattenObservations(ConnectorV2): + """A connector piece that flattens all observation components into a 1D array. + + - Should be used only in env-to-module pipelines. + - Works directly on the incoming episodes list and changes the last observation + in-place (write the flattened observation back into the episode). + - This connector does NOT alter the incoming batch (`data`) when called. + - This connector does NOT work in a `LearnerConnectorPipeline` because it requires + the incoming episodes to still be ongoing (in progress) as it only alters the + latest observation, not all observations in an episode. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.env_to_module import FlattenObservations + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Some arbitrarily nested, complex observation space. + obs_space = gym.spaces.Dict({ + "a": gym.spaces.Box(-10.0, 10.0, (), np.float32), + "b": gym.spaces.Tuple([ + gym.spaces.Discrete(2), + gym.spaces.Box(-1.0, 1.0, (2, 1), np.float32), + ]), + "c": gym.spaces.MultiDiscrete([2, 3]), + }) + act_space = gym.spaces.Discrete(2) + + # Two example episodes, both with initial (reset) observations coming from the + # above defined observation space. + episode_1 = SingleAgentEpisode( + observations=[ + { + "a": np.array(-10.0, np.float32), + "b": (1, np.array([[-1.0], [-1.0]], np.float32)), + "c": np.array([0, 2]), + }, + ], + ) + episode_2 = SingleAgentEpisode( + observations=[ + { + "a": np.array(10.0, np.float32), + "b": (0, np.array([[1.0], [1.0]], np.float32)), + "c": np.array([1, 1]), + }, + ], + ) + + # Construct our connector piece. + connector = FlattenObservations(obs_space, act_space) + + # Call our connector piece with the example data. + output_batch = connector( + rl_module=None, # This connector works without an RLModule. + batch={}, # This connector does not alter the input batch. + episodes=[episode_1, episode_2], + explore=True, + shared_data={}, + ) + + # The connector does not alter the data and acts as pure pass-through. + check(output_batch, {}) + + # The connector has flattened each item in the episodes to a 1D tensor. + check( + episode_1.get_observations(0), + # box() disc(2). box(2, 1). multidisc(2, 3)........ + np.array([-10.0, 0.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0]), + ) + check( + episode_2.get_observations(0), + # box() disc(2). box(2, 1). multidisc(2, 3)........ + np.array([10.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]), + ) + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ) -> gym.Space: + self._input_obs_base_struct = get_base_struct_from_space( + self.input_observation_space + ) + if self._multi_agent: + spaces = {} + for agent_id, space in self._input_obs_base_struct.items(): + if self._agent_ids and agent_id not in self._agent_ids: + spaces[agent_id] = self._input_obs_base_struct[agent_id] + else: + sample = flatten_inputs_to_1d_tensor( + tree.map_structure( + lambda s: s.sample(), + self._input_obs_base_struct[agent_id], + ), + self._input_obs_base_struct[agent_id], + batch_axis=False, + ) + spaces[agent_id] = Box( + float("-inf"), float("inf"), (len(sample),), np.float32 + ) + return gym.spaces.Dict(spaces) + else: + sample = flatten_inputs_to_1d_tensor( + tree.map_structure( + lambda s: s.sample(), + self._input_obs_base_struct, + ), + self._input_obs_base_struct, + batch_axis=False, + ) + return Box(float("-inf"), float("inf"), (len(sample),), np.float32) + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + multi_agent: bool = False, + agent_ids: Optional[Collection[AgentID]] = None, + **kwargs, + ): + """Initializes a FlattenObservations instance. + + Args: + multi_agent: Whether this connector operates on multi-agent observations, + in which case, the top-level of the Dict space (where agent IDs are + mapped to individual agents' observation spaces) is left as-is. + agent_ids: If multi_agent is True, this argument defines a collection of + AgentIDs for which to flatten. AgentIDs not in this collection are + ignored. + If None, flatten observations for all AgentIDs. None is the default. + """ + self._input_obs_base_struct = None + self._multi_agent = multi_agent + self._agent_ids = agent_ids + + super().__init__(input_observation_space, input_action_space, **kwargs) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=True + ): + # Episode is not finalized yet and thus still operates on lists of items. + assert not sa_episode.is_finalized + + last_obs = sa_episode.get_observations(-1) + + if self._multi_agent: + if ( + self._agent_ids is not None + and sa_episode.agent_id not in self._agent_ids + ): + flattened_obs = last_obs + else: + flattened_obs = flatten_inputs_to_1d_tensor( + inputs=last_obs, + # In the multi-agent case, we need to use the specific agent's + # space struct, not the multi-agent observation space dict. + spaces_struct=self._input_obs_base_struct[sa_episode.agent_id], + # Our items are individual observations (no batch axis present). + batch_axis=False, + ) + else: + flattened_obs = flatten_inputs_to_1d_tensor( + inputs=last_obs, + spaces_struct=self._input_obs_base_struct, + # Our items are individual observations (no batch axis present). + batch_axis=False, + ) + + # Write new observation directly back into the episode. + sa_episode.set_observations(at_indices=-1, new_data=flattened_obs) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..25c12fa4526a8cfb090360ab704e31ab889467da --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py @@ -0,0 +1,6 @@ +from functools import partial + +from ray.rllib.connectors.common.frame_stacking import _FrameStacking + + +FrameStackingEnvToModule = partial(_FrameStacking, as_learner_connector=False) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..120099ffe50b82f74490b71102b942dce1ad7e78 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py @@ -0,0 +1,80 @@ +import abc +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ObservationPreprocessor(ConnectorV2, abc.ABC): + """Env-to-module connector performing one preprocessor step on the last observation. + + This is a convenience class that simplifies the writing of few-step preprocessor + connectors. + + Users must implement the `preprocess()` method, which simplifies the usual procedure + of extracting some data from a list of episodes and adding it to the batch to a mere + "old-observation --transform--> return new-observation" step. + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Users should override this method only in case the `ObservationPreprocessor` + # changes the observation space of the pipeline. In this case, return the new + # observation space based on the incoming one (`input_observation_space`). + return super().recompute_output_observation_space( + input_observation_space, input_action_space + ) + + @abc.abstractmethod + def preprocess(self, observation): + """Override to implement the preprocessing logic. + + Args: + observation: A single (non-batched) observation item for a single agent to + be processed by this connector. + + Returns: + The new observation after `observation` has been preprocessed. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + persistent_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # We process and then replace observations inside the episodes directly. + # Thus, all following connectors will only see and operate on the already + # processed observation (w/o having access anymore to the original + # observations). + for sa_episode in self.single_agent_episode_iterator(episodes): + observation = sa_episode.get_observations(-1) + + # Process the observation and write the new observation back into the + # episode. + new_observation = self.preprocess(observation=observation) + sa_episode.set_observations(at_indices=-1, new_data=new_observation) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + # Leave `batch` as is. RLlib's default connector will automatically + # populate the OBS column therein from the episodes' now transformed + # observations. + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..329285e6929268d579742642190a49583e5a216e --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym +from gymnasium.spaces import Box +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import ( + batch as batch_fn, + flatten_to_single_ndarray, +) +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class PrevActionsPrevRewards(ConnectorV2): + """A connector piece that adds previous rewards and actions to the input obs. + + - Requires Columns.OBS to be already a part of the batch. + - This connector makes the assumption that under the Columns.OBS key in batch, + there is either a list of individual env observations to be flattened (single-agent + case) or a dict mapping (AgentID, ModuleID)-tuples to lists of data items to be + flattened (multi-agent case). + - Converts Columns.OBS data into a dict (or creates a sub-dict if obs are + already a dict), and adds "prev_rewards" and "prev_actions" + to this dict. The original observations are stored under the self.ORIG_OBS_KEY in + that dict. + - If your RLModule does not handle dict inputs, you will have to plug in an + `FlattenObservations` connector piece after this one. + - Does NOT work in a Learner pipeline as it operates on individual observation + items (as opposed to batched/time-ranked data). + - Therefore, assumes that the altered (flattened) observations will be written + back into the episode by a later connector piece in the env-to-module pipeline + (which this piece is part of as well). + - Only reads reward- and action information from the given list of Episode objects. + - Does NOT write any observations (or other data) to the given Episode objects. + """ + + ORIG_OBS_KEY = "_orig_obs" + PREV_ACTIONS_KEY = "prev_n_actions" + PREV_REWARDS_KEY = "prev_n_rewards" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + if self._multi_agent: + ret = {} + for agent_id, obs_space in input_observation_space.spaces.items(): + act_space = input_action_space[agent_id] + ret[agent_id] = self._convert_individual_space(obs_space, act_space) + return gym.spaces.Dict(ret) + else: + return self._convert_individual_space( + input_observation_space, input_action_space + ) + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + multi_agent: bool = False, + n_prev_actions: int = 1, + n_prev_rewards: int = 1, + **kwargs, + ): + """Initializes a PrevActionsPrevRewards instance. + + Args: + multi_agent: Whether this is a connector operating on a multi-agent + observation space mapping AgentIDs to individual agents' observations. + n_prev_actions: The number of previous actions to include in the output + data. Discrete actions are ont-hot'd. If > 1, will concatenate the + individual action tensors. + n_prev_rewards: The number of previous rewards to include in the output + data. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._multi_agent = multi_agent + self.n_prev_actions = n_prev_actions + self.n_prev_rewards = n_prev_rewards + + # TODO: Move into input_observation_space setter + # Thus far, this connector piece only operates on discrete action spaces. + # act_spaces = [self.input_action_space] + # if self._multi_agent: + # act_spaces = self.input_action_space.spaces.values() + # if not all(isinstance(s, gym.spaces.Discrete) for s in act_spaces): + # raise ValueError( + # f"{type(self).__name__} only works on Discrete action spaces " + # f"thus far (or, for multi-agent, on Dict spaces mapping AgentIDs to " + # f"the individual agents' Discrete action spaces)!" + # ) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=True + ): + # Episode is not finalized yet and thus still operates on lists of items. + assert not sa_episode.is_finalized + + augmented_obs = {self.ORIG_OBS_KEY: sa_episode.get_observations(-1)} + + if self.n_prev_actions: + augmented_obs[self.PREV_ACTIONS_KEY] = flatten_to_single_ndarray( + batch_fn( + sa_episode.get_actions( + indices=slice(-self.n_prev_actions, None), + fill=0.0, + one_hot_discrete=True, + ) + ) + ) + + if self.n_prev_rewards: + augmented_obs[self.PREV_REWARDS_KEY] = np.array( + sa_episode.get_rewards( + indices=slice(-self.n_prev_rewards, None), + fill=0.0, + ) + ) + + # Write new observation directly back into the episode. + sa_episode.set_observations(at_indices=-1, new_data=augmented_obs) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + return batch + + def _convert_individual_space(self, obs_space, act_space): + return gym.spaces.Dict( + { + self.ORIG_OBS_KEY: obs_space, + # Currently only works for Discrete action spaces. + self.PREV_ACTIONS_KEY: Box( + 0.0, 1.0, (act_space.n * self.n_prev_actions,), np.float32 + ), + self.PREV_REWARDS_KEY: Box( + float("-inf"), + float("inf"), + (self.n_prev_rewards,), + np.float32, + ), + } + ) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py new file mode 100644 index 0000000000000000000000000000000000000000..0c269348ce2dae4387f2133557c7a05bcbafbaf7 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py @@ -0,0 +1,131 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class WriteObservationsToEpisodes(ConnectorV2): + """Writes the observations from the batch into the running episodes. + + Note: This is one of the default env-to-module ConnectorV2 pieces that are added + automatically by RLlib into every env-to-module connector pipelines, unless + `config.add_default_connectors_to_env_to_module_pipeline` is set to False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Operates on a batch that already has observations in it and a list of Episode + objects. + - Writes the observation(s) from the batch to all the given episodes. Thereby + the number of observations in the batch must match the length of the list of + episodes given. + - Does NOT alter any observations (or other data) in the batch. + - Can only be used in an EnvToModule pipeline (writing into Episode objects in a + Learner pipeline does not make a lot of sense as - after the learner update - the + list of episodes is discarded). + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.env_to_module import WriteObservationsToEpisodes + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Assume we have two episodes (vectorized), then our forward batch will carry + # two observation records (batch size = 2). + # The connector in this example will write these two (possibly transformed) + # observations back into the two respective SingleAgentEpisode objects. + batch = { + "obs": [np.array([0.0, 1.0], np.float32), np.array([2.0, 3.0], np.float32)], + } + + # Our two episodes have one observation each (i.e. the reset one). This is the + # one that will be overwritten by the connector in this example. + obs_space = gym.spaces.Box(-10.0, 10.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + episodes = [ + SingleAgentEpisode( + observation_space=obs_space, + observations=[np.array([-10, -20], np.float32)], + len_lookback_buffer=0, + ) for _ in range(2) + ] + # Make sure everything is setup correctly. + check(episodes[0].get_observations(0), [-10.0, -20.0]) + check(episodes[1].get_observations(-1), [-10.0, -20.0]) + + # Create our connector piece. + connector = WriteObservationsToEpisodes(obs_space, act_space) + + # Call the connector (and thereby write the transformed observations back + # into the episodes). + output_batch = connector( + rl_module=None, # This particular connector works without an RLModule. + batch=batch, + episodes=episodes, + explore=True, + shared_data={}, + ) + + # The connector does NOT change the data batch being passed through. + check(output_batch, batch) + + # However, the connector has overwritten the last observations in the episodes. + check(episodes[0].get_observations(-1), [0.0, 1.0]) + check(episodes[1].get_observations(0), [2.0, 3.0]) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + observations = batch.get(Columns.OBS) + + if observations is None: + raise ValueError( + f"`batch` must already have a column named {Columns.OBS} in it " + f"for this connector to work!" + ) + + # Note that the following loop works with multi-agent as well as with + # single-agent episode, as long as the following conditions are met (these + # will be validated by `self.single_agent_episode_iterator()`): + # - Per single agent episode, one observation item is expected to exist in + # `data`, either in a list directly under the "obs" key OR for multi-agent: + # in a list sitting under a key `(agent_id, module_id)` of a dict sitting + # under the "obs" key. + for sa_episode, obs in self.single_agent_episode_iterator( + episodes=episodes, zip_with_batch_column=observations + ): + # Make sure episodes are NOT finalized yet (we are expecting to run in an + # env-to-module pipeline). + assert not sa_episode.is_finalized + # Write new information into the episode. + sa_episode.set_observations(at_indices=-1, new_data=obs) + # Change the observation space of the sa_episode. + sa_episode.observation_space = self.observation_space + + # Return the unchanged `batch`. + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dac2308ce2ebf45bf17e0c994cfe8ec12e79a7ea Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c047940bfbaaaa0df3040e7b769a4384b1f817a1 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f6aa743861d1bc6f7205f491e13362b2afb25bd Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09f454da1dd1f89e4330b1a511e8c74aad706826 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..2669dc49b5f9c33868a5b11727006bfa871e07e0 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py @@ -0,0 +1,165 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddColumnsFromEpisodesToTrainBatch(ConnectorV2): + """Adds infos/actions/rewards/terminateds/... to train batch. + + Note: This is one of the default Learner ConnectorV2 pieces that are added + automatically by RLlib into every Learner connector pipeline, unless + `config.add_default_connectors_to_learner_pipeline` is set to False. + + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + Does NOT add observations to train batch (these should have already been added + by another ConnectorV2 piece: `AddObservationsToTrainBatch` in the same pipeline). + + If provided with `episodes` data, this connector piece makes sure that the final + train batch going into the RLModule for updating (`forward_train()` call) contains + at the minimum: + - Observations: From all episodes under the Columns.OBS key. + - Actions, rewards, terminal/truncation flags: From all episodes under the + respective keys. + - All data inside the episodes' `extra_model_outs` property, e.g. action logp and + action probs under the respective keys. + - Internal states: These will NOT be added to the batch by this connector piece + as this functionality is handled by a different default connector piece: + `AddStatesFromEpisodesToBatch`. + + If the user wants to customize their own data under the given keys (e.g. obs, + actions, ...), they can extract from the episodes or recompute from `data` + their own data and store it in `data` under those keys. In this case, the default + connector will not change the data under these keys and simply act as a + pass-through. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Infos. + if Columns.INFOS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.INFOS, + items_to_add=sa_episode.get_infos(slice(0, len(sa_episode))), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Actions. + if Columns.ACTIONS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.ACTIONS, + items_to_add=[ + sa_episode.get_actions(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Rewards. + if Columns.REWARDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.REWARDS, + items_to_add=[ + sa_episode.get_rewards(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Terminateds. + if Columns.TERMINATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_terminated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Truncateds. + if Columns.TRUNCATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TRUNCATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_truncated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Extra model outputs (except for STATE_OUT, which will be handled by another + # default connector piece). Also, like with all the fields above, skip + # those that the user already seemed to have populated via custom connector + # pieces. + skip_columns = set(batch.keys()) | {Columns.STATE_IN, Columns.STATE_OUT} + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + for column in sa_episode.extra_model_outputs.keys(): + if column not in skip_columns: + self.add_n_batch_items( + batch, + column, + items_to_add=[ + sa_episode.get_extra_model_outputs(key=column, indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6efa3b706bf1f24e61f9791b273e7f11b08b5066 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py @@ -0,0 +1,103 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddNextObservationsFromEpisodesToTrainBatch(ConnectorV2): + """Adds the NEXT_OBS column with the correct episode observations to train batch. + + - Operates on a list of Episode objects. + - Gets all observation(s) from all the given episodes (except the very first ones) + and adds them to the batch under construction in the NEXT_OBS column (as a list of + individual observations). + - Does NOT alter any observations (or other data) in the given episodes. + - Can be used in Learner connector pipelines. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.learner import ( + AddNextObservationsFromEpisodesToTrainBatch + ) + from ray.rllib.core.columns import Columns + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create two dummy SingleAgentEpisodes, each containing 3 observations, + # 2 actions and 2 rewards (both episodes are length=2). + obs_space = gym.spaces.Box(-1.0, 1.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + + episodes = [SingleAgentEpisode( + observations=[obs_space.sample(), obs_space.sample(), obs_space.sample()], + actions=[act_space.sample(), act_space.sample()], + rewards=[1.0, 2.0], + len_lookback_buffer=0, + ) for _ in range(2)] + eps_1_next_obses = episodes[0].get_observations([1, 2]) + eps_2_next_obses = episodes[1].get_observations([1, 2]) + print(f"1st Episode's next obses are {eps_1_next_obses}") + print(f"2nd Episode's next obses are {eps_2_next_obses}") + + # Create an instance of this class. + connector = AddNextObservationsFromEpisodesToTrainBatch() + + # Call the connector with the two created episodes. + # Note that this particular connector works without an RLModule, so we + # simplify here for the sake of this example. + output_data = connector( + rl_module=None, + batch={}, + episodes=episodes, + explore=True, + shared_data={}, + ) + # The output data should now contain the last observations of both episodes, + # in a "per-episode organized" fashion. + check( + output_data, + { + Columns.NEXT_OBS: { + (episodes[0].id_,): eps_1_next_obses, + (episodes[1].id_,): eps_2_next_obses, + }, + }, + ) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If "obs" already in `batch`, early out. + if Columns.NEXT_OBS in batch: + return batch + + for sa_episode in self.single_agent_episode_iterator( + # This is a Learner-only connector -> Get all episodes (for train batch). + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.NEXT_OBS, + items_to_add=sa_episode.get_observations(slice(1, len(sa_episode) + 1)), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0a6d11bebe6c76966a2fc72fc180f99d97665e --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.postprocessing.episodes import add_one_ts_to_episodes_and_truncate +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddOneTsToEpisodesAndTruncate(ConnectorV2): + """Adds an artificial timestep to all incoming episodes at the end. + + In detail: The last observations, infos, actions, and all `extra_model_outputs` + will be duplicated and appended to each episode's data. An extra 0.0 reward + will be appended to the episode's rewards. The episode's timestep will be + increased by 1. Also, adds the truncated=True flag to each episode if the + episode is not already done (terminated or truncated). + + Useful for value function bootstrapping, where it is required to compute a + forward pass for the very last timestep within the episode, + i.e. using the following input dict: { + obs=[final obs], + state=[final state output], + prev. reward=[final reward], + etc.. + } + + .. testcode:: + + from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create 2 episodes (both to be extended by one timestep). + episode1 = SingleAgentEpisode( + observations=[0, 1, 2], + actions=[0, 1], + rewards=[0.0, 1.0], + terminated=False, + truncated=False, + len_lookback_buffer=0, + ).finalize() + check(len(episode1), 2) + check(episode1.is_truncated, False) + + episode2 = SingleAgentEpisode( + observations=[0, 1, 2, 3, 4, 5], + actions=[0, 1, 2, 3, 4], + rewards=[0.0, 1.0, 2.0, 3.0, 4.0], + terminated=True, # a terminated episode + truncated=False, + len_lookback_buffer=0, + ).finalize() + check(len(episode2), 5) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + + # Create an instance of this class. + connector = AddOneTsToEpisodesAndTruncate() + + # Call the connector. + shared_data = {} + _ = connector( + rl_module=None, # Connector used here does not require RLModule. + batch={}, + episodes=[episode1, episode2], + shared_data=shared_data, + ) + # Check on the episodes. Both of them should now be 1 timestep longer. + check(len(episode1), 3) + check(episode1.is_truncated, True) + check(len(episode2), 6) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Build the loss mask to make sure the extra added timesteps do not influence + # the final loss and fix the terminateds and truncateds in the batch. + + # For proper v-trace execution, the rules must be as follows: + # Legend: + # T: terminal=True + # R: truncated=True + # B0: bootstrap with value 0 (also: terminal=True) + # Bx: bootstrap with some vf-computed value (also: terminal=True) + + # batch: - - - - - - - T B0- - - - - R Bx- - - - R Bx + # mask : t t t t t t t t f t t t t t t f t t t t t f + + # TODO (sven): Same situation as in TODO below, but for multi-agent episode. + # Maybe add a dedicated connector piece for this task? + # We extend the MultiAgentEpisode's ID by a running number here to make sure + # we treat each MAEpisode chunk as separate (for potentially upcoming v-trace + # and LSTM zero-padding) and don't mix data from different chunks. + if isinstance(episodes[0], MultiAgentEpisode): + for i, ma_episode in enumerate(episodes): + ma_episode.id_ += "_" + str(i) + # Also change the underlying single-agent episode's + # `multi_agent_episode_id` properties. + for sa_episode in ma_episode.agent_episodes.values(): + sa_episode.multi_agent_episode_id = ma_episode.id_ + + for i, sa_episode in enumerate( + self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) + ): + # TODO (sven): This is a little bit of a hack: By extending the Episode's + # ID, we make sure that each episode chunk in `episodes` is treated as a + # separate episode in the `self.add_n_batch_items` below. Some algos (e.g. + # APPO) may have >1 episode chunks from the same episode (same ID) in the + # training data, thus leading to a malformatted batch in case of + # RNN-triggered zero-padding of the train batch. + # For example, if e1 (id=a len=4) and e2 (id=a len=5) are two chunks of the + # same episode in `episodes`, the resulting batch would have an additional + # timestep in the middle of the episode's "row": + # { "obs": { + # ("a", <- eps ID): [0, 1, 2, 3 <- len=4, [additional 1 ts (bad)], + # 0, 1, 2, 3, 4 <- len=5, [additional 1 ts]] + # }} + sa_episode.id_ += "_" + str(i) + + len_ = len(sa_episode) + + # Extend all episodes by one ts. + add_one_ts_to_episodes_and_truncate([sa_episode]) + + loss_mask = [True for _ in range(len_)] + [False] + self.add_n_batch_items( + batch, + Columns.LOSS_MASK, + loss_mask, + len_ + 1, + sa_episode, + ) + + terminateds = ( + [False for _ in range(len_ - 1)] + + [bool(sa_episode.is_terminated)] + + [True] # extra timestep + ) + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + terminateds, + len_ + 1, + sa_episode, + ) + + # Signal to following connector pieces that the loss-mask which masks out + # invalid episode ts (for the extra added ts at the end) has already been + # added to `data`. + shared_data["_added_loss_mask_for_valid_episode_ts"] = True + + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..648c7146fc5f9f8d568065240a34387f04c67f81 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py @@ -0,0 +1,6 @@ +from functools import partial + +from ray.rllib.connectors.common.frame_stacking import _FrameStacking + + +FrameStackingLearner = partial(_FrameStacking, as_learner_connector=True) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..31740593997259b077f65a5c9ec04f8431fc9af5 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py @@ -0,0 +1,7 @@ +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class LearnerConnectorPipeline(ConnectorPipelineV2): + pass diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7297080595ad11b5069953a36dd9c269b1006912 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py @@ -0,0 +1,70 @@ +from typing import Any, Dict, List, Optional + +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class RemoveSingleTsTimeRankFromBatch(ConnectorV2): + """ + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If single ts time-rank had not been added, early out. + if shared_data is None or not shared_data.get("_added_single_ts_time_rank"): + return batch + + def _remove_single_ts(item, eps_id, aid, mid): + # Only remove time-rank for modules that are statefule (only for those has + # a timerank been added). + if mid is None or rl_module[mid].is_stateful(): + return tree.map_structure(lambda s: np.squeeze(s, axis=0), item) + return item + + for column, column_data in batch.copy().items(): + # Skip state_out (doesn't have a time rank). + if column == Columns.STATE_OUT: + continue + self.foreach_batch_item_change_in_place( + batch, + column=column, + func=_remove_single_ts, + ) + + return batch diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7170d4ab8633c29d35180771e885e11cd2e34d2d Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd13112a6ddade87994c7bc3b415c22423036216 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a38123c5232d049707b5e975350baecd6372772 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ee52c22f3076b8221171debc9fd9bd39e33fbd Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e24ffb448c464a490595137b5dde9ba515708b7 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1040a15b4ba3335b3a500f7afa6353d2752fb3b0 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48da3af8320b70cda03ee4177abe1c510e8609b6 Binary files /dev/null and b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc differ diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..4aafac19470baa3081d06a5a3bc4cbd18d76e384 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py @@ -0,0 +1,50 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +torch, _ = try_import_torch() + + +@OldAPIStack +class ExponentialSchedule(Schedule): + """Exponential decay schedule from `initial_p` to `final_p`. + + Reduces output over `schedule_timesteps`. After this many time steps + always returns `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + framework: Optional[str] = None, + initial_p: float = 1.0, + decay_rate: float = 0.1, + ): + """Initializes a ExponentialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + decay_rate: The percentage of the original value after + 100% of the time has been reached (see formula above). + >0.0: The smaller the decay-rate, the stronger the decay. + 1.0: No decay at all. + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.initial_p = initial_p + self.decay_rate = decay_rate + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: initial_p * decay_rate ** (`t`/t_max).""" + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + return self.initial_p * self.decay_rate ** (t / self.schedule_timesteps) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..17a2820d9af811d8c647f467501cd906f2bbdd9d --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py @@ -0,0 +1,67 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class PolynomialSchedule(Schedule): + """Polynomial interpolation between `initial_p` and `final_p`. + + Over `schedule_timesteps`. After this many time steps, always returns + `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + final_p: float, + framework: Optional[str], + initial_p: float = 1.0, + power: float = 2.0, + ): + """Initializes a PolynomialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p + final_p: Final output value. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + power: The exponent to use (default: quadratic). + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.final_p = final_p + self.initial_p = initial_p + self.power = power + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: + final_p + (initial_p - final_p) * (1 - `t`/t_max) ** power + """ + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + t = min(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + t = tf.math.minimum(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) diff --git a/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..231b25c71ea5fd74c889fdc8f501bd1c3f29a786 --- /dev/null +++ b/infer_4_37_2/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py @@ -0,0 +1,167 @@ +from typing import Optional + +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.typing import LearningRateOrSchedule, TensorType +from ray.util.annotations import DeveloperAPI + + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + + +@DeveloperAPI +class Scheduler: + """Class to manage a scheduled (framework-dependent) tensor variable. + + Uses the PiecewiseSchedule (for maximum configuration flexibility) + """ + + def __init__( + self, + *, + fixed_value_or_schedule: LearningRateOrSchedule, + framework: str = "torch", + device: Optional[str] = None, + ): + """Initializes a Scheduler instance. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + framework: The framework string, for which to create the tensor variable + that hold the current value. This is the variable that can be used in + the graph, e.g. in a loss function. + device: Optional device (for torch) to place the tensor variable on. + """ + self.framework = framework + self.device = device + self.use_schedule = isinstance(fixed_value_or_schedule, (list, tuple)) + + if self.use_schedule: + # Custom schedule, based on list of + # ([ts], [value to be reached by ts])-tuples. + self._schedule = PiecewiseSchedule( + fixed_value_or_schedule, + outside_value=fixed_value_or_schedule[-1][-1], + framework=None, + ) + # As initial tensor valie, use the first timestep's (must be 0) value. + self._curr_value = self._create_tensor_variable( + initial_value=fixed_value_or_schedule[0][1] + ) + + # If no schedule, pin (fix) given value. + else: + self._curr_value = fixed_value_or_schedule + + @staticmethod + def validate( + *, + fixed_value_or_schedule: LearningRateOrSchedule, + setting_name: str, + description: str, + ) -> None: + """Performs checking of a certain schedule configuration. + + The first entry in `value_or_schedule` (if it's not a fixed value) must have a + timestep of 0. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + setting_name: The property name of the schedule setting (within a config), + e.g. `lr` or `entropy_coeff`. + description: A full text description of the property that's being scheduled, + e.g. `learning rate`. + + Raises: + ValueError: In case, errors are found in the schedule's format. + """ + if ( + isinstance(fixed_value_or_schedule, (int, float)) + or fixed_value_or_schedule is None + ): + return + + if not isinstance(fixed_value_or_schedule, (list, tuple)) or ( + len(fixed_value_or_schedule) < 2 + ): + raise ValueError( + f"Invalid `{setting_name}` ({fixed_value_or_schedule}) specified! " + f"Must be a list of at least 2 tuples, each of the form " + f"(`timestep`, `{description} to reach`), e.g. " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + elif fixed_value_or_schedule[0][0] != 0: + raise ValueError( + f"When providing a `{setting_name}`, the first timestep must be 0 " + f"and the corresponding lr value is the initial {description}! You " + f"provided ts={fixed_value_or_schedule[0][0]} {description}=" + f"{fixed_value_or_schedule[0][1]}." + ) + + def get_current_value(self) -> TensorType: + """Returns the current value (as a tensor variable). + + This method should be used in loss functions of other (in-graph) places + where the current value is needed. + + Returns: + The tensor variable (holding the current value to be used). + """ + return self._curr_value + + def update(self, timestep: int) -> float: + """Updates the underlying (framework specific) tensor variable. + + In case of a fixed value, this method does nothing and only returns the fixed + value as-is. + + Args: + timestep: The current timestep that the update might depend on. + + Returns: + The current value of the tensor variable as a python float. + """ + if self.use_schedule: + python_value = self._schedule.value(t=timestep) + if self.framework == "torch": + self._curr_value.data = torch.tensor(python_value) + else: + self._curr_value.assign(python_value) + else: + python_value = self._curr_value + + return python_value + + def _create_tensor_variable(self, initial_value: float) -> TensorType: + """Creates a framework-specific tensor variable to be scheduled. + + Args: + initial_value: The initial (float) value for the variable to hold. + + Returns: + The created framework-specific tensor variable. + """ + if self.framework == "torch": + return torch.tensor( + initial_value, + requires_grad=False, + dtype=torch.float32, + device=self.device, + ) + else: + return tf.Variable( + initial_value, + trainable=False, + dtype=tf.float32, + ) diff --git a/janus/lib/python3.10/_compat_pickle.py b/janus/lib/python3.10/_compat_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..f68496ae639f5f880ae5f4ca0a220a29d2e354be --- /dev/null +++ b/janus/lib/python3.10/_compat_pickle.py @@ -0,0 +1,251 @@ +# This module is used to map the old Python 2 names to the new names used in +# Python 3 for the pickle module. This needed to make pickle streams +# generated with Python 2 loadable by Python 3. + +# This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import +# lib2to3 and use the mapping defined there, because lib2to3 uses pickle. +# Thus, this could cause the module to be imported recursively. +IMPORT_MAPPING = { + '__builtin__' : 'builtins', + 'copy_reg': 'copyreg', + 'Queue': 'queue', + 'SocketServer': 'socketserver', + 'ConfigParser': 'configparser', + 'repr': 'reprlib', + 'tkFileDialog': 'tkinter.filedialog', + 'tkSimpleDialog': 'tkinter.simpledialog', + 'tkColorChooser': 'tkinter.colorchooser', + 'tkCommonDialog': 'tkinter.commondialog', + 'Dialog': 'tkinter.dialog', + 'Tkdnd': 'tkinter.dnd', + 'tkFont': 'tkinter.font', + 'tkMessageBox': 'tkinter.messagebox', + 'ScrolledText': 'tkinter.scrolledtext', + 'Tkconstants': 'tkinter.constants', + 'Tix': 'tkinter.tix', + 'ttk': 'tkinter.ttk', + 'Tkinter': 'tkinter', + 'markupbase': '_markupbase', + '_winreg': 'winreg', + 'thread': '_thread', + 'dummy_thread': '_dummy_thread', + 'dbhash': 'dbm.bsd', + 'dumbdbm': 'dbm.dumb', + 'dbm': 'dbm.ndbm', + 'gdbm': 'dbm.gnu', + 'xmlrpclib': 'xmlrpc.client', + 'SimpleXMLRPCServer': 'xmlrpc.server', + 'httplib': 'http.client', + 'htmlentitydefs' : 'html.entities', + 'HTMLParser' : 'html.parser', + 'Cookie': 'http.cookies', + 'cookielib': 'http.cookiejar', + 'BaseHTTPServer': 'http.server', + 'test.test_support': 'test.support', + 'commands': 'subprocess', + 'urlparse' : 'urllib.parse', + 'robotparser' : 'urllib.robotparser', + 'urllib2': 'urllib.request', + 'anydbm': 'dbm', + '_abcoll' : 'collections.abc', +} + + +# This contains rename rules that are easy to handle. We ignore the more +# complex stuff (e.g. mapping the names in the urllib and types modules). +# These rules should be run before import names are fixed. +NAME_MAPPING = { + ('__builtin__', 'xrange'): ('builtins', 'range'), + ('__builtin__', 'reduce'): ('functools', 'reduce'), + ('__builtin__', 'intern'): ('sys', 'intern'), + ('__builtin__', 'unichr'): ('builtins', 'chr'), + ('__builtin__', 'unicode'): ('builtins', 'str'), + ('__builtin__', 'long'): ('builtins', 'int'), + ('itertools', 'izip'): ('builtins', 'zip'), + ('itertools', 'imap'): ('builtins', 'map'), + ('itertools', 'ifilter'): ('builtins', 'filter'), + ('itertools', 'ifilterfalse'): ('itertools', 'filterfalse'), + ('itertools', 'izip_longest'): ('itertools', 'zip_longest'), + ('UserDict', 'IterableUserDict'): ('collections', 'UserDict'), + ('UserList', 'UserList'): ('collections', 'UserList'), + ('UserString', 'UserString'): ('collections', 'UserString'), + ('whichdb', 'whichdb'): ('dbm', 'whichdb'), + ('_socket', 'fromfd'): ('socket', 'fromfd'), + ('_multiprocessing', 'Connection'): ('multiprocessing.connection', 'Connection'), + ('multiprocessing.process', 'Process'): ('multiprocessing.context', 'Process'), + ('multiprocessing.forking', 'Popen'): ('multiprocessing.popen_fork', 'Popen'), + ('urllib', 'ContentTooShortError'): ('urllib.error', 'ContentTooShortError'), + ('urllib', 'getproxies'): ('urllib.request', 'getproxies'), + ('urllib', 'pathname2url'): ('urllib.request', 'pathname2url'), + ('urllib', 'quote_plus'): ('urllib.parse', 'quote_plus'), + ('urllib', 'quote'): ('urllib.parse', 'quote'), + ('urllib', 'unquote_plus'): ('urllib.parse', 'unquote_plus'), + ('urllib', 'unquote'): ('urllib.parse', 'unquote'), + ('urllib', 'url2pathname'): ('urllib.request', 'url2pathname'), + ('urllib', 'urlcleanup'): ('urllib.request', 'urlcleanup'), + ('urllib', 'urlencode'): ('urllib.parse', 'urlencode'), + ('urllib', 'urlopen'): ('urllib.request', 'urlopen'), + ('urllib', 'urlretrieve'): ('urllib.request', 'urlretrieve'), + ('urllib2', 'HTTPError'): ('urllib.error', 'HTTPError'), + ('urllib2', 'URLError'): ('urllib.error', 'URLError'), +} + +PYTHON2_EXCEPTIONS = ( + "ArithmeticError", + "AssertionError", + "AttributeError", + "BaseException", + "BufferError", + "BytesWarning", + "DeprecationWarning", + "EOFError", + "EnvironmentError", + "Exception", + "FloatingPointError", + "FutureWarning", + "GeneratorExit", + "IOError", + "ImportError", + "ImportWarning", + "IndentationError", + "IndexError", + "KeyError", + "KeyboardInterrupt", + "LookupError", + "MemoryError", + "NameError", + "NotImplementedError", + "OSError", + "OverflowError", + "PendingDeprecationWarning", + "ReferenceError", + "RuntimeError", + "RuntimeWarning", + # StandardError is gone in Python 3, so we map it to Exception + "StopIteration", + "SyntaxError", + "SyntaxWarning", + "SystemError", + "SystemExit", + "TabError", + "TypeError", + "UnboundLocalError", + "UnicodeDecodeError", + "UnicodeEncodeError", + "UnicodeError", + "UnicodeTranslateError", + "UnicodeWarning", + "UserWarning", + "ValueError", + "Warning", + "ZeroDivisionError", +) + +try: + WindowsError +except NameError: + pass +else: + PYTHON2_EXCEPTIONS += ("WindowsError",) + +for excname in PYTHON2_EXCEPTIONS: + NAME_MAPPING[("exceptions", excname)] = ("builtins", excname) + +MULTIPROCESSING_EXCEPTIONS = ( + 'AuthenticationError', + 'BufferTooShort', + 'ProcessError', + 'TimeoutError', +) + +for excname in MULTIPROCESSING_EXCEPTIONS: + NAME_MAPPING[("multiprocessing", excname)] = ("multiprocessing.context", excname) + +# Same, but for 3.x to 2.x +REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items()) +assert len(REVERSE_IMPORT_MAPPING) == len(IMPORT_MAPPING) +REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items()) +assert len(REVERSE_NAME_MAPPING) == len(NAME_MAPPING) + +# Non-mutual mappings. + +IMPORT_MAPPING.update({ + 'cPickle': 'pickle', + '_elementtree': 'xml.etree.ElementTree', + 'FileDialog': 'tkinter.filedialog', + 'SimpleDialog': 'tkinter.simpledialog', + 'DocXMLRPCServer': 'xmlrpc.server', + 'SimpleHTTPServer': 'http.server', + 'CGIHTTPServer': 'http.server', + # For compatibility with broken pickles saved in old Python 3 versions + 'UserDict': 'collections', + 'UserList': 'collections', + 'UserString': 'collections', + 'whichdb': 'dbm', + 'StringIO': 'io', + 'cStringIO': 'io', +}) + +REVERSE_IMPORT_MAPPING.update({ + '_bz2': 'bz2', + '_dbm': 'dbm', + '_functools': 'functools', + '_gdbm': 'gdbm', + '_pickle': 'pickle', +}) + +NAME_MAPPING.update({ + ('__builtin__', 'basestring'): ('builtins', 'str'), + ('exceptions', 'StandardError'): ('builtins', 'Exception'), + ('UserDict', 'UserDict'): ('collections', 'UserDict'), + ('socket', '_socketobject'): ('socket', 'SocketType'), +}) + +REVERSE_NAME_MAPPING.update({ + ('_functools', 'reduce'): ('__builtin__', 'reduce'), + ('tkinter.filedialog', 'FileDialog'): ('FileDialog', 'FileDialog'), + ('tkinter.filedialog', 'LoadFileDialog'): ('FileDialog', 'LoadFileDialog'), + ('tkinter.filedialog', 'SaveFileDialog'): ('FileDialog', 'SaveFileDialog'), + ('tkinter.simpledialog', 'SimpleDialog'): ('SimpleDialog', 'SimpleDialog'), + ('xmlrpc.server', 'ServerHTMLDoc'): ('DocXMLRPCServer', 'ServerHTMLDoc'), + ('xmlrpc.server', 'XMLRPCDocGenerator'): + ('DocXMLRPCServer', 'XMLRPCDocGenerator'), + ('xmlrpc.server', 'DocXMLRPCRequestHandler'): + ('DocXMLRPCServer', 'DocXMLRPCRequestHandler'), + ('xmlrpc.server', 'DocXMLRPCServer'): + ('DocXMLRPCServer', 'DocXMLRPCServer'), + ('xmlrpc.server', 'DocCGIXMLRPCRequestHandler'): + ('DocXMLRPCServer', 'DocCGIXMLRPCRequestHandler'), + ('http.server', 'SimpleHTTPRequestHandler'): + ('SimpleHTTPServer', 'SimpleHTTPRequestHandler'), + ('http.server', 'CGIHTTPRequestHandler'): + ('CGIHTTPServer', 'CGIHTTPRequestHandler'), + ('_socket', 'socket'): ('socket', '_socketobject'), +}) + +PYTHON3_OSERROR_EXCEPTIONS = ( + 'BrokenPipeError', + 'ChildProcessError', + 'ConnectionAbortedError', + 'ConnectionError', + 'ConnectionRefusedError', + 'ConnectionResetError', + 'FileExistsError', + 'FileNotFoundError', + 'InterruptedError', + 'IsADirectoryError', + 'NotADirectoryError', + 'PermissionError', + 'ProcessLookupError', + 'TimeoutError', +) + +for excname in PYTHON3_OSERROR_EXCEPTIONS: + REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError') + +PYTHON3_IMPORTERROR_EXCEPTIONS = ( + 'ModuleNotFoundError', +) + +for excname in PYTHON3_IMPORTERROR_EXCEPTIONS: + REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'ImportError') diff --git a/janus/lib/python3.10/contextvars.py b/janus/lib/python3.10/contextvars.py new file mode 100644 index 0000000000000000000000000000000000000000..d78c80dfe6f99cefe1a875b16a9e7296546636fe --- /dev/null +++ b/janus/lib/python3.10/contextvars.py @@ -0,0 +1,4 @@ +from _contextvars import Context, ContextVar, Token, copy_context + + +__all__ = ('Context', 'ContextVar', 'Token', 'copy_context') diff --git a/janus/lib/python3.10/copyreg.py b/janus/lib/python3.10/copyreg.py new file mode 100644 index 0000000000000000000000000000000000000000..356db6f083e39cc671278aaae97cd5d2c2274483 --- /dev/null +++ b/janus/lib/python3.10/copyreg.py @@ -0,0 +1,219 @@ +"""Helper to provide extensibility for pickle. + +This is only useful to add pickle support for extension types defined in +C, not for instances of user-defined classes. +""" + +__all__ = ["pickle", "constructor", + "add_extension", "remove_extension", "clear_extension_cache"] + +dispatch_table = {} + +def pickle(ob_type, pickle_function, constructor_ob=None): + if not callable(pickle_function): + raise TypeError("reduction functions must be callable") + dispatch_table[ob_type] = pickle_function + + # The constructor_ob function is a vestige of safe for unpickling. + # There is no reason for the caller to pass it anymore. + if constructor_ob is not None: + constructor(constructor_ob) + +def constructor(object): + if not callable(object): + raise TypeError("constructors must be callable") + +# Example: provide pickling support for complex numbers. + +try: + complex +except NameError: + pass +else: + + def pickle_complex(c): + return complex, (c.real, c.imag) + + pickle(complex, pickle_complex, complex) + +def pickle_union(obj): + import functools, operator + return functools.reduce, (operator.or_, obj.__args__) + +pickle(type(int | str), pickle_union) + +# Support for pickling new-style objects + +def _reconstructor(cls, base, state): + if base is object: + obj = object.__new__(cls) + else: + obj = base.__new__(cls, state) + if base.__init__ != object.__init__: + base.__init__(obj, state) + return obj + +_HEAPTYPE = 1<<9 +_new_type = type(int.__new__) + +# Python code for object.__reduce_ex__ for protocols 0 and 1 + +def _reduce_ex(self, proto): + assert proto < 2 + cls = self.__class__ + for base in cls.__mro__: + if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: + break + new = base.__new__ + if isinstance(new, _new_type) and new.__self__ is base: + break + else: + base = object # not really reachable + if base is object: + state = None + else: + if base is cls: + raise TypeError(f"cannot pickle {cls.__name__!r} object") + state = base(self) + args = (cls, base, state) + try: + getstate = self.__getstate__ + except AttributeError: + if getattr(self, "__slots__", None): + raise TypeError(f"cannot pickle {cls.__name__!r} object: " + f"a class that defines __slots__ without " + f"defining __getstate__ cannot be pickled " + f"with protocol {proto}") from None + try: + dict = self.__dict__ + except AttributeError: + dict = None + else: + dict = getstate() + if dict: + return _reconstructor, args, dict + else: + return _reconstructor, args + +# Helper for __reduce_ex__ protocol 2 + +def __newobj__(cls, *args): + return cls.__new__(cls, *args) + +def __newobj_ex__(cls, args, kwargs): + """Used by pickle protocol 4, instead of __newobj__ to allow classes with + keyword-only arguments to be pickled correctly. + """ + return cls.__new__(cls, *args, **kwargs) + +def _slotnames(cls): + """Return a list of slot names for a given class. + + This needs to find slots defined by the class and its bases, so we + can't simply return the __slots__ attribute. We must walk down + the Method Resolution Order and concatenate the __slots__ of each + class found there. (This assumes classes don't modify their + __slots__ attribute to misrepresent their slots after the class is + defined.) + """ + + # Get the value from a cache in the class if possible + names = cls.__dict__.get("__slotnames__") + if names is not None: + return names + + # Not cached -- calculate the value + names = [] + if not hasattr(cls, "__slots__"): + # This class has no slots + pass + else: + # Slots found -- gather slot names from all base classes + for c in cls.__mro__: + if "__slots__" in c.__dict__: + slots = c.__dict__['__slots__'] + # if class has a single slot, it can be given as a string + if isinstance(slots, str): + slots = (slots,) + for name in slots: + # special descriptors + if name in ("__dict__", "__weakref__"): + continue + # mangled names + elif name.startswith('__') and not name.endswith('__'): + stripped = c.__name__.lstrip('_') + if stripped: + names.append('_%s%s' % (stripped, name)) + else: + names.append(name) + else: + names.append(name) + + # Cache the outcome in the class if at all possible + try: + cls.__slotnames__ = names + except: + pass # But don't die if we can't + + return names + +# A registry of extension codes. This is an ad-hoc compression +# mechanism. Whenever a global reference to , is about +# to be pickled, the (, ) tuple is looked up here to see +# if it is a registered extension code for it. Extension codes are +# universal, so that the meaning of a pickle does not depend on +# context. (There are also some codes reserved for local use that +# don't have this restriction.) Codes are positive ints; 0 is +# reserved. + +_extension_registry = {} # key -> code +_inverted_registry = {} # code -> key +_extension_cache = {} # code -> object +# Don't ever rebind those names: pickling grabs a reference to them when +# it's initialized, and won't see a rebinding. + +def add_extension(module, name, code): + """Register an extension code.""" + code = int(code) + if not 1 <= code <= 0x7fffffff: + raise ValueError("code out of range") + key = (module, name) + if (_extension_registry.get(key) == code and + _inverted_registry.get(code) == key): + return # Redundant registrations are benign + if key in _extension_registry: + raise ValueError("key %s is already registered with code %s" % + (key, _extension_registry[key])) + if code in _inverted_registry: + raise ValueError("code %s is already in use for key %s" % + (code, _inverted_registry[code])) + _extension_registry[key] = code + _inverted_registry[code] = key + +def remove_extension(module, name, code): + """Unregister an extension code. For testing only.""" + key = (module, name) + if (_extension_registry.get(key) != code or + _inverted_registry.get(code) != key): + raise ValueError("key %s is not registered with code %s" % + (key, code)) + del _extension_registry[key] + del _inverted_registry[code] + if code in _extension_cache: + del _extension_cache[code] + +def clear_extension_cache(): + _extension_cache.clear() + +# Standard extension code assignments + +# Reserved ranges + +# First Last Count Purpose +# 1 127 127 Reserved for Python standard library +# 128 191 64 Reserved for Zope +# 192 239 48 Reserved for 3rd parties +# 240 255 16 Reserved for private use (will never be assigned) +# 256 Inf Inf Reserved for future assignment + +# Extension codes are assigned by the Python Software Foundation. diff --git a/janus/lib/python3.10/fnmatch.py b/janus/lib/python3.10/fnmatch.py new file mode 100644 index 0000000000000000000000000000000000000000..fee59bf73ff264cbe26a9af05a0b247e3397776c --- /dev/null +++ b/janus/lib/python3.10/fnmatch.py @@ -0,0 +1,199 @@ +"""Filename matching with shell patterns. + +fnmatch(FILENAME, PATTERN) matches according to the local convention. +fnmatchcase(FILENAME, PATTERN) always takes case in account. + +The functions operate by translating the pattern into a regular +expression. They cache the compiled regular expressions for speed. + +The function translate(PATTERN) returns a regular expression +corresponding to PATTERN. (It does not compile it.) +""" +import os +import posixpath +import re +import functools + +__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"] + +# Build a thread-safe incrementing counter to help create unique regexp group +# names across calls. +from itertools import count +_nextgroupnum = count().__next__ +del count + +def fnmatch(name, pat): + """Test whether FILENAME matches PATTERN. + + Patterns are Unix shell style: + + * matches everything + ? matches any single character + [seq] matches any character in seq + [!seq] matches any char not in seq + + An initial period in FILENAME is not special. + Both FILENAME and PATTERN are first case-normalized + if the operating system requires it. + If you don't want this, use fnmatchcase(FILENAME, PATTERN). + """ + name = os.path.normcase(name) + pat = os.path.normcase(pat) + return fnmatchcase(name, pat) + +@functools.lru_cache(maxsize=256, typed=True) +def _compile_pattern(pat): + if isinstance(pat, bytes): + pat_str = str(pat, 'ISO-8859-1') + res_str = translate(pat_str) + res = bytes(res_str, 'ISO-8859-1') + else: + res = translate(pat) + return re.compile(res).match + +def filter(names, pat): + """Construct a list from those elements of the iterable NAMES that match PAT.""" + result = [] + pat = os.path.normcase(pat) + match = _compile_pattern(pat) + if os.path is posixpath: + # normcase on posix is NOP. Optimize it away from the loop. + for name in names: + if match(name): + result.append(name) + else: + for name in names: + if match(os.path.normcase(name)): + result.append(name) + return result + +def fnmatchcase(name, pat): + """Test whether FILENAME matches PATTERN, including case. + + This is a version of fnmatch() which doesn't case-normalize + its arguments. + """ + match = _compile_pattern(pat) + return match(name) is not None + + +def translate(pat): + """Translate a shell PATTERN to a regular expression. + + There is no way to quote meta-characters. + """ + + STAR = object() + res = [] + add = res.append + i, n = 0, len(pat) + while i < n: + c = pat[i] + i = i+1 + if c == '*': + # compress consecutive `*` into one + if (not res) or res[-1] is not STAR: + add(STAR) + elif c == '?': + add('.') + elif c == '[': + j = i + if j < n and pat[j] == '!': + j = j+1 + if j < n and pat[j] == ']': + j = j+1 + while j < n and pat[j] != ']': + j = j+1 + if j >= n: + add('\\[') + else: + stuff = pat[i:j] + if '-' not in stuff: + stuff = stuff.replace('\\', r'\\') + else: + chunks = [] + k = i+2 if pat[i] == '!' else i+1 + while True: + k = pat.find('-', k, j) + if k < 0: + break + chunks.append(pat[i:k]) + i = k+1 + k = k+3 + chunk = pat[i:j] + if chunk: + chunks.append(chunk) + else: + chunks[-1] += '-' + # Remove empty ranges -- invalid in RE. + for k in range(len(chunks)-1, 0, -1): + if chunks[k-1][-1] > chunks[k][0]: + chunks[k-1] = chunks[k-1][:-1] + chunks[k][1:] + del chunks[k] + # Escape backslashes and hyphens for set difference (--). + # Hyphens that create ranges shouldn't be escaped. + stuff = '-'.join(s.replace('\\', r'\\').replace('-', r'\-') + for s in chunks) + # Escape set operations (&&, ~~ and ||). + stuff = re.sub(r'([&~|])', r'\\\1', stuff) + i = j+1 + if not stuff: + # Empty range: never match. + add('(?!)') + elif stuff == '!': + # Negated empty range: match any character. + add('.') + else: + if stuff[0] == '!': + stuff = '^' + stuff[1:] + elif stuff[0] in ('^', '['): + stuff = '\\' + stuff + add(f'[{stuff}]') + else: + add(re.escape(c)) + assert i == n + + # Deal with STARs. + inp = res + res = [] + add = res.append + i, n = 0, len(inp) + # Fixed pieces at the start? + while i < n and inp[i] is not STAR: + add(inp[i]) + i += 1 + # Now deal with STAR fixed STAR fixed ... + # For an interior `STAR fixed` pairing, we want to do a minimal + # .*? match followed by `fixed`, with no possibility of backtracking. + # We can't spell that directly, but can trick it into working by matching + # .*?fixed + # in a lookahead assertion, save the matched part in a group, then + # consume that group via a backreference. If the overall match fails, + # the lookahead assertion won't try alternatives. So the translation is: + # (?=(?P.*?fixed))(?P=name) + # Group names are created as needed: g0, g1, g2, ... + # The numbers are obtained from _nextgroupnum() to ensure they're unique + # across calls and across threads. This is because people rely on the + # undocumented ability to join multiple translate() results together via + # "|" to build large regexps matching "one of many" shell patterns. + while i < n: + assert inp[i] is STAR + i += 1 + if i == n: + add(".*") + break + assert inp[i] is not STAR + fixed = [] + while i < n and inp[i] is not STAR: + fixed.append(inp[i]) + i += 1 + fixed = "".join(fixed) + if i == n: + add(".*") + add(fixed) + else: + groupnum = _nextgroupnum() + add(f"(?=(?P.*?{fixed}))(?P=g{groupnum})") + assert i == n + res = "".join(res) + return fr'(?s:{res})\Z' diff --git a/janus/lib/python3.10/lzma.py b/janus/lib/python3.10/lzma.py new file mode 100644 index 0000000000000000000000000000000000000000..800f52198fbb794077fe43425df83db44e13960d --- /dev/null +++ b/janus/lib/python3.10/lzma.py @@ -0,0 +1,356 @@ +"""Interface to the liblzma compression library. + +This module provides a class for reading and writing compressed files, +classes for incremental (de)compression, and convenience functions for +one-shot (de)compression. + +These classes and functions support both the XZ and legacy LZMA +container formats, as well as raw compressed data streams. +""" + +__all__ = [ + "CHECK_NONE", "CHECK_CRC32", "CHECK_CRC64", "CHECK_SHA256", + "CHECK_ID_MAX", "CHECK_UNKNOWN", + "FILTER_LZMA1", "FILTER_LZMA2", "FILTER_DELTA", "FILTER_X86", "FILTER_IA64", + "FILTER_ARM", "FILTER_ARMTHUMB", "FILTER_POWERPC", "FILTER_SPARC", + "FORMAT_AUTO", "FORMAT_XZ", "FORMAT_ALONE", "FORMAT_RAW", + "MF_HC3", "MF_HC4", "MF_BT2", "MF_BT3", "MF_BT4", + "MODE_FAST", "MODE_NORMAL", "PRESET_DEFAULT", "PRESET_EXTREME", + + "LZMACompressor", "LZMADecompressor", "LZMAFile", "LZMAError", + "open", "compress", "decompress", "is_check_supported", +] + +import builtins +import io +import os +from _lzma import * +from _lzma import _encode_filter_properties, _decode_filter_properties +import _compression + + +_MODE_CLOSED = 0 +_MODE_READ = 1 +# Value 2 no longer used +_MODE_WRITE = 3 + + +class LZMAFile(_compression.BaseStream): + + """A file object providing transparent LZMA (de)compression. + + An LZMAFile can act as a wrapper for an existing file object, or + refer directly to a named file on disk. + + Note that LZMAFile provides a *binary* file interface - data read + is returned as bytes, and data to be written must be given as bytes. + """ + + def __init__(self, filename=None, mode="r", *, + format=None, check=-1, preset=None, filters=None): + """Open an LZMA-compressed file in binary mode. + + filename can be either an actual file name (given as a str, + bytes, or PathLike object), in which case the named file is + opened, or it can be an existing file object to read from or + write to. + + mode can be "r" for reading (default), "w" for (over)writing, + "x" for creating exclusively, or "a" for appending. These can + equivalently be given as "rb", "wb", "xb" and "ab" respectively. + + format specifies the container format to use for the file. + If mode is "r", this defaults to FORMAT_AUTO. Otherwise, the + default is FORMAT_XZ. + + check specifies the integrity check to use. This argument can + only be used when opening a file for writing. For FORMAT_XZ, + the default is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not + support integrity checks - for these formats, check must be + omitted, or be CHECK_NONE. + + When opening a file for reading, the *preset* argument is not + meaningful, and should be omitted. The *filters* argument should + also be omitted, except when format is FORMAT_RAW (in which case + it is required). + + When opening a file for writing, the settings used by the + compressor can be specified either as a preset compression + level (with the *preset* argument), or in detail as a custom + filter chain (with the *filters* argument). For FORMAT_XZ and + FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset + level. For FORMAT_RAW, the caller must always specify a filter + chain; the raw compressor does not support preset compression + levels. + + preset (if provided) should be an integer in the range 0-9, + optionally OR-ed with the constant PRESET_EXTREME. + + filters (if provided) should be a sequence of dicts. Each dict + should have an entry for "id" indicating ID of the filter, plus + additional entries for options to the filter. + """ + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + + if mode in ("r", "rb"): + if check != -1: + raise ValueError("Cannot specify an integrity check " + "when opening a file for reading") + if preset is not None: + raise ValueError("Cannot specify a preset compression " + "level when opening a file for reading") + if format is None: + format = FORMAT_AUTO + mode_code = _MODE_READ + elif mode in ("w", "wb", "a", "ab", "x", "xb"): + if format is None: + format = FORMAT_XZ + mode_code = _MODE_WRITE + self._compressor = LZMACompressor(format=format, check=check, + preset=preset, filters=filters) + self._pos = 0 + else: + raise ValueError("Invalid mode: {!r}".format(mode)) + + if isinstance(filename, (str, bytes, os.PathLike)): + if "b" not in mode: + mode += "b" + self._fp = builtins.open(filename, mode) + self._closefp = True + self._mode = mode_code + elif hasattr(filename, "read") or hasattr(filename, "write"): + self._fp = filename + self._mode = mode_code + else: + raise TypeError("filename must be a str, bytes, file or PathLike object") + + if self._mode == _MODE_READ: + raw = _compression.DecompressReader(self._fp, LZMADecompressor, + trailing_error=LZMAError, format=format, filters=filters) + self._buffer = io.BufferedReader(raw) + + def close(self): + """Flush and close the file. + + May be called more than once without error. Once the file is + closed, any other operation on it will raise a ValueError. + """ + if self._mode == _MODE_CLOSED: + return + try: + if self._mode == _MODE_READ: + self._buffer.close() + self._buffer = None + elif self._mode == _MODE_WRITE: + self._fp.write(self._compressor.flush()) + self._compressor = None + finally: + try: + if self._closefp: + self._fp.close() + finally: + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + + @property + def closed(self): + """True if this file is closed.""" + return self._mode == _MODE_CLOSED + + def fileno(self): + """Return the file descriptor for the underlying file.""" + self._check_not_closed() + return self._fp.fileno() + + def seekable(self): + """Return whether the file supports seeking.""" + return self.readable() and self._buffer.seekable() + + def readable(self): + """Return whether the file was opened for reading.""" + self._check_not_closed() + return self._mode == _MODE_READ + + def writable(self): + """Return whether the file was opened for writing.""" + self._check_not_closed() + return self._mode == _MODE_WRITE + + def peek(self, size=-1): + """Return buffered data without advancing the file position. + + Always returns at least one byte of data, unless at EOF. + The exact number of bytes returned is unspecified. + """ + self._check_can_read() + # Relies on the undocumented fact that BufferedReader.peek() always + # returns at least one byte (except at EOF) + return self._buffer.peek(size) + + def read(self, size=-1): + """Read up to size uncompressed bytes from the file. + + If size is negative or omitted, read until EOF is reached. + Returns b"" if the file is already at EOF. + """ + self._check_can_read() + return self._buffer.read(size) + + def read1(self, size=-1): + """Read up to size uncompressed bytes, while trying to avoid + making multiple reads from the underlying stream. Reads up to a + buffer's worth of data if size is negative. + + Returns b"" if the file is at EOF. + """ + self._check_can_read() + if size < 0: + size = io.DEFAULT_BUFFER_SIZE + return self._buffer.read1(size) + + def readline(self, size=-1): + """Read a line of uncompressed bytes from the file. + + The terminating newline (if present) is retained. If size is + non-negative, no more than size bytes will be read (in which + case the line may be incomplete). Returns b'' if already at EOF. + """ + self._check_can_read() + return self._buffer.readline(size) + + def write(self, data): + """Write a bytes object to the file. + + Returns the number of uncompressed bytes written, which is + always the length of data in bytes. Note that due to buffering, + the file on disk may not reflect the data written until close() + is called. + """ + self._check_can_write() + if isinstance(data, (bytes, bytearray)): + length = len(data) + else: + # accept any data that supports the buffer protocol + data = memoryview(data) + length = data.nbytes + + compressed = self._compressor.compress(data) + self._fp.write(compressed) + self._pos += length + return length + + def seek(self, offset, whence=io.SEEK_SET): + """Change the file position. + + The new position is specified by offset, relative to the + position indicated by whence. Possible values for whence are: + + 0: start of stream (default): offset must not be negative + 1: current stream position + 2: end of stream; offset must not be positive + + Returns the new file position. + + Note that seeking is emulated, so depending on the parameters, + this operation may be extremely slow. + """ + self._check_can_seek() + return self._buffer.seek(offset, whence) + + def tell(self): + """Return the current file position.""" + self._check_not_closed() + if self._mode == _MODE_READ: + return self._buffer.tell() + return self._pos + + +def open(filename, mode="rb", *, + format=None, check=-1, preset=None, filters=None, + encoding=None, errors=None, newline=None): + """Open an LZMA-compressed file in binary or text mode. + + filename can be either an actual file name (given as a str, bytes, + or PathLike object), in which case the named file is opened, or it + can be an existing file object to read from or write to. + + The mode argument can be "r", "rb" (default), "w", "wb", "x", "xb", + "a", or "ab" for binary mode, or "rt", "wt", "xt", or "at" for text + mode. + + The format, check, preset and filters arguments specify the + compression settings, as for LZMACompressor, LZMADecompressor and + LZMAFile. + + For binary mode, this function is equivalent to the LZMAFile + constructor: LZMAFile(filename, mode, ...). In this case, the + encoding, errors and newline arguments must not be provided. + + For text mode, an LZMAFile object is created, and wrapped in an + io.TextIOWrapper instance with the specified encoding, error + handling behavior, and line ending(s). + + """ + if "t" in mode: + if "b" in mode: + raise ValueError("Invalid mode: %r" % (mode,)) + else: + if encoding is not None: + raise ValueError("Argument 'encoding' not supported in binary mode") + if errors is not None: + raise ValueError("Argument 'errors' not supported in binary mode") + if newline is not None: + raise ValueError("Argument 'newline' not supported in binary mode") + + lz_mode = mode.replace("t", "") + binary_file = LZMAFile(filename, lz_mode, format=format, check=check, + preset=preset, filters=filters) + + if "t" in mode: + encoding = io.text_encoding(encoding) + return io.TextIOWrapper(binary_file, encoding, errors, newline) + else: + return binary_file + + +def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None): + """Compress a block of data. + + Refer to LZMACompressor's docstring for a description of the + optional arguments *format*, *check*, *preset* and *filters*. + + For incremental compression, use an LZMACompressor instead. + """ + comp = LZMACompressor(format, check, preset, filters) + return comp.compress(data) + comp.flush() + + +def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): + """Decompress a block of data. + + Refer to LZMADecompressor's docstring for a description of the + optional arguments *format*, *check* and *filters*. + + For incremental decompression, use an LZMADecompressor instead. + """ + results = [] + while True: + decomp = LZMADecompressor(format, memlimit, filters) + try: + res = decomp.decompress(data) + except LZMAError: + if results: + break # Leftover data is not a valid LZMA/XZ stream; ignore it. + else: + raise # Error on the first iteration; bail out. + results.append(res) + if not decomp.eof: + raise LZMAError("Compressed data ended before the " + "end-of-stream marker was reached") + data = decomp.unused_data + if not data: + break + return b"".join(results) diff --git a/janus/lib/python3.10/profile.py b/janus/lib/python3.10/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..90c4e4c9ff583e43e164179c0c6fd37e22434e76 --- /dev/null +++ b/janus/lib/python3.10/profile.py @@ -0,0 +1,611 @@ +#! /usr/bin/env python3 +# +# Class for profiling python code. rev 1.0 6/2/94 +# +# Written by James Roskind +# Based on prior profile module by Sjoerd Mullender... +# which was hacked somewhat by: Guido van Rossum + +"""Class for profiling Python code.""" + +# Copyright Disney Enterprises, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +# either express or implied. See the License for the specific language +# governing permissions and limitations under the License. + + +import io +import sys +import time +import marshal + +__all__ = ["run", "runctx", "Profile"] + +# Sample timer for use with +#i_count = 0 +#def integer_timer(): +# global i_count +# i_count = i_count + 1 +# return i_count +#itimes = integer_timer # replace with C coded timer returning integers + +class _Utils: + """Support class for utility functions which are shared by + profile.py and cProfile.py modules. + Not supposed to be used directly. + """ + + def __init__(self, profiler): + self.profiler = profiler + + def run(self, statement, filename, sort): + prof = self.profiler() + try: + prof.run(statement) + except SystemExit: + pass + finally: + self._show(prof, filename, sort) + + def runctx(self, statement, globals, locals, filename, sort): + prof = self.profiler() + try: + prof.runctx(statement, globals, locals) + except SystemExit: + pass + finally: + self._show(prof, filename, sort) + + def _show(self, prof, filename, sort): + if filename is not None: + prof.dump_stats(filename) + else: + prof.print_stats(sort) + + +#************************************************************************** +# The following are the static member functions for the profiler class +# Note that an instance of Profile() is *not* needed to call them. +#************************************************************************** + +def run(statement, filename=None, sort=-1): + """Run statement under profiler optionally saving results in filename + + This function takes a single argument that can be passed to the + "exec" statement, and an optional file name. In all cases this + routine attempts to "exec" its first argument and gather profiling + statistics from the execution. If no file name is present, then this + function automatically prints a simple profiling report, sorted by the + standard name string (file/line/function-name) that is presented in + each line. + """ + return _Utils(Profile).run(statement, filename, sort) + +def runctx(statement, globals, locals, filename=None, sort=-1): + """Run statement under profiler, supplying your own globals and locals, + optionally saving results in filename. + + statement and filename have the same semantics as profile.run + """ + return _Utils(Profile).runctx(statement, globals, locals, filename, sort) + + +class Profile: + """Profiler class. + + self.cur is always a tuple. Each such tuple corresponds to a stack + frame that is currently active (self.cur[-2]). The following are the + definitions of its members. We use this external "parallel stack" to + avoid contaminating the program that we are profiling. (old profiler + used to write into the frames local dictionary!!) Derived classes + can change the definition of some entries, as long as they leave + [-2:] intact (frame and previous tuple). In case an internal error is + detected, the -3 element is used as the function name. + + [ 0] = Time that needs to be charged to the parent frame's function. + It is used so that a function call will not have to access the + timing data for the parent frame. + [ 1] = Total time spent in this frame's function, excluding time in + subfunctions (this latter is tallied in cur[2]). + [ 2] = Total time spent in subfunctions, excluding time executing the + frame's function (this latter is tallied in cur[1]). + [-3] = Name of the function that corresponds to this frame. + [-2] = Actual frame that we correspond to (used to sync exception handling). + [-1] = Our parent 6-tuple (corresponds to frame.f_back). + + Timing data for each function is stored as a 5-tuple in the dictionary + self.timings[]. The index is always the name stored in self.cur[-3]. + The following are the definitions of the members: + + [0] = The number of times this function was called, not counting direct + or indirect recursion, + [1] = Number of times this function appears on the stack, minus one + [2] = Total time spent internal to this function + [3] = Cumulative time that this function was present on the stack. In + non-recursive functions, this is the total execution time from start + to finish of each invocation of a function, including time spent in + all subfunctions. + [4] = A dictionary indicating for each function name, the number of times + it was called by us. + """ + + bias = 0 # calibration constant + + def __init__(self, timer=None, bias=None): + self.timings = {} + self.cur = None + self.cmd = "" + self.c_func_name = "" + + if bias is None: + bias = self.bias + self.bias = bias # Materialize in local dict for lookup speed. + + if not timer: + self.timer = self.get_time = time.process_time + self.dispatcher = self.trace_dispatch_i + else: + self.timer = timer + t = self.timer() # test out timer function + try: + length = len(t) + except TypeError: + self.get_time = timer + self.dispatcher = self.trace_dispatch_i + else: + if length == 2: + self.dispatcher = self.trace_dispatch + else: + self.dispatcher = self.trace_dispatch_l + # This get_time() implementation needs to be defined + # here to capture the passed-in timer in the parameter + # list (for performance). Note that we can't assume + # the timer() result contains two values in all + # cases. + def get_time_timer(timer=timer, sum=sum): + return sum(timer()) + self.get_time = get_time_timer + self.t = self.get_time() + self.simulate_call('profiler') + + # Heavily optimized dispatch routine for time.process_time() timer + + def trace_dispatch(self, frame, event, arg): + timer = self.timer + t = timer() + t = t[0] + t[1] - self.t - self.bias + + if event == "c_call": + self.c_func_name = arg.__name__ + + if self.dispatch[event](self, frame,t): + t = timer() + self.t = t[0] + t[1] + else: + r = timer() + self.t = r[0] + r[1] - t # put back unrecorded delta + + # Dispatch routine for best timer program (return = scalar, fastest if + # an integer but float works too -- and time.process_time() relies on that). + + def trace_dispatch_i(self, frame, event, arg): + timer = self.timer + t = timer() - self.t - self.bias + + if event == "c_call": + self.c_func_name = arg.__name__ + + if self.dispatch[event](self, frame, t): + self.t = timer() + else: + self.t = timer() - t # put back unrecorded delta + + # Dispatch routine for macintosh (timer returns time in ticks of + # 1/60th second) + + def trace_dispatch_mac(self, frame, event, arg): + timer = self.timer + t = timer()/60.0 - self.t - self.bias + + if event == "c_call": + self.c_func_name = arg.__name__ + + if self.dispatch[event](self, frame, t): + self.t = timer()/60.0 + else: + self.t = timer()/60.0 - t # put back unrecorded delta + + # SLOW generic dispatch routine for timer returning lists of numbers + + def trace_dispatch_l(self, frame, event, arg): + get_time = self.get_time + t = get_time() - self.t - self.bias + + if event == "c_call": + self.c_func_name = arg.__name__ + + if self.dispatch[event](self, frame, t): + self.t = get_time() + else: + self.t = get_time() - t # put back unrecorded delta + + # In the event handlers, the first 3 elements of self.cur are unpacked + # into vrbls w/ 3-letter names. The last two characters are meant to be + # mnemonic: + # _pt self.cur[0] "parent time" time to be charged to parent frame + # _it self.cur[1] "internal time" time spent directly in the function + # _et self.cur[2] "external time" time spent in subfunctions + + def trace_dispatch_exception(self, frame, t): + rpt, rit, ret, rfn, rframe, rcur = self.cur + if (rframe is not frame) and rcur: + return self.trace_dispatch_return(rframe, t) + self.cur = rpt, rit+t, ret, rfn, rframe, rcur + return 1 + + + def trace_dispatch_call(self, frame, t): + if self.cur and frame.f_back is not self.cur[-2]: + rpt, rit, ret, rfn, rframe, rcur = self.cur + if not isinstance(rframe, Profile.fake_frame): + assert rframe.f_back is frame.f_back, ("Bad call", rfn, + rframe, rframe.f_back, + frame, frame.f_back) + self.trace_dispatch_return(rframe, 0) + assert (self.cur is None or \ + frame.f_back is self.cur[-2]), ("Bad call", + self.cur[-3]) + fcode = frame.f_code + fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) + self.cur = (t, 0, 0, fn, frame, self.cur) + timings = self.timings + if fn in timings: + cc, ns, tt, ct, callers = timings[fn] + timings[fn] = cc, ns + 1, tt, ct, callers + else: + timings[fn] = 0, 0, 0, 0, {} + return 1 + + def trace_dispatch_c_call (self, frame, t): + fn = ("", 0, self.c_func_name) + self.cur = (t, 0, 0, fn, frame, self.cur) + timings = self.timings + if fn in timings: + cc, ns, tt, ct, callers = timings[fn] + timings[fn] = cc, ns+1, tt, ct, callers + else: + timings[fn] = 0, 0, 0, 0, {} + return 1 + + def trace_dispatch_return(self, frame, t): + if frame is not self.cur[-2]: + assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3]) + self.trace_dispatch_return(self.cur[-2], 0) + + # Prefix "r" means part of the Returning or exiting frame. + # Prefix "p" means part of the Previous or Parent or older frame. + + rpt, rit, ret, rfn, frame, rcur = self.cur + rit = rit + t + frame_total = rit + ret + + ppt, pit, pet, pfn, pframe, pcur = rcur + self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur + + timings = self.timings + cc, ns, tt, ct, callers = timings[rfn] + if not ns: + # This is the only occurrence of the function on the stack. + # Else this is a (directly or indirectly) recursive call, and + # its cumulative time will get updated when the topmost call to + # it returns. + ct = ct + frame_total + cc = cc + 1 + + if pfn in callers: + callers[pfn] = callers[pfn] + 1 # hack: gather more + # stats such as the amount of time added to ct courtesy + # of this specific call, and the contribution to cc + # courtesy of this call. + else: + callers[pfn] = 1 + + timings[rfn] = cc, ns - 1, tt + rit, ct, callers + + return 1 + + + dispatch = { + "call": trace_dispatch_call, + "exception": trace_dispatch_exception, + "return": trace_dispatch_return, + "c_call": trace_dispatch_c_call, + "c_exception": trace_dispatch_return, # the C function returned + "c_return": trace_dispatch_return, + } + + + # The next few functions play with self.cmd. By carefully preloading + # our parallel stack, we can force the profiled result to include + # an arbitrary string as the name of the calling function. + # We use self.cmd as that string, and the resulting stats look + # very nice :-). + + def set_cmd(self, cmd): + if self.cur[-1]: return # already set + self.cmd = cmd + self.simulate_call(cmd) + + class fake_code: + def __init__(self, filename, line, name): + self.co_filename = filename + self.co_line = line + self.co_name = name + self.co_firstlineno = 0 + + def __repr__(self): + return repr((self.co_filename, self.co_line, self.co_name)) + + class fake_frame: + def __init__(self, code, prior): + self.f_code = code + self.f_back = prior + + def simulate_call(self, name): + code = self.fake_code('profile', 0, name) + if self.cur: + pframe = self.cur[-2] + else: + pframe = None + frame = self.fake_frame(code, pframe) + self.dispatch['call'](self, frame, 0) + + # collect stats from pending stack, including getting final + # timings for self.cmd frame. + + def simulate_cmd_complete(self): + get_time = self.get_time + t = get_time() - self.t + while self.cur[-1]: + # We *can* cause assertion errors here if + # dispatch_trace_return checks for a frame match! + self.dispatch['return'](self, self.cur[-2], t) + t = 0 + self.t = get_time() - t + + + def print_stats(self, sort=-1): + import pstats + pstats.Stats(self).strip_dirs().sort_stats(sort). \ + print_stats() + + def dump_stats(self, file): + with open(file, 'wb') as f: + self.create_stats() + marshal.dump(self.stats, f) + + def create_stats(self): + self.simulate_cmd_complete() + self.snapshot_stats() + + def snapshot_stats(self): + self.stats = {} + for func, (cc, ns, tt, ct, callers) in self.timings.items(): + callers = callers.copy() + nc = 0 + for callcnt in callers.values(): + nc += callcnt + self.stats[func] = cc, nc, tt, ct, callers + + + # The following two methods can be called by clients to use + # a profiler to profile a statement, given as a string. + + def run(self, cmd): + import __main__ + dict = __main__.__dict__ + return self.runctx(cmd, dict, dict) + + def runctx(self, cmd, globals, locals): + self.set_cmd(cmd) + sys.setprofile(self.dispatcher) + try: + exec(cmd, globals, locals) + finally: + sys.setprofile(None) + return self + + # This method is more useful to profile a single function call. + def runcall(self, func, /, *args, **kw): + self.set_cmd(repr(func)) + sys.setprofile(self.dispatcher) + try: + return func(*args, **kw) + finally: + sys.setprofile(None) + + + #****************************************************************** + # The following calculates the overhead for using a profiler. The + # problem is that it takes a fair amount of time for the profiler + # to stop the stopwatch (from the time it receives an event). + # Similarly, there is a delay from the time that the profiler + # re-starts the stopwatch before the user's code really gets to + # continue. The following code tries to measure the difference on + # a per-event basis. + # + # Note that this difference is only significant if there are a lot of + # events, and relatively little user code per event. For example, + # code with small functions will typically benefit from having the + # profiler calibrated for the current platform. This *could* be + # done on the fly during init() time, but it is not worth the + # effort. Also note that if too large a value specified, then + # execution time on some functions will actually appear as a + # negative number. It is *normal* for some functions (with very + # low call counts) to have such negative stats, even if the + # calibration figure is "correct." + # + # One alternative to profile-time calibration adjustments (i.e., + # adding in the magic little delta during each event) is to track + # more carefully the number of events (and cumulatively, the number + # of events during sub functions) that are seen. If this were + # done, then the arithmetic could be done after the fact (i.e., at + # display time). Currently, we track only call/return events. + # These values can be deduced by examining the callees and callers + # vectors for each functions. Hence we *can* almost correct the + # internal time figure at print time (note that we currently don't + # track exception event processing counts). Unfortunately, there + # is currently no similar information for cumulative sub-function + # time. It would not be hard to "get all this info" at profiler + # time. Specifically, we would have to extend the tuples to keep + # counts of this in each frame, and then extend the defs of timing + # tuples to include the significant two figures. I'm a bit fearful + # that this additional feature will slow the heavily optimized + # event/time ratio (i.e., the profiler would run slower, fur a very + # low "value added" feature.) + #************************************************************** + + def calibrate(self, m, verbose=0): + if self.__class__ is not Profile: + raise TypeError("Subclasses must override .calibrate().") + + saved_bias = self.bias + self.bias = 0 + try: + return self._calibrate_inner(m, verbose) + finally: + self.bias = saved_bias + + def _calibrate_inner(self, m, verbose): + get_time = self.get_time + + # Set up a test case to be run with and without profiling. Include + # lots of calls, because we're trying to quantify stopwatch overhead. + # Do not raise any exceptions, though, because we want to know + # exactly how many profile events are generated (one call event, + + # one return event, per Python-level call). + + def f1(n): + for i in range(n): + x = 1 + + def f(m, f1=f1): + for i in range(m): + f1(100) + + f(m) # warm up the cache + + # elapsed_noprofile <- time f(m) takes without profiling. + t0 = get_time() + f(m) + t1 = get_time() + elapsed_noprofile = t1 - t0 + if verbose: + print("elapsed time without profiling =", elapsed_noprofile) + + # elapsed_profile <- time f(m) takes with profiling. The difference + # is profiling overhead, only some of which the profiler subtracts + # out on its own. + p = Profile() + t0 = get_time() + p.runctx('f(m)', globals(), locals()) + t1 = get_time() + elapsed_profile = t1 - t0 + if verbose: + print("elapsed time with profiling =", elapsed_profile) + + # reported_time <- "CPU seconds" the profiler charged to f and f1. + total_calls = 0.0 + reported_time = 0.0 + for (filename, line, funcname), (cc, ns, tt, ct, callers) in \ + p.timings.items(): + if funcname in ("f", "f1"): + total_calls += cc + reported_time += tt + + if verbose: + print("'CPU seconds' profiler reported =", reported_time) + print("total # calls =", total_calls) + if total_calls != m + 1: + raise ValueError("internal error: total calls = %d" % total_calls) + + # reported_time - elapsed_noprofile = overhead the profiler wasn't + # able to measure. Divide by twice the number of calls (since there + # are two profiler events per call in this test) to get the hidden + # overhead per event. + mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls + if verbose: + print("mean stopwatch overhead per profile event =", mean) + return mean + +#**************************************************************************** + +def main(): + import os + from optparse import OptionParser + + usage = "profile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." + parser = OptionParser(usage=usage) + parser.allow_interspersed_args = False + parser.add_option('-o', '--outfile', dest="outfile", + help="Save stats to ", default=None) + parser.add_option('-m', dest="module", action="store_true", + help="Profile a library module.", default=False) + parser.add_option('-s', '--sort', dest="sort", + help="Sort order when printing to stdout, based on pstats.Stats class", + default=-1) + + if not sys.argv[1:]: + parser.print_usage() + sys.exit(2) + + (options, args) = parser.parse_args() + sys.argv[:] = args + + # The script that we're profiling may chdir, so capture the absolute path + # to the output file at startup. + if options.outfile is not None: + options.outfile = os.path.abspath(options.outfile) + + if len(args) > 0: + if options.module: + import runpy + code = "run_module(modname, run_name='__main__')" + globs = { + 'run_module': runpy.run_module, + 'modname': args[0] + } + else: + progname = args[0] + sys.path.insert(0, os.path.dirname(progname)) + with io.open_code(progname) as fp: + code = compile(fp.read(), progname, 'exec') + globs = { + '__file__': progname, + '__name__': '__main__', + '__package__': None, + '__cached__': None, + } + try: + runctx(code, globs, None, options.outfile, options.sort) + except BrokenPipeError as exc: + # Prevent "Exception ignored" during interpreter shutdown. + sys.stdout = None + sys.exit(exc.errno) + else: + parser.print_usage() + return parser + +# When invoked as main program, invoke the profiler on a script +if __name__ == '__main__': + main() diff --git a/janus/lib/python3.10/this.py b/janus/lib/python3.10/this.py new file mode 100644 index 0000000000000000000000000000000000000000..e68dd3ff39b04ff857420b98889bee590b344024 --- /dev/null +++ b/janus/lib/python3.10/this.py @@ -0,0 +1,28 @@ +s = """Gur Mra bs Clguba, ol Gvz Crgref + +Ornhgvshy vf orggre guna htyl. +Rkcyvpvg vf orggre guna vzcyvpvg. +Fvzcyr vf orggre guna pbzcyrk. +Pbzcyrk vf orggre guna pbzcyvpngrq. +Syng vf orggre guna arfgrq. +Fcnefr vf orggre guna qrafr. +Ernqnovyvgl pbhagf. +Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. +Nygubhtu cenpgvpnyvgl orngf chevgl. +Reebef fubhyq arire cnff fvyragyl. +Hayrff rkcyvpvgyl fvyraprq. +Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. +Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. +Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. +Abj vf orggre guna arire. +Nygubhtu arire vf bsgra orggre guna *evtug* abj. +Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. +Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. +Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" + +d = {} +for c in (65, 97): + for i in range(26): + d[chr(i+c)] = chr((i+13) % 26 + c) + +print("".join([d.get(c, c) for c in s])) diff --git a/janus/lib/tcl8.6/msgs/af_za.msg b/janus/lib/tcl8.6/msgs/af_za.msg new file mode 100644 index 0000000000000000000000000000000000000000..fef48ad48fe899ab4bbc86f28edcf11edb66c5d8 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/af_za.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset af_ZA DATE_FORMAT "%d %B %Y" + ::msgcat::mcset af_ZA TIME_FORMAT_12 "%l:%M:%S %P" + ::msgcat::mcset af_ZA DATE_TIME_FORMAT "%d %B %Y %l:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/ar.msg b/janus/lib/tcl8.6/msgs/ar.msg new file mode 100644 index 0000000000000000000000000000000000000000..257157fd0e84065c8cf3bb2b58826781579d5e79 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/ar.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset ar DAYS_OF_WEEK_ABBREV [list \ + "\u062d"\ + "\u0646"\ + "\u062b"\ + "\u0631"\ + "\u062e"\ + "\u062c"\ + "\u0633"] + ::msgcat::mcset ar DAYS_OF_WEEK_FULL [list \ + "\u0627\u0644\u0623\u062d\u062f"\ + "\u0627\u0644\u0627\u062b\u0646\u064a\u0646"\ + "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621"\ + "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621"\ + "\u0627\u0644\u062e\u0645\u064a\u0633"\ + "\u0627\u0644\u062c\u0645\u0639\u0629"\ + "\u0627\u0644\u0633\u0628\u062a"] + ::msgcat::mcset ar MONTHS_ABBREV [list \ + "\u064a\u0646\u0627"\ + "\u0641\u0628\u0631"\ + "\u0645\u0627\u0631"\ + "\u0623\u0628\u0631"\ + "\u0645\u0627\u064a"\ + "\u064a\u0648\u0646"\ + "\u064a\u0648\u0644"\ + "\u0623\u063a\u0633"\ + "\u0633\u0628\u062a"\ + "\u0623\u0643\u062a"\ + "\u0646\u0648\u0641"\ + "\u062f\u064a\u0633"\ + ""] + ::msgcat::mcset ar MONTHS_FULL [list \ + "\u064a\u0646\u0627\u064a\u0631"\ + "\u0641\u0628\u0631\u0627\u064a\u0631"\ + "\u0645\u0627\u0631\u0633"\ + "\u0623\u0628\u0631\u064a\u0644"\ + "\u0645\u0627\u064a\u0648"\ + "\u064a\u0648\u0646\u064a\u0648"\ + "\u064a\u0648\u0644\u064a\u0648"\ + "\u0623\u063a\u0633\u0637\u0633"\ + "\u0633\u0628\u062a\u0645\u0628\u0631"\ + "\u0623\u0643\u062a\u0648\u0628\u0631"\ + "\u0646\u0648\u0641\u0645\u0628\u0631"\ + "\u062f\u064a\u0633\u0645\u0628\u0631"\ + ""] + ::msgcat::mcset ar BCE "\u0642.\u0645" + ::msgcat::mcset ar CE "\u0645" + ::msgcat::mcset ar AM "\u0635" + ::msgcat::mcset ar PM "\u0645" + ::msgcat::mcset ar DATE_FORMAT "%d/%m/%Y" + ::msgcat::mcset ar TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset ar DATE_TIME_FORMAT "%d/%m/%Y %I:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/ar_lb.msg b/janus/lib/tcl8.6/msgs/ar_lb.msg new file mode 100644 index 0000000000000000000000000000000000000000..e62acd35092b7bc3f9ade6c5a34dae2baa12aa30 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/ar_lb.msg @@ -0,0 +1,39 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset ar_LB DAYS_OF_WEEK_ABBREV [list \ + "\u0627\u0644\u0623\u062d\u062f"\ + "\u0627\u0644\u0627\u062b\u0646\u064a\u0646"\ + "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621"\ + "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621"\ + "\u0627\u0644\u062e\u0645\u064a\u0633"\ + "\u0627\u0644\u062c\u0645\u0639\u0629"\ + "\u0627\u0644\u0633\u0628\u062a"] + ::msgcat::mcset ar_LB MONTHS_ABBREV [list \ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0634\u0628\u0627\u0637"\ + "\u0622\u0630\u0627\u0631"\ + "\u0646\u064a\u0633\u0627\u0646"\ + "\u0646\u0648\u0627\u0631"\ + "\u062d\u0632\u064a\u0631\u0627\u0646"\ + "\u062a\u0645\u0648\u0632"\ + "\u0622\u0628"\ + "\u0623\u064a\u0644\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"\ + ""] + ::msgcat::mcset ar_LB MONTHS_FULL [list \ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0634\u0628\u0627\u0637"\ + "\u0622\u0630\u0627\u0631"\ + "\u0646\u064a\u0633\u0627\u0646"\ + "\u0646\u0648\u0627\u0631"\ + "\u062d\u0632\u064a\u0631\u0627\u0646"\ + "\u062a\u0645\u0648\u0632"\ + "\u0622\u0628"\ + "\u0623\u064a\u0644\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"\ + ""] +} diff --git a/janus/lib/tcl8.6/msgs/bn_in.msg b/janus/lib/tcl8.6/msgs/bn_in.msg new file mode 100644 index 0000000000000000000000000000000000000000..28c000f23595f3da231fefbb1d3b08030abe1e66 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/bn_in.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset bn_IN DATE_FORMAT "%A %d %b %Y" + ::msgcat::mcset bn_IN TIME_FORMAT_12 "%I:%M:%S %z" + ::msgcat::mcset bn_IN DATE_TIME_FORMAT "%A %d %b %Y %I:%M:%S %z %z" +} diff --git a/janus/lib/tcl8.6/msgs/de.msg b/janus/lib/tcl8.6/msgs/de.msg new file mode 100644 index 0000000000000000000000000000000000000000..9eb31454b5ce32f90f68e6518378c008a662f5f1 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/de.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset de DAYS_OF_WEEK_ABBREV [list \ + "So"\ + "Mo"\ + "Di"\ + "Mi"\ + "Do"\ + "Fr"\ + "Sa"] + ::msgcat::mcset de DAYS_OF_WEEK_FULL [list \ + "Sonntag"\ + "Montag"\ + "Dienstag"\ + "Mittwoch"\ + "Donnerstag"\ + "Freitag"\ + "Samstag"] + ::msgcat::mcset de MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mrz"\ + "Apr"\ + "Mai"\ + "Jun"\ + "Jul"\ + "Aug"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dez"\ + ""] + ::msgcat::mcset de MONTHS_FULL [list \ + "Januar"\ + "Februar"\ + "M\u00e4rz"\ + "April"\ + "Mai"\ + "Juni"\ + "Juli"\ + "August"\ + "September"\ + "Oktober"\ + "November"\ + "Dezember"\ + ""] + ::msgcat::mcset de BCE "v. Chr." + ::msgcat::mcset de CE "n. Chr." + ::msgcat::mcset de AM "vorm." + ::msgcat::mcset de PM "nachm." + ::msgcat::mcset de DATE_FORMAT "%d.%m.%Y" + ::msgcat::mcset de TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset de DATE_TIME_FORMAT "%d.%m.%Y %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/en_au.msg b/janus/lib/tcl8.6/msgs/en_au.msg new file mode 100644 index 0000000000000000000000000000000000000000..7f9870c924cf9590a720d790b1e14faceb66a56a --- /dev/null +++ b/janus/lib/tcl8.6/msgs/en_au.msg @@ -0,0 +1,7 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset en_AU DATE_FORMAT "%e/%m/%Y" + ::msgcat::mcset en_AU TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset en_AU TIME_FORMAT_12 "%I:%M:%S %P %z" + ::msgcat::mcset en_AU DATE_TIME_FORMAT "%e/%m/%Y %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/en_bw.msg b/janus/lib/tcl8.6/msgs/en_bw.msg new file mode 100644 index 0000000000000000000000000000000000000000..8fd20c7e3a8dff031501a2ded266f7c20b5d344e --- /dev/null +++ b/janus/lib/tcl8.6/msgs/en_bw.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset en_BW DATE_FORMAT "%d %B %Y" + ::msgcat::mcset en_BW TIME_FORMAT_12 "%l:%M:%S %P" + ::msgcat::mcset en_BW DATE_TIME_FORMAT "%d %B %Y %l:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/en_nz.msg b/janus/lib/tcl8.6/msgs/en_nz.msg new file mode 100644 index 0000000000000000000000000000000000000000..b419017a91d9e3db7435c34a68bd54a224454bf9 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/en_nz.msg @@ -0,0 +1,7 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset en_NZ DATE_FORMAT "%e/%m/%Y" + ::msgcat::mcset en_NZ TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset en_NZ TIME_FORMAT_12 "%I:%M:%S %P %z" + ::msgcat::mcset en_NZ DATE_TIME_FORMAT "%e/%m/%Y %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/en_za.msg b/janus/lib/tcl8.6/msgs/en_za.msg new file mode 100644 index 0000000000000000000000000000000000000000..fe43797fda976a1328445a338fe7deab323d647f --- /dev/null +++ b/janus/lib/tcl8.6/msgs/en_za.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset en_ZA DATE_FORMAT "%Y/%m/%d" + ::msgcat::mcset en_ZA TIME_FORMAT_12 "%I:%M:%S" + ::msgcat::mcset en_ZA DATE_TIME_FORMAT "%Y/%m/%d %I:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/eo.msg b/janus/lib/tcl8.6/msgs/eo.msg new file mode 100644 index 0000000000000000000000000000000000000000..1d2a24fece6b010f0020fb9b814ac9ab1ae07445 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/eo.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset eo DAYS_OF_WEEK_ABBREV [list \ + "di"\ + "lu"\ + "ma"\ + "me"\ + "\u0135a"\ + "ve"\ + "sa"] + ::msgcat::mcset eo DAYS_OF_WEEK_FULL [list \ + "diman\u0109o"\ + "lundo"\ + "mardo"\ + "merkredo"\ + "\u0135a\u016ddo"\ + "vendredo"\ + "sabato"] + ::msgcat::mcset eo MONTHS_ABBREV [list \ + "jan"\ + "feb"\ + "mar"\ + "apr"\ + "maj"\ + "jun"\ + "jul"\ + "a\u016dg"\ + "sep"\ + "okt"\ + "nov"\ + "dec"\ + ""] + ::msgcat::mcset eo MONTHS_FULL [list \ + "januaro"\ + "februaro"\ + "marto"\ + "aprilo"\ + "majo"\ + "junio"\ + "julio"\ + "a\u016dgusto"\ + "septembro"\ + "oktobro"\ + "novembro"\ + "decembro"\ + ""] + ::msgcat::mcset eo BCE "aK" + ::msgcat::mcset eo CE "pK" + ::msgcat::mcset eo AM "atm" + ::msgcat::mcset eo PM "ptm" + ::msgcat::mcset eo DATE_FORMAT "%Y-%b-%d" + ::msgcat::mcset eo TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset eo DATE_TIME_FORMAT "%Y-%b-%d %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/es_do.msg b/janus/lib/tcl8.6/msgs/es_do.msg new file mode 100644 index 0000000000000000000000000000000000000000..0e283da84744a0fac4250b580bf325c42ceba0d8 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/es_do.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_DO DATE_FORMAT "%m/%d/%Y" + ::msgcat::mcset es_DO TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_DO DATE_TIME_FORMAT "%m/%d/%Y %I:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/es_ni.msg b/janus/lib/tcl8.6/msgs/es_ni.msg new file mode 100644 index 0000000000000000000000000000000000000000..7c394953a3d069ae78355c632ae28a25fbf111d2 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/es_ni.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_NI DATE_FORMAT "%m-%d-%Y" + ::msgcat::mcset es_NI TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_NI DATE_TIME_FORMAT "%m-%d-%Y %I:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/es_pr.msg b/janus/lib/tcl8.6/msgs/es_pr.msg new file mode 100644 index 0000000000000000000000000000000000000000..8511b126ed0be24c044315366f7c75b87aa70f36 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/es_pr.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_PR DATE_FORMAT "%m-%d-%Y" + ::msgcat::mcset es_PR TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_PR DATE_TIME_FORMAT "%m-%d-%Y %I:%M:%S %P %z" +} diff --git a/janus/lib/tcl8.6/msgs/fa.msg b/janus/lib/tcl8.6/msgs/fa.msg new file mode 100644 index 0000000000000000000000000000000000000000..89b2f90894a4336f0f5cc15365b08e3a07539a20 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/fa.msg @@ -0,0 +1,47 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset fa DAYS_OF_WEEK_ABBREV [list \ + "\u06cc\u2214"\ + "\u062f\u2214"\ + "\u0633\u2214"\ + "\u0686\u2214"\ + "\u067e\u2214"\ + "\u062c\u2214"\ + "\u0634\u2214"] + ::msgcat::mcset fa DAYS_OF_WEEK_FULL [list \ + "\u06cc\u06cc\u200c\u0634\u0646\u0628\u0647"\ + "\u062f\u0648\u0634\u0646\u0628\u0647"\ + "\u0633\u0647\u200c\u0634\u0646\u0628\u0647"\ + "\u0686\u0647\u0627\u0631\u0634\u0646\u0628\u0647"\ + "\u067e\u0646\u062c\u200c\u0634\u0646\u0628\u0647"\ + "\u062c\u0645\u0639\u0647"\ + "\u0634\u0646\u0628\u0647"] + ::msgcat::mcset fa MONTHS_ABBREV [list \ + "\u0698\u0627\u0646"\ + "\u0641\u0648\u0631"\ + "\u0645\u0627\u0631"\ + "\u0622\u0648\u0631"\ + "\u0645\u0640\u0647"\ + "\u0698\u0648\u0646"\ + "\u0698\u0648\u06cc"\ + "\u0627\u0648\u062a"\ + "\u0633\u067e\u062a"\ + "\u0627\u0643\u062a"\ + "\u0646\u0648\u0627"\ + "\u062f\u0633\u0627"\ + ""] + ::msgcat::mcset fa MONTHS_FULL [list \ + "\u0698\u0627\u0646\u0648\u06cc\u0647"\ + "\u0641\u0648\u0631\u0648\u06cc\u0647"\ + "\u0645\u0627\u0631\u0633"\ + "\u0622\u0648\u0631\u06cc\u0644"\ + "\u0645\u0647"\ + "\u0698\u0648\u0626\u0646"\ + "\u0698\u0648\u0626\u06cc\u0647"\ + "\u0627\u0648\u062a"\ + "\u0633\u067e\u062a\u0627\u0645\u0628\u0631"\ + "\u0627\u0643\u062a\u0628\u0631"\ + "\u0646\u0648\u0627\u0645\u0628\u0631"\ + "\u062f\u0633\u0627\u0645\u0628\u0631"\ + ""] +} diff --git a/janus/lib/tcl8.6/msgs/fr_be.msg b/janus/lib/tcl8.6/msgs/fr_be.msg new file mode 100644 index 0000000000000000000000000000000000000000..cdb13bd75f307b2498698ebaef0c572877dfe9eb --- /dev/null +++ b/janus/lib/tcl8.6/msgs/fr_be.msg @@ -0,0 +1,7 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset fr_BE DATE_FORMAT "%d/%m/%y" + ::msgcat::mcset fr_BE TIME_FORMAT "%T" + ::msgcat::mcset fr_BE TIME_FORMAT_12 "%T" + ::msgcat::mcset fr_BE DATE_TIME_FORMAT "%a %d %b %Y %T %z" +} diff --git a/janus/lib/tcl8.6/msgs/gl.msg b/janus/lib/tcl8.6/msgs/gl.msg new file mode 100644 index 0000000000000000000000000000000000000000..4b869e8550665690bf621afdf659cd9d39e9cb2c --- /dev/null +++ b/janus/lib/tcl8.6/msgs/gl.msg @@ -0,0 +1,47 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset gl DAYS_OF_WEEK_ABBREV [list \ + "Dom"\ + "Lun"\ + "Mar"\ + "M\u00e9r"\ + "Xov"\ + "Ven"\ + "S\u00e1b"] + ::msgcat::mcset gl DAYS_OF_WEEK_FULL [list \ + "Domingo"\ + "Luns"\ + "Martes"\ + "M\u00e9rcores"\ + "Xoves"\ + "Venres"\ + "S\u00e1bado"] + ::msgcat::mcset gl MONTHS_ABBREV [list \ + "Xan"\ + "Feb"\ + "Mar"\ + "Abr"\ + "Mai"\ + "Xu\u00f1"\ + "Xul"\ + "Ago"\ + "Set"\ + "Out"\ + "Nov"\ + "Dec"\ + ""] + ::msgcat::mcset gl MONTHS_FULL [list \ + "Xaneiro"\ + "Febreiro"\ + "Marzo"\ + "Abril"\ + "Maio"\ + "Xu\u00f1o"\ + "Xullo"\ + "Agosto"\ + "Setembro"\ + "Outubro"\ + "Novembro"\ + "Decembro"\ + ""] +} diff --git a/janus/lib/tcl8.6/msgs/lv.msg b/janus/lib/tcl8.6/msgs/lv.msg new file mode 100644 index 0000000000000000000000000000000000000000..a037b151cc531d0fbb9f6ec82ca25ce067cc40ea --- /dev/null +++ b/janus/lib/tcl8.6/msgs/lv.msg @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset lv DAYS_OF_WEEK_ABBREV [list \ + "Sv"\ + "P"\ + "O"\ + "T"\ + "C"\ + "Pk"\ + "S"] + ::msgcat::mcset lv DAYS_OF_WEEK_FULL [list \ + "sv\u0113tdiena"\ + "pirmdiena"\ + "otrdiena"\ + "tre\u0161diena"\ + "ceturdien"\ + "piektdiena"\ + "sestdiena"] + ::msgcat::mcset lv MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mar"\ + "Apr"\ + "Maijs"\ + "J\u016bn"\ + "J\u016bl"\ + "Aug"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dec"\ + ""] + ::msgcat::mcset lv MONTHS_FULL [list \ + "janv\u0101ris"\ + "febru\u0101ris"\ + "marts"\ + "apr\u012blis"\ + "maijs"\ + "j\u016bnijs"\ + "j\u016blijs"\ + "augusts"\ + "septembris"\ + "oktobris"\ + "novembris"\ + "decembris"\ + ""] + ::msgcat::mcset lv BCE "pm\u0113" + ::msgcat::mcset lv CE "m\u0113" + ::msgcat::mcset lv DATE_FORMAT "%Y.%e.%m" + ::msgcat::mcset lv TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset lv DATE_TIME_FORMAT "%Y.%e.%m %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/mr.msg b/janus/lib/tcl8.6/msgs/mr.msg new file mode 100644 index 0000000000000000000000000000000000000000..cea427a9065c619748b2807040a5314cc0915c1e --- /dev/null +++ b/janus/lib/tcl8.6/msgs/mr.msg @@ -0,0 +1,39 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset mr DAYS_OF_WEEK_FULL [list \ + "\u0930\u0935\u093f\u0935\u093e\u0930"\ + "\u0938\u094b\u092e\u0935\u093e\u0930"\ + "\u092e\u0902\u0917\u0933\u0935\u093e\u0930"\ + "\u092e\u0902\u0917\u0933\u0935\u093e\u0930"\ + "\u0917\u0941\u0930\u0941\u0935\u093e\u0930"\ + "\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930"\ + "\u0936\u0928\u093f\u0935\u093e\u0930"] + ::msgcat::mcset mr MONTHS_ABBREV [list \ + "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940"\ + "\u092b\u0947\u092c\u0943\u0935\u093e\u0930\u0940"\ + "\u092e\u093e\u0930\u094d\u091a"\ + "\u090f\u092a\u094d\u0930\u093f\u0932"\ + "\u092e\u0947"\ + "\u091c\u0942\u0928"\ + "\u091c\u0941\u0932\u0948"\ + "\u0913\u0917\u0938\u094d\u091f"\ + "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930"\ + "\u0913\u0915\u094d\u091f\u094b\u092c\u0930"\ + "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930"\ + "\u0921\u093f\u0938\u0947\u0902\u092c\u0930"] + ::msgcat::mcset mr MONTHS_FULL [list \ + "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940"\ + "\u092b\u0947\u092c\u0943\u0935\u093e\u0930\u0940"\ + "\u092e\u093e\u0930\u094d\u091a"\ + "\u090f\u092a\u094d\u0930\u093f\u0932"\ + "\u092e\u0947"\ + "\u091c\u0942\u0928"\ + "\u091c\u0941\u0932\u0948"\ + "\u0913\u0917\u0938\u094d\u091f"\ + "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930"\ + "\u0913\u0915\u094d\u091f\u094b\u092c\u0930"\ + "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930"\ + "\u0921\u093f\u0938\u0947\u0902\u092c\u0930"] + ::msgcat::mcset mr AM "BC" + ::msgcat::mcset mr PM "AD" +} diff --git a/janus/lib/tcl8.6/msgs/ms.msg b/janus/lib/tcl8.6/msgs/ms.msg new file mode 100644 index 0000000000000000000000000000000000000000..e954431b7b7bfc876c3a1c53d22d3843546dee2d --- /dev/null +++ b/janus/lib/tcl8.6/msgs/ms.msg @@ -0,0 +1,47 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset ms DAYS_OF_WEEK_ABBREV [list \ + "Aha"\ + "Isn"\ + "Sei"\ + "Rab"\ + "Kha"\ + "Jum"\ + "Sab"] + ::msgcat::mcset ms DAYS_OF_WEEK_FULL [list \ + "Ahad"\ + "Isnin"\ + "Selasa"\ + "Rahu"\ + "Khamis"\ + "Jumaat"\ + "Sabtu"] + ::msgcat::mcset ms MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mac"\ + "Apr"\ + "Mei"\ + "Jun"\ + "Jul"\ + "Ogos"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dis"\ + ""] + ::msgcat::mcset ms MONTHS_FULL [list \ + "Januari"\ + "Februari"\ + "Mac"\ + "April"\ + "Mei"\ + "Jun"\ + "Julai"\ + "Ogos"\ + "September"\ + "Oktober"\ + "November"\ + "Disember"\ + ""] +} diff --git a/janus/lib/tcl8.6/msgs/nl_be.msg b/janus/lib/tcl8.6/msgs/nl_be.msg new file mode 100644 index 0000000000000000000000000000000000000000..4b19670fc6dc2c3a4412fa8f49b2de77347b5cc3 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/nl_be.msg @@ -0,0 +1,7 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset nl_BE DATE_FORMAT "%d-%m-%y" + ::msgcat::mcset nl_BE TIME_FORMAT "%T" + ::msgcat::mcset nl_BE TIME_FORMAT_12 "%T" + ::msgcat::mcset nl_BE DATE_TIME_FORMAT "%a %d %b %Y %T %z" +} diff --git a/janus/lib/tcl8.6/msgs/nn.msg b/janus/lib/tcl8.6/msgs/nn.msg new file mode 100644 index 0000000000000000000000000000000000000000..bd61ac9493955b92806bfa55c43c769d5c522cb4 --- /dev/null +++ b/janus/lib/tcl8.6/msgs/nn.msg @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset nn DAYS_OF_WEEK_ABBREV [list \ + "su"\ + "m\u00e5"\ + "ty"\ + "on"\ + "to"\ + "fr"\ + "lau"] + ::msgcat::mcset nn DAYS_OF_WEEK_FULL [list \ + "sundag"\ + "m\u00e5ndag"\ + "tysdag"\ + "onsdag"\ + "torsdag"\ + "fredag"\ + "laurdag"] + ::msgcat::mcset nn MONTHS_ABBREV [list \ + "jan"\ + "feb"\ + "mar"\ + "apr"\ + "mai"\ + "jun"\ + "jul"\ + "aug"\ + "sep"\ + "okt"\ + "nov"\ + "des"\ + ""] + ::msgcat::mcset nn MONTHS_FULL [list \ + "januar"\ + "februar"\ + "mars"\ + "april"\ + "mai"\ + "juni"\ + "juli"\ + "august"\ + "september"\ + "oktober"\ + "november"\ + "desember"\ + ""] + ::msgcat::mcset nn BCE "f.Kr." + ::msgcat::mcset nn CE "e.Kr." + ::msgcat::mcset nn DATE_FORMAT "%e. %B %Y" + ::msgcat::mcset nn TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset nn DATE_TIME_FORMAT "%e. %B %Y %H:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/msgs/th.msg b/janus/lib/tcl8.6/msgs/th.msg new file mode 100644 index 0000000000000000000000000000000000000000..7486c35a68f7a5abbb2e085cbf4a5285dc3c612b --- /dev/null +++ b/janus/lib/tcl8.6/msgs/th.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset th DAYS_OF_WEEK_ABBREV [list \ + "\u0e2d\u0e32."\ + "\u0e08."\ + "\u0e2d."\ + "\u0e1e."\ + "\u0e1e\u0e24."\ + "\u0e28."\ + "\u0e2a."] + ::msgcat::mcset th DAYS_OF_WEEK_FULL [list \ + "\u0e27\u0e31\u0e19\u0e2d\u0e32\u0e17\u0e34\u0e15\u0e22\u0e4c"\ + "\u0e27\u0e31\u0e19\u0e08\u0e31\u0e19\u0e17\u0e23\u0e4c"\ + "\u0e27\u0e31\u0e19\u0e2d\u0e31\u0e07\u0e04\u0e32\u0e23"\ + "\u0e27\u0e31\u0e19\u0e1e\u0e38\u0e18"\ + "\u0e27\u0e31\u0e19\u0e1e\u0e24\u0e2b\u0e31\u0e2a\u0e1a\u0e14\u0e35"\ + "\u0e27\u0e31\u0e19\u0e28\u0e38\u0e01\u0e23\u0e4c"\ + "\u0e27\u0e31\u0e19\u0e40\u0e2a\u0e32\u0e23\u0e4c"] + ::msgcat::mcset th MONTHS_ABBREV [list \ + "\u0e21.\u0e04."\ + "\u0e01.\u0e1e."\ + "\u0e21\u0e35.\u0e04."\ + "\u0e40\u0e21.\u0e22."\ + "\u0e1e.\u0e04."\ + "\u0e21\u0e34.\u0e22."\ + "\u0e01.\u0e04."\ + "\u0e2a.\u0e04."\ + "\u0e01.\u0e22."\ + "\u0e15.\u0e04."\ + "\u0e1e.\u0e22."\ + "\u0e18.\u0e04."\ + ""] + ::msgcat::mcset th MONTHS_FULL [list \ + "\u0e21\u0e01\u0e23\u0e32\u0e04\u0e21"\ + "\u0e01\u0e38\u0e21\u0e20\u0e32\u0e1e\u0e31\u0e19\u0e18\u0e4c"\ + "\u0e21\u0e35\u0e19\u0e32\u0e04\u0e21"\ + "\u0e40\u0e21\u0e29\u0e32\u0e22\u0e19"\ + "\u0e1e\u0e24\u0e29\u0e20\u0e32\u0e04\u0e21"\ + "\u0e21\u0e34\u0e16\u0e38\u0e19\u0e32\u0e22\u0e19"\ + "\u0e01\u0e23\u0e01\u0e0e\u0e32\u0e04\u0e21"\ + "\u0e2a\u0e34\u0e07\u0e2b\u0e32\u0e04\u0e21"\ + "\u0e01\u0e31\u0e19\u0e22\u0e32\u0e22\u0e19"\ + "\u0e15\u0e38\u0e25\u0e32\u0e04\u0e21"\ + "\u0e1e\u0e24\u0e28\u0e08\u0e34\u0e01\u0e32\u0e22\u0e19"\ + "\u0e18\u0e31\u0e19\u0e27\u0e32\u0e04\u0e21"\ + ""] + ::msgcat::mcset th BCE "\u0e25\u0e17\u0e35\u0e48" + ::msgcat::mcset th CE "\u0e04.\u0e28." + ::msgcat::mcset th AM "\u0e01\u0e48\u0e2d\u0e19\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07" + ::msgcat::mcset th PM "\u0e2b\u0e25\u0e31\u0e07\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07" + ::msgcat::mcset th DATE_FORMAT "%e/%m/%Y" + ::msgcat::mcset th TIME_FORMAT "%k:%M:%S" + ::msgcat::mcset th DATE_TIME_FORMAT "%e/%m/%Y %k:%M:%S %z" +} diff --git a/janus/lib/tcl8.6/opt0.4/pkgIndex.tcl b/janus/lib/tcl8.6/opt0.4/pkgIndex.tcl new file mode 100644 index 0000000000000000000000000000000000000000..c763a3d671057caba6089842b40e2f220b310bb6 --- /dev/null +++ b/janus/lib/tcl8.6/opt0.4/pkgIndex.tcl @@ -0,0 +1,12 @@ +# Tcl package index file, version 1.1 +# This file is generated by the "pkg_mkIndex -direct" command +# and sourced either when an application starts up or +# by a "package unknown" script. It invokes the +# "package ifneeded" command to set up package-related +# information so that packages will be loaded automatically +# in response to "package require" commands. When this +# script is sourced, the variable $dir must contain the +# full path name of this file's directory. + +if {![package vsatisfies [package provide Tcl] 8.5-]} {return} +package ifneeded opt 0.4.9 [list source [file join $dir optparse.tcl]]