# Regional Risk Analysis

AI's impact on work isn't uniform-it depends heavily on regional occupational mix. A metro concentrated in administrative roles faces different pressures than one anchored by healthcare or manufacturing. This guide shows how to analyze regional vulnerability with Cubit.

**Tier Required:** Enterprise

## Why Regional Analysis?

The same national automation statistics mean different things in different places:

* **San Jose**: Heavy tech employment -> augmentation-dominated
* **Las Vegas**: Hospitality focus -> mixed exposure profile
* **Detroit**: Manufacturing legacy -> physical work protection
* **Washington DC**: Government/policy -> knowledge work exposure

## Listing Regions

```python
from cubit import CubitClient

client = CubitClient("cubit_your_key")

# List all regions, sorted by employment
regions = client.list_regions(limit=20, sort_by="employment")

print(f"{'MSA Name':<45} {'Employment':>12} {'At-Risk Jobs':>12}")
print("-" * 72)

for region in regions["regions"]:
    print(f"{region['msa_name'][:45]:<45} "
          f"{region['total_employment']:>12,.0f} "
          f"{region['total_at_risk_jobs']:>12,.0f}")
```

### Filtering by State

```python
# Get California metros
ca_regions = client.list_regions(state="CA", limit=20)

print("California Metropolitan Areas:\n")
for region in ca_regions["regions"]:
    print(f"{region['msa_name']}")
    print(f"  Employment: {region['total_employment']:,.0f}")
    print(f"  At-Risk Wages: ${region['total_at_risk_wages']:,.0f}")
    print(f"  Mean Automation Score: {region['mean_automation_score']:.1f}")
    print()
```

### By Risk Level

```python
# Find regions with highest automation exposure
regions = client.list_regions(limit=50)

# Sort by mean automation score
high_risk = sorted(
    regions["regions"],
    key=lambda r: r["mean_automation_score"],
    reverse=True
)[:10]

print("Highest Automation Exposure Metros:\n")
for region in high_risk:
    print(f"{region['msa_name']}: {region['mean_automation_score']:.1f} avg exposure")
```

## Regional Deep Dive

```python
# Los Angeles detailed profile
la = client.get_region("31084", include_jobs=True)

print(f"Region: {la['msa_name']}\n")

print("Summary:")
print(f"  Total Employment: {la['summary']['total_employment']:,.0f}")
print(f"  Jobs at Risk: {la['summary']['total_at_risk_jobs']:,.0f}")
print(f"  Wages at Risk: ${la['summary']['total_at_risk_wages']:,.0f}")
print(f"  High-Risk Jobs: {la['summary']['total_high_risk_jobs']:,.0f}")
print(f"  Mean Automation Score: {la['summary']['mean_automation_score']:.1f}")
print(f"  Mean Resilience Score: {la['summary']['mean_resilience_score']:.1f}")

print("\nMost Exposed Occupations:")
for job in la["top_exposed_jobs"][:5]:
    print(f"  - {job['title']}")
    print(f"    Employment: {job['employment']:,.0f}")
    print(f"    At-Risk Wages: ${job.get('at_risk_wages', 0):,.0f}")
    print(f"    Automation Score: {job['automation_susceptibility_score']:.0f}")

print("\nMost Resilient Occupations:")
for job in la["top_resilient_jobs"][:5]:
    print(f"  - {job['title']}")
    print(f"    Employment: {job['employment']:,.0f}")
    print(f"    Resilience Score: {job['human_centric_resilience_score']:.0f}")
```

## Comparative Analysis

### Metro Comparison

```python
def compare_metros(msa_codes: list[str], client):
    """Compare multiple metros side by side."""
    
    metros = [client.get_region(code) for code in msa_codes]
    
    print(f"{'Metro':<35} {'Emp':>10} {'At-Risk':>10} {'Auto':>8} {'Resil':>8}")
    print("-" * 75)
    
    for metro in metros:
        name = metro["msa_name"].split(",")[0][:35]
        print(f"{name:<35} "
              f"{metro['summary']['total_employment']:>10,.0f} "
              f"{metro['summary']['total_at_risk_jobs']:>10,.0f} "
              f"{metro['summary']['mean_automation_score']:>8.1f} "
              f"{metro['summary']['mean_resilience_score']:>8.1f}")

# Compare major metros
compare_metros(["31084", "35620", "16980", "26420"], client)
# LA, NYC, Chicago, Houston
```

**Output:**

```
Metro                               Emp      At-Risk      Auto    Resil
---------------------------------------------------------------------------
Los Angeles-Long Beach-Glendale   5,425,980     10,220     45.0     60.9
New York-Newark-Jersey City       9,234,000  1,456,000     51.2     50.3
Chicago-Naperville-Elgin          4,012,000    756,000     50.8     49.2
Houston-The Woodlands-Sugar Land  2,987,000    534,000     49.5     51.1
```

### State Aggregation

```python
def aggregate_state(state_code: str, client):
    """Aggregate regional data to state level."""
    
    regions = client.list_regions(state=state_code, limit=100)
    
    total_employment = sum(r["total_employment"] for r in regions["regions"])
    total_at_risk = sum(r["total_at_risk_jobs"] for r in regions["regions"])
    total_wages_at_risk = sum(r["total_at_risk_wages"] for r in regions["regions"])
    
    # Employment-weighted average scores
    weighted_auto = sum(
        r["mean_automation_score"] * r["total_employment"] 
        for r in regions["regions"]
    ) / total_employment
    
    weighted_resil = sum(
        r["mean_resilience_score"] * r["total_employment"]
        for r in regions["regions"]
    ) / total_employment
    
    return {
        "state": state_code,
        "metros": len(regions["regions"]),
        "total_employment": total_employment,
        "at_risk_jobs": total_at_risk,
        "at_risk_wages": total_wages_at_risk,
        "mean_automation": weighted_auto,
        "mean_resilience": weighted_resil
    }

# Compare states
for state in ["CA", "TX", "NY", "FL"]:
    data = aggregate_state(state, client)
    print(f"{state}: {data['total_employment']:,} workers, "
          f"{data['at_risk_jobs']:,} at risk, "
          f"Auto: {data['mean_automation']:.1f}")
```

## Building Regional Dashboards

### Map Visualization Data

```python
import json

def get_map_data(client, limit=100):
    """Prepare data for map visualization."""
    
    regions = client.list_regions(limit=limit)
    
    features = []
    for region in regions["regions"]:
        # MSA codes can be mapped to geographic boundaries
        features.append({
            "msa_code": region["msa_code"],
            "name": region["msa_name"],
            "employment": region["total_employment"],
            "at_risk_jobs": region["total_at_risk_jobs"],
            "at_risk_pct": region["total_at_risk_jobs"] / region["total_employment"] * 100,
            "automation_score": region["mean_automation_score"],
            "resilience_score": region["mean_resilience_score"],
            # Color scale value (0-1)
            "risk_intensity": min(region["mean_automation_score"] / 70, 1)
        })
    
    return features

map_data = get_map_data(client)
# Use with Mapbox, Leaflet, or D3.js
```

### React Dashboard Component

```tsx
interface RegionData {
  msa_code: string;
  msa_name: string;
  total_employment: number;
  total_at_risk_jobs: number;
  total_at_risk_wages: number;
  mean_automation_score: number;
  mean_resilience_score: number;
}

function RegionalDashboard() {
  const [regions, setRegions] = useState<RegionData[]>([]);
  const [selectedState, setSelectedState] = useState<string>('');
  const [sortBy, setSortBy] = useState<string>('employment');

  useEffect(() => {
    const params = new URLSearchParams({ limit: '100', sort_by: sortBy });
    if (selectedState) params.append('state', selectedState);
    
    fetch(`/api/regions?${params}`)
      .then(r => r.json())
      .then(data => setRegions(data.regions));
  }, [selectedState, sortBy]);

  const totalAtRisk = regions.reduce((sum, r) => sum + r.total_at_risk_jobs, 0);
  const totalWagesAtRisk = regions.reduce((sum, r) => sum + r.total_at_risk_wages, 0);

  return (
    <div className="dashboard">
      <div className="summary-cards grid grid-cols-3 gap-4 mb-6">
        <SummaryCard 
          title="Metros Analyzed" 
          value={regions.length} 
        />
        <SummaryCard 
          title="Jobs at Risk" 
          value={totalAtRisk.toLocaleString()} 
        />
        <SummaryCard 
          title="Wages at Risk" 
          value={`$${(totalWagesAtRisk / 1e9).toFixed(1)}B`} 
        />
      </div>

      <div className="filters flex gap-4 mb-4">
        <select 
          value={selectedState} 
          onChange={e => setSelectedState(e.target.value)}
        >
          <option value="">All States</option>
          <option value="CA">California</option>
          <option value="TX">Texas</option>
          <option value="NY">New York</option>
          {/* ... */}
        </select>

        <select value={sortBy} onChange={e => setSortBy(e.target.value)}>
          <option value="employment">By Employment</option>
          <option value="at_risk_jobs">By Jobs at Risk</option>
          <option value="mean_automation_score">By Automation Score</option>
        </select>
      </div>

      <RegionTable regions={regions} />
    </div>
  );
}

function RegionTable({ regions }: { regions: RegionData[] }) {
  return (
    <table className="w-full">
      <thead>
        <tr className="border-b">
          <th className="text-left py-2">Metro Area</th>
          <th className="text-right">Employment</th>
          <th className="text-right">At-Risk Jobs</th>
          <th className="text-right">Auto Score</th>
          <th className="text-right">Resilience</th>
        </tr>
      </thead>
      <tbody>
        {regions.map(region => (
          <tr key={region.msa_code} className="border-b hover:bg-gray-50">
            <td className="py-2">
              <a href={`/regions/${region.msa_code}`} className="text-blue-600 hover:underline">
                {region.msa_name}
              </a>
            </td>
            <td className="text-right">{region.total_employment.toLocaleString()}</td>
            <td className="text-right">{region.total_at_risk_jobs.toLocaleString()}</td>
            <td className="text-right">{region.mean_automation_score.toFixed(1)}</td>
            <td className="text-right">{region.mean_resilience_score.toFixed(1)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

## Use Cases

### Economic Development Planning

```python
def identify_priority_regions(client, risk_threshold: float = 55):
    """Find regions that need transition support investment."""
    
    regions = client.list_regions(limit=200)
    
    priority = [
        r for r in regions["regions"]
        if r["mean_automation_score"] > risk_threshold
        and r["total_employment"] > 100000  # Significant workforce
    ]
    
    # Sort by total wages at risk
    priority.sort(key=lambda r: r["total_at_risk_wages"], reverse=True)
    
    print("Priority Regions for Transition Investment:\n")
    for r in priority[:10]:
        print(f"{r['msa_name']}")
        print(f"  Wages at Risk: ${r['total_at_risk_wages']:,.0f}")
        print(f"  Automation Score: {r['mean_automation_score']:.1f}")
        print()
    
    return priority

priority_regions = identify_priority_regions(client)
```

### Sector Concentration Analysis

```python
def analyze_sector_concentration(msa_code: str, client):
    """Analyze which sectors drive regional exposure."""
    
    region = client.get_region(msa_code, include_jobs=True)
    
    # Group jobs by major group
    from collections import defaultdict
    sectors = defaultdict(lambda: {"employment": 0, "at_risk": 0})
    
    for job in region.get("top_exposed_jobs", []) + region.get("top_resilient_jobs", []):
        # Extract major group from SOC code (first 2 digits)
        major = job["soc_code"][:2] + "-0000"
        sectors[major]["employment"] += job["employment"]
        sectors[major]["at_risk"] += job.get("at_risk_jobs", 0)
    
    return dict(sectors)

sectors = analyze_sector_concentration("31080", client)
```

## Next Steps

* [Career Transitions](/guides/career-transitions.md) - Finding pathways for at-risk workers
* [Custom Scoring](/guides/custom-scoring.md) - Apply regional weightings
* [API Reference: Regions](/api-reference/regions.md) - Full endpoint documentation


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maidenlabs.tools/guides/regional-analysis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
