repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
dspy
dspy/adapters/types/history.py
.py
from typing import Any import pydantic class History(pydantic.BaseModel): """Class representing the conversation history. The conversation history is a list of messages, each message entity should have keys from the associated signature. For example, if you have the following signature: ``` cla...
69
2,113
dspy
dspy/adapters/types/code.py
.py
import re from typing import Any, ClassVar import pydantic from pydantic import create_model from dspy.adapters.types.base_type import Type class Code(Type): """Code type in DSPy. This type is useful for code generation and code analysis. Example 1: dspy.Code as output type in code generation: ``...
132
3,837
dspy
dspy/adapters/types/audio.py
.py
import base64 import io import mimetypes import os import warnings from typing import Any, Union from urllib.parse import urlparse import pydantic import requests from dspy.adapters.types.base_type import Type try: import soundfile as sf SF_AVAILABLE = True except ImportError: SF_AVAILABLE = False def...
213
8,656
dspy
dspy/adapters/types/tool.py
.py
import asyncio import inspect from typing import TYPE_CHECKING, Any, Callable, get_origin, get_type_hints import json_repair import pydantic from jsonschema import ValidationError, validate from pydantic import BaseModel, TypeAdapter, create_model from dspy.adapters.types.base_type import Type from dspy.dsp.utils.set...
560
21,554
dspy
dspy/adapters/types/reasoning.py
.py
from typing import TYPE_CHECKING, Any, Optional import pydantic from dspy.adapters.types.base_type import Type from dspy.clients.base_lm import BaseLM if TYPE_CHECKING: from dspy.signatures.signature import Signature class Reasoning(Type): """Reasoning type in DSPy. This type is useful when you want t...
171
6,231
dspy
dspy/adapters/types/document.py
.py
from typing import Any, Literal import pydantic from dspy.adapters.types.base_type import Type from dspy.utils.annotation import experimental @experimental(version="3.0.4") class Document(Type): """A document type for providing content that can be cited by language models. This type represents documents th...
115
3,843
dspy
dspy/adapters/types/base_type.py
.py
import json import re from typing import TYPE_CHECKING, Any, Optional, get_args, get_origin import json_repair import pydantic from dspy.clients.base_lm import BaseLM if TYPE_CHECKING: from litellm import ModelResponseStream from dspy.signatures.signature import Signature CUSTOM_TYPE_START_IDENTIFIER = "<<...
218
7,718
gym
setup.py
.py
"""Setups the project.""" import itertools import re from setuptools import find_packages, setup with open("gym/version.py") as file: full_version = file.read() assert ( re.match(r'VERSION = "\d\.\d+\.\d+"\n', full_version).group(0) == full_version ), f"Unexpected version: {full_version}" VERS...
91
3,048
gym
gym/error.py
.py
"""Set of Error classes for gym.""" import warnings class Error(Exception): """Error superclass.""" # Local errors class Unregistered(Error): """Raised when the user requests an item from the registry that does not actually exist.""" class UnregisteredEnv(Unregistered): """Raised when the user reque...
195
5,545
gym
gym/logger.py
.py
"""Set of functions for logging messages.""" import sys import warnings from typing import Optional, Type from gym.utils import colorize DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 min_level = 30 # Ensure DeprecationWarning to be displayed (#2685, #3059) warnings.filterwarnings("once", "", DeprecationW...
74
1,774
gym
gym/__init__.py
.py
"""Root __init__ of the gym module setting the __all__ of gym modules.""" # isort: skip_file from gym import error from gym.version import VERSION as __version__ from gym.core import ( Env, Wrapper, ObservationWrapper, ActionWrapper, RewardWrapper, ) from gym.spaces import Space from gym.envs impo...
44
1,177
gym
gym/core.py
.py
"""Core API for Environment, Wrapper, ActionWrapper, RewardWrapper and ObservationWrapper.""" import sys from typing import ( TYPE_CHECKING, Any, Dict, Generic, List, Optional, SupportsFloat, Tuple, TypeVar, Union, ) import numpy as np from gym import spaces from gym.logger imp...
469
20,620
gym
gym/wrappers/clip_action.py
.py
"""Wrapper for clipping actions within a valid bound.""" import numpy as np import gym from gym import ActionWrapper from gym.spaces import Box class ClipAction(ActionWrapper): """Clip the continuous action within the valid :class:`Box` observation space bound. Example: >>> import gym >>> en...
41
1,155
gym
gym/wrappers/normalize.py
.py
"""Set of wrappers for normalizing actions and observations.""" import numpy as np import gym # taken from https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py class RunningMeanStd: """Tracks the mean, variance and count of values.""" # https://en.wikipedia.org/wiki/Algo...
145
5,712
gym
gym/wrappers/time_limit.py
.py
"""Wrapper for limiting the time steps of an environment.""" from typing import Optional import gym class TimeLimit(gym.Wrapper): """This wrapper will issue a `truncated` signal if a maximum number of timesteps is exceeded. If a truncation is not defined inside the environment itself, this is the only place...
69
2,527
gym
gym/wrappers/transform_reward.py
.py
"""Wrapper for transforming the reward.""" from typing import Callable import gym from gym import RewardWrapper class TransformReward(RewardWrapper): """Transform the reward via an arbitrary function. Warning: If the base environment specifies a reward range which is not invariant under :attr:`f`, t...
45
1,332
gym
gym/wrappers/atari_preprocessing.py
.py
"""Implementation of Atari 2600 Preprocessing following the guidelines of Machado et al., 2018.""" import numpy as np import gym from gym.spaces import Box try: import cv2 except ImportError: cv2 = None class AtariPreprocessing(gym.Wrapper): """Atari 2600 preprocessing wrapper. This class follows t...
191
7,860
gym
gym/wrappers/gray_scale_observation.py
.py
"""Wrapper that converts a color observation to grayscale.""" import numpy as np import gym from gym.spaces import Box class GrayScaleObservation(gym.ObservationWrapper): """Convert the image observation from RGB to gray scale. Example: >>> env = gym.make('CarRacing-v1') >>> env.observation_...
65
2,079
gym
gym/wrappers/env_checker.py
.py
"""A passive environment checker wrapper for an environment's observation and action space along with the reset, step and render functions.""" import gym from gym.core import ActType from gym.utils.passive_env_checker import ( check_action_space, check_observation_space, env_render_passive_checker, env_...
56
2,306
gym
gym/wrappers/order_enforcing.py
.py
"""Wrapper to enforce the proper ordering of environment operations.""" import gym from gym.error import ResetNeeded class OrderEnforcing(gym.Wrapper): """A wrapper that will produce an error if :meth:`step` is called before an initial :meth:`reset`. Example: >>> from gym.envs.classic_control import ...
57
2,158
gym
gym/wrappers/pixel_observation.py
.py
"""Wrapper for augmenting observations by pixel values.""" import collections import copy from collections.abc import MutableMapping from typing import Any, Dict, List, Optional, Tuple import numpy as np import gym from gym import spaces STATE_KEY = "state" class PixelObservationWrapper(gym.ObservationWrapper): ...
208
8,049
gym
gym/wrappers/vector_list_info.py
.py
"""Wrapper that converts the info format for vec envs into the list format.""" from typing import List import gym class VectorListInfo(gym.Wrapper): """Converts infos of vectorized environments from dict to List[dict]. This wrapper converts the info format of a vector environment from a dictionary to a...
112
3,821
gym
gym/wrappers/record_video.py
.py
"""Wrapper for recording videos.""" import os from typing import Callable, Optional import gym from gym import logger from gym.wrappers.monitoring import video_recorder def capped_cubic_video_schedule(episode_id: int) -> bool: """The default episode trigger. This function will trigger recordings at the epis...
212
8,310
gym
gym/wrappers/flatten_observation.py
.py
"""Wrapper for flattening observations of an environment.""" import gym import gym.spaces as spaces class FlattenObservation(gym.ObservationWrapper): """Observation wrapper that flattens the observation. Example: >>> import gym >>> env = gym.make('CarRacing-v1') >>> env.observation_sp...
41
1,092
gym
gym/wrappers/record_episode_statistics.py
.py
"""Wrapper that tracks the cumulative rewards and episode lengths.""" import time from collections import deque from typing import Optional import numpy as np import gym def add_vector_episode_statistics( info: dict, episode_info: dict, num_envs: int, env_num: int ): """Add episode statistics. Add stat...
152
5,650
gym
gym/wrappers/time_aware_observation.py
.py
"""Wrapper for adding time aware observations to environment observation.""" import numpy as np import gym from gym.spaces import Box class TimeAwareObservation(gym.ObservationWrapper): """Augment the observation with the current time step in the episode. The observation space of the wrapped environment is ...
72
2,402
gym
gym/wrappers/frame_stack.py
.py
"""Wrapper that stacks frames.""" from collections import deque from typing import Union import numpy as np import gym from gym.error import DependencyNotInstalled from gym.spaces import Box class LazyFrames: """Ensures common frames are only stored once to optimize memory use. To further reduce the memory...
191
6,322
gym
gym/wrappers/compatibility.py
.py
"""A compatibility wrapper converting an old-style environment into a valid environment.""" import sys from typing import Any, Dict, Optional, Tuple import gym from gym.core import ObsType from gym.utils.step_api_compatibility import convert_to_terminated_truncated_step_api if sys.version_info >= (3, 8): from typ...
131
4,288
gym
gym/wrappers/filter_observation.py
.py
"""A wrapper for filtering dictionary observations by their keys.""" import copy from typing import Sequence import gym from gym import spaces class FilterObservation(gym.ObservationWrapper): """Filter Dict observation space by the keys. Example: >>> import gym >>> env = gym.wrappers.Transfo...
92
3,435
gym
gym/wrappers/resize_observation.py
.py
"""Wrapper for resizing observations.""" from typing import Union import numpy as np import gym from gym.error import DependencyNotInstalled from gym.spaces import Box class ResizeObservation(gym.ObservationWrapper): """Resize the image observation. This wrapper works on environments with image observation...
73
2,399
gym
gym/wrappers/autoreset.py
.py
"""Wrapper that autoreset environments when `terminated=True` or `truncated=True`.""" import gym class AutoResetWrapper(gym.Wrapper): """A class for providing an automatic reset functionality for gym environments when calling :meth:`self.step`. When calling step causes :meth:`Env.step` to return `terminated=...
62
3,131
gym
gym/wrappers/render_collection.py
.py
"""A wrapper that adds render collection mode to an environment.""" import gym class RenderCollection(gym.Wrapper): """Save collection of render frames.""" def __init__(self, env: gym.Env, pop_frames: bool = True, reset_clean: bool = True): """Initialize a :class:`RenderCollection` instance. ...
53
1,804
gym
gym/wrappers/transform_observation.py
.py
"""Wrapper for transforming observations.""" from typing import Any, Callable import gym class TransformObservation(gym.ObservationWrapper): """Transform the observation via an arbitrary function :attr:`f`. The function :attr:`f` should be defined on the observation space of the base environment, ``env``, a...
44
1,672
gym
gym/wrappers/rescale_action.py
.py
"""Wrapper for rescaling actions to within a max and min action.""" from typing import Union import numpy as np import gym from gym import spaces class RescaleAction(gym.ActionWrapper): """Affinely rescales the continuous action space of the environment to the range [min_action, max_action]. The base envir...
83
3,100
gym
gym/wrappers/human_rendering.py
.py
"""A wrapper that adds human-renering functionality to an environment.""" import numpy as np import gym from gym.error import DependencyNotInstalled class HumanRendering(gym.Wrapper): """Performs human rendering for an environment that only supports "rgb_array"rendering. This wrapper is particularly useful ...
133
5,051
gym
gym/wrappers/step_api_compatibility.py
.py
"""Implementation of StepAPICompatibility wrapper class for transforming envs between new and old step API.""" import gym from gym.logger import deprecation from gym.utils.step_api_compatibility import ( convert_to_done_step_api, convert_to_terminated_truncated_step_api, ) class StepAPICompatibility(gym.Wrapp...
59
2,649
gym
gym/wrappers/monitoring/video_recorder.py
.py
"""A wrapper for video recording environments by rolling it out, frame by frame.""" import json import os import os.path import tempfile from typing import List, Optional from gym import error, logger class VideoRecorder: """VideoRecorder renders a nice movie of a rollout, frame by frame. It comes with an `...
179
6,362
gym
gym/vector/__init__.py
.py
"""Module for vector environments.""" from typing import Iterable, List, Optional, Union import gym from gym.vector.async_vector_env import AsyncVectorEnv from gym.vector.sync_vector_env import SyncVectorEnv from gym.vector.vector_env import VectorEnv, VectorEnvWrapper __all__ = ["AsyncVectorEnv", "SyncVectorEnv", "V...
74
3,023
gym
gym/vector/async_vector_env.py
.py
"""An async vector environment.""" import multiprocessing as mp import sys import time from copy import deepcopy from enum import Enum from typing import List, Optional, Sequence, Tuple, Union import numpy as np import gym from gym import logger from gym.core import ObsType from gym.error import ( AlreadyPendingC...
685
27,608
gym
gym/vector/sync_vector_env.py
.py
"""A synchronous vector environment.""" from copy import deepcopy from typing import Any, Callable, Iterator, List, Optional, Sequence, Union import numpy as np from gym import Env from gym.spaces import Space from gym.vector.utils import concatenate, create_empty_array, iterate from gym.vector.vector_env import Vect...
237
8,760
gym
gym/vector/vector_env.py
.py
"""Base class for vectorized environments.""" from typing import Any, List, Optional, Tuple, Union import numpy as np import gym from gym.vector.utils.spaces import batch_space __all__ = ["VectorEnv"] class VectorEnv(gym.Env): """Base class for vectorized environments. Runs multiple independent copies of the s...
333
11,487
gym
gym/vector/utils/misc.py
.py
"""Miscellaneous utilities.""" import contextlib import os __all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"] class CloudpickleWrapper: """Wrapper that uses cloudpickle to pickle and unpickle the result.""" def __init__(self, fn: callable): """Cloudpickle wrapper for a function.""" self....
56
1,587
gym
gym/vector/utils/shared_memory.py
.py
"""Utility functions for vector environments to share memory between processes.""" import multiprocessing as mp from collections import OrderedDict from ctypes import c_bool from functools import singledispatch from typing import Union import numpy as np from gym.error import CustomSpaceError from gym.spaces import B...
183
6,522
gym
gym/vector/utils/__init__.py
.py
"""Module for gym vector utils.""" from gym.vector.utils.misc import CloudpickleWrapper, clear_mpi_env_vars from gym.vector.utils.numpy_utils import concatenate, create_empty_array from gym.vector.utils.shared_memory import ( create_shared_memory, read_from_shared_memory, write_to_shared_memory, ) from gym....
24
727
gym
gym/vector/utils/spaces.py
.py
"""Utility functions for gym spaces: batch space and iterator.""" from collections import OrderedDict from copy import deepcopy from functools import singledispatch from typing import Iterator import numpy as np from gym.error import CustomSpaceError from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscr...
212
6,434
gym
gym/vector/utils/numpy_utils.py
.py
"""Numpy utility functions: concatenate space samples and create empty array.""" from collections import OrderedDict from functools import singledispatch from typing import Iterable, Union import numpy as np from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple __all__ = ["concatenate"...
137
4,477
gym
gym/spaces/multi_binary.py
.py
"""Implementation of a space that consists of binary np.ndarrays of a fixed shape.""" from typing import Optional, Sequence, Tuple, Union import numpy as np from gym.spaces.space import Space class MultiBinary(Space[np.ndarray]): """An n-shape binary space. Elements of this space are binary arrays of a sha...
119
4,569
gym
gym/spaces/utils.py
.py
"""Implementation of utility functions that can be applied to spaces. These functions mostly take care of flattening and unflattening elements of spaces to facilitate their usage in learning code. """ import operator as op from collections import OrderedDict from functools import reduce, singledispatch from typing im...
451
14,940
gym
gym/spaces/sequence.py
.py
"""Implementation of a space that represents finite-length sequences.""" from collections.abc import Sequence as CollectionSequence from typing import Any, List, Optional, Tuple, Union import numpy as np import gym from gym.spaces.space import Space class Sequence(Space[Tuple]): r"""This space represent sets of...
127
5,487
gym
gym/spaces/box.py
.py
"""Implementation of a space that represents closed boxes in euclidean space.""" from typing import Dict, List, Optional, Sequence, SupportsFloat, Tuple, Type, Union import numpy as np import gym.error from gym import logger from gym.spaces.space import Space def _short_repr(arr: np.ndarray) -> str: """Create a...
339
12,732
gym
gym/spaces/__init__.py
.py
"""This module implements various spaces. Spaces describe mathematical sets and are used in Gym to specify valid actions and observations. Every Gym environment must have the attributes ``action_space`` and ``observation_space``. If, for instance, three possible actions (0,1,2) can be performed in your environment and...
40
1,266
gym
gym/spaces/multi_discrete.py
.py
"""Implementation of a space that represents the cartesian product of `Discrete` spaces.""" from typing import Iterable, List, Optional, Sequence, Tuple, Union import numpy as np from gym import logger from gym.spaces.discrete import Discrete from gym.spaces.space import Space class MultiDiscrete(Space[np.ndarray])...
176
7,519
gym
gym/spaces/tuple.py
.py
"""Implementation of a space that represents the cartesian product of other spaces.""" from collections.abc import Sequence as CollectionSequence from typing import Iterable, Optional from typing import Sequence as TypingSequence from typing import Tuple as TypingTuple from typing import Union import numpy as np from...
163
6,382
gym
gym/spaces/text.py
.py
"""Implementation of a space that represents textual strings.""" from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Union import numpy as np from gym.spaces.space import Space alphanumeric: FrozenSet[str] = frozenset( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) class Text(Spa...
186
7,660
gym
gym/spaces/discrete.py
.py
"""Implementation of a space consisting of finitely many elements.""" from typing import Optional, Union import numpy as np from gym.spaces.space import Space class Discrete(Space[int]): r"""A space consisting of finitely many elements. This class represents a finite subset of integers, more specifically a...
127
4,476
gym
gym/spaces/dict.py
.py
"""Implementation of a space that represents the cartesian product of other spaces as a dictionary.""" from collections import OrderedDict from collections.abc import Mapping, Sequence from typing import Any from typing import Dict as TypingDict from typing import List, Optional from typing import Sequence as TypingSeq...
246
10,427
gym
gym/spaces/space.py
.py
"""Implementation of the `Space` metaclass.""" from typing import ( Any, Generic, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) import numpy as np from gym.utils import seeding T_cov = TypeVar("T_cov", covariant=True) class Space(Generic[T_...
151
5,653
gym
gym/spaces/graph.py
.py
"""Implementation of a space that represents graph information where nodes and edges can be represented with euclidean space.""" from typing import NamedTuple, Optional, Sequence, Tuple, Union import numpy as np from gym.logger import warn from gym.spaces.box import Box from gym.spaces.discrete import Discrete from g...
239
9,771
gym
gym/utils/colorize.py
.py
"""A set of common utilities used within the environments. These are not intended as API functions, and will not remain stable over time. """ color2num = dict( gray=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, crimson=38, ) def colorize( string: st...
42
974
gym
gym/utils/ezpickle.py
.py
"""Class for pickling and unpickling objects via their constructor arguments.""" class EzPickle: """Objects that are pickled and unpickled via their constructor arguments. Example:: >>> class Dog(Animal, EzPickle): ... def __init__(self, furcolor, tailkind="bushy"): ... Ani...
36
1,354
gym
gym/utils/env_checker.py
.py
"""A set of functions for checking an environment details. This file is originally from the Stable Baselines3 repository hosted on GitHub (https://github.com/DLR-RM/stable-baselines3/) Original Author: Antonin Raffin It also uses some warnings/assertions from the PettingZoo repository hosted on GitHub (https://github...
311
12,606
gym
gym/utils/__init__.py
.py
"""A set of common utilities used within the environments. These are not intended as API functions, and will not remain stable over time. """ # These submodules should not have any import-time dependencies. # We want this since we use `utils` during our import-time sanity checks # that verify that our dependencies ar...
11
420
gym
gym/utils/play.py
.py
"""Utilities of visualising an environment.""" from collections import deque from typing import Callable, Dict, List, Optional, Tuple, Union import numpy as np import gym.error from gym import Env, logger from gym.core import ActType, ObsType from gym.error import DependencyNotInstalled from gym.logger import depreca...
387
15,289
gym
gym/utils/seeding.py
.py
"""Set of random number generator functions: seeding, generator, hashing seeds.""" from typing import Any, Optional, Tuple import numpy as np from gym import error def np_random(seed: Optional[int] = None) -> Tuple[np.random.Generator, Any]: """Generates a random number generator from the seed and returns the G...
31
911
gym
gym/utils/save_video.py
.py
"""Utility functions to save rendering videos.""" import os from typing import Callable, Optional import gym from gym import logger try: from moviepy.video.io.ImageSequenceClip import ImageSequenceClip except ImportError: raise gym.error.DependencyNotInstalled( "MoviePy is not installed, run `pip inst...
108
4,191
gym
gym/utils/passive_env_checker.py
.py
"""A set of functions for passively checking environment implementations.""" import inspect from functools import partial from typing import Callable import numpy as np from gym import Space, error, logger, spaces def _check_box_observation_space(observation_space: spaces.Box): """Checks that a :class:`Box` obs...
321
15,046
gym
gym/utils/step_api_compatibility.py
.py
"""Contains methods for step compatibility, from old-to-new and new-to-old API.""" from typing import Tuple, Union import numpy as np from gym.core import ObsType DoneStepType = Tuple[ Union[ObsType, np.ndarray], Union[float, np.ndarray], Union[bool, np.ndarray], Union[dict, list], ] TerminatedTrunc...
162
6,522
gym
gym/envs/__init__.py
.py
from gym.envs.registration import load_env_plugins as _load_env_plugins from gym.envs.registration import make, register, registry, spec # Hook to load plugins from entry points _load_env_plugins() # Classic # ---------------------------------------- register( id="CartPole-v0", entry_point="gym.envs.classic...
321
6,961
gym
gym/envs/registration.py
.py
import contextlib import copy import difflib import importlib import importlib.util import re import sys import warnings from dataclasses import dataclass, field from typing import ( Callable, Dict, List, Optional, Sequence, SupportsFloat, Tuple, Union, overload, ) import numpy as n...
704
26,208
gym
gym/envs/classic_control/continuous_mountain_car.py
.py
""" @author: Olivier Sigaud A merge between two sources: * Adaptation of the MountainCar Environment from the "FAReinforcement" library of Jose Antonio Martin H. (version 1.0), adapted by 'Tom Schaul, tom@idsia.ch' and then modified by Arnaud de Broissia * the gym MountainCar environment itself from http://incomple...
301
10,546
gym
gym/envs/classic_control/cartpole.py
.py
""" Classic cart-pole system implemented by Rich Sutton et al. Copied from http://incompleteideas.net/sutton/book/code/pole.c permalink: https://perma.cc/C9ZM-652R """ import math from typing import Optional, Union import numpy as np import gym from gym import logger, spaces from gym.envs.classic_control import utils...
313
11,579
gym
gym/envs/classic_control/acrobot.py
.py
"""classic Acrobot task""" from typing import Optional import numpy as np from numpy import cos, pi, sin from gym import core, logger, spaces from gym.error import DependencyNotInstalled __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __credits__ = [ "Alborz Geramifard", "Robert H. Klein", ...
466
16,814
gym
gym/envs/classic_control/utils.py
.py
""" Utility functions used for classic control environments. """ from typing import Optional, SupportsFloat, Tuple def verify_number_and_cast(x: SupportsFloat) -> float: """Verify parameter is a single number and cast to a float.""" try: x = float(x) except (ValueError, TypeError): raise ...
47
1,415
gym
gym/envs/classic_control/mountain_car.py
.py
""" http://incompleteideas.net/MountainCar/MountainCar1.cp permalink: https://perma.cc/6Z2N-PFWC """ import math from typing import Optional import numpy as np import gym from gym import spaces from gym.envs.classic_control import utils from gym.error import DependencyNotInstalled class MountainCarEnv(gym.Env): ...
283
9,826
gym
gym/envs/classic_control/pendulum.py
.py
__credits__ = ["Carlos Luis"] from os import path from typing import Optional import numpy as np import gym from gym import spaces from gym.envs.classic_control import utils from gym.error import DependencyNotInstalled DEFAULT_X = np.pi DEFAULT_Y = 1.0 class PendulumEnv(gym.Env): """ ### Description ...
272
9,519
gym
gym/envs/toy_text/blackjack.py
.py
import os from typing import Optional import numpy as np import gym from gym import spaces from gym.error import DependencyNotInstalled def cmp(a, b): return float(a > b) - float(a < b) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def draw_card(np_r...
319
10,806
gym
gym/envs/toy_text/utils.py
.py
import numpy as np def categorical_sample(prob_n, np_random: np.random.Generator): """Sample from categorical distribution where each row specifies class probabilities.""" prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return np.argmax(csprob_n > np_random.random())
9
295
gym
gym/envs/toy_text/frozen_lake.py
.py
from contextlib import closing from io import StringIO from os import path from typing import List, Optional import numpy as np from gym import Env, logger, spaces, utils from gym.envs.toy_text.utils import categorical_sample from gym.error import DependencyNotInstalled LEFT = 0 DOWN = 1 RIGHT = 2 UP = 3 MAPS = { ...
414
13,715
gym
gym/envs/toy_text/cliffwalking.py
.py
from contextlib import closing from io import StringIO from os import path from typing import Optional import numpy as np from gym import Env, logger, spaces from gym.envs.toy_text.utils import categorical_sample from gym.error import DependencyNotInstalled UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class CliffWalkingEnv(...
294
10,940
gym
gym/envs/toy_text/taxi.py
.py
from contextlib import closing from io import StringIO from os import path from typing import Optional import numpy as np from gym import Env, logger, spaces, utils from gym.envs.toy_text.utils import categorical_sample from gym.error import DependencyNotInstalled MAP = [ "+---------+", "|R: | : :G|", "|...
473
18,318
gym
gym/envs/box2d/car_dynamics.py
.py
""" Top-down car dynamics simulation. Some ideas are taken from this great tutorial http://www.iforce2d.net/b2dtut/top-down-car by Chris Campbell. This simulation is a bit more detailed, with wheels rotation. Created by Oleg Klimov """ import math import Box2D import numpy as np from gym.error import DependencyNot...
352
12,147
gym
gym/envs/box2d/bipedal_walker.py
.py
__credits__ = ["Andrea PIERRÉ"] import math from typing import TYPE_CHECKING, List, Optional import numpy as np import gym from gym import error, spaces from gym.error import DependencyNotInstalled from gym.utils import EzPickle try: import Box2D from Box2D.b2 import ( circleShape, contactLi...
858
31,175
gym
gym/envs/box2d/lunar_lander.py
.py
__credits__ = ["Andrea PIERRÉ"] import math import warnings from typing import TYPE_CHECKING, Optional import numpy as np import gym from gym import error, spaces from gym.error import DependencyNotInstalled from gym.utils import EzPickle, colorize from gym.utils.step_api_compatibility import step_api_compatibility ...
818
29,802
gym
gym/envs/box2d/car_racing.py
.py
__credits__ = ["Andrea PIERRÉ"] import math from typing import Optional, Union import numpy as np import gym from gym import spaces from gym.envs.box2d.car_dynamics import Car from gym.error import DependencyNotInstalled, InvalidAction from gym.utils import EzPickle try: import Box2D from Box2D.b2 import co...
829
28,932
gym
gym/envs/mujoco/mujoco_env.py
.py
from os import path from typing import Optional, Union import numpy as np import gym from gym import error, logger, spaces from gym.spaces import Space try: import mujoco_py except ImportError as e: MUJOCO_PY_IMPORT_ERROR = e else: MUJOCO_PY_IMPORT_ERROR = None try: import mujoco except ImportError ...
438
14,450
gym
gym/envs/mujoco/ant.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class AntEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 20, } de...
81
2,400
gym
gym/envs/mujoco/pusher_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box class PusherEnv(MujocoEnv, utils.EzPickle): """ ### Description "Pusher" is a multi-jointed robot arm which is very similar to that of a human. The goal is to move a target cylinder (called *obj...
207
12,160
gym
gym/envs/mujoco/walker2d_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 2, "distance": 4.0, "lookat": np.array((0.0, 0.0, 1.15)), "elevation": -20.0, } class Walker2dEnv(MujocoEnv, utils.EzPickle): """ ### Description...
297
16,500
gym
gym/envs/mujoco/inverted_pendulum_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box class InvertedPendulumEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment is the cartpole environment based on the work done by Barto, Sutton, and Anderson in ["Neuronlike adapt...
133
5,736
gym
gym/envs/mujoco/swimmer_v3.py
.py
__credits__ = ["Rushiv Arora"] import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = {} class SwimmerEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "...
129
3,877
gym
gym/envs/mujoco/half_cheetah_v4.py
.py
__credits__ = ["Rushiv Arora"] import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "distance": 4.0, } class HalfCheetahEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment is based on the work by P. Waw...
246
13,252
gym
gym/envs/mujoco/hopper_v3.py
.py
__credits__ = ["Rushiv Arora"] import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 2, "distance": 3.0, "lookat": np.array((0.0, 0.0, 1.15)), "elevation": -20.0, } class HopperEnv(MuJocoPyEnv, utils.EzPi...
178
5,316
gym
gym/envs/mujoco/inverted_double_pendulum_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box class InvertedDoublePendulumEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment originates from control theory and builds on the cartpole environment based on the work done by B...
174
9,332
gym
gym/envs/mujoco/half_cheetah.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class HalfCheetahEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 20, }...
65
1,840
gym
gym/envs/mujoco/reacher_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box class ReacherEnv(MujocoEnv, utils.EzPickle): """ ### Description "Reacher" is a two-jointed robot arm. The goal is to move the robot's end effector (called *fingertip*) close to a target that is ...
188
10,039
gym
gym/envs/mujoco/humanoid_v3.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 1, "distance": 4.0, "lookat": np.array((0.0, 0.0, 2.0)), "elevation": -20.0, } def mass_center(model, sim): mass = np.expand_dims(model.body_mass, ...
200
6,299
gym
gym/envs/mujoco/humanoidstandup.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class HumanoidStandupEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 67, ...
88
2,449
gym
gym/envs/mujoco/half_cheetah_v3.py
.py
__credits__ = ["Rushiv Arora"] import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "distance": 4.0, } class HalfCheetahEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", ...
128
3,669
gym
gym/envs/mujoco/hopper.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class HopperEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 125, } ...
68
2,026
gym
gym/envs/mujoco/walker2d_v3.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 2, "distance": 4.0, "lookat": np.array((0.0, 0.0, 1.15)), "elevation": -20.0, } class Walker2dEnv(MuJocoPyEnv, utils.EzPickle): metadata = { ...
168
4,942