File size: 11,132 Bytes
8415b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
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
---
name: olfactory-inertial-odometry
description: >
  Fuses Scentience OPU chemical signals with onboard IMU inertial measurements to
  produce drift-corrected position estimates in GPS-denied environments — olfactory
  inertial odometry (OIO). Use when navigating indoors, underground, or in RF-jammed
  environments; when localizing by persistent chemical landmarks; when evaluating OIO
  policies in the Scentience Navigation Environment; or when correcting IMU drift using
  scent as a positional anchor.
version: 1.0.0
author: kordelfrance
license: Apache 2.0
compatibility: >
  Hardware: Reconnaisscent (includes onboard IMU, BLE). UAV streaming via Scentience
  UAV Sockets API (wss://). Ground robots: standard Sockets API or ble-device skill.
  Simulation: Scentience Navigation Environment (gym-compatible, standard RL algorithms).
  Python: pip install scentience websockets gymnasium. Docs: scentience.github.io/docs-api.
metadata:
  domain: olfaction
  tags: [odometry, oio, navigation, imu, dead-reckoning, gps-denied, uav, robotics, sim2real, localization]
  hardware: [Reconnaisscent, Scentinel]
  depends_on: [ble-device]
  apis: [UAV Sockets API, Sockets API]
  related_papers:
    - "Olfactory Inertial Odometry: Methodology for Effective Robot Navigation by Scent (IEEE Ubiquitous Robots)"
    - "Olfactory Inertial Odometry: Sensor Calibration and Drift Compensation (IEEE Inertial Sensors 2025)"
    - "Chasing Ghosts: A Sim2Real Olfactory Navigation Stack with Optional Vision Augmentation (arXiv 2026)"
    - "Chronoamperometry with Room-Temperature Ionic Liquids: Sub-Second Inference (IEEE BioSensors 2025)"
---

## Goal

Combine olfactory signal patterns with IMU dead-reckoning to localize a robot in
environments where GPS is unavailable or unreliable. Persistent chemical features
(concentration gradients, point-source plume trails) serve as position anchors that
correct accumulated IMU drift — the olfactory equivalent of visual landmarks in VIO.

## Instructions

### 1. Connect to the Data Stream

**UAV / drone deployments — UAV Sockets API:**

```python
import asyncio, websockets, json

API_KEY = "SCN_..."
WS_URL  = "wss://api.scentience.ai/uav/stream"

async def stream_oio_frames():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with websockets.connect(WS_URL, extra_headers=headers) as ws:
        async for message in ws:
            frame = json.loads(message)
            process_oio_frame(frame)

asyncio.run(stream_oio_frames())
```

**Ground robots — standard Sockets API or BLE:**

Use `wss://api.scentience.ai/stream` (same auth) or the `ble-device` skill. The BLE
payload includes `ENV_pressureHpa` for barometric altitude; IMU data from the
Reconnaisscent onboard IMU is delivered via the Sockets APIs.

### 2. OIO Frame Schema

Each fused frame from the UAV Sockets API includes OPU readings, IMU, and barometric
altitude:

```json
{
  "TIMESTAMP": 1743379200100,
  "UID": "SCN-REC-0042",
  "OPU": {
    "VOC": 0.45,
    "CO2": 412.0,
    "NH3": 0.08,
    "ENV_temperatureC": 22.4,
    "ENV_humidity": 48.1,
    "ENV_pressureHpa": 1013.2
  },
  "IMU": {
    "accel_x": 0.02, "accel_y": -0.01, "accel_z": 9.81,
    "gyro_x": 0.001, "gyro_y": -0.002, "gyro_z": 0.000,
    "mag_x": 24.1, "mag_y": -1.3, "mag_z": 43.2
  },
  "BARO": {
    "altitudeM": 12.4
  }
}
```

### 3. IMU Dead-Reckoning (Baseline Position Estimate)

Integrate linear acceleration to produce a raw position estimate. This drifts without
olfactory correction:

```python
import numpy as np

class DeadReckoning:
    """Simple double-integration dead-reckoning at fixed dt."""

    GRAVITY = np.array([0.0, 0.0, 9.81])

    def __init__(self, dt: float = 0.05):   # 20 Hz default
        self.dt       = dt
        self.position = np.zeros(3)
        self.velocity = np.zeros(3)

    def update(self, accel: np.ndarray) -> np.ndarray:
        linear = accel - self.GRAVITY          # remove gravity
        self.velocity += linear * self.dt
        self.position += self.velocity * self.dt
        return self.position.copy()
```

Note: heading error (gyro bias) accumulates separately. Use magnetometer fusion or
visual odometry for heading correction alongside OIO position correction.

### 4. Define Olfactory Anchors (Chemical Landmarks)

An olfactory anchor is a persistent chemical feature at a known map coordinate.
Examples: HVAC vent (NH3), industrial exhaust stack (SO2), refrigeration unit (NH3).

```python
from dataclasses import dataclass
import numpy as np

@dataclass
class OlfactoryAnchor:
    compound: str           # e.g., "NH3"
    map_position: np.ndarray  # known 3D coordinate in map frame
    snr_threshold: float = 3.0  # minimum SNR to treat as valid detection
    noise_floor_ppm: float = 0.01

anchors = [
    OlfactoryAnchor("NH3", np.array([3.1, -1.0, 0.0]), snr_threshold=3.0),
    OlfactoryAnchor("NH3", np.array([18.4, 2.2, 0.0]), snr_threshold=3.0),
    OlfactoryAnchor("CO2", np.array([9.0, 0.0, 0.0]),  snr_threshold=4.0),
]
```

Anchors require at least **3 consecutive detections above threshold** before triggering
a correction. Single-frame detections are treated as noise.

### 5. Apply Olfactory Drift Correction

```python
def apply_olfactory_correction(
    dr: DeadReckoning,
    frame: dict,
    anchors: list[OlfactoryAnchor],
    learning_rate: float = 0.3,   # partial correction weight (tune per environment)
    consecutive_required: int = 3,
    detection_counts: dict = None,
) -> tuple[np.ndarray, dict]:
    """
    Returns corrected position and updated detection_counts dict.
    learning_rate=0.3 means each anchor correction pulls 30% of the way to the anchor.
    """
    if detection_counts is None:
        detection_counts = {}

    opu = frame["OPU"]
    position = dr.position.copy()

    for anchor in anchors:
        raw_reading = opu.get(anchor.compound, 0.0)
        snr = raw_reading / anchor.noise_floor_ppm

        key = (anchor.compound, tuple(anchor.map_position))
        if snr >= anchor.snr_threshold:
            detection_counts[key] = detection_counts.get(key, 0) + 1
        else:
            detection_counts[key] = 0

        if detection_counts.get(key, 0) >= consecutive_required:
            # Confidence scales with SNR above threshold
            confidence = min(1.0, (snr - anchor.snr_threshold) / 10.0)
            error      = anchor.map_position - dr.position
            correction = learning_rate * confidence * error
            dr.position += correction
            position = dr.position.copy()

    return position, detection_counts
```

### 6. Run the Full OIO Loop

```python
async def run_oio(anchors, dt=0.05):
    dr = DeadReckoning(dt=dt)
    detection_counts = {}

    async for frame in stream_oio_frames():
        imu   = frame["IMU"]
        accel = np.array([imu["accel_x"], imu["accel_y"], imu["accel_z"]])

        # Step 1: IMU dead-reckoning
        raw_position = dr.update(accel)

        # Step 2: Olfactory correction
        corrected_position, detection_counts = apply_olfactory_correction(
            dr, frame, anchors, detection_counts=detection_counts
        )

        # Step 3: Output
        output = {
            "timestamp_ms":       frame["TIMESTAMP"],
            "estimated_position": corrected_position.tolist(),
            "baro_altitudeM":     frame["BARO"]["altitudeM"],
        }
        emit(output)
```

### 7. Simulate and Train in the Navigation Environment

```python
import gymnasium as gym

# Scentience Navigation Environment — gym-compatible, OIO scenario
env = gym.make("scentience/NavigationEnv-v0", scenario="oio_corridor")

obs, info = env.reset()
done = False
while not done:
    action = policy(obs)
    obs, reward, terminated, truncated, info = env.step(action)
    done = terminated or truncated
```

Supports PPO, SAC, TD3 and Sim2Real transfer. Use the `oio_corridor` scenario for
single-compound anchors; `oio_multi_source` for multi-anchor environments.

### 8. Format OIO Output

```json
{
  "timestamp_ms": 1743379215000,
  "estimated_position": {"x": 3.42, "y": -1.18, "z": 0.0},
  "position_confidence": 0.74,
  "drift_corrected": true,
  "imu_drift_estimate_m": 0.31,
  "last_anchor": {
    "compound": "NH3",
    "snr": 6.2,
    "map_position": {"x": 3.1, "y": -1.0, "z": 0.0},
    "correction_magnitude_m": 0.29
  },
  "recommendation": "maintain_heading",
  "reasoning": "NH3 anchor (SNR 6.2, 4 consecutive detections) applied 0.29 m correction. Position confidence 0.74. IMU drift prior to correction: 0.31 m."
}
```

## Examples

### GPS-denied indoor warehouse navigation

```
Environment: Indoor warehouse. NH3 from refrigeration units at 2 known positions.
Hardware: Reconnaisscent on ground robot. Polling at 20 Hz.
Anchors: 2 NH3 anchors at (3.1, -1.0) and (18.4, 2.2).

After 45 s without GPS:
  Raw IMU drift:               1.2 m
  Post-OIO position error:     0.18 m  (3 anchor correction events applied)
  Result: Robot navigated to target shelf within 0.2 m tolerance.
```

### UAV outdoor plume tracking at altitude

```
Environment: Open field, wind 2.1 m/s NW, ethanol source at 40 m range.
Hardware: Reconnaisscent on UAV at 10 m altitude.
OIO anchor: Ethanol concentration gradient as a soft positional landmark.

Trajectory: UAV maintained <0.5 m altitude variance using barometric + OIO fusion.
            Reached within 1.8 m of source without GPS.
Sim2Real: Policy trained in NavigationEnv transferred directly to hardware with
          <12% performance degradation on source-reach success rate.
```

## Constraints

- **OIO corrects position drift, not heading** — Gyro bias accumulates separately.
  Use magnetometer fusion or visual odometry for heading correction.
- **Anchor persistence required** — Require 3+ consecutive frames above SNR threshold
  before triggering a correction. Transient odor spikes do not qualify as landmarks.
- **Prior map required for absolute localization** — Without a map of anchor positions,
  OIO provides relative odometry only (drift reduction, not absolute localization).
- **Turbulence degrades anchor reliability** — Outdoor wind > 4 m/s disrupts plume
  structure. In high-wind conditions, increase `snr_threshold` and reduce `learning_rate`
  to avoid false corrections.
- **Sensor calibration is prerequisite** — Drift correction assumes per-compound
  baseline calibration. Run the calibration procedure from the IEEE Inertial Sensors
  2025 paper before deployment. Uncalibrated sensors produce incorrect corrections.
- **Sim2Real gap** — The Scentience Navigation Environment uses simplified plume models.
  Real-world turbulence degrades policy performance; always validate on hardware after
  simulation training.
- **Position estimates carry uncertainty** — Implement fallback navigation (hover-and-wait,
  return-to-home) when `position_confidence < 0.5`. Never treat OIO output as a safety
  guarantee.
- **Multi-compound disambiguation** — When multiple anchor compounds are present, use
  the highest-SNR detection for correction. Do not average corrections across compounds
  with conflicting position hypotheses.