behaviorsim-rs 0.7.0

Domain-agnostic specification for modeling individual psychology and social dynamics
Documentation
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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Individual state aggregate container.
//!
//! IndividualState composes all the individual psychological state components:
//! - Hexaco (personality)
//! - Mood (PAD dimensions)
//! - Recent moral violation flag (disgust gating)
//! - Needs (physiological and psychological)
//! - SocialCognition (interpersonal beliefs)
//! - AttachmentStyle (attachment anxiety and avoidance)
//! - MentalHealth (ITS factors)
//! - Disposition (behavioral tendencies)
//! - PersonCharacteristics (PPCT factors)
//!
//! This is the primary container for an entity's internal state.

use crate::state::{
    AttachmentStyle, Disposition, EntityModelConfig, Hexaco, MentalHealth, Mood, Needs,
    PersonCharacteristics, SocialCognition, StateValue,
};
use crate::types::Duration;
use serde::{Deserialize, Serialize};

/// Aggregate container for all individual psychological state.
///
/// This struct composes all state components that define who an entity
/// is and how they currently feel. It provides unified access to all
/// state dimensions.
///
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IndividualState {
    /// HEXACO personality factors.
    hexaco: Hexaco,

    /// PAD mood dimensions.
    mood: Mood,

    /// Recent moral violation flag (gates disgust derivation).
    recent_moral_violation_flag: StateValue,

    /// Physiological and psychological needs.
    needs: Needs,

    /// Social cognition (interpersonal beliefs).
    social_cognition: SocialCognition,

    /// Attachment style (anxiety and avoidance).
    attachment: AttachmentStyle,

    /// Mental health / ITS factors.
    mental_health: MentalHealth,

    /// Behavioral dispositions.
    disposition: Disposition,

    /// PPCT person characteristics.
    person_characteristics: PersonCharacteristics,

    /// Entity model configuration.
    config: EntityModelConfig,
}

impl IndividualState {
    /// Creates a new IndividualState with default components.
    ///
    #[must_use]
    pub fn new() -> Self {
        IndividualState {
            hexaco: Hexaco::default(),
            mood: Mood::default(),
            recent_moral_violation_flag: StateValue::new(0.0)
                .with_decay_half_life(Duration::hours(24)),
            needs: Needs::default(),
            social_cognition: SocialCognition::default(),
            attachment: AttachmentStyle::default(),
            mental_health: MentalHealth::default(),
            disposition: Disposition::default(),
            person_characteristics: PersonCharacteristics::default(),
            config: EntityModelConfig::default(),
        }
    }

    // Builder methods

    /// Sets the Hexaco personality.
    #[must_use]
    pub fn with_hexaco(mut self, hexaco: Hexaco) -> Self {
        self.hexaco = hexaco;
        self
    }

    /// Sets the Mood state.
    #[must_use]
    pub fn with_mood(mut self, mood: Mood) -> Self {
        self.mood = mood;
        self
    }

    /// Sets the Needs state.
    #[must_use]
    pub fn with_needs(mut self, needs: Needs) -> Self {
        self.needs = needs;
        self
    }

    /// Sets the SocialCognition state.
    #[must_use]
    pub fn with_social_cognition(mut self, social_cognition: SocialCognition) -> Self {
        self.social_cognition = social_cognition;
        self
    }

    /// Sets the AttachmentStyle state.
    #[must_use]
    pub fn with_attachment(mut self, attachment: AttachmentStyle) -> Self {
        self.attachment = attachment;
        self
    }

    /// Sets the MentalHealth state.
    #[must_use]
    pub fn with_mental_health(mut self, mental_health: MentalHealth) -> Self {
        self.mental_health = mental_health;
        self
    }

    /// Sets the Disposition state.
    #[must_use]
    pub fn with_disposition(mut self, disposition: Disposition) -> Self {
        self.disposition = disposition;
        self
    }

    /// Sets the PersonCharacteristics.
    #[must_use]
    pub fn with_person_characteristics(mut self, pc: PersonCharacteristics) -> Self {
        self.person_characteristics = pc;
        self
    }

    /// Sets the EntityModelConfig.
    #[must_use]
    pub fn with_config(mut self, config: EntityModelConfig) -> Self {
        self.config = config;
        self
    }

    // Accessors (immutable)

    /// Returns a reference to the Hexaco personality.
    #[must_use]
    pub fn hexaco(&self) -> &Hexaco {
        &self.hexaco
    }

    /// Returns a reference to the Mood state.
    #[must_use]
    pub fn mood(&self) -> &Mood {
        &self.mood
    }

    /// Returns the recent moral violation flag (0.0 to 1.0).
    #[must_use]
    pub fn recent_moral_violation_flag(&self) -> f32 {
        self.recent_moral_violation_flag.effective()
    }

    /// Returns a reference to the Needs state.
    #[must_use]
    pub fn needs(&self) -> &Needs {
        &self.needs
    }

    /// Returns a reference to the SocialCognition state.
    #[must_use]
    pub fn social_cognition(&self) -> &SocialCognition {
        &self.social_cognition
    }

    /// Returns a reference to the AttachmentStyle state.
    #[must_use]
    pub fn attachment(&self) -> &AttachmentStyle {
        &self.attachment
    }

    /// Returns a reference to the MentalHealth state.
    #[must_use]
    pub fn mental_health(&self) -> &MentalHealth {
        &self.mental_health
    }

    /// Returns a reference to the Disposition state.
    #[must_use]
    pub fn disposition(&self) -> &Disposition {
        &self.disposition
    }

    /// Returns a reference to the PersonCharacteristics.
    #[must_use]
    pub fn person_characteristics(&self) -> &PersonCharacteristics {
        &self.person_characteristics
    }

    /// Returns a reference to the EntityModelConfig.
    #[must_use]
    pub fn config(&self) -> &EntityModelConfig {
        &self.config
    }

    // Accessors (mutable)

    /// Returns a mutable reference to the Hexaco personality.
    pub fn hexaco_mut(&mut self) -> &mut Hexaco {
        &mut self.hexaco
    }

    /// Returns a mutable reference to the Mood state.
    pub fn mood_mut(&mut self) -> &mut Mood {
        &mut self.mood
    }

    /// Sets the recent moral violation flag (0.0 to 1.0).
    pub fn set_recent_moral_violation_flag(&mut self, value: f32) {
        self.recent_moral_violation_flag
            .set_delta(value.clamp(0.0, 1.0));
    }

    /// Returns a mutable reference to the Needs state.
    pub fn needs_mut(&mut self) -> &mut Needs {
        &mut self.needs
    }

    /// Returns a mutable reference to the SocialCognition state.
    pub fn social_cognition_mut(&mut self) -> &mut SocialCognition {
        &mut self.social_cognition
    }

    /// Returns a mutable reference to the AttachmentStyle state.
    pub fn attachment_mut(&mut self) -> &mut AttachmentStyle {
        &mut self.attachment
    }

    /// Returns a mutable reference to the MentalHealth state.
    pub fn mental_health_mut(&mut self) -> &mut MentalHealth {
        &mut self.mental_health
    }

    /// Returns a mutable reference to the Disposition state.
    pub fn disposition_mut(&mut self) -> &mut Disposition {
        &mut self.disposition
    }

    /// Returns a mutable reference to the PersonCharacteristics.
    pub fn person_characteristics_mut(&mut self) -> &mut PersonCharacteristics {
        &mut self.person_characteristics
    }

    /// Returns a mutable reference to the EntityModelConfig.
    pub fn config_mut(&mut self) -> &mut EntityModelConfig {
        &mut self.config
    }

    // Unified operations

    /// Applies decay to all state components over the specified duration.
    ///
    /// Note: Hexaco (personality) is stable and does not decay.
    /// Note: Acquired Capability in MentalHealth does not decay.
    pub fn apply_decay(&mut self, elapsed: Duration) {
        // Hexaco is stable - no decay
        self.mood.apply_decay(elapsed);
        self.recent_moral_violation_flag.apply_decay(elapsed);
        self.needs.apply_decay(elapsed);
        self.social_cognition.apply_decay(elapsed);
        self.attachment.apply_decay(elapsed);
        self.mental_health.apply_decay(elapsed);
        self.disposition.apply_decay(elapsed);
        self.person_characteristics.apply_decay(elapsed);
    }

    /// Resets all deltas across all components.
    ///
    /// Note: Acquired Capability delta is not reset (permanent accumulation).
    pub fn reset_all_deltas(&mut self) {
        self.mood.reset_deltas();
        self.recent_moral_violation_flag.reset_delta();
        self.needs.reset_deltas();
        self.social_cognition.reset_deltas();
        self.attachment.reset_deltas();
        self.mental_health.reset_deltas();
        self.disposition.reset_deltas();
        self.person_characteristics.reset_deltas();
    }

    // ITS computation convenience methods

    /// Computes Thwarted Belongingness from current social cognition.
    #[must_use]
    pub fn compute_thwarted_belongingness(&self) -> f32 {
        self.mental_health
            .compute_thwarted_belongingness(&self.social_cognition)
    }

    /// Computes Perceived Burdensomeness from current social cognition.
    #[must_use]
    pub fn compute_perceived_burdensomeness(&self) -> f32 {
        self.mental_health
            .compute_perceived_burdensomeness(&self.social_cognition)
    }

    /// Computes suicidal desire from current state.
    #[must_use]
    pub fn compute_suicidal_desire(&self) -> f32 {
        self.mental_health
            .compute_suicidal_desire(&self.social_cognition)
    }

    /// Computes attempt risk from current state.
    #[must_use]
    pub fn compute_attempt_risk(&self) -> f32 {
        self.mental_health
            .compute_attempt_risk(&self.social_cognition)
    }

    /// Computes ITS convergence across TB, PB, and AC.
    #[must_use]
    pub fn its_convergence(&self) -> crate::state::ITSConvergence {
        self.mental_health.its_convergence(&self.social_cognition)
    }

    /// Computes categorical ITS risk level from current state.
    #[must_use]
    pub fn its_risk_level(&self) -> crate::state::ITSRiskLevel {
        self.mental_health.its_risk_level(&self.social_cognition)
    }
}

impl Default for IndividualState {
    fn default() -> Self {
        IndividualState::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::enums::PersonalityProfile;

    #[test]
    fn individual_state_composes_all_components() {
        let state = IndividualState::new();

        // All components should be accessible
        let _ = state.hexaco();
        let _ = state.mood();
        let _ = state.recent_moral_violation_flag();
        let _ = state.needs();
        let _ = state.mental_health();
        let _ = state.disposition();
        let _ = state.person_characteristics();
        let _ = state.attachment();
        let _ = state.config();
    }

    #[test]
    fn new_creates_default_components() {
        let state = IndividualState::new();

        // Mood should be neutral
        assert!(state.mood().valence_effective().abs() < 0.1);

        // Moral violation flag should be clear
        assert!(state.recent_moral_violation_flag().abs() < f32::EPSILON);

        // Social cognition should be healthy
        assert!(state.social_cognition().loneliness_effective() < 0.5);

        // Mental health should be healthy
        assert!(state.mental_health().depression_effective() < 0.3);

        // Disposition should be healthy
        assert!(state.disposition().empathy_effective() > 0.5);

        // Attachment should be secure by default
        assert!(state.attachment().anxiety_effective() < 0.5);
        assert!(state.attachment().avoidance_effective() < 0.5);
    }

    #[test]
    fn builder_methods_set_components() {
        let hexaco = Hexaco::from_profile(PersonalityProfile::Leader);
        let mood = Mood::new().with_valence_base(0.5);

        let state = IndividualState::new()
            .with_hexaco(hexaco.clone())
            .with_mood(mood.clone());

        assert_eq!(state.hexaco(), &hexaco);
        assert_eq!(state.mood(), &mood);
    }

    #[test]
    fn builder_sets_social_cognition() {
        let social = SocialCognition::default();
        let state = IndividualState::new().with_social_cognition(social.clone());

        assert_eq!(state.social_cognition(), &social);
    }

    #[test]
    fn mutable_references_work() {
        let mut state = IndividualState::new();

        state.mood_mut().add_valence_delta(0.3);
        assert!((state.mood().valence_delta() - 0.3).abs() < f32::EPSILON);

        state.needs_mut().add_stress_delta(0.2);
        assert!((state.needs().stress().delta() - 0.2).abs() < f32::EPSILON);
    }

    #[test]
    fn apply_decay_affects_all_decaying_components() {
        let mut state = IndividualState::new();

        state.mood_mut().add_valence_delta(0.8);
        state.needs_mut().add_stress_delta(0.8);
        state.disposition_mut().add_grievance_delta(0.8);
        state.attachment_mut().add_anxiety_delta(0.8);

        // Apply 1 week of decay
        state.apply_decay(Duration::weeks(1));

        // Mood should have decayed significantly (6 hour half-life)
        assert!(state.mood().valence_delta() < 0.1);

        // Stress should have decayed (12 hour half-life)
        assert!(state.needs().stress().delta() < 0.1);

        // Grievance should be halved (1 week half-life)
        assert!(state.disposition().grievance().delta() < 0.5);

        // Attachment deltas should decay
        assert!(state.attachment().anxiety().delta() < 0.8);
    }

    #[test]
    fn apply_decay_does_not_affect_acquired_capability() {
        let mut state = IndividualState::new();

        state.mental_health_mut().add_acquired_capability_delta(0.5);

        state.apply_decay(Duration::years(10));

        // AC should not have decayed
        assert!((state.mental_health().acquired_capability().delta() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn recent_moral_violation_flag_decays_over_a_day() {
        let mut state = IndividualState::new();
        state.set_recent_moral_violation_flag(1.0);

        state.apply_decay(Duration::hours(24));

        let flag = state.recent_moral_violation_flag();
        assert!((flag - 0.5).abs() < 0.01);
    }

    #[test]
    fn reset_all_deltas_clears_components() {
        let mut state = IndividualState::new();

        state.mood_mut().add_valence_delta(0.5);
        state.social_cognition_mut().add_loneliness_delta(0.3);
        state.disposition_mut().add_aggression_delta(0.2);
        state.attachment_mut().add_avoidance_delta(0.2);

        state.reset_all_deltas();

        assert!(state.mood().valence_delta().abs() < f32::EPSILON);
        assert!(state.social_cognition().loneliness().delta().abs() < f32::EPSILON);
        assert!(state.disposition().aggression().delta().abs() < f32::EPSILON);
        assert!(state.attachment().avoidance().delta().abs() < f32::EPSILON);
    }

    #[test]
    fn its_convenience_methods_work() {
        let mut state = IndividualState::new();

        // Set up high risk state
        state.social_cognition_mut().loneliness_mut().set_base(0.9);
        state
            .social_cognition_mut()
            .perceived_reciprocal_caring_mut()
            .set_base(0.1);
        state
            .social_cognition_mut()
            .perceived_liability_mut()
            .set_base(0.9);
        state.social_cognition_mut().self_hate_mut().set_base(0.9);
        state
            .mental_health_mut()
            .interpersonal_hopelessness_mut()
            .set_base(0.7);
        state
            .mental_health_mut()
            .acquired_capability_mut()
            .set_base(0.8);

        // Compute TB and PB
        let tb = state.compute_thwarted_belongingness();
        let pb = state.compute_perceived_burdensomeness();

        assert!(tb > 0.6);
        assert!(pb > 0.7);

        // Compute desire and risk
        let desire = state.compute_suicidal_desire();
        let risk = state.compute_attempt_risk();

        assert!(desire > 0.0);
        assert!(risk > 0.0);
    }

    #[test]
    fn its_convergence_and_risk_level_use_current_state() {
        let mut state = IndividualState::new();

        state.social_cognition_mut().loneliness_mut().set_base(0.9);
        state
            .social_cognition_mut()
            .perceived_reciprocal_caring_mut()
            .set_base(0.1);
        state
            .social_cognition_mut()
            .perceived_liability_mut()
            .set_base(0.9);
        state.social_cognition_mut().self_hate_mut().set_base(0.9);
        state
            .mental_health_mut()
            .interpersonal_hopelessness_mut()
            .set_base(0.7);
        state
            .mental_health_mut()
            .acquired_capability_mut()
            .set_base(0.8);

        let convergence = state.its_convergence();
        let risk_level = state.its_risk_level();

        assert!(convergence.all_factors_present);
        assert_eq!(risk_level, crate::state::ITSRiskLevel::HighestRisk);
    }

    #[test]
    fn default_is_new() {
        let state = IndividualState::default();
        assert!(state.social_cognition().loneliness_effective() < 0.5);
    }

    #[test]
    fn clone_and_equality() {
        let state1 = IndividualState::new();
        let state2 = state1.clone();
        assert_eq!(state1, state2);
    }

    #[test]
    fn debug_format() {
        let state = IndividualState::new();
        let debug = format!("{:?}", state);
        assert!(debug.contains("IndividualState"));
    }

    #[test]
    fn config_builder_and_accessor() {
        let config = EntityModelConfig::animal_simple();
        let state = IndividualState::new().with_config(config.clone());

        assert_eq!(state.config(), &config);
    }

    #[test]
    fn config_mutable() {
        let mut state = IndividualState::new();
        state.config_mut().set_time_scale(2.0);
        assert!((state.config().time_scale() - 2.0).abs() < f32::EPSILON);
    }

    #[test]
    fn all_builder_methods() {
        let hexaco = Hexaco::default();
        let mood = Mood::default();
        let needs = Needs::default();
        let mental_health = MentalHealth::default();
        let disposition = Disposition::default();
        let pc = PersonCharacteristics::default();
        let attachment = AttachmentStyle::default();
        let config = EntityModelConfig::default();

        let state = IndividualState::new()
            .with_hexaco(hexaco.clone())
            .with_mood(mood.clone())
            .with_needs(needs.clone())
            .with_mental_health(mental_health.clone())
            .with_disposition(disposition.clone())
            .with_person_characteristics(pc.clone())
            .with_attachment(attachment.clone())
            .with_config(config.clone());

        assert_eq!(state.hexaco(), &hexaco);
        assert_eq!(state.mood(), &mood);
        assert_eq!(state.needs(), &needs);
        assert_eq!(state.mental_health(), &mental_health);
        assert_eq!(state.disposition(), &disposition);
        assert_eq!(state.person_characteristics(), &pc);
        assert_eq!(state.attachment(), &attachment);
        assert_eq!(state.config(), &config);
    }

    #[test]
    fn all_mutable_refs() {
        let mut state = IndividualState::new();

        state.hexaco_mut().set_openness(0.5);
        state.disposition_mut().add_empathy_delta(0.1);
        state
            .person_characteristics_mut()
            .social_capital_mut()
            .add_delta(0.2);
        state.attachment_mut().add_anxiety_delta(0.1);

        assert!((state.hexaco().openness() - 0.5).abs() < f32::EPSILON);
        assert!((state.disposition().empathy().delta() - 0.1).abs() < f32::EPSILON);
        assert!(
            (state.person_characteristics().social_capital().delta() - 0.2).abs() < f32::EPSILON
        );
        assert!((state.attachment().anxiety().delta() - 0.1).abs() < f32::EPSILON);
    }

    #[test]
    fn recent_moral_violation_flag_clamps_bounds() {
        let mut state = IndividualState::new();
        state.set_recent_moral_violation_flag(1.5);
        assert!((state.recent_moral_violation_flag() - 1.0).abs() < f32::EPSILON);

        state.set_recent_moral_violation_flag(-0.5);
        assert!((state.recent_moral_violation_flag() - 0.0).abs() < f32::EPSILON);
    }
}