File size: 8,465 Bytes
629a363
 
 
 
 
 
 
 
 
 
 
514b626
 
 
 
 
 
 
3934b26
 
 
514b626
 
 
 
 
 
 
 
3934b26
 
 
 
514b626
 
 
3934b26
 
 
 
514b626
3934b26
514b626
 
 
 
 
efc82d6
16a929f
3934b26
16a929f
 
 
 
 
 
3934b26
 
 
16a929f
 
 
3934b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a929f
514b626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3934b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514b626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3934b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514b626
 
 
 
 
 
 
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
---
title: AI Personas for Urban Planning
emoji: πŸ™οΈ
colorFrom: blue
colorTo: purple
sdk: streamlit
sdk_version: "1.40.1"
app_file: web_app.py
pinned: false
---

# AI Personas for Urban Planning

A multi-phase persona simulation system for urban planning and built environment design, enabling stakeholder perspective analysis and opinion dynamics modeling.

## Overview

This system allows users to:
- **Phase 1** βœ…: Query synthetic personas representing urban stakeholders and receive contextually-aware responses
- **Phase 2** βœ…: Generate response distributions from populations of persona variants
- **Phase 3** βœ…: Model multi-persona interactions to discover opinion equilibria using scale-free and small-world networks

## Project Structure

```
AI_Personas/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ personas/          # Persona data models and database
β”‚   β”œβ”€β”€ context/           # Environmental/built environment context
β”‚   β”œβ”€β”€ llm/               # LLM integration (Anthropic Claude)
β”‚   β”œβ”€β”€ pipeline/          # Phase 1: Query-response pipeline
β”‚   β”œβ”€β”€ population/        # Phase 2: Population sampling and analysis
β”‚   └── influence/         # Phase 3: Social influence networks & equilibrium
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ personas/          # Persona JSON definitions
β”‚   └── contexts/          # Environmental context data
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ 1_πŸ’¬_Chat.py      # Phase 1 web interface
β”‚   β”œβ”€β”€ 2_πŸ“Š_Population_Analysis.py  # Phase 2 web interface
β”‚   └── 3_🌐_Opinion_Equilibria.py   # Phase 3 web interface
β”œβ”€β”€ tests/
β”œβ”€β”€ web_app.py             # Main Streamlit app entry point
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ .env.example          # Environment variable template
└── README.md
```

## 🎨 Web UI (Multi-Page!)

**Beautiful visual interface with three integrated pages:**

```bash
# Launch the web interface
streamlit run web_app.py
```

### Page 1: Chat with Personas πŸ’¬
**Phase 1: Individual persona conversations**
- πŸ‘₯ Visual persona cards with avatars and color themes
- πŸ’¬ Chat-style conversation interface
- πŸ“œ Full conversation history
- 🎯 Quick suggestion buttons
- πŸŒ† Contextual awareness (built environment, social context)

### Page 2: Population Analysis πŸ“Š
**Phase 2: Response distributions from persona populations**
- πŸ”’ Query 100+ persona variants simultaneously
- πŸ“Š Position distribution visualizations (support/oppose/neutral)
- 😊 Sentiment analysis across populations
- 🏷️ Theme extraction and clustering (affordability, equity, sustainability, etc.)
- πŸ“ˆ Interactive Plotly charts and statistical summaries
- βš™οΈ Configurable variation levels (Conservative/Moderate/Diverse)
- πŸ’Ύ Export results as reports

### Page 3: Opinion Equilibria 🌐 ✨ NEW!
**Phase 3: Multi-persona influence and opinion dynamics**
- πŸ•ΈοΈ Scale-free and small-world network topologies (BarabΓ‘si-Albert, Watts-Strogatz)
- πŸ”„ Multi-round opinion dynamics simulation
- πŸ“ˆ Opinion evolution timeline visualization
- 🎯 Equilibrium detection and convergence analysis
- πŸ‘₯ Opinion cluster identification
- ⭐ Opinion leader detection (influence centrality)
- 🌐 Interactive network graph visualization
- πŸ“Š Consensus strength metrics
- πŸ’Ύ Export equilibrium reports

## Quick Start

### 1. Installation

```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

### 2. Configuration

```bash
# Copy environment template
cp .env.example .env

# Edit .env and add your Anthropic API key
```

### 3. Run Example

```bash
# Phase 1: Single persona query
python examples/phase1_single_query.py

# Interactive CLI
python -m src.cli
```

## Personas

The system includes 6 synthetic personas representing diverse urban planning stakeholders:

1. **Sarah Chen** - Urban Planner (30s, progressive, sustainability-focused)
2. **Marcus Thompson** - Local Business Owner (50s, pragmatic, economy-focused)
3. **Dr. Elena Rodriguez** - Transportation Engineer (40s, data-driven, efficiency-focused)
4. **James O'Brien** - Long-time Resident (65+, traditional, community-focused)
5. **Priya Patel** - Housing Advocate (20s, activist, equity-focused)
6. **David Kim** - Real Estate Developer (40s, market-driven, growth-focused)

## Phase Roadmap

### Phase 1: Single Persona Query-Response βœ… COMPLETE
- βœ“ Query individual personas with contextual awareness
- βœ“ Anthropic Claude integration
- βœ“ Environmental context system
- βœ“ Beautiful chat interface with persona cards
- βœ“ Conversation history and quick suggestions

### Phase 2: Population Response Distribution βœ… COMPLETE
- βœ“ Generate persona variants with configurable variation levels
- βœ“ Parallel querying of persona populations (100+)
- βœ“ Response clustering and statistical analysis
- βœ“ Position detection (support/oppose/neutral)
- βœ“ Sentiment analysis and theme extraction
- βœ“ Interactive Plotly visualizations
- βœ“ Export functionality

### Phase 3: Multi-Persona Influence & Equilibrium βœ… COMPLETE
- βœ“ Scale-free network topology (BarabΓ‘si-Albert model)
- βœ“ Small-world network topology (Watts-Strogatz model)
- βœ“ Fully connected network option
- βœ“ Opinion dynamics simulation (multi-round interactions)
- βœ“ Influence weight calculation based on persona characteristics
- βœ“ Equilibrium detection algorithms
- βœ“ Opinion leader identification (centrality analysis)
- βœ“ Opinion cluster detection and stability metrics
- βœ“ Interactive network graph visualization
- βœ“ Consensus strength metrics
- βœ“ Opinion evolution timeline charts
- βœ“ Export equilibrium reports

## Technology Stack

- **Python 3.11+**: Core language
- **FastAPI**: REST API layer
- **SQLite/PostgreSQL**: Persona and context storage
- **Anthropic Claude**: LLM (will support Be.FM from Stanford)
- **Pydantic**: Data validation
- **NumPy/SciPy**: Statistical analysis (Phase 2)
- **NetworkX**: Graph modeling (Phase 3)

## Usage Examples

### Query a Persona

```python
from src.pipeline.query_engine import QueryEngine

engine = QueryEngine()

# Ask a persona about a planning issue
response = engine.query(
    persona_id="sarah_chen",
    question="What do you think about the proposed bike lane on Main Street?",
    context={
        "location": "downtown_district",
        "time": "rush_hour",
        "recent_events": ["community_meeting_last_week"]
    }
)

print(response)
```

### Get Population Distribution (Phase 2)

```python
from src.population.sampler import PopulationSampler

sampler = PopulationSampler(base_persona="sarah_chen", n_variants=100)
distribution = sampler.query_population(
    question="Rate your support for the bike lane (1-10)"
)

# distribution.mean, distribution.std, distribution.histogram
```

### Model Opinion Dynamics (Phase 3)

```python
from src.personas.database import PersonaDatabase
from src.llm.anthropic_client import AnthropicClient
from src.influence.dynamics import OpinionDynamicsEngine
from src.influence.equilibrium import EquilibriumDetector
from src.influence.network import InfluenceNetwork

# Initialize
persona_db = PersonaDatabase()
persona_db.load_from_directory("data/personas")
llm_client = AnthropicClient()

# Select personas for discussion
persona_ids = ["sarah_chen", "marcus_thompson", "david_kim"]

# Run opinion dynamics with scale-free network
engine = OpinionDynamicsEngine(persona_db, llm_client)
results = engine.run_dynamics(
    persona_ids=persona_ids,
    question="Should we allow high-rise development downtown?",
    max_rounds=5,
    network_type="scale_free",  # or "small_world", "fully_connected"
)

# Analyze equilibrium
personas = [persona_db.get_persona(pid) for pid in persona_ids]
influence_network = InfluenceNetwork(personas, network_type="scale_free")
detector = EquilibriumDetector()
equilibrium = detector.analyze_equilibrium(results, influence_network, max_rounds=5)

# Results
print(f"Equilibrium reached: {equilibrium.reached_equilibrium}")
print(f"Consensus strength: {equilibrium.consensus_strength:.0%}")
print(f"Majority position: {equilibrium.majority_position.value}")
print(f"Opinion leaders: {[l['persona_name'] for l in equilibrium.opinion_leaders[:3]]}")
```

## Contributing

This project is under active development. Contributions welcome!

## License

MIT License