dpct-env 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dpct_env-0.0.1/PKG-INFO +86 -0
- dpct_env-0.0.1/README.md +63 -0
- dpct_env-0.0.1/dpct_env/__init__.py +1 -0
- dpct_env-0.0.1/dpct_env/evaluation/__init__.py +1 -0
- dpct_env-0.0.1/dpct_env/evaluation/docs/__init__.py +1 -0
- dpct_env-0.0.1/dpct_env/fitness/__init__.py +19 -0
- dpct_env-0.0.1/dpct_env/fitness/base.py +61 -0
- dpct_env-0.0.1/dpct_env/fitness/control_effort.py +66 -0
- dpct_env-0.0.1/dpct_env/fitness/height_achieved.py +82 -0
- dpct_env-0.0.1/dpct_env/fitness/observation_variance.py +95 -0
- dpct_env-0.0.1/dpct_env/fitness/registry.py +85 -0
- dpct_env-0.0.1/dpct_env/processors/__init__.py +30 -0
- dpct_env-0.0.1/dpct_env/processors/base.py +93 -0
- dpct_env-0.0.1/dpct_env/processors/cartpole.py +46 -0
- dpct_env-0.0.1/dpct_env/processors/wind_turbine.py +187 -0
- dpct_env-0.0.1/dpct_env/wrappers/__init__.py +1 -0
- dpct_env-0.0.1/dpct_env/wrappers/action_mappers.py +1 -0
- dpct_env-0.0.1/dpct_env.egg-info/PKG-INFO +86 -0
- dpct_env-0.0.1/dpct_env.egg-info/SOURCES.txt +24 -0
- dpct_env-0.0.1/dpct_env.egg-info/dependency_links.txt +1 -0
- dpct_env-0.0.1/dpct_env.egg-info/requires.txt +7 -0
- dpct_env-0.0.1/dpct_env.egg-info/top_level.txt +1 -0
- dpct_env-0.0.1/pyproject.toml +44 -0
- dpct_env-0.0.1/setup.cfg +4 -0
- dpct_env-0.0.1/tests/test_fitness.py +178 -0
- dpct_env-0.0.1/tests/test_processors.py +114 -0
dpct_env-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dpct-env
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Environment-specific plugins for the DPCT framework
|
|
5
|
+
Author-email: rupert-ai-agent <rupert@perceptualrobots.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/rupert-ai-agent/dpct-env
|
|
8
|
+
Project-URL: Documentation, https://rupert-ai-agent.github.io/dpct-env/
|
|
9
|
+
Keywords: dpct,gymnasium,environment,pct,fitness
|
|
10
|
+
Classifier: Natural Language :: English
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: dpct
|
|
18
|
+
Requires-Dist: gymnasium>=0.29.0
|
|
19
|
+
Requires-Dist: numpy>=1.26.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest; extra == "dev"
|
|
22
|
+
Requires-Dist: nbdev; extra == "dev"
|
|
23
|
+
|
|
24
|
+
# dpct-env
|
|
25
|
+
|
|
26
|
+
Environment-specific plugins for the [DPCT](https://github.com/perceptualrobots/dpct) framework.
|
|
27
|
+
|
|
28
|
+
This package provides:
|
|
29
|
+
|
|
30
|
+
- **Fitness functions** — class-based fitness computation for specific environments
|
|
31
|
+
- **Results processors** — Comet ML logging for environment-specific metrics
|
|
32
|
+
- **Environment evaluations** — documentation on environment suitability for DPCT
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install dpct-env
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
### Fitness Functions
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from dpct_env.fitness import get_fitness_functions, ControlEffortFitness
|
|
46
|
+
|
|
47
|
+
# Get all fitness functions registered for CartPole-v1
|
|
48
|
+
fns = get_fitness_functions("CartPole-v1")
|
|
49
|
+
|
|
50
|
+
# Compute a fitness value
|
|
51
|
+
fitness = fns["stability_ratio"](observation_history=obs, action_history=acts)
|
|
52
|
+
|
|
53
|
+
# Use a fitness function directly
|
|
54
|
+
effort_fn = ControlEffortFitness(mode="changes")
|
|
55
|
+
fitness = effort_fn(observation_history=obs, action_history=acts)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Results Processors
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from dpct_env.processors import create_environment_results_processor
|
|
62
|
+
|
|
63
|
+
processor = create_environment_results_processor("CartPole-v1")
|
|
64
|
+
processor.log_results(experiment=exp, individual=ind, history=history)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Registered Environments
|
|
68
|
+
|
|
69
|
+
| Environment | Fitness Functions |
|
|
70
|
+
|---|---|
|
|
71
|
+
| CartPole-v1 | control_effort, observation_variance, stability_ratio |
|
|
72
|
+
| MountainCar-v0 | control_effort, height_achieved |
|
|
73
|
+
| Acrobot-v1 | control_effort, height_achieved |
|
|
74
|
+
| Pendulum-v1 | control_effort, observation_variance |
|
|
75
|
+
|
|
76
|
+
## Architecture
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
dpct-env ──depends on──▶ dpct
|
|
80
|
+
│ │
|
|
81
|
+
└── provides plugins ───┘
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`dpct-env` is a pure plugin package — it imports from `dpct` but `dpct` never
|
|
85
|
+
imports from `dpct-env`. This keeps the core framework clean while allowing
|
|
86
|
+
environment-specific functionality to evolve independently.
|
dpct_env-0.0.1/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# dpct-env
|
|
2
|
+
|
|
3
|
+
Environment-specific plugins for the [DPCT](https://github.com/perceptualrobots/dpct) framework.
|
|
4
|
+
|
|
5
|
+
This package provides:
|
|
6
|
+
|
|
7
|
+
- **Fitness functions** — class-based fitness computation for specific environments
|
|
8
|
+
- **Results processors** — Comet ML logging for environment-specific metrics
|
|
9
|
+
- **Environment evaluations** — documentation on environment suitability for DPCT
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install dpct-env
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
### Fitness Functions
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from dpct_env.fitness import get_fitness_functions, ControlEffortFitness
|
|
23
|
+
|
|
24
|
+
# Get all fitness functions registered for CartPole-v1
|
|
25
|
+
fns = get_fitness_functions("CartPole-v1")
|
|
26
|
+
|
|
27
|
+
# Compute a fitness value
|
|
28
|
+
fitness = fns["stability_ratio"](observation_history=obs, action_history=acts)
|
|
29
|
+
|
|
30
|
+
# Use a fitness function directly
|
|
31
|
+
effort_fn = ControlEffortFitness(mode="changes")
|
|
32
|
+
fitness = effort_fn(observation_history=obs, action_history=acts)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Results Processors
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from dpct_env.processors import create_environment_results_processor
|
|
39
|
+
|
|
40
|
+
processor = create_environment_results_processor("CartPole-v1")
|
|
41
|
+
processor.log_results(experiment=exp, individual=ind, history=history)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Registered Environments
|
|
45
|
+
|
|
46
|
+
| Environment | Fitness Functions |
|
|
47
|
+
|---|---|
|
|
48
|
+
| CartPole-v1 | control_effort, observation_variance, stability_ratio |
|
|
49
|
+
| MountainCar-v0 | control_effort, height_achieved |
|
|
50
|
+
| Acrobot-v1 | control_effort, height_achieved |
|
|
51
|
+
| Pendulum-v1 | control_effort, observation_variance |
|
|
52
|
+
|
|
53
|
+
## Architecture
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
dpct-env ──depends on──▶ dpct
|
|
57
|
+
│ │
|
|
58
|
+
└── provides plugins ───┘
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`dpct-env` is a pure plugin package — it imports from `dpct` but `dpct` never
|
|
62
|
+
imports from `dpct-env`. This keeps the core framework clean while allowing
|
|
63
|
+
environment-specific functionality to evolve independently.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Evaluation docs — see README.md in the parent directory.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Docs
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Fitness functions for environment-specific evaluation."""
|
|
2
|
+
|
|
3
|
+
from .base import FitnessFunction
|
|
4
|
+
from .control_effort import ControlEffortFitness
|
|
5
|
+
from .observation_variance import ObservationVarianceFitness, StabilityRatioFitness
|
|
6
|
+
from .height_achieved import HeightAchievedFitness
|
|
7
|
+
from .registry import FITNESS_REGISTRY, get_fitness_functions, register_fitness_function, list_environments
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"FitnessFunction",
|
|
11
|
+
"ControlEffortFitness",
|
|
12
|
+
"ObservationVarianceFitness",
|
|
13
|
+
"StabilityRatioFitness",
|
|
14
|
+
"HeightAchievedFitness",
|
|
15
|
+
"FITNESS_REGISTRY",
|
|
16
|
+
"get_fitness_functions",
|
|
17
|
+
"register_fitness_function",
|
|
18
|
+
"list_environments",
|
|
19
|
+
]
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Base class for environment-specific fitness functions.
|
|
2
|
+
|
|
3
|
+
Each fitness function is a class that takes episode history (observations,
|
|
4
|
+
actions, infos) and computes a scalar fitness value. Fitness functions are
|
|
5
|
+
registered per-environment in the registry.
|
|
6
|
+
|
|
7
|
+
Classes are used instead of plain functions to allow configuration (e.g.,
|
|
8
|
+
which observation index to monitor, what threshold to use).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from typing import Any, Dict, Optional
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FitnessFunction(ABC):
|
|
18
|
+
"""Base class for environment-specific fitness functions.
|
|
19
|
+
|
|
20
|
+
Subclasses implement `compute()` to calculate fitness from episode history.
|
|
21
|
+
The standard interface takes observation, action, and info histories as
|
|
22
|
+
numpy arrays.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
name: str = "base"
|
|
26
|
+
|
|
27
|
+
def __init__(self, **kwargs):
|
|
28
|
+
"""Store any configuration parameters."""
|
|
29
|
+
self.config = kwargs
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def compute(
|
|
33
|
+
self,
|
|
34
|
+
observation_history: Optional[np.ndarray] = None,
|
|
35
|
+
action_history: Optional[np.ndarray] = None,
|
|
36
|
+
info_history: Optional[list] = None,
|
|
37
|
+
) -> float:
|
|
38
|
+
"""Compute fitness from episode history.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
observation_history: Array of shape (T, obs_dim) or None
|
|
42
|
+
action_history: Array of shape (T,) or (T, action_dim) or None
|
|
43
|
+
info_history: List of info dicts or None
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Scalar fitness value (higher is better unless minimize=True)
|
|
47
|
+
"""
|
|
48
|
+
...
|
|
49
|
+
|
|
50
|
+
def __call__(
|
|
51
|
+
self,
|
|
52
|
+
observation_history: Optional[np.ndarray] = None,
|
|
53
|
+
action_history: Optional[np.ndarray] = None,
|
|
54
|
+
info_history: Optional[list] = None,
|
|
55
|
+
) -> float:
|
|
56
|
+
"""Allow calling a FitnessFunction instance like a function."""
|
|
57
|
+
return self.compute(observation_history, action_history, info_history)
|
|
58
|
+
|
|
59
|
+
def __repr__(self) -> str:
|
|
60
|
+
params = ", ".join(f"{k}={v!r}" for k, v in self.config.items()) if self.config else ""
|
|
61
|
+
return f"{self.__class__.__name__}({params})"
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Control effort fitness — measures action smoothness.
|
|
2
|
+
|
|
3
|
+
Applicable to any control environment. Lower action change frequency = higher
|
|
4
|
+
fitness. This is the universal fitness function that works across all
|
|
5
|
+
environments with action history.
|
|
6
|
+
|
|
7
|
+
The logic is copied from the CartPole analysis but parameterized so it works
|
|
8
|
+
for any action space (continuous or discrete).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
from .base import FitnessFunction
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ControlEffortFitness(FitnessFunction):
|
|
18
|
+
"""Fitness based on action smoothness / control effort.
|
|
19
|
+
|
|
20
|
+
Two modes:
|
|
21
|
+
- "changes": counts the number of action direction changes (for discrete actions)
|
|
22
|
+
- "magnitude": sum of absolute action deltas (for continuous actions)
|
|
23
|
+
|
|
24
|
+
Returns negative value (fewer changes / smoother = higher fitness).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
name = "control_effort"
|
|
28
|
+
|
|
29
|
+
def __init__(self, mode: str = "auto", **kwargs):
|
|
30
|
+
"""
|
|
31
|
+
Args:
|
|
32
|
+
mode: "changes" for discrete actions, "magnitude" for continuous,
|
|
33
|
+
"auto" to infer from action history.
|
|
34
|
+
"""
|
|
35
|
+
super().__init__(mode=mode, **kwargs)
|
|
36
|
+
self.mode = mode
|
|
37
|
+
|
|
38
|
+
def compute(
|
|
39
|
+
self,
|
|
40
|
+
observation_history: Optional[np.ndarray] = None,
|
|
41
|
+
action_history: Optional[np.ndarray] = None,
|
|
42
|
+
info_history: Optional[list] = None,
|
|
43
|
+
) -> float:
|
|
44
|
+
if action_history is None or len(action_history) < 2:
|
|
45
|
+
return 0.0
|
|
46
|
+
|
|
47
|
+
actions = np.asarray(action_history).reshape(-1)
|
|
48
|
+
|
|
49
|
+
# Infer mode if auto
|
|
50
|
+
mode = self.mode
|
|
51
|
+
if mode == "auto":
|
|
52
|
+
# If actions look like integers → discrete
|
|
53
|
+
mode = "changes" if np.all(actions == actions.astype(int)) else "magnitude"
|
|
54
|
+
|
|
55
|
+
if mode == "changes":
|
|
56
|
+
# Count direction changes (zero-crossings or value changes)
|
|
57
|
+
diffs = np.diff(actions)
|
|
58
|
+
changes = np.count_nonzero(diffs)
|
|
59
|
+
return -float(changes)
|
|
60
|
+
else:
|
|
61
|
+
# Sum of absolute deltas
|
|
62
|
+
diffs = np.abs(np.diff(actions))
|
|
63
|
+
return -float(np.sum(diffs))
|
|
64
|
+
|
|
65
|
+
def __repr__(self):
|
|
66
|
+
return f"ControlEffortFitness(mode={self.mode!r})"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Height achieved fitness — for climbing/high-reaching environments.
|
|
2
|
+
|
|
3
|
+
Used for MountainCar and Acrobot where the goal is to reach a height target.
|
|
4
|
+
Returns the maximum height achieved during the episode (continuous proxy for
|
|
5
|
+
task success that provides gradient even before the goal is reached).
|
|
6
|
+
|
|
7
|
+
For MountainCar: height = sin(3 * position)
|
|
8
|
+
For Acrobot: height = -cos(θ₁) - cos(θ₂ + θ₁)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
from .base import FitnessFunction
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HeightAchievedFitness(FitnessFunction):
|
|
18
|
+
"""Fitness based on maximum height achieved during the episode.
|
|
19
|
+
|
|
20
|
+
Uses the observation to compute height. Supports different height
|
|
21
|
+
computation modes for different environments.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
name = "height_achieved"
|
|
25
|
+
|
|
26
|
+
def __init__(self, mode: str = "position_sin", **kwargs):
|
|
27
|
+
"""
|
|
28
|
+
Args:
|
|
29
|
+
mode: How to compute height from observations:
|
|
30
|
+
- "position_sin": height = sin(3 * obs[0]) — for MountainCar
|
|
31
|
+
- "direct": height = obs[0] — use first observation directly
|
|
32
|
+
- "acrobot": height = -cos(θ₁) - cos(θ₂ + θ₁) — for Acrobot
|
|
33
|
+
(uses obs[0]=cos(θ₁), obs[1]=sin(θ₁), obs[2]=cos(θ₂), obs[3]=sin(θ₂))
|
|
34
|
+
"""
|
|
35
|
+
super().__init__(mode=mode, **kwargs)
|
|
36
|
+
self.mode = mode
|
|
37
|
+
|
|
38
|
+
def compute(
|
|
39
|
+
self,
|
|
40
|
+
observation_history: Optional[np.ndarray] = None,
|
|
41
|
+
action_history: Optional[np.ndarray] = None,
|
|
42
|
+
info_history: Optional[list] = None,
|
|
43
|
+
) -> float:
|
|
44
|
+
if observation_history is None or len(observation_history) == 0:
|
|
45
|
+
return 0.0
|
|
46
|
+
|
|
47
|
+
obs = np.asarray(observation_history, dtype=np.float32)
|
|
48
|
+
if obs.ndim != 2:
|
|
49
|
+
return 0.0
|
|
50
|
+
|
|
51
|
+
if self.mode == "position_sin":
|
|
52
|
+
# MountainCar: height = sin(3 * position)
|
|
53
|
+
if obs.shape[1] < 1:
|
|
54
|
+
return 0.0
|
|
55
|
+
heights = np.sin(3 * obs[:, 0])
|
|
56
|
+
|
|
57
|
+
elif self.mode == "direct":
|
|
58
|
+
# Use first observation as height proxy
|
|
59
|
+
if obs.shape[1] < 1:
|
|
60
|
+
return 0.0
|
|
61
|
+
heights = obs[:, 0]
|
|
62
|
+
|
|
63
|
+
elif self.mode == "acrobot":
|
|
64
|
+
# Acrobot: height = -cos(θ₁) - cos(θ₂ + θ₁)
|
|
65
|
+
# obs[0]=cos(θ₁), obs[1]=sin(θ₁), obs[2]=cos(θ₂), obs[3]=sin(θ₂)
|
|
66
|
+
if obs.shape[1] < 4:
|
|
67
|
+
return 0.0
|
|
68
|
+
cos_theta1 = obs[:, 0]
|
|
69
|
+
sin_theta1 = obs[:, 1]
|
|
70
|
+
cos_theta2 = obs[:, 2]
|
|
71
|
+
sin_theta2 = obs[:, 3]
|
|
72
|
+
theta1 = np.arctan2(sin_theta1, cos_theta1)
|
|
73
|
+
theta2 = np.arctan2(sin_theta2, cos_theta2)
|
|
74
|
+
heights = -cos_theta1 - np.cos(theta2 + theta1)
|
|
75
|
+
|
|
76
|
+
else:
|
|
77
|
+
return 0.0
|
|
78
|
+
|
|
79
|
+
return float(np.max(heights))
|
|
80
|
+
|
|
81
|
+
def __repr__(self):
|
|
82
|
+
return f"HeightAchievedFitness(mode={self.mode!r})"
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Observation variance fitness — measures stability of a tracked variable.
|
|
2
|
+
|
|
3
|
+
Generalized from CartPole's `stability` fitness. Configure with `obs_index`
|
|
4
|
+
to select which observation dimension to monitor, and `threshold` for the
|
|
5
|
+
stability band.
|
|
6
|
+
|
|
7
|
+
Returns negative variance (lower variance = more stable = higher fitness).
|
|
8
|
+
Optionally returns the fraction of steps within the threshold band.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
from .base import FitnessFunction
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ObservationVarianceFitness(FitnessFunction):
|
|
18
|
+
"""Fitness based on variance of a specific observation dimension.
|
|
19
|
+
|
|
20
|
+
Returns negative variance (lower variance = higher fitness). This is the
|
|
21
|
+
generalization of CartPole's `stability` function to any environment.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
name = "observation_variance"
|
|
25
|
+
|
|
26
|
+
def __init__(self, obs_index: int = 0, **kwargs):
|
|
27
|
+
"""
|
|
28
|
+
Args:
|
|
29
|
+
obs_index: Which observation dimension to monitor (default: 0)
|
|
30
|
+
"""
|
|
31
|
+
super().__init__(obs_index=obs_index, **kwargs)
|
|
32
|
+
self.obs_index = obs_index
|
|
33
|
+
|
|
34
|
+
def compute(
|
|
35
|
+
self,
|
|
36
|
+
observation_history: Optional[np.ndarray] = None,
|
|
37
|
+
action_history: Optional[np.ndarray] = None,
|
|
38
|
+
info_history: Optional[list] = None,
|
|
39
|
+
) -> float:
|
|
40
|
+
if observation_history is None or len(observation_history) == 0:
|
|
41
|
+
return 0.0
|
|
42
|
+
|
|
43
|
+
obs = np.asarray(observation_history, dtype=np.float32)
|
|
44
|
+
if obs.ndim != 2 or obs.shape[1] <= self.obs_index:
|
|
45
|
+
return 0.0
|
|
46
|
+
|
|
47
|
+
values = obs[:, self.obs_index]
|
|
48
|
+
variance = float(np.var(values))
|
|
49
|
+
return -variance
|
|
50
|
+
|
|
51
|
+
def __repr__(self):
|
|
52
|
+
return f"ObservationVarianceFitness(obs_index={self.obs_index})"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StabilityRatioFitness(FitnessFunction):
|
|
56
|
+
"""Fitness based on fraction of steps within a stability band.
|
|
57
|
+
|
|
58
|
+
Returns the fraction of observations where the tracked dimension stayed
|
|
59
|
+
within +/- threshold of zero. Higher = more stable.
|
|
60
|
+
|
|
61
|
+
This is the generalization of CartPole's `balance_time` to any env.
|
|
62
|
+
Maps 1.0 (always stable) → 0.0 (never stable).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
name = "stability_ratio"
|
|
66
|
+
|
|
67
|
+
def __init__(self, obs_index: int = 0, threshold: float = 0.05, **kwargs):
|
|
68
|
+
"""
|
|
69
|
+
Args:
|
|
70
|
+
obs_index: Which observation dimension to monitor
|
|
71
|
+
threshold: Acceptable range around zero (default: 0.05 rad)
|
|
72
|
+
"""
|
|
73
|
+
super().__init__(obs_index=obs_index, threshold=threshold, **kwargs)
|
|
74
|
+
self.obs_index = obs_index
|
|
75
|
+
self.threshold = threshold
|
|
76
|
+
|
|
77
|
+
def compute(
|
|
78
|
+
self,
|
|
79
|
+
observation_history: Optional[np.ndarray] = None,
|
|
80
|
+
action_history: Optional[np.ndarray] = None,
|
|
81
|
+
info_history: Optional[list] = None,
|
|
82
|
+
) -> float:
|
|
83
|
+
if observation_history is None or len(observation_history) == 0:
|
|
84
|
+
return 0.0
|
|
85
|
+
|
|
86
|
+
obs = np.asarray(observation_history, dtype=np.float32)
|
|
87
|
+
if obs.ndim != 2 or obs.shape[1] <= self.obs_index:
|
|
88
|
+
return 0.0
|
|
89
|
+
|
|
90
|
+
values = obs[:, self.obs_index]
|
|
91
|
+
stable_fraction = float(np.mean(np.abs(values) <= self.threshold))
|
|
92
|
+
return stable_fraction
|
|
93
|
+
|
|
94
|
+
def __repr__(self):
|
|
95
|
+
return f"StabilityRatioFitness(obs_index={self.obs_index}, threshold={self.threshold})"
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Registry mapping environment names to their available fitness functions.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
from dpct_env.fitness.registry import FITNESS_REGISTRY, get_fitness_functions
|
|
5
|
+
|
|
6
|
+
# Get all fitness functions for CartPole-v1
|
|
7
|
+
fns = get_fitness_functions("CartPole-v1")
|
|
8
|
+
# Returns: {"control_effort": ControlEffortFitness(), "stability_ratio": StabilityRatioFitness(obs_index=2, threshold=0.05), ...}
|
|
9
|
+
|
|
10
|
+
# Compute fitness
|
|
11
|
+
fitness = fns["stability_ratio"](observation_history=obs, action_history=acts)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from typing import Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
from .base import FitnessFunction
|
|
17
|
+
from .control_effort import ControlEffortFitness
|
|
18
|
+
from .observation_variance import ObservationVarianceFitness, StabilityRatioFitness
|
|
19
|
+
from .height_achieved import HeightAchievedFitness
|
|
20
|
+
|
|
21
|
+
# Type alias: env_name → {fitness_name → FitnessFunction instance}
|
|
22
|
+
FitnessRegistry = Dict[str, Dict[str, FitnessFunction]]
|
|
23
|
+
|
|
24
|
+
FITNESS_REGISTRY: FitnessRegistry = {
|
|
25
|
+
"CartPole-v1": {
|
|
26
|
+
"control_effort": ControlEffortFitness(mode="changes"),
|
|
27
|
+
"observation_variance": ObservationVarianceFitness(obs_index=2),
|
|
28
|
+
"stability_ratio": StabilityRatioFitness(obs_index=2, threshold=0.05),
|
|
29
|
+
},
|
|
30
|
+
"MountainCar-v0": {
|
|
31
|
+
"control_effort": ControlEffortFitness(mode="changes"),
|
|
32
|
+
"height_achieved": HeightAchievedFitness(mode="position_sin"),
|
|
33
|
+
},
|
|
34
|
+
"Acrobot-v1": {
|
|
35
|
+
"control_effort": ControlEffortFitness(mode="changes"),
|
|
36
|
+
"height_achieved": HeightAchievedFitness(mode="acrobot"),
|
|
37
|
+
},
|
|
38
|
+
"Pendulum-v1": {
|
|
39
|
+
"control_effort": ControlEffortFitness(mode="magnitude"),
|
|
40
|
+
"observation_variance": ObservationVarianceFitness(obs_index=0),
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_fitness_functions(env_name: str) -> Dict[str, FitnessFunction]:
|
|
46
|
+
"""Get all registered fitness functions for an environment.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
env_name: Gymnasium environment name (e.g., "CartPole-v1")
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
Dict mapping fitness function name to instance.
|
|
53
|
+
Returns empty dict if env_name is not registered.
|
|
54
|
+
"""
|
|
55
|
+
return FITNESS_REGISTRY.get(env_name, {})
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def register_fitness_function(
|
|
59
|
+
env_name: str,
|
|
60
|
+
name: str,
|
|
61
|
+
fitness_fn: FitnessFunction,
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Register a new fitness function for an environment.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
env_name: Gymnasium environment name
|
|
67
|
+
name: Short name for the fitness function
|
|
68
|
+
fitness_fn: FitnessFunction instance
|
|
69
|
+
"""
|
|
70
|
+
if env_name not in FITNESS_REGISTRY:
|
|
71
|
+
FITNESS_REGISTRY[env_name] = {}
|
|
72
|
+
FITNESS_REGISTRY[env_name][name] = fitness_fn
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def list_environments() -> List[str]:
|
|
76
|
+
"""List all environments with registered fitness functions."""
|
|
77
|
+
return list(FITNESS_REGISTRY.keys__)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"FITNESS_REGISTRY",
|
|
82
|
+
"get_fitness_functions",
|
|
83
|
+
"register_fitness_function",
|
|
84
|
+
"list_environments",
|
|
85
|
+
]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Environment-specific results processors for Comet ML logging."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from .base import EnvironmentResultsProcessor, DEFAULT_ENVIRONMENT_LOGGING_STEPS
|
|
6
|
+
from .cartpole import CartPoleResultsProcessor
|
|
7
|
+
from .wind_turbine import WindTurbineResultsProcessor
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _normalize_env_name(env_name: Optional[str]) -> str:
|
|
11
|
+
return (env_name or '').lower().strip().replace('-', '_')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def create_environment_results_processor(env_name: Optional[str]) -> EnvironmentResultsProcessor:
|
|
15
|
+
"""Factory returning an environment-specific results processor."""
|
|
16
|
+
normalized = _normalize_env_name(env_name)
|
|
17
|
+
if normalized == 'cartpole' or normalized.startswith('cartpole_'):
|
|
18
|
+
return CartPoleResultsProcessor()
|
|
19
|
+
if normalized == 'windturbine' or normalized.startswith('windturbine_'):
|
|
20
|
+
return WindTurbineResultsProcessor()
|
|
21
|
+
return EnvironmentResultsProcessor()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"EnvironmentResultsProcessor",
|
|
26
|
+
"DEFAULT_ENVIRONMENT_LOGGING_STEPS",
|
|
27
|
+
"CartPoleResultsProcessor",
|
|
28
|
+
"WindTurbineResultsProcessor",
|
|
29
|
+
"create_environment_results_processor",
|
|
30
|
+
]
|