---
title: "EFA-Boosting Algorithm"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{EFA-Boosting Algorithm}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = FALSE
)
```

## Algorithm Overview

The EFA-Boosting algorithm is an iterative optimization procedure designed to find the optimal item configuration for exploratory factor analysis models. It combines multiple fit indices into an adaptive composite score that adjusts based on model complexity and sample size.

## How It Works

### Step 1: Initial Model Fit

The algorithm starts by fitting an initial EFA model with all items using the package's internal EFA engine, which fits the `efa()` block syntax of lavaan with the requested estimator and rotation.

### Step 2: Problem Detection

At each iteration, the algorithm checks for:

1. **Heywood cases**: Factor loadings > 1.0
2. **Near-Heywood cases**: Factor loadings > 0.95
3. **Cross-loadings**: Items loading on multiple factors above the threshold
4. **Low loadings**: Items with loadings below the minimum threshold
5. **Interfactor correlations**: Correlations > 0.85 between factors

### Step 3: Item Removal Strategy

Two search strategies are available:

#### Greedy Search (Default)

Removes one problematic item at a time based on priority:
1. Heywood cases
2. Near-Heywood cases
3. Cross-loadings
4. Lowest adaptive fit contribution

#### Global Search

Evaluates all possible combinations of removing 1 to `global_max_remove` items simultaneously, selecting the combination that produces the best adaptive composite fit.

### Step 4: Adaptive Fit Calculation

The composite fit is calculated as:

```
Composite = (w_RMSEA × RMSEA_norm) + (w_SRMR × SRMR_norm) + (w_CFI × CFI_inv)
```

Where weights are adapted based on df × N following Kenny & McCoach (2003) and Shi et al. (2019).

### Step 5: Convergence

The algorithm stops when:
- All fit targets are met (RMSEA, SRMR, CFI)
- Minimum items per factor constraint is reached
- Maximum iterations exceeded
- No improvement possible

## Usage Examples

### Basic Usage

Items must be named with a common prefix and a number (`PPTQ1`, `PPTQ2`, ...).

```{r}
library(OptimalFactor)

result <- efa_boosting(
  data = Data_Personality,
  name_items = "PPTQ",
  n_factors = 3
)
```

### Advanced Configuration

```{r}
result <- efa_boosting(
  data = Data_Personality,
  name_items = "PPTQ",
  n_factors = 3,
  thresholds = list(loading = 0.40, min_items_per_factor = 3, min_omega = 0.60),
  model_config = list(estimator = "WLSMV", rotation = "oblimin"),
  fit_config = list(targets = list(rmsea = 0.06, srmr = 0.06, cfi = 0.95)),
  use_global = TRUE,
  global_opt = list(max_drop = 2)
)
```

### With AI Analysis

The default model is `claude-haiku-5-5` and needs an Anthropic API key. Each item
is sent with the definition you provide.

```{r}
result <- efa_boosting(
  data = Data_Personality,
  name_items = "PPTQ",
  n_factors = 3,
  use_ai_analysis = TRUE,
  ai_config = list(
    api_key = Sys.getenv("ANTHROPIC_API_KEY"),
    language = "english",
    scale_title = "Scale title",
    construct_definition = "Definition of the construct",
    item_definitions = list(PPTQ1 = "Wording of item 1", PPTQ2 = "Wording of item 2")
  )
)

# Print AI analysis
print_conceptual_analysis(result$conceptual_analysis)
```

## Main Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `data` | - | Data frame with items |
| `name_items` | - | Prefix of item columns |
| `n_factors` | 3 | Number of factors to extract |
| `thresholds$loading` | 0.30 | Minimum acceptable loading |
| `thresholds$min_items_per_factor` | 3 | Minimum items per factor |
| `thresholds$min_omega` | NULL | Reliability floor per factor |
| `model_config$rotation` | "oblimin" | Rotation method |
| `fit_config$targets` | RMSEA .08, SRMR .06, CFI .95 | Fit targets |
| `use_global` | FALSE | Enable global search |
| `global_opt$max_drop` | 2 | Max items removed at once in global search |
| `use_ai_analysis` | FALSE | Enable AI analysis |
| `verbose` | TRUE | Print progress |

## Output

The function returns a list containing, among others:

- `final_structure`: Final factor loadings
- `removed_items`: Items removed, in order
- `steps_log`: Reason and fit at each removal
- `stop_reason`: Why the search ended
- `bondades_original`: Fit indices of the final model
- `omega_final`: Reliability per factor
- `conceptual_analysis`: AI analysis (if enabled)
