---
title: "Strategus Execution"
always_allow_html: yes
output:
  html_document:
    toc: yes
    toc_depth: '3'
    df_print: paged
  html_vignette:
    toc: yes
    toc_depth: 3
    vignette: >
      %\VignetteIndexEntry{ComputingTreatmentPathways}
      %\VignetteEngine{knitr::rmarkdown}
      %\VignetteEncoding{UTF-8}
  pdf_document:
    toc: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Introduction
This vignette shows to to run a `TreatmentPatterns` analysis using `Strategus`.

>The `Strategus` package is a new approach for coordinating and executing analytics using HADES modules. The goal is to have OHDSI network sites install Strategus and exchange an analysis specification in JSON format to execute a network study. The analysis specification will capture all of the design choices that pertain to the methods used in a given study. The analysis specification format aims to allow for combining different HADES modules together as a pipeline to execute a study.

*[Introduction to Strategus](https://ohdsi.github.io/Strategus/articles/IntroductionToStrategus.html)*

## Database settings

First we specify the execution settings, which dictate how to connect to the database.

```{r database, eval=FALSE}
library(Strategus)
library(Eunomia)
library(CohortGenerator)
library(CirceR)
library(TreatmentPatterns)

connectionDetails <- Eunomia::getEunomiaConnectionDetails()

outputFolder <- tempdir()

executeSettings <- Strategus::createCdmExecutionSettings(
  workDatabaseSchema = "main",
  cdmDatabaseSchema = "main",
  cohortTableNames = CohortGenerator::getCohortTableNames(cohortTable = "cohort_table"),
  workFolder = file.path(outputFolder, "work"),
  resultsFolder = file.path(outputFolder, "result"),
  minCellCount = 5
)
```

## CohortGenerator Module

Secondly we need need to tell Strategus which cohorts to generate, and where.

```{r cohort_generator, eval=FALSE}
# Read cohort json files provided by TreatmentPatterns
files <- list.files(
  path = system.file(package = "TreatmentPatterns", "exampleCohorts"),
  full.names = TRUE
)
json <- sapply(files, readLines)
json <- sapply(json, paste, collapse = "")

# Build SQL from JSON definition
sql <- sapply(
  X = json,
  FUN = CirceR::buildCohortQuery,
  options = CirceR::createGenerateOptions(generateStats = FALSE)
)

# Set cohort names
cohortNames <- sapply(basename(files), function(name) {
  strtrim(name, nchar(name) - 5)
})

# Build cohortSet
cohortSet <- data.frame(
  cohortId = seq_len(length(json)),
  cohortName = cohortNames,
  sql = sql,
  json = json
)

# Specify CohortGenerator module
cgMod <- Strategus::CohortGeneratorModule$new()

# Add `cohortSet` to the shared specifications
cohortSharedResource <- cgMod$createCohortSharedResourceSpecifications(
  cohortDefinitionSet = cohortSet
)

# Create the CohortGenerator specification
cgSpec <- cgMod$createModuleSpecifications()
```

## TreatmentPatterns module

Then we tell Strategus how to execute TreatmentPatterns.

```{r treatment_patterns, eval=FALSE}
# Create a cohort 'types' table from the cohortSet to indicate whcih cohorts
# are a 'target' and 'event' cohorts
cohorts <- data.frame(
  cohortId = cohortSet$cohortId,
  cohortName = cohortSet$cohortName,
  type = c(rep("event", 7), "target")
)

# Create the TreatmentPatterns module
tpMod <- Strategus::TreatmentPatternsModule$new()

# Create the TreatmentPatterns specification
tpSpec <- tpMod$createModuleSpecifications(
  cohorts = cohorts,
  minEraDuration = 30,
  combinationWindow = 30,
  minPostCombinationDuration = 30
  # ...
)
```

## Execution

Finally we design our analysis and execute it against the database.

```{r execution, eval=FALSE}
# Add specifications to an empty analysis specification
analysisSpec <- Strategus::createEmptyAnalysisSpecificiations() |>
  Strategus::addSharedResources(cohortSharedResource) |>
  Strategus::addCohortGeneratorModuleSpecifications(cgSpec) |>
  Strategus::addTreatmentPatternsModuleSpecifications(tpSpec)

# Execute the analysis
Strategus::execute(
  analysisSpecifications = analysisSpec,
  executionSettings = executeSettings,
  connectionDetails = connectionDetails
)
```
