Skip to main content

qualia_core_db/research/
sentiment.rs

1//! Sentiment analysis — deterministic symbolic sentiment assessment.
2
3use std::collections::BTreeMap;
4
5/// Sentiment dimension.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub enum SentimentDimension {
8    Valence,      // Positive/negative
9    Arousal,      // Calm/excited
10    Dominance,    // Submissive/dominant
11    Authenticity, // Performed/genuine
12}
13
14impl SentimentDimension {
15    /// Stable string form.
16    pub fn as_str(&self) -> &'static str {
17        match self {
18            Self::Valence => "valence",
19            Self::Arousal => "arousal",
20            Self::Dominance => "dominance",
21            Self::Authenticity => "authenticity",
22        }
23    }
24}
25
26/// A sentiment assessment of a text.
27#[derive(Debug, Clone)]
28pub struct SentimentAssessment {
29    pub id: String,
30    pub text_ref: String,
31    pub dimensions: BTreeMap<SentimentDimension, f64>,
32    pub performed: bool,
33    pub manipulation_detected: bool,
34    pub manipulation_indicators: Vec<String>,
35}
36
37/// A sentiment trend over time.
38#[derive(Debug, Clone)]
39pub struct SentimentTrend {
40    pub timestamps: Vec<String>,
41    pub values: Vec<f64>,
42}
43
44impl SentimentTrend {
45    /// Creates an empty trend.
46    pub fn new() -> Self {
47        Self {
48            timestamps: Vec::new(),
49            values: Vec::new(),
50        }
51    }
52
53    /// Appends a `(timestamp, value)` point.
54    pub fn add_point(&mut self, timestamp: &str, value: f64) {
55        self.timestamps.push(timestamp.to_string());
56        self.values.push(value);
57    }
58
59    /// Analyse the trend — direction, volatility, and manipulation indicators.
60    pub fn analyse(&self) -> TrendAnalysis {
61        if self.values.len() < 2 {
62            return TrendAnalysis {
63                direction: TrendDirection::Flat,
64                volatility: 0.0,
65                suspicious_uniformity: false,
66            };
67        }
68        let first = self.values.first().unwrap();
69        let last = self.values.last().unwrap();
70        let direction = if last > first {
71            TrendDirection::Increasing
72        } else if last < first {
73            TrendDirection::Decreasing
74        } else {
75            TrendDirection::Flat
76        };
77
78        let mean = self.values.iter().sum::<f64>() / self.values.len() as f64;
79        let variance =
80            self.values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / self.values.len() as f64;
81        let volatility = variance.sqrt();
82
83        // Suspicious uniformity — all values within 0.01 of each other.
84        let suspicious_uniformity = self.values.iter().all(|v| (v - mean).abs() < 0.01);
85
86        TrendAnalysis {
87            direction,
88            volatility,
89            suspicious_uniformity,
90        }
91    }
92}
93
94#[derive(Debug, Clone)]
95pub struct TrendAnalysis {
96    pub direction: TrendDirection,
97    pub volatility: f64,
98    pub suspicious_uniformity: bool,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum TrendDirection {
103    Increasing,
104    Decreasing,
105    Flat,
106}
107
108impl Default for SentimentTrend {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114impl SentimentAssessment {
115    /// Creates an assessment for `text_ref`.
116    pub fn new(id: &str, text_ref: &str) -> Self {
117        Self {
118            id: id.to_string(),
119            text_ref: text_ref.to_string(),
120            dimensions: BTreeMap::new(),
121            performed: false,
122            manipulation_detected: false,
123            manipulation_indicators: Vec::new(),
124        }
125    }
126
127    /// Sets one sentiment `dimension` value.
128    pub fn set_dimension(&mut self, dimension: SentimentDimension, value: f64) {
129        self.dimensions.insert(dimension, value.clamp(-1.0, 1.0));
130    }
131
132    /// Assess sentiment from text using deterministic lexical matching.
133    pub fn assess_sentiment(text: &str) -> f64 {
134        let positive_words = [
135            "good",
136            "great",
137            "excellent",
138            "happy",
139            "positive",
140            "wonderful",
141            "amazing",
142            "love",
143            "best",
144            "beautiful",
145        ];
146        let negative_words = [
147            "bad", "terrible", "awful", "sad", "negative", "horrible", "hate", "worst", "ugly",
148            "angry",
149        ];
150        let lower = text.to_lowercase();
151        let words: Vec<&str> = lower.split_whitespace().collect();
152        let positive = words
153            .iter()
154            .filter(|w| {
155                positive_words.contains(
156                    &w.to_lowercase()
157                        .trim_matches(|c: char| !c.is_alphanumeric()),
158                )
159            })
160            .count();
161        let negative = words
162            .iter()
163            .filter(|w| {
164                negative_words.contains(
165                    &w.to_lowercase()
166                        .trim_matches(|c: char| !c.is_alphanumeric()),
167                )
168            })
169            .count();
170        let total = positive + negative;
171        if total == 0 {
172            0.0
173        } else {
174            (positive as f64 - negative as f64) / total as f64
175        }
176    }
177
178    /// Detect performed (inauthentic) sentiment — excessive positivity or
179    /// uniform emotional language.
180    pub fn detect_performed_sentiment(text: &str) -> bool {
181        let lower = text.to_lowercase();
182        let exclamation_count = lower.matches('!').count();
183        let positive_words = [
184            "amazing",
185            "incredible",
186            "awesome",
187            "perfect",
188            "best ever",
189            "love love",
190        ];
191        let positive_count = positive_words.iter().filter(|w| lower.contains(*w)).count();
192        exclamation_count >= 3 || positive_count > 2
193    }
194
195    /// Detect sentiment manipulation — coordinated messaging patterns.
196    pub fn detect_sentiment_manipulation(texts: &[String]) -> Vec<String> {
197        let mut indicators = Vec::new();
198        if texts.is_empty() {
199            return indicators;
200        }
201
202        // Check for uniform sentiment across texts (coordinated messaging).
203        let sentiments: Vec<f64> = texts.iter().map(|t| Self::assess_sentiment(t)).collect();
204        let mean = sentiments.iter().sum::<f64>() / sentiments.len() as f64;
205        let all_similar = sentiments.iter().all(|s| (s - mean).abs() < 0.1);
206        if all_similar && texts.len() > 3 {
207            indicators.push(
208                "uniform sentiment across multiple texts — possible coordination".to_string(),
209            );
210        }
211
212        // Check for excessive positive sentiment.
213        if mean > 0.8 {
214            indicators.push("excessively positive sentiment — possible astroturfing".to_string());
215        }
216
217        // Check for performed sentiment markers.
218        let performed_count = texts
219            .iter()
220            .filter(|t| Self::detect_performed_sentiment(t))
221            .count();
222        if performed_count > texts.len() / 2 {
223            indicators.push("majority of texts show performed sentiment markers".to_string());
224        }
225
226        indicators
227    }
228
229    /// Map a sentiment network — which entities are associated with which sentiments.
230    pub fn map_sentiment_network(
231        mentions: &[(String, String, f64)],
232    ) -> BTreeMap<String, Vec<(String, f64)>> {
233        // (entity, target, sentiment) → entity → [(target, sentiment)]
234        let mut network: BTreeMap<String, Vec<(String, f64)>> = BTreeMap::new();
235        for (entity, target, sentiment) in mentions {
236            network
237                .entry(entity.clone())
238                .or_default()
239                .push((target.clone(), *sentiment));
240        }
241        network
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn assess_positive_sentiment() {
251        let score =
252            SentimentAssessment::assess_sentiment("This is great and wonderful, I love it!");
253        assert!(score > 0.0);
254    }
255
256    #[test]
257    fn assess_negative_sentiment() {
258        let score = SentimentAssessment::assess_sentiment("This is terrible and awful, I hate it.");
259        assert!(score < 0.0);
260    }
261
262    #[test]
263    fn assess_neutral_sentiment() {
264        let score = SentimentAssessment::assess_sentiment("The table is brown.");
265        assert_eq!(score, 0.0);
266    }
267
268    #[test]
269    fn detect_performed_sentiment_exclamation() {
270        assert!(SentimentAssessment::detect_performed_sentiment(
271            "This is amazing!!!"
272        ));
273    }
274
275    #[test]
276    fn detect_performed_sentiment_normal() {
277        assert!(!SentimentAssessment::detect_performed_sentiment(
278            "This is a normal sentence."
279        ));
280    }
281
282    #[test]
283    fn detect_manipulation_uniform() {
284        let texts = vec![
285            "This is great and wonderful".to_string(),
286            "This is great and wonderful".to_string(),
287            "This is great and wonderful".to_string(),
288            "This is great and wonderful".to_string(),
289        ];
290        let indicators = SentimentAssessment::detect_sentiment_manipulation(&texts);
291        assert!(!indicators.is_empty());
292    }
293
294    #[test]
295    fn map_sentiment_network_basic() {
296        let mentions = vec![
297            ("alice".to_string(), "bob".to_string(), 0.8),
298            ("alice".to_string(), "carol".to_string(), -0.3),
299        ];
300        let network = SentimentAssessment::map_sentiment_network(&mentions);
301        assert!(network.contains_key("alice"));
302        assert_eq!(network.get("alice").unwrap().len(), 2);
303    }
304
305    #[test]
306    fn trend_analysis() {
307        let mut trend = SentimentTrend::new();
308        trend.add_point("t1", 0.2);
309        trend.add_point("t2", 0.5);
310        trend.add_point("t3", 0.8);
311        let analysis = trend.analyse();
312        assert_eq!(analysis.direction, TrendDirection::Increasing);
313    }
314
315    #[test]
316    fn trend_suspicious_uniformity() {
317        let mut trend = SentimentTrend::new();
318        trend.add_point("t1", 0.5);
319        trend.add_point("t2", 0.5);
320        trend.add_point("t3", 0.5);
321        let analysis = trend.analyse();
322        assert!(analysis.suspicious_uniformity);
323    }
324}