mattbitzesty commited on
Commit
680d9cb
·
unverified ·
1 Parent(s): e5ed910

feat(semantics): compute OAV-weighted descriptor targets from Pyrfume data

Browse files

Replace deterministic genre curves with log10(OAV+1)-weighted mixture
descriptor vectors backed by pyrfume_descriptors_by_cas.json and
pyrfume_odt_by_cas.json. Keep fallback profile for tests.

Files changed (1) hide show
  1. src/pino/semantics.py +179 -65
src/pino/semantics.py CHANGED
@@ -1,75 +1,198 @@
1
  from __future__ import annotations
2
 
 
 
 
 
 
3
  import numpy as np
4
 
 
5
 
6
- def _one_hot(indices: list[int], dim: int = 138) -> np.ndarray:
7
- arr = np.zeros(dim, dtype=np.float32)
8
- for idx in indices:
9
- arr[idx] = 1.0
10
- return arr
11
 
 
 
 
12
 
13
- GENRE_OBJECTIVE_PROFILES: dict[str, np.ndarray] = {
14
- "citrus_cologne": _one_hot([0, 2, 3], 138),
15
- "fougere": _one_hot([1, 2, 3], 138),
16
- "floral_woody": _one_hot([1, 2], 138),
17
- "amber_oriental": _one_hot([2, 3], 138),
18
- "wildcard": _one_hot([0, 1, 2, 3], 138),
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
- def get_objective_targets(generation_strategy: str, timesteps: int, seed: int = 2026) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
- Return a (timesteps, 138) objective odor-descriptor target matrix.
25
 
26
- In the placeholder phase, indices 0-3 encode core genre notes:
27
- 0 = Citrus (Top), 1 = Lavender (Heart), 2 = Wood (Base), 3 = Musk (Base)
 
 
28
 
29
- Each class follows a distinct volatility curve across normalized time tau:
30
- Citrus (top): exp(-6 * tau) sharp decay
31
- Lavender (heart): 4 * tau * exp(-4 * tau) surge, peak ~tau=0.25
32
- Wood / Musk (base): 0.1 + 0.9 * (1 - exp(-3 * tau)) asymptotic rise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- Remaining indices are filled with a tiny random noise floor to keep tensors
35
- dense and stable during training.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  """
37
- rng = np.random.default_rng(seed)
38
- tau = np.linspace(0.0, 1.0, timesteps, dtype=np.float32)
39
 
40
- # Volatility curves.
41
- citrus_curve = np.exp(-6.0 * tau)
42
- lavender_curve = 4.0 * tau * np.exp(-4.0 * tau)
43
- base_curve = 0.1 + 0.9 * (1.0 - np.exp(-3.0 * tau))
44
-
45
- # Per-genre activation coefficients for the 4 notes.
46
- coeffs = {
47
- "citrus_cologne": [1.0, 0.1, 0.1, 0.0],
48
- "fougere": [0.1, 0.8, 0.4, 0.1],
49
- "floral_woody": [0.1, 0.7, 0.6, 0.1],
50
- "amber_oriental": [0.0, 0.1, 0.9, 1.0],
51
- "wildcard": [0.7, 0.6, 0.5, 0.4],
52
- }.get(generation_strategy, [0.7, 0.6, 0.7, 0.6])
53
- coeffs = np.array(coeffs, dtype=np.float32)
54
-
55
- targets = np.zeros((timesteps, 138), dtype=np.float32)
56
- targets[:, 0] = coeffs[0] * citrus_curve
57
- targets[:, 1] = coeffs[1] * lavender_curve
58
- targets[:, 2] = coeffs[2] * base_curve
59
- targets[:, 3] = coeffs[3] * base_curve
60
-
61
- # Fill remaining indices with a trace noise floor < 1e-4.
62
- noise_floor = rng.uniform(0.0, 1e-4, size=(timesteps, 134)).astype(np.float32)
63
- targets[:, 4:] = noise_floor
64
 
 
 
 
 
 
 
 
 
 
 
65
  return np.clip(targets, 0.0, 1.0).astype(np.float32)
66
 
67
 
68
- # Weak-label semantic targets derived from the generation_strategy tag.
69
- # Each entry maps to a dict with:
70
- # seasonality: 4-class softmax target [Spring, Summer, Autumn, Winter]
71
- # gender_profile: scalar in [-1, 1] where -1 = masculine, +1 = feminine
72
- # wearability: 4-label vector [Office-Safe, Date-Night, Casual, Formal]
73
 
74
  GENRE_SEMANTICS: dict[str, dict[str, np.ndarray]] = {
75
  "citrus_cologne": {
@@ -106,20 +229,14 @@ def get_semantic_targets(generation_strategy: str) -> dict[str, np.ndarray]:
106
 
107
 
108
  def get_psychometric_targets(generation_strategy: str) -> np.ndarray:
109
- """
110
- Return a 7-dimensional psychometric target vector that concatenates:
111
- - seasonality (4)
112
- - gender_profile (1)
113
- - wearability (2, averaged from 4 categories)
114
- """
115
  base = get_semantic_targets(generation_strategy)
116
  season = base["seasonality"]
117
  gender = base["gender_profile"].reshape(-1)
118
  wear = base["wearability"]
119
- # Compress 4 wearability categories into 2: formal/casual vs office/date
120
  wear_compressed = np.array([
121
- (wear[0] + wear[2]) / 2.0, # daytime/social
122
- (wear[1] + wear[3]) / 2.0, # evening/formal
123
  ], dtype=np.float32)
124
  return np.concatenate([season, gender, wear_compressed]).astype(np.float32)
125
 
@@ -136,14 +253,11 @@ def sample_noisy_psychometric_targets(
136
  rng = rng or np.random.default_rng()
137
  base = get_psychometric_targets(generation_strategy)
138
  noisy = base.copy()
139
- # Seasonality (first 4) + noise, then re-normalize
140
  noisy[:4] += rng.normal(0, seasonality_noise, size=4).astype(np.float32)
141
  noisy[:4] = np.clip(noisy[:4], 0.0, 1.0)
142
  noisy[:4] = noisy[:4] / noisy[:4].sum() if noisy[:4].sum() > 0 else noisy[:4]
143
- # Gender (index 4)
144
  noisy[4] += rng.normal(0, gender_noise, size=1).astype(np.float32)[0]
145
  noisy[4] = np.clip(noisy[4], -1.0, 1.0)
146
- # Wearability (last 2)
147
  noisy[5:] += rng.normal(0, wearability_noise, size=2).astype(np.float32)
148
  noisy[5:] = np.clip(noisy[5:], 0.0, 1.0)
149
  return noisy
 
1
  from __future__ import annotations
2
 
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
  import numpy as np
9
 
10
+ logger = logging.getLogger("pino.semantics")
11
 
12
+ DESCRIPTOR_DIM = 138
 
 
 
 
13
 
14
+ # ---------------------------------------------------------------------------
15
+ # Vocabulary / annotation loading
16
+ # ---------------------------------------------------------------------------
17
 
18
+
19
+ def _project_data_dir() -> Path:
20
+ """Return the project-level data/ directory."""
21
+ # src/pino/semantics.py -> src/pino/ -> src/ -> project root
22
+ return Path(__file__).resolve().parents[2] / "data"
23
+
24
+
25
+ def load_vocabulary(path: str | Path | None = None) -> list[str]:
26
+ """Load the 138-D pyrfume descriptor vocabulary from disk."""
27
+ path = Path(path) if path else _project_data_dir() / "pyrfume_vocabulary.json"
28
+ if not path.exists():
29
+ raise FileNotFoundError(f"Vocabulary file not found: {path}")
30
+ data = json.loads(path.read_text(encoding="utf-8"))
31
+ return data["vocabulary"]
32
+
33
+
34
+ def load_descriptor_annotations(path: str | Path | None = None) -> dict[str, list[float]]:
35
+ """Load the CAS/SMILES -> 138-D binary descriptor vector mapping."""
36
+ path = Path(path) if path else _project_data_dir() / "pyrfume_descriptors_by_cas.json"
37
+ if not path.exists():
38
+ raise FileNotFoundError(f"Descriptor annotations not found: {path}")
39
+ return json.loads(path.read_text(encoding="utf-8"))
40
+
41
+
42
+ def load_odt_annotations(path: str | Path | None = None) -> dict[str, float]:
43
+ """Load the CAS/SMILES -> ODT (mg/m³) mapping."""
44
+ path = Path(path) if path else _project_data_dir() / "pyrfume_odt_by_cas.json"
45
+ if not path.exists():
46
+ raise FileNotFoundError(f"ODT annotations not found: {path}")
47
+ return {k: float(v) for k, v in json.loads(path.read_text(encoding="utf-8")).items()}
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Per-compound lookup helpers
52
+ # ---------------------------------------------------------------------------
53
 
54
 
55
+ def _registry_key(cas: str | None, smiles: str | None) -> str | None:
56
+ if cas and not cas.startswith("SMILES:"):
57
+ return cas
58
+ return smiles
59
+
60
+
61
+ def get_compound_descriptor_vector(
62
+ cas: str | None,
63
+ smiles: str | None,
64
+ descriptor_map: dict[str, list[float]] | None = None,
65
+ ) -> np.ndarray | None:
66
+ """Return the 138-D binary descriptor vector for a compound, if known."""
67
+ if descriptor_map is None:
68
+ descriptor_map = load_descriptor_annotations()
69
+ key = _registry_key(cas, smiles)
70
+ if key is None:
71
+ return None
72
+ vec = descriptor_map.get(key)
73
+ if vec is None:
74
+ return None
75
+ return np.array(vec, dtype=np.float32)
76
+
77
+
78
+ def get_compound_odt(
79
+ cas: str | None,
80
+ smiles: str | None,
81
+ odt_map: dict[str, float] | None = None,
82
+ ) -> float | None:
83
+ """Return the ODT (mg/m³) for a compound, if known."""
84
+ if odt_map is None:
85
+ odt_map = load_odt_annotations()
86
+ key = _registry_key(cas, smiles)
87
+ if key is None:
88
+ return None
89
+ return odt_map.get(key)
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # OAV-weighted mixture descriptor targets
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ def compute_oav_targets(
98
+ composition: list[dict[str, Any]],
99
+ concentrations: np.ndarray,
100
+ *,
101
+ descriptor_map: dict[str, list[float]] | None = None,
102
+ odt_map: dict[str, float] | None = None,
103
+ eps: float = 1e-12,
104
+ ) -> np.ndarray:
105
  """
106
+ Compute time-resolved OAV-weighted mixture descriptor vectors.
107
 
108
+ Args:
109
+ composition: list of compound dicts, each with at least 'cas' and/or 'smiles'.
110
+ concentrations: (timesteps, n_compounds) array of instantaneous concentrations
111
+ in mg/m³.
112
 
113
+ Returns:
114
+ targets: (timesteps, 138) array of mixture descriptor vectors.
115
+ """
116
+ timesteps, n_compounds = concentrations.shape
117
+ if descriptor_map is None:
118
+ descriptor_map = load_descriptor_annotations()
119
+ if odt_map is None:
120
+ odt_map = load_odt_annotations()
121
+
122
+ # Build per-compound descriptor vectors and ODTs.
123
+ descriptors: list[np.ndarray] = []
124
+ odt_values: list[float] = []
125
+ for comp in composition:
126
+ cas = comp.get("cas")
127
+ smiles = comp.get("smiles")
128
+ vec = get_compound_descriptor_vector(cas, smiles, descriptor_map=descriptor_map)
129
+ odt = get_compound_odt(cas, smiles, odt_map=odt_map)
130
+ if vec is None or odt is None:
131
+ # Compound lacks annotation; leave it out of the target.
132
+ descriptors.append(np.zeros(DESCRIPTOR_DIM, dtype=np.float32))
133
+ odt_values.append(1.0) # dummy, will multiply by zero vector
134
+ continue
135
+ descriptors.append(vec)
136
+ odt_values.append(odt)
137
+
138
+ descriptors = np.vstack(descriptors) # (n_compounds, 138)
139
+ odt_values = np.array(odt_values, dtype=np.float32) # (n_compounds,)
140
+
141
+ # log10(OAV + 1) is used as a positive monotonic weight that equals log-OAV
142
+ # for strongly supra-threshold compounds (OAV >> 1) while keeping sub-threshold
143
+ # ingredients from collapsing the target to a zero vector.
144
+ oav = concentrations / (odt_values[None, :] + eps) # (timesteps, n_compounds)
145
+ weights = np.log10(oav + 1.0) # (timesteps, n_compounds)
146
+
147
+ weighted = weights[:, :, None] * descriptors[None, :, :] # (T, C, 138)
148
+ targets = weighted.sum(axis=1) # (T, 138)
149
+
150
+ # Normalise each timestep vector to unit length (cosine-style target).
151
+ norms = np.linalg.norm(targets, axis=1, keepdims=True)
152
+ targets = np.divide(targets, norms, out=np.zeros_like(targets), where=norms > eps)
153
 
154
+ return targets.astype(np.float32)
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Legacy / compatibility API
159
+ # ---------------------------------------------------------------------------
160
+
161
+
162
+ def get_objective_targets(
163
+ generation_strategy: str,
164
+ timesteps: int,
165
+ *,
166
+ composition: list[dict[str, Any]] | None = None,
167
+ concentrations: np.ndarray | None = None,
168
+ seed: int = 2026,
169
+ ) -> np.ndarray:
170
  """
171
+ Return a (timesteps, 138) objective odor-descriptor target matrix.
 
172
 
173
+ If composition and concentrations are provided, the target is a real
174
+ OAV-weighted mixture descriptor vector. Otherwise, a deterministic
175
+ fallback profile is returned for compatibility.
176
+ """
177
+ if composition is not None and concentrations is not None:
178
+ return compute_oav_targets(composition, concentrations)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
+ # Fallback: simple genre-agnostic descriptor profile for tests/back-compat.
181
+ rng = np.random.default_rng(seed)
182
+ tau = np.linspace(0.0, 1.0, timesteps, dtype=np.float32)
183
+ targets = np.zeros((timesteps, DESCRIPTOR_DIM), dtype=np.float32)
184
+ # Use a few broad descriptors to keep the tensor non-degenerate.
185
+ targets[:, 0] = np.exp(-6.0 * tau) # citrus / top decay
186
+ targets[:, 1] = 4.0 * tau * np.exp(-4.0 * tau) # floral / heart surge
187
+ targets[:, 2] = 0.1 + 0.9 * (1.0 - np.exp(-3.0 * tau)) # woody / base rise
188
+ targets[:, 3] = 0.1 + 0.9 * (1.0 - np.exp(-3.0 * tau)) # musk / base rise
189
+ targets[:, 4:] = rng.uniform(0.0, 1e-4, size=(timesteps, DESCRIPTOR_DIM - 4)).astype(np.float32)
190
  return np.clip(targets, 0.0, 1.0).astype(np.float32)
191
 
192
 
193
+ # ---------------------------------------------------------------------------
194
+ # Weak-label semantic targets (kept for compatibility; derived from strategy)
195
+ # ---------------------------------------------------------------------------
 
 
196
 
197
  GENRE_SEMANTICS: dict[str, dict[str, np.ndarray]] = {
198
  "citrus_cologne": {
 
229
 
230
 
231
  def get_psychometric_targets(generation_strategy: str) -> np.ndarray:
232
+ """Return a 7-D psychometric target vector."""
 
 
 
 
 
233
  base = get_semantic_targets(generation_strategy)
234
  season = base["seasonality"]
235
  gender = base["gender_profile"].reshape(-1)
236
  wear = base["wearability"]
 
237
  wear_compressed = np.array([
238
+ (wear[0] + wear[2]) / 2.0,
239
+ (wear[1] + wear[3]) / 2.0,
240
  ], dtype=np.float32)
241
  return np.concatenate([season, gender, wear_compressed]).astype(np.float32)
242
 
 
253
  rng = rng or np.random.default_rng()
254
  base = get_psychometric_targets(generation_strategy)
255
  noisy = base.copy()
 
256
  noisy[:4] += rng.normal(0, seasonality_noise, size=4).astype(np.float32)
257
  noisy[:4] = np.clip(noisy[:4], 0.0, 1.0)
258
  noisy[:4] = noisy[:4] / noisy[:4].sum() if noisy[:4].sum() > 0 else noisy[:4]
 
259
  noisy[4] += rng.normal(0, gender_noise, size=1).astype(np.float32)[0]
260
  noisy[4] = np.clip(noisy[4], -1.0, 1.0)
 
261
  noisy[5:] += rng.normal(0, wearability_noise, size=2).astype(np.float32)
262
  noisy[5:] = np.clip(noisy[5:], 0.0, 1.0)
263
  return noisy