diff --git a/NAMESPACE b/NAMESPACE index d0f7213..cfbe573 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -9,6 +9,7 @@ export(EvidenceSynthesisModule) export(PatientLevelPredictionModule) export(SelfControlledCaseSeriesModule) export(StrategusModule) +export(TreatmentPatternsModule) export(addCharacterizationModuleSpecifications) export(addCohortDiagnosticsModuleSpecifications) export(addCohortGeneratorModuleSpecifications) @@ -19,6 +20,7 @@ export(addModuleSpecifications) export(addPatientLevelPredictionModuleSpecifications) export(addSelfControlledCaseSeriesModuleSpecifications) export(addSharedResources) +export(addTreatmentPatternsModuleSpecifications) export(createCdmExecutionSettings) export(createEmptyAnalysisSpecificiations) export(createResultDataModel) diff --git a/R/Module-TreatmentPatterns.R b/R/Module-TreatmentPatterns.R new file mode 100644 index 0000000..f84df2b --- /dev/null +++ b/R/Module-TreatmentPatterns.R @@ -0,0 +1,206 @@ +# Copyright 2024 Observational Health Data Sciences and Informatics +# +# This file is part of Strategus +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#' @title Evaluate phenotypes with the \href{https://github.com/darwin-eu/TreatmentPatterns/}{DARWIN TreatmentPatterns Package} +#' @export +#' @description +#' Characterisation and description of patterns of events (cohorts). against the OMOP Common Data Model. +TreatmentPatternsModule <- R6::R6Class( + classname = "TreatmentPatternsModule", + inherit = StrategusModule, + + ## Public ---- + public = list( + ### Fields ---- + #' @field tablePrefix The table prefix to append to the results tables + tablePrefix = "tp_", + + ### Methods ---- + #' @description Initialize the module + initialize = function() { + super$initialize() + }, + + #' @description Execute Treatment Patterns + #' + #' @template connectionDetails + #' @template analysisSpecifications + #' @template executionSettings + execute = function(connectionDetails, analysisSpecifications, executionSettings) { + super$.validateCdmExecutionSettings(executionSettings) + super$execute(connectionDetails, analysisSpecifications, executionSettings) + + jobContext <- private$jobContext + workFolder <- jobContext$moduleExecutionSettings$workSubFolder + resultsFolder <- jobContext$moduleExecutionSettings$resultsSubFolder + + spec <- jobContext$settings + outputEnv <- TreatmentPatterns::computePathways( + cohorts = spec$cohorts, + cohortTableName = spec$cohortTableName, + connectionDetails = connectionDetails, + cdmSchema = executionSettings$cdmDatabaseSchema, + resultSchema = executionSettings$workDatabaseSchema, + tempEmulationSchema = executionSettings$tempEmulationSchema, + includeTreatments = spec$includeTreatments, + indexDateOffset = spec$indexDateOffset, + minEraDuration = spec$minEraDuration, + splitEventCohorts = spec$splitEventCohorts, + splitTime = spec$splitTime, + eraCollapseSize = spec$eraCollapseSize, + combinationWindow = spec$combinationWindow, + minPostCombinationDuration = spec$minPostCombinationDuration, + filterTreatments = spec$filterTreatments, + maxPathLength = spec$maxPathLength + ) + + if (!dir.exists(executionSettings$resultsFolder)) dir.create(executionSettings$resultsFolder, recursive = TRUE, showWarnings = FALSE) + + TreatmentPatterns::export( + andromeda = outputEnv, + outputPath = executionSettings$resultsFolder, + ageWindow = spec$ageWindow, + minCellCount = executionSettings$minCellCount, + censorType = spec$censorType, + archiveName = NULL + ) + + on.exit(Andromeda::close(outputEnv)) + }, + + #' @description Create the results data model for the module + #' @template resultsConnectionDetails + #' @template resultsDatabaseSchema + #' @template tablePrefix + createResultsDataModel = function(resultsConnectionDetails, resultsDatabaseSchema, tablePrefix = "") { + super$createResultsDataModel(resultsConnectionDetails, resultsDatabaseSchema, tablePrefix) + message("`createResultsDataModel()` is not implemented.") + }, + + #' @description Get the results data model specification for the module + #' @template tablePrefix + getResultsDataModelSpecification = function(tablePrefix = "") { + super$getResultsDataModelSpecification() + message("`getResultsDataModelSpecification()` is not implemented") + }, + + #' @description Upload the results for TreatmentPatterns + #' @template resultsConnectionDetails + #' @template analysisSpecifications + #' @template resultsDataModelSettings + uploadResults = function(resultsConnectionDetails, analysisSpecifications, resultsDataModelSettings) { + super$uplaodResults(resultsConnectionDetails, analysisSpecifications, resultsDataModelSettings) + message("`uploadResults()` is not implemented") + }, + + #' @description Creates the TreatmentPatternsnModule Specifications + #' + #' @param cohorts (`data.frame()`)\cr + #' Data frame containing the following columns and data types: + #' \describe{ + #' \item{cohortId `numeric(1)`}{Cohort ID's of the cohorts to be used in the cohort table.} + #' \item{cohortName `character(1)`}{Cohort names of the cohorts to be used in the cohort table.} + #' \item{type `character(1)` \["target", "event', "exit"\]}{Cohort type, describing if the cohort is a target, event, or exit cohort} + #' } + #' @param cohortTableName (`character(1)`)\cr + #' Cohort table name. + #' @param connectionDetails (`DatabaseConnector::createConnectionDetails()`: `NULL`)\cr + #' Optional; In congruence with `cdmSchema` and `resultSchema`. Ignores `cdm`. + #' @param cdmSchema (`character(1)`: `NULL`)\cr + #' Optional; In congruence with `connectionDetails` and `resultSchema`. Ignores `cdm`. + #' @param resultSchema (`character(1)`: `NULL`)\cr + #' Optional; In congruence with `connectionDetails` and `cdmSchema`. Ignores `cdm`. + #' @param tempEmulationSchema Schema used to emulate temp tables + #' @param includeTreatments (`character(1)`: `"startDate"`)\cr + #' \describe{ + #' \item{`"startDate"`}{Include treatments after the target cohort start date and onwards.} + #' \item{`"endDate"`}{Include treatments before target cohort end date and before.} + #' } + #' @param indexDateOffset (`integer(1)`: `0`)\cr + #' Offset the index date of the `Target` cohort. + #' @param minEraDuration (`integer(1)`: `0`)\cr + #' Minimum time an event era should last to be included in analysis + #' @param splitEventCohorts (`character(n)`: `""`)\cr + #' Specify event cohort to split in acute (< X days) and therapy (>= X days) + #' @param splitTime (`integer(1)`: `30`)\cr + #' Specify number of days (X) at which each of the split event cohorts should + #' be split in acute and therapy + #' @param eraCollapseSize (`integer(1)`: `30`)\cr + #' Window of time between which two eras of the same event cohort are collapsed + #' into one era + #' @param combinationWindow (`integer(1)`: `30`)\cr + #' Window of time two event cohorts need to overlap to be considered a + #' combination treatment + #' @param minPostCombinationDuration (`integer(1)`: `30`)\cr + #' Minimum time an event era before or after a generated combination treatment + #' should last to be included in analysis + #' @param filterTreatments (`character(1)`: `"First"` \["first", "Changes", "all"\])\cr + #' Select first occurrence of (‘First’); changes between (‘Changes’); or all + #' event cohorts (‘All’). + #' @param maxPathLength (`integer(1)`: `5`)\cr + #' Maximum number of steps included in treatment pathway + #' @param ageWindow (`integer(n)`: `10`)\cr + #' Number of years to bin age groups into. It may also be a vector of integers. + #' I.e. `c(0, 18, 150)` which will results in age group `0-18` which includes + #' subjects `< 19`. And age group `18-150` which includes subjects `> 18`. + #' @param minCellCount (`integer(1)`: `5`)\cr + #' Minimum count required per pathway. Censors data below `x` as ` \code{TreatmentPatternsModule} +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{tablePrefix}}{The table prefix to append to the results tables} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-TreatmentPatternsModule-new}{\code{TreatmentPatternsModule$new()}} +\item \href{#method-TreatmentPatternsModule-execute}{\code{TreatmentPatternsModule$execute()}} +\item \href{#method-TreatmentPatternsModule-createResultsDataModel}{\code{TreatmentPatternsModule$createResultsDataModel()}} +\item \href{#method-TreatmentPatternsModule-getResultsDataModelSpecification}{\code{TreatmentPatternsModule$getResultsDataModelSpecification()}} +\item \href{#method-TreatmentPatternsModule-uploadResults}{\code{TreatmentPatternsModule$uploadResults()}} +\item \href{#method-TreatmentPatternsModule-createModuleSpecifications}{\code{TreatmentPatternsModule$createModuleSpecifications()}} +\item \href{#method-TreatmentPatternsModule-validateModuleSpecifications}{\code{TreatmentPatternsModule$validateModuleSpecifications()}} +\item \href{#method-TreatmentPatternsModule-clone}{\code{TreatmentPatternsModule$clone()}} +} +} +\if{html}{\out{ +
Inherited methods + +
+}} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-new}{}}} +\subsection{Method \code{new()}}{ +Initialize the module +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$new()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-execute}{}}} +\subsection{Method \code{execute()}}{ +Execute Treatment Patterns +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$execute( + connectionDetails, + analysisSpecifications, + executionSettings +)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{connectionDetails}}{An object of class \code{connectionDetails} as created by the +\code{\link[DatabaseConnector:createConnectionDetails]{DatabaseConnector::createConnectionDetails()}} function.} + +\item{\code{analysisSpecifications}}{An object of type \code{AnalysisSpecifications} as created +by \code{\link[=createEmptyAnalysisSpecificiations]{createEmptyAnalysisSpecificiations()}}.} + +\item{\code{analysisSpecifications}}{An object of type \code{AnalysisSpecifications} as created +by \code{\link[=createEmptyAnalysisSpecificiations]{createEmptyAnalysisSpecificiations()}}.} + +\item{\code{executionSettings}}{An object of type \code{ExecutionSettings} as created +by \code{\link[=createCdmExecutionSettings]{createCdmExecutionSettings()}} or \code{\link[=createResultsExecutionSettings]{createResultsExecutionSettings()}}.} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-createResultsDataModel}{}}} +\subsection{Method \code{createResultsDataModel()}}{ +Create the results data model for the module +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$createResultsDataModel( + resultsConnectionDetails, + resultsDatabaseSchema, + tablePrefix = "" +)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{resultsConnectionDetails}}{The connection details to the results database which +is an object of class \code{connectionDetails} as created by the +\code{\link[DatabaseConnector:createConnectionDetails]{DatabaseConnector::createConnectionDetails()}} function.} + +\item{\code{resultsConnectionDetails}}{The connection details to the results database which +is an object of class \code{connectionDetails} as created by the +\code{\link[DatabaseConnector:createConnectionDetails]{DatabaseConnector::createConnectionDetails()}} function.} + +\item{\code{resultsDatabaseSchema}}{The schema in the results database that holds the results data model.} + +\item{\code{tablePrefix}}{A prefix to apply to the database table names (optional).} + +\item{\code{tablePrefix}}{A prefix to apply to the database table names (optional).} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-getResultsDataModelSpecification}{}}} +\subsection{Method \code{getResultsDataModelSpecification()}}{ +Get the results data model specification for the module +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$getResultsDataModelSpecification(tablePrefix = "")}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{tablePrefix}}{A prefix to apply to the database table names (optional).} + +\item{\code{tablePrefix}}{A prefix to apply to the database table names (optional).} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-uploadResults}{}}} +\subsection{Method \code{uploadResults()}}{ +Upload the results for TreatmentPatterns +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$uploadResults( + resultsConnectionDetails, + analysisSpecifications, + resultsDataModelSettings +)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{resultsConnectionDetails}}{The connection details to the results database which +is an object of class \code{connectionDetails} as created by the +\code{\link[DatabaseConnector:createConnectionDetails]{DatabaseConnector::createConnectionDetails()}} function.} + +\item{\code{resultsConnectionDetails}}{The connection details to the results database which +is an object of class \code{connectionDetails} as created by the +\code{\link[DatabaseConnector:createConnectionDetails]{DatabaseConnector::createConnectionDetails()}} function.} + +\item{\code{analysisSpecifications}}{An object of type \code{AnalysisSpecifications} as created +by \code{\link[=createEmptyAnalysisSpecificiations]{createEmptyAnalysisSpecificiations()}}.} + +\item{\code{analysisSpecifications}}{An object of type \code{AnalysisSpecifications} as created +by \code{\link[=createEmptyAnalysisSpecificiations]{createEmptyAnalysisSpecificiations()}}.} + +\item{\code{resultsDataModelSettings}}{The results data model settings as created using [@seealso \code{\link[=createResultsDataModelSettings]{createResultsDataModelSettings()}}]} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-createModuleSpecifications}{}}} +\subsection{Method \code{createModuleSpecifications()}}{ +Creates the TreatmentPatternsnModule Specifications +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$createModuleSpecifications( + cohorts, + cohortTableName, + connectionDetails = NULL, + cdmSchema = NULL, + resultSchema = NULL, + tempEmulationSchema = NULL, + includeTreatments = "startDate", + indexDateOffset = 0, + minEraDuration = 0, + splitEventCohorts = NULL, + splitTime = NULL, + eraCollapseSize = 30, + combinationWindow = 30, + minPostCombinationDuration = 30, + filterTreatments = "First", + maxPathLength = 5, + ageWindow = 5, + minCellCount = 1, + censorType = "minCellCount" +)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{cohorts}}{(\code{data.frame()})\cr +Data frame containing the following columns and data types: +\describe{ +\item{cohortId \code{numeric(1)}}{Cohort ID's of the cohorts to be used in the cohort table.} +\item{cohortName \code{character(1)}}{Cohort names of the cohorts to be used in the cohort table.} +\item{type \code{character(1)} ["target", "event', "exit"]}{Cohort type, describing if the cohort is a target, event, or exit cohort} +}} + +\item{\code{cohortTableName}}{(\code{character(1)})\cr +Cohort table name.} + +\item{\code{connectionDetails}}{(\code{DatabaseConnector::createConnectionDetails()}: \code{NULL})\cr +Optional; In congruence with \code{cdmSchema} and \code{resultSchema}. Ignores \code{cdm}.} + +\item{\code{cdmSchema}}{(\code{character(1)}: \code{NULL})\cr +Optional; In congruence with \code{connectionDetails} and \code{resultSchema}. Ignores \code{cdm}.} + +\item{\code{resultSchema}}{(\code{character(1)}: \code{NULL})\cr +Optional; In congruence with \code{connectionDetails} and \code{cdmSchema}. Ignores \code{cdm}.} + +\item{\code{tempEmulationSchema}}{Schema used to emulate temp tables} + +\item{\code{includeTreatments}}{(\code{character(1)}: \code{"startDate"})\cr +\describe{ +\item{\code{"startDate"}}{Include treatments after the target cohort start date and onwards.} +\item{\code{"endDate"}}{Include treatments before target cohort end date and before.} +}} + +\item{\code{indexDateOffset}}{(\code{integer(1)}: \code{0})\cr +Offset the index date of the \code{Target} cohort.} + +\item{\code{minEraDuration}}{(\code{integer(1)}: \code{0})\cr +Minimum time an event era should last to be included in analysis} + +\item{\code{splitEventCohorts}}{(\code{character(n)}: \code{""})\cr +Specify event cohort to split in acute (< X days) and therapy (>= X days)} + +\item{\code{splitTime}}{(\code{integer(1)}: \code{30})\cr +Specify number of days (X) at which each of the split event cohorts should +be split in acute and therapy} + +\item{\code{eraCollapseSize}}{(\code{integer(1)}: \code{30})\cr +Window of time between which two eras of the same event cohort are collapsed +into one era} + +\item{\code{combinationWindow}}{(\code{integer(1)}: \code{30})\cr +Window of time two event cohorts need to overlap to be considered a +combination treatment} + +\item{\code{minPostCombinationDuration}}{(\code{integer(1)}: \code{30})\cr +Minimum time an event era before or after a generated combination treatment +should last to be included in analysis} + +\item{\code{filterTreatments}}{(\code{character(1)}: \code{"First"} ["first", "Changes", "all"])\cr +Select first occurrence of (‘First’); changes between (‘Changes’); or all +event cohorts (‘All’).} + +\item{\code{maxPathLength}}{(\code{integer(1)}: \code{5})\cr +Maximum number of steps included in treatment pathway} + +\item{\code{ageWindow}}{(\code{integer(n)}: \code{10})\cr +Number of years to bin age groups into. It may also be a vector of integers. +I.e. \code{c(0, 18, 150)} which will results in age group \code{0-18} which includes +subjects \verb{< 19}. And age group \code{18-150} which includes subjects \verb{> 18}.} + +\item{\code{minCellCount}}{(\code{integer(1)}: \code{5})\cr +Minimum count required per pathway. Censors data below \code{x} as \verb{}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-validateModuleSpecifications}{}}} +\subsection{Method \code{validateModuleSpecifications()}}{ +Validate the module specifications +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$validateModuleSpecifications(moduleSpecifications)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{moduleSpecifications}}{The CohortMethod module specifications} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-TreatmentPatternsModule-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{TreatmentPatternsModule$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/man/addTreatmentPatternsModuleSpecifications.Rd b/man/addTreatmentPatternsModuleSpecifications.Rd new file mode 100644 index 0000000..53692b1 --- /dev/null +++ b/man/addTreatmentPatternsModuleSpecifications.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Settings.R +\name{addTreatmentPatternsModuleSpecifications} +\alias{addTreatmentPatternsModuleSpecifications} +\title{Add Treatment Patterns Module specifications to analysis specifications} +\usage{ +addTreatmentPatternsModuleSpecifications( + analysisSpecifications, + moduleSpecifications +) +} +\arguments{ +\item{analysisSpecifications}{An object of type \code{AnalysisSpecifications} as created +by \code{\link[=createEmptyAnalysisSpecificiations]{createEmptyAnalysisSpecificiations()}}.} + +\item{moduleSpecifications}{Created by the "tbd"} +} +\value{ +Returns the \code{analysisSpecifications} object with the module specifications added +} +\description{ +Add Treatment Patterns Module specifications to analysis specifications +} diff --git a/tests/testthat/helper-TreatmentPatterns.R b/tests/testthat/helper-TreatmentPatterns.R new file mode 100644 index 0000000..6d50003 --- /dev/null +++ b/tests/testthat/helper-TreatmentPatterns.R @@ -0,0 +1,92 @@ +ableToRunTreatmentPatterns <- function() { + all( + require("CirceR", character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE), + require("CohortGenerator", character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE), + require("DatabaseConnector", character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE), + require("SqlRender", character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE), + require("Eunomia", character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE) + ) +} + +generateCohortTable <- function() { + if (ableToRunTreatmentPatterns()) { + connectionDetails <- Eunomia::getEunomiaConnectionDetails() + cohortTableName <- "cohort_table" + resultSchema <- "main" + cdmSchema <- "main" + + cohortsToCreate <- CohortGenerator::createEmptyCohortDefinitionSet() + + cohortJsonFiles <- list.files( + system.file( + package = "TreatmentPatterns", + "exampleCohorts"), + full.names = TRUE) + + for (i in seq_len(length(cohortJsonFiles))) { + cohortJsonFileName <- cohortJsonFiles[i] + cohortName <- tools::file_path_sans_ext(basename(cohortJsonFileName)) + cohortJson <- readChar(cohortJsonFileName, file.info( + cohortJsonFileName)$size) + + cohortExpression <- CirceR::cohortExpressionFromJson(cohortJson) + + cohortSql <- CirceR::buildCohortQuery( + cohortExpression, + options = CirceR::createGenerateOptions(generateStats = FALSE)) + cohortsToCreate <- rbind( + cohortsToCreate, + data.frame( + cohortId = i, + cohortName = cohortName, + sql = cohortSql, + stringsAsFactors = FALSE)) + } + + cohortTableNames <- CohortGenerator::getCohortTableNames( + cohortTable = cohortTableName) + + CohortGenerator::createCohortTables( + connectionDetails = connectionDetails, + cohortDatabaseSchema = resultSchema, + cohortTableNames = cohortTableNames) + + # Generate the cohorts + cohortsGenerated <- CohortGenerator::generateCohortSet( + connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmSchema, + cohortDatabaseSchema = resultSchema, + cohortTableNames = cohortTableNames, + cohortDefinitionSet = cohortsToCreate) + + # Select Viral Sinusitis Cohort + targetCohorts <- cohortsGenerated %>% + dplyr::filter(cohortName == "ViralSinusitis") %>% + dplyr::select(cohortId, cohortName) + + # Select everything BUT Viral Sinusitis cohorts + eventCohorts <- cohortsGenerated %>% + dplyr::filter(cohortName != "ViralSinusitis" & cohortName != "Death") %>% + dplyr::select(cohortId, cohortName) + + exitCohorts <- cohortsGenerated %>% + dplyr::filter(cohortName == "Death") %>% + dplyr::select(cohortId, cohortName) + + cohorts <- dplyr::bind_rows( + targetCohorts %>% dplyr::mutate(type = "target"), + eventCohorts %>% dplyr::mutate(type = "event"), + exitCohorts %>% dplyr::mutate(type = "exit") + ) + + return(list( + cohorts = cohorts, + connectionDetails = connectionDetails, + cohortTableName = cohortTableName, + resultSchema = resultSchema, + cdmSchema = cdmSchema + )) + } else { + return(NULL) + } +} diff --git a/tests/testthat/test-TreatmentPatterns.R b/tests/testthat/test-TreatmentPatterns.R new file mode 100644 index 0000000..784d223 --- /dev/null +++ b/tests/testthat/test-TreatmentPatterns.R @@ -0,0 +1,122 @@ +library(testthat) +library(dplyr) + +test_that("TreatmentPatterns: execute method", { + tempDir <- file.path(tempdir(), "Strategus-TP") + on.exit(unlink(tempDir, recursive = TRUE)) + + testSettings <- generateCohortTable() + + tp <- TreatmentPatternsModule$new() + + modSpec <- tp$createModuleSpecifications( + cohorts = testSettings$cohorts, + cohortTableName = testSettings$cohortTableName, + connectionDetails = testSettings$connectionDetails, + resultSchema = "main", + tempEmulationSchema = NULL, + cdmSchema = "main", + includeTreatments = "startDate", + indexDateOffset = 0, + minEraDuration = 7, + splitEventCohorts = NULL, + splitTime = NULL, + eraCollapseSize = 14, + combinationWindow = 7, + minPostCombinationDuration = 7, + filterTreatments = "First", + maxPathLength = 5 + ) + + analysisSpec <- Strategus::createEmptyAnalysisSpecificiations() + + executionSettings <- Strategus::createCdmExecutionSettings( + workDatabaseSchema = testSettings$resultSchema, + cdmDatabaseSchema = testSettings$cdmSchema, + cohortTableNames = list("cohort_table"), + tempEmulationSchema = NULL, + workFolder = tempDir, + resultsFolder = tempDir, + logFileName = "log.txt", + minCellCount = 5, + incremental = FALSE, + maxCores = 1 + ) + + tp$execute( + connectionDetails = testSettings$connectionDetails, + analysisSpecifications = addTreatmentPatternsModuleSpecifications( + analysisSpecifications = analysisSpec, + moduleSpecifications = modSpec + ), + executionSettings = executionSettings + ) + + expect_true(file.exists(file.path(executionSettings$resultsFolder, "attrition.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsAge.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsSex.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsYear.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "metadata.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "summaryEventDuration.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "treatmentPathways.csv"))) +}) + +test_that("TreatmentPatterns: execute function", { + tempDir <- file.path(tempdir(), "Strategus-TP") + on.exit(unlink(tempDir, recursive = TRUE)) + + testSettings <- generateCohortTable() + + tp <- TreatmentPatternsModule$new() + + modSpec <- tp$createModuleSpecifications( + cohorts = testSettings$cohorts, + cohortTableName = testSettings$cohortTableName, + connectionDetails = testSettings$connectionDetails, + resultSchema = "main", + tempEmulationSchema = NULL, + cdmSchema = "main", + includeTreatments = "startDate", + indexDateOffset = 0, + minEraDuration = 30, + splitEventCohorts = NULL, + splitTime = NULL, + eraCollapseSize = 14, + combinationWindow = 30, + minPostCombinationDuration = 30, + filterTreatments = "First", + maxPathLength = 5 + ) + + analysisSpec <- Strategus::createEmptyAnalysisSpecificiations() + + executionSettings <- Strategus::createCdmExecutionSettings( + workDatabaseSchema = testSettings$resultSchema, + cdmDatabaseSchema = testSettings$cdmSchema, + cohortTableNames = list("cohort_table"), + tempEmulationSchema = NULL, + workFolder = tempDir, + resultsFolder = tempDir, + logFileName = "log.txt", + minCellCount = 5, + incremental = FALSE, + maxCores = 1 + ) + + Strategus::execute( + connectionDetails = testSettings$connectionDetails, + analysisSpecifications = addTreatmentPatternsModuleSpecifications( + analysisSpecifications = analysisSpec, + moduleSpecifications = modSpec + ), + executionSettings = executionSettings + ) + + expect_true(file.exists(file.path(executionSettings$resultsFolder, "attrition.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsAge.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsSex.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "countsYear.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "metadata.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "summaryEventDuration.csv"))) + expect_true(file.exists(file.path(executionSettings$resultsFolder, "treatmentPathways.csv"))) +})