File size: 10,729 Bytes
3279f65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
# user_cloud.py — Temporal Emotional Fingerprint
#
# Tracks user's emotional history with exponential decay.
# Recent emotions matter more (24h half-life).
#
# The "user cloud" is a 100D vector where each dimension
# represents cumulative exposure to that emotion anchor.
#
# Decay formula:
#   weight(t) = exp(-t / tau)
#   where tau = 24 hours, t = time since event

from __future__ import annotations
import asyncio
import numpy as np
import time
from pathlib import Path
from typing import List, Dict, Optional
from dataclasses import dataclass, field
import json


@dataclass
class EmotionEvent:
    """Single emotion event in user history."""
    timestamp: float  # Unix timestamp
    primary_idx: int  # Index of primary emotion (0-99)
    secondary_idx: int  # Index of secondary emotion (0-99)
    weight: float = 1.0  # Event weight (default 1.0)


@dataclass
class UserCloud:
    """
    Temporal emotional fingerprint with exponential decay.

    Maintains:
        - History of emotion events
        - Decayed fingerprint (100D vector)
        - Decay half-life (default 24 hours)

    The fingerprint is recomputed on-the-fly with decay applied.
    """

    events: List[EmotionEvent] = field(default_factory=list)
    half_life_hours: float = 24.0  # 24h half-life
    max_history: int = 1000  # Keep last N events

    @property
    def tau(self) -> float:
        """Decay constant (in seconds)."""
        return self.half_life_hours * 3600 / np.log(2)

    def add_event(
        self,
        primary_idx: int,
        secondary_idx: int,
        weight: float = 1.0,
        timestamp: Optional[float] = None,
    ) -> None:
        """
        Add an emotion event to history.

        Args:
            primary_idx: primary emotion index (0-99)
            secondary_idx: secondary emotion index (0-99)
            weight: event importance (default 1.0)
            timestamp: Unix timestamp (default: now)
        """
        if timestamp is None:
            timestamp = time.time()

        event = EmotionEvent(
            timestamp=timestamp,
            primary_idx=primary_idx,
            secondary_idx=secondary_idx,
            weight=weight,
        )

        self.events.append(event)

        # Prune old events if history too long
        if len(self.events) > self.max_history:
            self.events = self.events[-self.max_history:]

    def get_fingerprint(self, current_time: Optional[float] = None) -> np.ndarray:
        """
        Compute current emotional fingerprint with temporal decay.

        Returns:
            (100,) vector of decayed emotion exposures
        """
        if current_time is None:
            current_time = time.time()

        fingerprint = np.zeros(100, dtype=np.float32)

        for event in self.events:
            # Time since event (in seconds)
            dt = current_time - event.timestamp

            # Exponential decay: exp(-dt / tau)
            decay = np.exp(-dt / self.tau)

            # Add decayed weight to fingerprint
            fingerprint[event.primary_idx] += event.weight * decay * 0.7
            fingerprint[event.secondary_idx] += event.weight * decay * 0.3

        # Normalize to [0, 1] range
        if fingerprint.max() > 0:
            fingerprint = fingerprint / fingerprint.max()

        return fingerprint

    def get_recent_emotions(
        self,
        hours: float = 24.0,
        current_time: Optional[float] = None,
    ) -> List[EmotionEvent]:
        """Get events from last N hours."""
        if current_time is None:
            current_time = time.time()

        cutoff = current_time - (hours * 3600)
        return [e for e in self.events if e.timestamp >= cutoff]

    def get_dominant_emotions(
        self,
        top_k: int = 5,
        current_time: Optional[float] = None,
    ) -> List[tuple]:
        """
        Get top-k dominant emotions from fingerprint.

        Returns:
            List of (emotion_idx, strength) tuples
        """
        fingerprint = self.get_fingerprint(current_time)
        top_indices = np.argsort(fingerprint)[-top_k:][::-1]
        return [(int(idx), float(fingerprint[idx])) for idx in top_indices]

    def save(self, path: Path) -> None:
        """Save user cloud to JSON file."""
        data = {
            "events": [
                {
                    "timestamp": e.timestamp,
                    "primary_idx": e.primary_idx,
                    "secondary_idx": e.secondary_idx,
                    "weight": e.weight,
                }
                for e in self.events
            ],
            "half_life_hours": self.half_life_hours,
            "max_history": self.max_history,
        }

        with open(path, "w") as f:
            json.dump(data, f, indent=2)

        print(f"[user_cloud] saved {len(self.events)} events to {path}")

    @classmethod
    def load(cls, path: Path) -> "UserCloud":
        """Load user cloud from JSON file."""
        with open(path, "r") as f:
            data = json.load(f)

        events = [
            EmotionEvent(
                timestamp=e["timestamp"],
                primary_idx=e["primary_idx"],
                secondary_idx=e["secondary_idx"],
                weight=e.get("weight", 1.0),
            )
            for e in data["events"]
        ]

        cloud = cls(
            events=events,
            half_life_hours=data.get("half_life_hours", 24.0),
            max_history=data.get("max_history", 1000),
        )

        print(f"[user_cloud] loaded {len(events)} events from {path}")
        return cloud

    def stats(self) -> Dict:
        """Return statistics about user cloud."""
        current_time = time.time()
        fingerprint = self.get_fingerprint(current_time)

        recent_24h = len(self.get_recent_emotions(24.0, current_time))
        recent_7d = len(self.get_recent_emotions(24.0 * 7, current_time))

        return {
            "total_events": len(self.events),
            "events_24h": recent_24h,
            "events_7d": recent_7d,
            "fingerprint_max": float(fingerprint.max()),
            "fingerprint_mean": float(fingerprint.mean()),
            "fingerprint_nonzero": int((fingerprint > 0).sum()),
            "half_life_hours": self.half_life_hours,
        }


class AsyncUserCloud:
    """
    Async wrapper for UserCloud with field lock discipline.
    
    Based on HAZE's async pattern - achieves coherence through
    explicit operation ordering and atomicity.
    
    "The asyncio.Lock doesn't add information—it adds discipline."
    """
    
    def __init__(self, cloud: UserCloud):
        self._sync = cloud
        self._lock = asyncio.Lock()
    
    @classmethod
    def create(cls, half_life_hours: float = 24.0) -> "AsyncUserCloud":
        """Create new async user cloud."""
        cloud = UserCloud(half_life_hours=half_life_hours)
        return cls(cloud)
    
    @classmethod
    def load(cls, path: Path) -> "AsyncUserCloud":
        """Load from file."""
        cloud = UserCloud.load(path)
        return cls(cloud)
    
    async def add_event(
        self,
        primary_idx: int,
        secondary_idx: int,
        weight: float = 1.0,
        timestamp: Optional[float] = None,
    ) -> None:
        """Add event with lock protection."""
        async with self._lock:
            self._sync.add_event(primary_idx, secondary_idx, weight, timestamp)
    
    async def get_fingerprint(self, current_time: Optional[float] = None) -> np.ndarray:
        """Get fingerprint (read-only, but lock for consistency)."""
        async with self._lock:
            return self._sync.get_fingerprint(current_time)
    
    async def get_dominant_emotions(
        self,
        top_k: int = 5,
        current_time: Optional[float] = None,
    ) -> List[tuple]:
        """Get dominant emotions."""
        async with self._lock:
            return self._sync.get_dominant_emotions(top_k, current_time)
    
    async def save(self, path: Path) -> None:
        """Save with lock protection."""
        async with self._lock:
            self._sync.save(path)
    
    async def stats(self) -> Dict:
        """Get stats."""
        async with self._lock:
            return self._sync.stats()


if __name__ == "__main__":
    from .anchors import get_all_anchors

    print("=" * 60)
    print("  CLOUD v3.0 — User Cloud (Temporal Fingerprint)")
    print("=" * 60)
    print()

    # Initialize empty cloud
    cloud = UserCloud(half_life_hours=24.0)
    print(f"Initialized user cloud (half-life={cloud.half_life_hours}h)")
    print()

    # Simulate emotion events over time
    print("Simulating emotion events:")
    current_time = time.time()

    # Add events at different times
    events_to_add = [
        (0, 5, -48),   # FEAR event 48h ago
        (20, 22, -24), # LOVE event 24h ago
        (38, 40, -12), # RAGE event 12h ago
        (55, 58, -6),  # VOID event 6h ago
        (70, 72, -1),  # FLOW event 1h ago
    ]

    anchors = get_all_anchors()

    for primary, secondary, hours_ago in events_to_add:
        timestamp = current_time + (hours_ago * 3600)
        cloud.add_event(primary, secondary, timestamp=timestamp)
        print(f"  {hours_ago:+3d}h: {anchors[primary]} + {anchors[secondary]}")
    print()

    # Get fingerprint
    print("Current emotional fingerprint:")
    fingerprint = cloud.get_fingerprint(current_time)
    print(f"  Shape: {fingerprint.shape}")
    print(f"  Max: {fingerprint.max():.3f}")
    print(f"  Mean: {fingerprint.mean():.3f}")
    print(f"  Nonzero: {(fingerprint > 0).sum()}/100")
    print()

    # Show dominant emotions
    print("Top 5 dominant emotions:")
    for idx, strength in cloud.get_dominant_emotions(5, current_time):
        bar = "█" * int(strength * 40)
        print(f"  {anchors[idx]:15s}: {strength:.3f}  {bar}")
    print()

    # Show decay effect
    print("Decay effect over time:")
    for hours in [1, 6, 12, 24, 48, 72]:
        past_time = current_time - (hours * 3600)
        fp = cloud.get_fingerprint(past_time)
        print(f"  {hours:3d}h ago: max={fp.max():.3f}, nonzero={int((fp > 0).sum())}")
    print()

    # Test save/load
    print("Testing save/load:")
    path = Path("./cloud_data.json")
    cloud.save(path)

    cloud2 = UserCloud.load(path)
    fp2 = cloud2.get_fingerprint(current_time)

    match = np.allclose(fingerprint, fp2)
    print(f"  Save/load {'✓' if match else '✗'}")
    print()

    # Stats
    print("User cloud statistics:")
    for k, v in cloud.stats().items():
        print(f"  {k}: {v}")
    print()

    print("=" * 60)
    print("  Temporal fingerprint operational. Memory with decay.")
    print("=" * 60)