--- 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