-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbase_generator.py
212 lines (172 loc) · 7.65 KB
/
base_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
from abc import ABC, abstractmethod
from typing import Any, ClassVar, Dict, List, Optional, Type, TypeVar, Generic
import rospy
from rosnav_rl.states import SimulationStateContainer
from ..collectors import BaseUnit
GeneratedDataType = TypeVar("D")
class GenerationError(Exception):
"""Exception raised when there's an error generating an observation."""
def __init__(self, generator_name: str, message: str, original_exception: Optional[Exception] = None) -> None:
self.generator_name = generator_name
self.original_exception = original_exception
super().__init__(f"Error in generator '{generator_name}': {message}")
class ObservationGeneratorUnit(BaseUnit, Generic[GeneratedDataType], ABC):
"""
Base class for observation generator units.
This class serves as a foundation for units that generate processed observations
from other observation data. Generators can have dependencies on other observation
units, which are verified before attempting to generate data.
Class Attributes:
name (ClassVar[str]): The name identifier for this generator.
requires (ClassVar[List[BaseUnit]]): A list of required base units.
data_class (Type[GeneratedDataType]): The type of data generated by this unit.
fallback_value (ClassVar[Optional[Any]]): Fallback value to use when generation fails.
max_consecutive_errors (ClassVar[int]): Maximum allowed consecutive errors before failing.
Instance Attributes:
_error_count (int): Count of total errors encountered.
_consecutive_errors (int): Count of consecutive errors without successful generation.
Args:
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
"""
name: ClassVar[str]
requires: ClassVar[List[BaseUnit]]
data_class: Type[GeneratedDataType]
fallback_value: ClassVar[Optional[Any]] = None
max_consecutive_errors: ClassVar[int] = 3
def __init__(self, *args, **kwargs) -> None:
"""Initialize the observation generator unit."""
super().__init__(*args, **kwargs)
self._error_count = 0
self._consecutive_errors = 0
def validate_requirements(self, obs_dict: Dict[str, Any]) -> List[str]:
"""
Check if all required observations are present in the observation dictionary.
Args:
obs_dict (Dict[str, Any]): Dictionary containing observations
Returns:
List[str]: List of missing requirements (empty if all are present)
"""
return [
req.name for req in self.requires
if req.name not in obs_dict or obs_dict[req.name] is None
]
def validate_input(self, obs_dict: Dict[str, Any]) -> bool:
"""
Validate input observations beyond checking for presence.
This can be overridden by subclasses to perform additional validation
of input observations.
Args:
obs_dict (Dict[str, Any]): Dictionary containing observations
Returns:
bool: True if inputs are valid, False otherwise
"""
return True
def safe_generate(
self,
obs_dict: Dict[str, Any],
simulation_state_container: SimulationStateContainer,
*args,
**kwargs,
) -> GeneratedDataType:
"""
Safely generate observation data with error handling.
This method wraps the generate method with proper error handling,
dependency checking, and fallback mechanisms.
Args:
obs_dict (Dict[str, Any]): Dictionary containing observations
simulation_state_container (SimulationStateContainer): Container for simulation state
*args: Additional positional arguments
**kwargs: Additional keyword arguments
Returns:
GeneratedDataType: The generated observation data
Raises:
GenerationError: If generation fails and error tolerance is exceeded
"""
# Check requirements
missing_requirements = self.validate_requirements(obs_dict)
if missing_requirements:
error_msg = f"Missing required observations: {', '.join(missing_requirements)}"
rospy.logwarn_once(f"[{self.name}] {error_msg}")
self._error_count += 1
self._consecutive_errors += 1
if self._consecutive_errors > self.max_consecutive_errors:
raise GenerationError(
generator_name=self.name,
message=error_msg
)
if self.fallback_value is not None:
return self.fallback_value
raise GenerationError(
generator_name=self.name,
message=error_msg
)
# Validate inputs
if not self.validate_input(obs_dict):
error_msg = "Input validation failed"
rospy.logwarn_once(f"[{self.name}] {error_msg}")
self._error_count += 1
self._consecutive_errors += 1
if self._consecutive_errors > self.max_consecutive_errors:
raise GenerationError(
generator_name=self.name,
message=error_msg
)
if self.fallback_value is not None:
return self.fallback_value
raise GenerationError(
generator_name=self.name,
message=error_msg
)
# Generate observation
try:
result = self.generate(
obs_dict=obs_dict,
simulation_state_container=simulation_state_container,
*args,
**kwargs
)
# Reset consecutive errors on success
self._consecutive_errors = 0
return result
except Exception as e:
error_msg = f"Generation failed: {str(e)}"
rospy.logwarn_throttle(5.0, f"[{self.name}] {error_msg}")
self._error_count += 1
self._consecutive_errors += 1
if self._consecutive_errors > self.max_consecutive_errors:
raise GenerationError(
generator_name=self.name,
message=error_msg,
original_exception=e
)
if self.fallback_value is not None:
return self.fallback_value
raise GenerationError(
generator_name=self.name,
message=error_msg,
original_exception=e
)
@abstractmethod
def generate(
self,
obs_dict: Dict[str, Any],
simulation_state_container: SimulationStateContainer,
*args,
**kwargs,
) -> GeneratedDataType:
"""
Generates the observation data based on the given observation dictionary.
Implementations should focus on the core generation logic without worrying
about error handling or dependency checking, which is handled by safe_generate.
Args:
obs_dict (Dict[str, Any]): The observation dictionary.
simulation_state_container (SimulationStateContainer): The simulation state container.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
GeneratedDataType: The generated observation data.
Raises:
NotImplementedError: If the method is not implemented by a subclass.
"""
raise NotImplementedError