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, for reinforcement learning (RL) models of spatial navigation. A reward field can serve as the potential of potential-based reward shaping (Ng et al., 1999).
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, max_distance: 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
|
Environment
|
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, in the environment's distance units.
Required for, and only accepted with, |
None
|
max_distance
|
float
|
Geodesic distance from the region, in the environment's distance
units, at which the linear reward reaches 0. Only accepted with
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
reward |
(NDArray[float64], shape(n_bins))
|
Reward field with specified decay profile. |
Raises:
| Type | Description |
|---|---|
RegionNotFoundError
|
If region_name is not found in env.regions (a |
ValueError
|
If |
Notes
Decay Types:
-
Constant: Binary reward useful for sparse reward RL tasks. Creates clear goal regions with no reward shaping.
-
Linear:
reward_value * max(0, 1 - d / max_distance), wheredis the geodesic distance from the bin centre to the nearest region bin centre: the length of the shortest path between two positions that stays inside the environment (it goes around walls and never leaves the environment, and on a track it runs along the track's centerline). Bins that cannot reach the region (another connected component) get 0. -
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: A reward field can serve as the potential
Phi(s) of potential-based reward shaping [1]_, which adds
gamma * Phi(s') - Phi(s) to the task reward and leaves the optimal
policy unchanged. Adding the field itself to the task reward is not
potential-based and can change the optimal policy. Gaussian decay
provides the smoothest gradients; validate any shaped agent against a
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.default_rng(0).normal(0, 50, (1000, 2))
>>> env = Environment.from_samples(positions, bin_size=5.0)
>>> # Add goal region (use polygon, not point)
>>> goal_polygon = Point([0.0, 0.0]).buffer(10.0)
>>> from neurospatial.regions import Regions
>>> regions = Regions(env.regions.values())
>>> _ = regions.add("goal", polygon=goal_polygon)
>>> env = env.with_regions(regions)
>>> # Binary reward (sparse RL)
>>> reward_binary = region_reward_field(env, region_name="goal", decay="constant")
>>> # Smooth Gaussian reward shaping
>>> reward_smooth = region_reward_field(
... env, region_name="goal", decay="gaussian", bandwidth=10.0
... )
>>> # Linear decay that reaches 0 at 30 units from the region
>>> reward_linear = region_reward_field(
... env, region_name="goal", decay="linear", max_distance=30.0
... )
>>> float(reward_linear.max()), float(reward_linear.min())
(1.0, 0.0)
See Also
goal_reward_field : Distance-based rewards from goal bins neurospatial.ops.distance_field : Bin-graph distance maps neurospatial.ops.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
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 217 218 219 220 221 222 223 224 225 226 | |
goal_reward_field
¶
goal_reward_field(env: Environment[CartesianSystem], 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
|
Environment
|
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 of the geodesic distance
|
'linear'
|
scale
|
float
|
Reward at the goal for every decay. For 'exponential' it is also the
decay length, in distance units (not a rate): the reward falls to
|
1.0
|
max_distance
|
float
|
Distance, in the environment's distance units, at which the linear
reward reaches 0. Required for, and only accepted with,
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
reward |
(NDArray[float64], shape(n_bins))
|
Distance-based reward field. Bins that cannot reach any goal (another connected component) get 0 for every decay. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Decay Functions:
-
Exponential: Most common in RL literature. Provides smooth gradients that decay exponentially with distance.
scalesets both the peak reward and the decay length, so they cannot be chosen separately; for a unit peak with decay lengthL, divide the field fromscale=LbyL. -
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. The
1in1 + dis one distance unit, so the shape depends on the units of the environment: the reward halves 1 cm from the goal in a centimetre environment but 1 m from it in a metre environment.
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.ops.distance_field : Bin-graph distance maps
Source code in src/neurospatial/behavior/reward.py
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |