# Sex Trafficking in Massachusetts — Supplemental Materials

Supplemental materials for a system dynamics model of commercial sex work (CSW) and sex trafficking in Massachusetts, built in [AnyLogic](https://www.anylogic.com/). This repository contains the model file, parameter-generation scripts, sensitivity analyses, policy scenario visualizations, and an interactive R Shiny explorer.

---

## Repository Structure

```
├── Sex_Trafficking_SDM/
│   ├── Sex_Trafficking_SDM.alp          # AnyLogic model file
│   └── database/                        # Embedded AnyLogic database
│
└── Analysis/
    ├── sensitivity_analysis_param_generation.py   # Generate LHS / OAT parameter sets
    ├── sensitivity_analysis.py                    # PRCC / SRCC sensitivity analysis (LHS)
    ├── sensitivity_analysis_oat.py                # OAT signed sensitivity index analysis
    ├── policy_visualization.py                    # Policy scenario figures
    ├── app.R                                      # R Shiny interactive explorer
    ├── lhs_samples.xlsx                           # Pre-generated LHS parameter sets
    ├── lhs_samples_manual_bounds.xlsx             # LHS sets with manually specified bounds
    ├── oat_samples.xlsx                           # Pre-generated OAT parameter sets
    ├── oat_samples_manual_bounds.xlsx             # OAT sets with manually specified bounds
    ├── PolicyScenarios.xlsx                       # Policy scenario definitions
    ├── pyproject.toml                             # Python dependencies
    │
    ├── policy_figures/                            # Results figures from policy scenario experiments
    ├── sensitivity_results/                       # Results figures from LHS sensitivity analysis
    └── sensitivity_results_oat/                   # Results figures from OAT sensitivity analysis
```

---

## AnyLogic Model (`Sex_Trafficking_SDM`)

`Sex_Trafficking_SDM.alp` is a system dynamics model of commercial sex work and sex trafficking in Massachusetts. Open it in AnyLogic (Personal Learning Edition or higher).

### Model Overview

The model tracks population stocks across several states (active sex sellers, exited, in services, etc.) for both adults and youth, driven by flows governed by the parameters below. Key **output variables** reported by the model include:

| Variable | Description |
|---|---|
| `TotalTSS` | Total trafficked sex sellers |
| `TotalSS` | Total sex sellers (trafficked + non-trafficked) |
| `TotalYouthTSS` | Youth trafficked sex sellers |
| `pctTraffickedVsNontrafficked` | Fraction of sex sellers who are trafficked |
| `Buyers` | Number of active buyers |
| `demand` | Aggregate demand |
| `Traffickers` | Number of active traffickers |
| `pctSSCrimRecord` | Fraction of sex sellers with a criminal record |
| `pctExitedCrimRecord` | Fraction of exited individuals with a criminal record |
| `EmServicesAdult` | Adults in emergency services |
| `STServicesAdult` | Adults in short-term services |
| `LTServicesAdult` | Adults in long-term services |
| `cost` | Total cost |

### Key Parameter Domains

| Domain | Example Parameters |
|---|---|
| Recruitment & Crime | `st_recruitment`, `org_crime_prevalence`, `trafficker_exposure`, `trafficking_educ` |
| Population | Adult / youth population size, homelessness rate, poverty rate, lack of support network |
| Prosecution & Policy | `prosecution_culture`, `buyer_prosecution_culture`, `prosecution_mult`, `pctExpungement` |
| Services (Adult) | `em_services_capacity`, `st_services_capacity`, `lt_services_capacity`, recovery rates |
| Services (Youth) | Youth-specific equivalents of all adult service parameters |
| Recovery & Recidivism | `base_adult_recovery_rate`, `post_service_vulnerability`, `vulnerable_recidivism` |
| Supply / Demand / Economics | `csw_acceptance`, `csw_exhaustion`, `sb_benefit`, `ss_desired_profit`, `buyer_base_trns` |

The baseline population figures reflect Massachusetts: ~5.66 million adults and ~1.34 million youth.

### Running Sensitivity Experiments

The model is configured to export results to CSV files consumed by the analysis scripts:

- **LHS runs** → `Sex_Trafficking_SDM/LHSVariationOutput.csv`
- **OAT runs** → `Sex_Trafficking_SDM/OATVariationOutput_manual.csv`
- **Policy scenarios** → `CSWPolicyScenarioOutput.xlsx` (three sheets: `PolicyPercentChanges`, `PolicyChanges`, `PolicyVals`)
- **General / policy CSW outputs** → `CSWOutput_General.csv`, `CSWOutput_Policy.csv`

---

## Analysis Scripts (Python)

### Setup

```bash
cd Analysis
pip install -e .          # installs dependencies from pyproject.toml
# or: uv sync
```

Requires Python ≥ 3.12. Dependencies: `numpy`, `pandas`, `scipy`, `matplotlib`, `openpyxl`.

---

### 1. Parameter Generation — `sensitivity_analysis_param_generation.py`

Generates parameter sets for either Latin Hypercube Sampling (LHS) or One-At-a-Time (OAT) sweeps.

```bash
# LHS — 5000 quasi-random samples (default)
python sensitivity_analysis_param_generation.py

# OAT — sweep each parameter across its range, 10 steps each
python sensitivity_analysis_param_generation.py --mode oat

# OAT with 20 steps per parameter
python sensitivity_analysis_param_generation.py --mode oat --oat-steps 20

# Custom output file
python sensitivity_analysis_param_generation.py -o my_params.xlsx
```

Parameters and their bounds are defined in the `PARAMETERS` dict at the top of the script. Each entry specifies a `default` value and optional `bounds`; setting `"fixed": True` holds a parameter constant.

---

### 2. LHS Sensitivity Analysis — `sensitivity_analysis.py`

Computes **Partial Rank Correlation Coefficients (PRCC)** and **Spearman Rank Correlation Coefficients (SRCC)** between each input parameter and each output, using a row-matched LHS parameter file and model output CSV.

```bash
python sensitivity_analysis.py
```

**Outputs** (saved to `sensitivity_results/`):

| File | Contents |
|---|---|
| `prcc_table.csv` | PRCC for each (parameter, output) pair |
| `prcc_pvalues.csv` | p-values for all PRCC estimates |
| `srcc_table.csv` | SRCC for each (parameter, output) pair |
| `tornado_<output>.png` | Tornado chart of PRCC by parameter |
| `heatmap_prcc.png` | PRCC heatmap across all outputs |
| `scatter_<output>.png` | Scatter plots for the top 3 parameters |
| `prcc_vs_srcc.png` | PRCC vs. SRCC comparison (detects multicollinearity) |
| `power_curve.png` | Required sample size vs. minimum detectable \|PRCC\| |
| `power_heatmap.png` | Power grid across n and effect size |

Configure the input/output file paths and the outputs of interest at the top of the script.

---

### 3. OAT Sensitivity Analysis — `sensitivity_analysis_oat.py`

Analyzes OAT sweep results using a **Signed Sensitivity Index** (SSI): the percentage change in each output when a parameter is swept over its full range, with sign indicating direction.

```bash
python sensitivity_analysis_oat.py
```

**Outputs** (saved to `sensitivity_results_oat/`):

| File | Contents |
|---|---|
| `oat_signed_si.csv` | SSI for each (parameter, output) pair |
| `oat_pct_change.csv` | Unsigned % change for each pair |
| `oat_tornado_<output>.png` | OAT tornado chart per output |
| `oat_heatmap.png` | SSI heatmap across all outputs |
| `oat_response_<output>.png` | Response curves for top parameters |

---

### 4. Policy Scenario Visualization — `policy_visualization.py`

Generates figures comparing policy scenarios from `CSWPolicyScenarioOutput.xlsx`.

```bash
# All five figure types
python policy_visualization.py

# A single figure type
python policy_visualization.py --plot heatmap
python policy_visualization.py --plot grouped_bar
python policy_visualization.py --plot diverging_bar
python policy_visualization.py --plot changes_panels
python policy_visualization.py --plot vals_panels

# Custom output directory and DPI
python policy_visualization.py --output results/ --dpi 300
```

| Figure | Description |
|---|---|
| `policy_heatmap.png` | % change from baseline for all scenarios × metrics |
| `policy_grouped_bar.png` | Clustered vertical bar chart of % changes |
| `policy_diverging_bar.png` | Small-multiple horizontal diverging bars, one panel per metric |
| `policy_changes_panels.png` | Absolute change from baseline, small multiples |
| `policy_vals_panels.png` | Absolute values with baseline reference, small multiples |

---

## Interactive Explorer (R Shiny) — `app.R`

An interactive dashboard for exploring CSW model output CSVs (`CSWOutput_<tag>.csv`) placed in the same directory as `app.R`.

### Setup

```r
install.packages(c("shiny", "shinyWidgets", "plotly", "tidyverse", "readr"))
```

### Running

```r
shiny::runApp("Analysis/app.R")
```

Or from within the `Analysis/` directory:

```r
shiny::runApp("app.R")
```

The app auto-detects any `CSWOutput_<tag>.csv` files present and exposes three tabs:

| Tab | Description |
|---|---|
| **Summary Across All Runs** | Mean ± SD of selected dependent variables vs. an independent variable, across all runs |
| **Base-Filtered Runs** | Same plot, but filtered to rows matching specified baseline values of all other independent variables |
| **3-D Scatter** | Interactive 3D scatter (plotly) with two independent variables on X/Y and a dependent variable on Z |

Independent variables available for exploration include prosecution culture, service capacities, expungement rate, buyer prosecution rate, criminal record obstacle, and CSW acceptance. Dependent variables include all key model outputs listed above.
