neurospatial.behavior.reward¶
reward
¶
Reward field generation for reinforcement learning applications.
This module provides functions for creating reward fields from spatial regions and goal locations. These are essential primitives for reinforcement learning (RL) and reward shaping in spatial navigation tasks.
Imports
from neurospatial.behavior.reward import goal_reward_field, region_reward_field
Or via behavior package:
from neurospatial.behavior import goal_reward_field, region_reward_field
Classes¶
Functions¶
region_reward_field
¶
region_reward_field(env: Environment, region_name: str, *, reward_value: float = 1.0, decay: Literal['constant', 'linear', 'gaussian'] = 'constant', bandwidth: float | None = None) -> NDArray[np.float64]
Generate reward field from a named region.
Creates a spatial reward field based on a region defined in the environment. Supports different decay profiles for reward shaping in reinforcement learning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
EnvironmentProtocol
|
Environment with regions defined. |
required |
region_name
|
str
|
Name of region in env.regions to use as reward source. |
required |
reward_value
|
float
|
Maximum reward value in the region. |
1.0
|
decay
|
('constant', 'linear', 'gaussian')
|
Reward decay profile: - 'constant': Binary reward (reward_value inside, 0 outside) - 'linear': Linear decay from region boundary - 'gaussian': Smooth Gaussian falloff from region |
'constant'
|
bandwidth
|
float
|
Gaussian smoothing bandwidth (required for decay='gaussian'). Should be in same units as environment coordinates. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
reward |
(NDArray[float64], shape(n_bins))
|
Reward field with specified decay profile. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If region_name is not found in env.regions. |
ValueError
|
If bandwidth is not provided for decay='gaussian'. |
Notes
Decay Types:
-
Constant: Binary reward useful for sparse reward RL tasks. Creates clear goal regions with no reward shaping.
-
Linear: Linear decay from region boundary. Provides gradient information while maintaining clear boundaries. Distance computed using graph connectivity (respects environment structure).
-
Gaussian: Smooth falloff using Gaussian kernel smoothing. After smoothing, rescales so maximum within the region equals reward_value. This preserves the intended reward magnitude while providing smooth gradients for policy learning.
Reward Shaping: These primitives implement potential-based reward shaping (Ng et al., 1999). Gaussian decay provides the smoothest gradients but may inadvertently guide agents away from optimal paths. Use with caution and validate against sparse reward baseline.
Examples:
>>> import numpy as np
>>> from neurospatial import Environment
>>> from neurospatial.behavior.reward import region_reward_field
>>> from shapely.geometry import Point
>>> # Create environment
>>> positions = np.random.randn(1000, 2) * 50
>>> env = Environment.from_samples(positions, bin_size=5.0)
>>> # Add goal region (use polygon, not point)
>>> goal_polygon = Point([0.0, 0.0]).buffer(5.0)
>>> _ = env.regions.add("goal", polygon=goal_polygon)
>>> # Binary reward (sparse RL)
>>> reward_binary = region_reward_field(env, "goal", decay="constant")
>>> # Smooth Gaussian reward shaping
>>> reward_smooth = region_reward_field(
... env, "goal", decay="gaussian", bandwidth=10.0
... )
See Also
goal_reward_field : Distance-based rewards from goal bins neurospatial.distance_field : Compute distance maps neurospatial.spatial.regions_to_mask : Convert regions to binary masks
References
.. [1] Ng, A. Y., Harada, D., & Russell, S. (1999). Policy invariance under reward transformations: Theory and application to reward shaping. ICML.
Source code in src/neurospatial/behavior/reward.py
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 213 214 215 216 | |
goal_reward_field
¶
goal_reward_field(env: Environment, goal_bins: int | list[int] | NDArray[int_], *, decay: Literal['linear', 'exponential', 'inverse'] = 'exponential', scale: float = 1.0, max_distance: float | None = None) -> NDArray[np.float64]
Generate distance-based reward field from goal bins.
Creates a reward field that decays with distance from goal locations. Common for goal-directed navigation tasks and reward shaping in RL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
EnvironmentProtocol
|
Spatial environment. |
required |
goal_bins
|
int or list[int] or NDArray[int_]
|
Goal bin index or indices. Can be scalar or array. |
required |
decay
|
('linear', 'exponential', 'inverse')
|
Distance-based decay function: - 'linear': reward = scale * max(0, 1 - d/max_distance) - 'exponential': reward = scale * exp(-d/scale) - 'inverse': reward = scale / (1 + d) |
'linear'
|
scale
|
float
|
Reward scale parameter. Interpretation depends on decay type: - 'linear': maximum reward at goal - 'exponential': reward at goal (also decay rate) - 'inverse': reward scale factor |
1.0
|
max_distance
|
float
|
Maximum distance for linear decay. Required for decay='linear'. Reward is zero beyond this distance. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
reward |
(NDArray[float64], shape(n_bins))
|
Distance-based reward field. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If scale <= 0 for decay='exponential'. If max_distance not provided for decay='linear'. If goal_bins contains invalid indices. |
Notes
Decay Functions:
-
Exponential: Most common in RL literature. Provides smooth gradients that decay exponentially with distance. Scale parameter controls both peak reward and decay rate. Larger scale = slower decay.
-
Linear: Reaches exactly zero at max_distance. Useful when reward should be strictly local. Provides constant gradient within range.
-
Inverse: Inverse distance function (1/(1+d)). Never reaches zero, providing global gradients. Can lead to suboptimal policies if not carefully tuned.
Multiple Goals: When goal_bins contains multiple indices, distance is computed to the nearest goal. This creates a Voronoi-like partition where each bin is influenced by its closest goal.
Examples:
>>> import numpy as np
>>> from neurospatial import Environment
>>> from neurospatial.behavior.reward import goal_reward_field
>>> # Create environment with fixed seed for reproducibility
>>> rng = np.random.default_rng(42)
>>> positions = rng.standard_normal((1000, 2)) * 50
>>> env = Environment.from_samples(positions, bin_size=5.0)
>>> # Select goal bin at center of environment
>>> goal_bin = len(env.bin_centers) // 2
>>> # Exponential decay (most common)
>>> reward = goal_reward_field(
... env, goal_bins=goal_bin, decay="exponential", scale=10.0
... )
>>> # Linear decay with cutoff
>>> reward_linear = goal_reward_field(
... env, goal_bins=goal_bin, decay="linear", scale=1.0, max_distance=50.0
... )
See Also
region_reward_field : Reward fields from spatial regions neurospatial.distance_field : Compute distance maps
Source code in src/neurospatial/behavior/reward.py
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |