ygoldi's picture
Upload folder using huggingface_hub
43d29b8 verified
Raw
History Blame Contribute Delete
14 kB
# =============================================================================
# needs.py
# -----------------------------------------------------------------------------
# Responsible for: The "Individual Value System" of EduMirror -- the
# Psychological Need System with 5 major categories and 13
# sub-dimensions, the trait -> expected-value mapping, and the
# unmet-need gap computation.
# Role in project: This is the motivational core that the Value-driven Planner
# (agents.py) reads from and that the Social Value System
# (svo.py) aggregates over. It is the direct subject of
# Claim 1 of the reproduction.
# Assumptions: Follows arXiv:2606.07948 Section 3.3 ("Individual Value System")
# and Appendix E.1 / Table 9. All values live on a 0-10 Likert
# scale. No LLM calls happen in this file -- it is pure state, so
# it can be unit-tested deterministically.
# =============================================================================
"""Psychological Need System for EduMirror value-driven agents.
Paper grounding (arXiv:2606.07948):
- Sec 3.3: "We formalize the Value System as a Psychological Need System
comprising five major categories, namely Safety, Mental Health,
Self-Esteem, Social Belonging, and Meaning and Growth, with 13
sub-dimensions in total. Each need is represented on a Likert scale
ranging from 0 to 10."
- Sec 3.3: unmet-need gap Delta_t(d) = clip(v*(d) - v_t(d), 0, S_max)
- App E.1 + Table 9: the 13 named sub-dimensions, their associated
personality traits, and the degree-adverb -> expected-value mapping
(slightly->7.5, moderately->8, quite->8.5, extremely->9).
Note on naming: the main text (Sec 3.3) and the appendix (E.1) use slightly
different labels for two categories -- main text says "Mental Health" and
"Self-Esteem", the appendix says "Psychological Health Needs" and "Esteem".
We keep the main-text category names as canonical and record the appendix
aliases, since the sub-dimension membership is identical in both.
"""
from __future__ import annotations
import random
from dataclasses import dataclass, field
# -----------------------------------------------------------------------------
# The taxonomy. This literal IS the claim under test: 5 categories, 13
# sub-dimensions, each sub-dimension bound to the personality trait that
# Table 9 associates with it.
# -----------------------------------------------------------------------------
#: Likert scale bounds for every need dimension (paper Sec 3.3: "0 to 10").
VALUE_MIN, VALUE_MAX = 0.0, 10.0
#: S_max, the clip ceiling on a single dimension's unmet-need gap. The paper
#: writes clip(v* - v, 0, S_max) without pinning S_max numerically; since both
#: v* and v live on [0, 10], a gap can never exceed 10, so S_max = 10 is the
#: tightest bound that leaves the paper's formula unchanged.
S_MAX = 10.0
#: Appendix E.1 degree-adverb -> expected-value (v*) mapping. The paper
#: initializes v* high, in [7.5, 9.0], to encode "desired state of well-being":
#: a higher expectation makes the agent more sensitive to a deficit.
DEGREE_TO_EXPECTED = {
"slightly": 7.5,
"moderately": 8.0,
"quite": 8.5,
"extremely": 9.0,
}
#: The Psychological Need System: category -> ordered sub-dimensions.
#: Sub-dimension names and their trait bindings come from Table 9; the
#: category groupings come from Appendix E.1's enumerated list.
NEED_TAXONOMY: dict[str, list[str]] = {
"Safety": [
"psychological safety",
"emotional safety",
],
"Social Belonging": [
"group acceptance",
"support system",
"sense of superiority",
],
"Self-Esteem": [
"self worth",
"sense of respect",
],
"Meaning and Growth": [
"sense of meaning",
"sense of control",
"passion and motivation",
],
"Mental Health": [
"emotional stability",
"emotional wellbeing",
"psychological resilience",
],
}
#: Appendix E.1 uses these alternative labels for two of the categories.
#: Recorded so the reproduction can be checked against either wording.
CATEGORY_ALIASES = {
"Mental Health": "Psychological Health Needs",
"Self-Esteem": "Esteem",
}
#: Table 9: mapping between each psychological need and its associated trait.
NEED_TO_TRAIT: dict[str, str] = {
"psychological safety": "Timid",
"emotional safety": "Emotionally Sensitive",
"group acceptance": "Sociable",
"support system": "Dependent",
"sense of superiority": "Competitive",
"self worth": "Reputation-conscious",
"sense of respect": "Ego-driven",
"sense of meaning": "Spiritual",
"sense of control": "Possessive",
"passion and motivation": "Passionate",
"emotional stability": "Emotionally Stable",
"emotional wellbeing": "Hedonistic",
"psychological resilience": "Resilient",
}
#: Flat ordered list of all 13 sub-dimensions.
ALL_NEEDS: list[str] = [d for dims in NEED_TAXONOMY.values() for d in dims]
#: Reverse index: sub-dimension -> its parent category.
NEED_TO_CATEGORY: dict[str, str] = {
d: cat for cat, dims in NEED_TAXONOMY.items() for d in dims
}
def qualitative_description(value: float) -> str:
"""
Convert a raw 0-10 need score into a natural-language band label.
Args:
value: The current need score on the 0-10 Likert scale.
Returns:
A short adjective phrase describing the satisfaction level.
Why:
Appendix E.1 is explicit that "large language models struggle to
interpret raw numerical values", so EduMirror runs a "qualitative
description" step that textualizes v_t before handing it to the
planner. Reproducing that step matters: feeding bare numbers into the
prompt would be a different (and per the paper, worse) architecture.
The band edges are our choice -- the paper describes the mechanism but
does not publish its thresholds.
"""
if value < 2.0:
return "severely unmet"
if value < 4.0:
return "largely unmet"
if value < 6.0:
return "partially met"
if value < 8.0:
return "mostly met"
return "fully satisfied"
@dataclass
class NeedState:
"""
The evolving psychological need state of a single EduMirror agent.
Attributes:
current: Sub-dimension -> current value v_t(d), on [0, 10].
expected: Sub-dimension -> expected value v*(d), on [7.5, 9.0].
traits: The sampled "<degree> <trait>" phrases describing this agent,
e.g. "extremely Timid". Used to build the persona prompt.
Why:
The paper separates *current* from *expected* per dimension so that the
unmet-need gap (the planner's objective) is personality-relative rather
than absolute: two agents at the same v_t feel different degrees of
deprivation if their v* differ. Collapsing these into one number would
destroy the trait-sensitivity the paper's Figure 5 depends on.
"""
current: dict[str, float]
expected: dict[str, float]
traits: dict[str, str] = field(default_factory=dict)
def gap(self, dim: str) -> float:
"""
Unmet-need gap for one dimension: Delta_t(d) = clip(v*(d) - v_t(d), 0, S_max).
Args:
dim: Sub-dimension name (must be one of ALL_NEEDS).
Returns:
Non-negative gap in [0, S_MAX]. Zero when the need is at or above
its expectation.
Why:
This is Eq. (unnumbered) in Sec 3.3 verbatim. Clipping at 0 encodes
"a need that is over-satisfied creates no drive" -- an agent whose
safety exceeds its expectation is not motivated to seek more safety.
"""
raw = self.expected[dim] - self.current[dim]
return min(max(raw, 0.0), S_MAX)
def gaps(self) -> dict[str, float]:
"""
Unmet-need gaps across all 13 dimensions.
Args:
None.
Returns:
Sub-dimension -> gap, for every dimension in ALL_NEEDS.
Why:
The planner and the Social Value System both consume the full gap
vector (Delta_t), so materializing it once keeps them consistent.
"""
return {d: self.gap(d) for d in ALL_NEEDS}
def category_means(self) -> dict[str, float]:
"""
Mean current value per major category.
Args:
None.
Returns:
Category name -> mean of its sub-dimensions' current values.
Why:
Figures 5 and 6 of the paper plot psychological dynamics at the
5-category level, not the 13-dimension level, so the reproduction
needs this aggregation to produce comparable plots.
"""
return {
cat: sum(self.current[d] for d in dims) / len(dims)
for cat, dims in NEED_TAXONOMY.items()
}
def describe(self) -> str:
"""
Render the full need state as the textual block shown to the planner.
Args:
None.
Returns:
A multi-line string, one line per category, listing each
sub-dimension's qualitative band and its unmet gap.
Why:
Implements the Appendix E.1 "qualitative description" process that
precedes every planning step. Grouping by category keeps the prompt
compact and mirrors how the paper describes the taxonomy.
"""
lines = []
for cat, dims in NEED_TAXONOMY.items():
parts = []
for d in dims:
band = qualitative_description(self.current[d])
gap = self.gap(d)
# Surfacing the gap (not just the band) is what lets the planner
# rank candidate actions by need-gap reduction, per Sec 3.3.
parts.append(f"{d}: {band} (unmet gap {gap:.1f})")
lines.append(f"- {cat}: " + "; ".join(parts))
return "\n".join(lines)
def apply_deltas(self, deltas: dict[str, float]) -> None:
"""
Update current need values in place, clamped to the Likert range.
Args:
deltas: Sub-dimension -> signed change to apply. Unknown keys are
ignored so a noisy LLM update cannot inject new dimensions.
Returns:
None. Mutates `self.current`.
Why:
Appendix E.1's update step integrates (a_t, o_t, v_{t-1}, d_{t-1})
into v_t. We let the LLM propose per-dimension deltas rather than
absolute values, because deltas keep the update anchored to the
previous state and make a malformed response degrade gracefully
(a missing dimension simply does not move) instead of resetting the
agent's history.
"""
for dim, delta in deltas.items():
if dim not in self.current:
continue # ignore hallucinated dimensions
self.current[dim] = min(max(self.current[dim] + delta, VALUE_MIN), VALUE_MAX)
def init_need_state(rng: random.Random) -> NeedState:
"""
Initialize an agent's need state by sampling traits and values, per Appendix E.1.
Args:
rng: Seeded RNG. Passed in (not module-global) so a whole simulation is
reproducible from a single seed.
Returns:
A NeedState with expected values in [7.5, 9.0] derived from sampled
degree adverbs, and current values sampled uniformly from [0, 10].
Why:
The paper: "At initialization, adjectives and degree adverbs are
randomly selected to establish these personal expected values, while
the initial current scores v_0 are randomly sampled within [0, 10]."
The wide v_0 range is deliberate -- it is what produces the
"higher initial values enhance resilience, lower values increase
volatility" contrast the paper reports in Figure 5.
"""
expected: dict[str, float] = {}
current: dict[str, float] = {}
traits: dict[str, str] = {}
for dim in ALL_NEEDS:
degree = rng.choice(list(DEGREE_TO_EXPECTED))
expected[dim] = DEGREE_TO_EXPECTED[degree]
current[dim] = rng.uniform(VALUE_MIN, VALUE_MAX)
traits[dim] = f"{degree} {NEED_TO_TRAIT[dim]}"
return NeedState(current=current, expected=expected, traits=traits)
def init_need_state_from_profile(
rng: random.Random,
degree_by_need: dict[str, str] | None = None,
baseline_current: float | None = None,
) -> NeedState:
"""
Initialize a need state with explicit control over traits and starting values.
Args:
rng: Seeded RNG, used for any dimension not pinned by `degree_by_need`.
degree_by_need: Optional sub-dimension -> degree adverb (one of
DEGREE_TO_EXPECTED). Dimensions left out are sampled randomly.
baseline_current: If given, every current value starts here instead of
being sampled from [0, 10].
Returns:
A configured NeedState.
Why:
Two experiments need determinism that `init_need_state` cannot give.
Case Study 1 contrasts "high initial state" vs "low initial state"
victims (Figure 5), which requires pinning v_0. The intervention
experiments (Figure 6) require "20 bullying scenarios with identical
initial settings", which requires pinning both v_0 and v*. This is the
seam that makes those controlled comparisons possible.
"""
state = init_need_state(rng)
if degree_by_need:
for dim, degree in degree_by_need.items():
if dim in state.expected:
state.expected[dim] = DEGREE_TO_EXPECTED[degree]
state.traits[dim] = f"{degree} {NEED_TO_TRAIT[dim]}"
if baseline_current is not None:
for dim in state.current:
state.current[dim] = baseline_current
return state