---
title: "AccSamplingDesign: Acceptance Sampling Plan Design - R Package"
author: "Ha Truong"
date: "`r Sys.Date()`"
output: 
  rmarkdown::html_vignette:
    number_sections: true
vignette: >
  %\VignetteIndexEntry{AccSamplingDesign: Acceptance Sampling Plan Design - R Package}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5
)
library(AccSamplingDesign)
library(VGAM)
```

# Introduction

The **AccSamplingDesign** package provides tools to create and evaluate 
acceptance sampling plans for both attribute and variable quality data. The 
focus is on controlling producer's and consumer's risk specifications while 
minimizing required sample sizes.

The package supports:

* Attributes sampling plans (e.g., pass/fail outcomes)
* Variables sampling plans under Normal and Beta distributions
* Easy-to-use functions for computing acceptance probability and visualizing OC curves

Install from CRAN:

```r
install.packages("AccSamplingDesign")
```

Or from GitHub:

```r
devtools::install_github("vietha/AccSamplingDesign")
```

# Attributes Sampling Examples

```{r}
# Create an attribute plan with binomial assumption
plan_attr <- optPlan(
  PRQ = 0.01,   # Acceptable quality level (1%)
  CRQ = 0.05,   # Rejectable quality level (5%)
  alpha = 0.02, # Producer's risk
  beta = 0.15,  # Consumer's risk
  distribution = "binomial"
)

# Summary of the plan
summary(plan_attr)

# Probability of accepting 3% defective
accProb(plan_attr, 0.03)

# Plot the OC curve
plot(plan_attr)
```

# Variables Sampling Examples 

## Normal Distribution, Known Sigma

```{r}
# Create a variable plan assuming known sigma
plan_var <- optPlan(
  PRQ = 0.025,
  CRQ = 0.1,
  alpha = 0.05,
  beta = 0.10,
  distribution = "normal",
  sigma_type = "known"
)

# Summary
summary(plan_var)

# Plot OC curve
plot(plan_var)
```

## Normal Distribution, Unknown Sigma

```{r}
# Create a variable plan assuming known sigma
plan_var2 <- optPlan(
  PRQ = 0.025,
  CRQ = 0.1,
  alpha = 0.05,
  beta = 0.10,
  distribution = "normal",
  sigma_type = "unknown"
)

# Summary
summary(plan_var2)
```

## Beta Distribution, Known Theta

```{r}
# Create a variable plan using Beta distribution
plan_beta <- optPlan(
  PRQ = 0.05,
  CRQ = 0.2,
  alpha = 0.05,
  beta = 0.10,
  distribution = "beta",
  theta = 44000000,
  theta_type = "known",
  LSL = 0.00001          # Lower Specification Limit
)

# Summary
summary(plan_beta)

# Plot OC curve
plot(plan_beta)
# Plot OC curve be the process mean
plot(plan_beta, by = "mean")
```

## Beta Distribution, Unknown Theta

```{r}
# Create a variable plan using Beta distribution
plan_beta2 <- optPlan(
  PRQ = 0.05,
  CRQ = 0.2,
  alpha = 0.05,
  beta = 0.10,
  distribution = "beta",
  theta = 44000000,
  theta_type = "unknown",
  LSL = 0.00001
)

# Summary
summary(plan_beta2)
```

## Variables Sampling Plan Output Note

When designing a variables acceptance sampling plan using `optPlan()` or `optVarPlan()`,  
the returned object includes two related quantities for the sample size:

- **`sample_size`** — for practical application, the final plan uses the smallest integer greater than or equal to the theoretical value (`ceiling(n)`).
- **`n`** — the raw (non-rounded) computed sample size based on the optimization model.

Example:

```{r}
plan_beta2$sample_size  # integer sample size used in plan
plan_beta2$n            # raw computed (non-rounded) value
```

## Estimating θ for Beta-Based Plans
For Beta-distributed quality characteristics, the precision parameter **θ** 
reflects the concentration of the distribution around the mean.
If θ is unknown, it can be estimated from historical process data.

A practical approach is to use the `VGAM` package, which provides the `betaff` function for fitting a Beta distribution and obtaining θ:
  
```{r}
# Example data
y <- c(0.75, 0.68, 0.72, 0.70, 0.76)

# Fit Beta model
fit <- vglm(y ~ 1, betaff, data = data.frame(y = y))

# Extract estimated parameters
coef(fit, matrix = TRUE)
```

The output provides estimates of the mean (μ) and the precision parameter (θ).
Use the estimated θ directly in `optPlan()`, e.g.:

```{r}
theta_est <- exp(coef(fit, matrix = TRUE)[1, "loglink(phi)"])
theta_est
optPlan(PRQ = 0.05, CRQ = 0.20, alpha = 0.05, beta = 0.10,
           USL = 0.8, distribution = "beta", theta_type = "unknown",
           theta = theta_est)
```

## Optimization Approach for Sampling Plans

The **AccSamplingDesign** package determines optimal sample sizes and acceptance criteria for variable sampling plans via numerical optimization.

- **Normal Plans (σ unknown):** Optimization is performed using the derivative-free method of Nelder and Mead (1965) via the `optim()` function in R. This method is robust for the non-linear objective functions that arise when σ is unknown.

- **Beta Plans:** Optimization is performed using the `optim()` function in R with the `"L-BFGS-B"` method (Byrd et al., 1995), which efficiently handles bound constraints on sample size and acceptance numbers.

This approach ensures stable and efficient plan calculations while relying solely on base R functionality, avoiding additional package dependencies.


# Custom Plan Comparison

```{r}
# Define range of defect rates
pd <- seq(0, 0.15, by = 0.001)

# Generate OC data from optimal plan
oc_opt <- OCdata(plan = plan_attr, pd = pd)

# Compare with manual plans
mplan1 <- manualPlan(n = plan_attr$n, c = plan_attr$c - 1, distribution = "binomial")
oc_alt1 <- OCdata(plan = mplan1, pd = pd)

# Plot comparison
plot(pd, oc_opt$paccept, type = "l", col = "blue", lwd = 2,
     xlab = "Proportion Defective", ylab = "Probability of Acceptance",
     main = "OC Curves Comparison for Attributes Sampling Plan")
lines(pd, oc_alt1$paccept, col = "red", lwd = 2, lty = 2)
legend("topright", legend = c("Optimal Plan", "Manual Plan c - 1"),
       col = c("blue", "red"), lty = c(1, 2), lwd = 2)
```


# References
This vignette provides a quick start for using the **AccSamplingDesign** package. 
For a full discussion of the statistical foundations, models, and optimization 
methods used, please refer to the foundation sources such as:

* Schilling, E.G., & Neubauer, D.V. (2017). Acceptance Sampling in Quality Control (3rd ed.). CRC Press.

* Wilrich, P.T. (2004). Single Sampling Plans for Inspection by Variables under a Variance Component Situation. In Frontiers in Statistical Quality Control 7.

* Govindaraju, K., & Kissling, R. (2015). Sampling plans for Beta-distributed compositional fractions. Quality Engineering, 27(1), 1–13.

* J. A. Nelder and R. Mead. A simplex method for function minimization. The Computer Journal, 7(4): 308–313, 1965. DOI 10.1093/comjnl/7.4.308.

* R. H. Byrd, P. Lu, J. Nocedal and C. Zhu. A limited memory algorithm for bound constrained optimization. SIAM Journal on Scientific Computing, 16(5): 1190–1208, 1995. DOI 10.1137/0916069.
.
