print_fr <- FALSE
print_en <- FALSE
print_pt <- FALSE
if (params$lang == "fr") {
  print_fr <- TRUE
  title <- "Naomi rapport de synthèse"
} else if (params$lang == "pt") {
  print_pt <- TRUE
  title <- "Naomi relatório de síntese"
} else {
  print_en <- TRUE
  title <- "Naomi summary report"
}

title: r title

#Set limit for scientific notation
options(scipen=10000000)

# Read files if hintr rds provided
if(tolower(tools::file_ext(params$outputs)) %in% c("rds", "qs")) {

  model_object <- read_hintr_output(params$outputs)
  outputs <- model_object$output_package
  inputs <- readr::read_csv(model_object$info$inputs.csv)
  options <- yaml::read_yaml(text = model_object$info$options.yml)

  calibration_files <- names(model_object$info)
  if("calibration_options.yml" %in% calibration_files) {
    calibration_options <- yaml::read_yaml(text = model_object$info$calibration_options.yml)
  } else {
    # In the event there is no calibration options, add in defaults:
    calibration_options <- tibble::tribble( ~option, ~value, 
                                    "spectrum_population_calibration", "none",         
                                    "spectrum_plhiv_calibration_level","subnational", 
                                    "spectrum_plhiv_calibration_strat","sex_age_group",
                                    "spectrum_artnum_calibration_level","national",     
                                    "spectrum_artnum_calibration_strat","age_coarse",   
                                    "spectrum_aware_calibration_level","national",     
                                    "spectrum_aware_calibration_strat","age_coarse",   
                                    "spectrum_infections_calibration_level","none",         
                                    "spectrum_infections_calibration_strat","age_coarse",  
                                    "calibrate_method","logistic")
  }
}
# Read files if zipped output package provided
if(grepl("\\.zip$", params$outputs)) {
  output_zip <- params$outputs
  outputs <- naomi::read_output_package(output_zip)
  inputs <- unz(output_zip, "info/inputs.csv") 
  inputs <- utils::read.csv(inputs)
  options <- unz(output_zip, "info/options.yml")
  options <- yaml::read_yaml(options)


  if("calibration_options" %in% names(outputs$fit)) {
    calibration_options <- outputs$fit$calibration_options
  } else {
    calibration_options <- options[grep("calibration", names(options))]
  }
}

# Grab inputs and model options from model output zip file
# # concatenating strings where more than one option may be selected
report_date <- format(Sys.Date(), "%d-%m-%Y")
t1 <- options$calendar_quarter_t1
t2 <- options$calendar_quarter_t2
iso <- options$area_scope
quarter_t1 <- outputs$meta_period[outputs$meta_period$calendar_quarter == t1,]$quarter_label
quarter_t2 <- outputs$meta_period[outputs$meta_period$calendar_quarter == t2,]$quarter_label
level <- as.integer(options$area_level)
spectrum_file <- paste0(inputs[inputs$role == "pjnz",]$filename)


# Filter data for specific analytics
indicators <- naomi::add_output_labels(outputs) 
indicators_geom <- naomi::add_output_labels(outputs, geometry = TRUE)

# Identify area_level_label for model estimates
area_level_map <- outputs$meta_area %>%
  sf::st_drop_geometry() %>%
  dplyr::group_by(area_level, area_level_label) %>%
  dplyr::summarise(.groups = "drop")

area_level_label <- area_level_map$area_level_label[area_level_map$area_level == level]

country <- paste0(outputs$meta_area$area_name[outputs$meta_area$area_id == iso],
                  sep = "", collapse = "")


# Filter indicator data for area + calendar options selected in model run 
data <- dplyr::filter(indicators, area_level == level, calendar_quarter == t2)
# Number of districts in lowest area level
district_count <- length(levels(as.factor(data$area_name)))

# Determine if and when programme data has been included 
if (is.null(options$include_art_t1) || options$include_art_t1 == "") {
  options$include_art_t1 <- NA
}
if (is.null(options$include_art_t2) || options$include_art_t2 == "") {
  options$include_art_t2 <- NA
}

if (is.null(quarter_t1) || quarter_t1 == "") {
  quarter_t1 <- NA
}
if (is.null(quarter_t2) || quarter_t2 == "") {
  quarter_t2 <- NA
}

if (is.null(options[["artattend"]]) || options[["artattend"]] == "") {
  options[["artattend"]] <- NA
}
if (is.null(options[["artattend_t2"]]) || options[["artattend_t2"]] == "") {
  options[["artattend_t2"]] <- NA
}

include <- tibble::tibble(
  art = c(options$include_art_t1, options$include_art_t2),
  art_year = c(quarter_t1, quarter_t2),
  art_attend = c(options$artattend, options$artattend_t2)
)

# Select years where programme data is included
collapse_and <- " and "
if (print_fr) { collapse_and <- " et "} else if (print_pt) { collapse_and <- " e "}

# ART data included
if("true" %in% include$art) {
  df <- include %>% dplyr::filter(art == "true")
  art_year <- paste0(df$art_year, sep = "", collapse = collapse_and)
} else {
  art_year <- NA
}

# ART attendance reallocation is implemented
if("true" %in% include$art_attend ) {
  df <- include %>% dplyr::filter(art_attend == "true")
  art_attend <- paste0(df$art_year, sep = "", collapse = collapse_and)
} else {
  art_attend <- NA
}

# ANC ART programme data included
anc_art_options = list(options$anc_art_coverage_year1, options$anc_art_coverage_year2) 
anc_art_options <- anc_art_options[!sapply(anc_art_options,is.null)]

if(length(anc_art_options)) {
  anc_art <- paste0(anc_art_options, sep = "", collapse = collapse_and)
} else {
  anc_art <- NA
}

# ANC prev programme data
anc_prev_options = list(options$anc_prevalence_year1,options$anc_prevalence_year2)
anc_prev_options <- anc_art_options[!sapply(anc_art_options,is.null)]

if(length(anc_prev_options)) {
  anc_prev <- paste0(anc_prev_options, sep = "", collapse = collapse_and)
} else {
  anc_prev <- NA
}
if (print_en) {
  cat(paste0("# ", country, " Subnational HIV Estimates \n"))
  cat(paste0("### **", quarter_t2, "** (report ", report_date, ")"))
}

if (print_fr) {
  cat(paste0("# Estimations infranationales du VIH ", country, " \n"))
  cat(paste0("### **", quarter_t2, "** (rapport ", report_date, ")"))
}

if (print_pt) {
  cat(paste0("# Estimativas subnacionais do VIH ", country, "\n"))
  cat(paste0("### **", quarter_t2, "** (relatório ", report_date, ")"))
}

``` {r, echo = FALSE, results = 'asis'}

if (print_en) { cat(paste0("This report summarises the ", area_level_label, "-level HIV indicators for ", country, " from the Naomi model", sep = "\n")) }

if (print_fr) { cat(paste0("Ce rapport résume les ", area_level_label, " indicateurs VIH pour ",country, " du modèle Naomi", sep = "\n")) }

if (print_pt) { cat(paste0("Este relatório resume os Indicadores de VIH ", area_level_label, " para ", country, " a partir do modelo Naomi", sep = "\n")) }

```r

if (print_en) {
  cat("Naomi is a statistical model that uses data from several sources, including:  \n")
  cat("\nNational survey data:   \n")
}

if (print_fr) {
  cat("Naomi est un modèle statistique qui utilise des données provenant de plusieurs sources, notamment:  \n")
  cat("\nDonnées d'enquête nationales:   \n")
}

if (print_pt) {
  cat("Naomi é um modelo estatístico que utiliza dados de várias fontes, incluindo:  \n")
  cat("\nDados de inquéritos nacionais:   \n")
}
survey_prev <- paste0(options$survey_prevalence, collapse = ", ")
survey_art <- paste0(options$survey_art_coverage, collapse = ", ")
survey_recent <- paste0(options$survey_recently_infected, collapse = ", ")

text <- tibble::tibble(prefix = c(t_("INFECTIONS_SURVEY_PREFIX"), 
                                  t_("PREVALENCE_SURVEY_PREFIX"), 
                                  t_("ART_SURVEY_PREFIX")), 
                        source = c(survey_recent,
                                   survey_prev,
                                   survey_art)) %>%
  dplyr::filter(source != "")
cat(paste0("* ", text$prefix, " _", text$source, "_"), sep = "\n")
programme_data <- c(art_year, anc_prev, anc_art)

if (sum(is.na(programme_data)) <3 ) {

  cat(paste0("\n Operational programme data: \n", sep = "\n"))

  text2 <- tibble::tibble(prefix = c("National programme data on ART coverage for ",
                                  "National programme data on ANC HIV prevalence for ", 
                                  "National programme data on ANC ART coverage for "
                                  ), 
                       source = c(art_year,
                                  anc_prev, 
                                  anc_art)) %>% tidyr::drop_na()

  cat(paste0("\n ",cat(paste0("* ", text2$prefix, "_", text2$source, "_"), sep = "\n")))

}

 cat(paste0("\n and national HIV estimates from Spectrum file _", spectrum_file,"_",
           "\n using calibration options: \n " ))
programme_data <- c(art_year, anc_prev, anc_art)

if (sum(is.na(programme_data)) <3 ) {

  cat(paste0("\n Données du programme opérationnel: \n", sep = "\n"))

  text2 <- tibble::tibble(prefix = c("Données national sur la couverture TARV pour ",
                                  "Données national sur la prévalence du VIH parmi CPN pour ", 
                                  "Données national sur la couverture du TARV parmi CPN pour "
                                  ), 
                       source = c(art_year,
                                  anc_prev, 
                                  anc_art)) %>% tidyr::drop_na()

  cat(paste0("\n ",cat(paste0("* ", text2$prefix, "_", text2$source, "_"), sep = "\n")))

}

 cat(paste0("\n et estimations nationales du VIH à partir du fichier Spectrum _", spectrum_file,"_",
           "\n à l'aide des options d'étalonnage: \n " ))
programme_data <- c(art_year, anc_prev, anc_art)

if (sum(is.na(programme_data)) <3 ) {

  cat(paste0("\n Dados do programa operacional: \n", sep = "\n"))

  text2 <- tibble::tibble(prefix = c("Dados do programa nacional sobre a cobertura de TARV para ",
                                  "Dados do programa nacional sobre a prevalência de VIH na CPN para ", 
                                  "Dados do programa nacional sobre a cobertura de TARV na CPN para "
                                  ), 
                       source = c(art_year,
                                  anc_prev, 
                                  anc_art)) %>% tidyr::drop_na()

  cat(paste0("\n ",cat(paste0("* ", text2$prefix, "_", text2$source, "_"), sep = "\n")))

}

 cat(paste0("\n e estimativas nacionais de VIH do ficheiro Spectrum _", spectrum_file,"_",
           "\n usando opções de calibração: \n " ))
# Translate calibration options to human readable
calibration_options <- naomi.options::get_calibration_option_labels(calibration_options)
calibration_df <- stack(calibration_options)

text <- tibble::tribble(
  ~key,         ~prefix,
  "spectrum_population_calibration", t_("POPULATION_CALIBRATION_LEVEL_LABEL"),
  "spectrum_plhiv_calibration_level", t_("PLHIV_CALIBRATION_LEVEL_LABEL"), 
  "spectrum_plhiv_calibration_strat",  t_("PLHIV_CALIBRATION_STRATA_LABEL"),
  "spectrum_aware_calibration_level", t_("STATUS_CALIBRATION_LEVEL_LABEL"),
  "spectrum_aware_calibration_strat",  t_("STATUS_CALIBRATION_STRATA_LABEL"),
  "spectrum_artnum_calibration_level",  t_("ARTNUM_CALIBRATION_LEVEL_LABEL"), 
  "spectrum_artnum_calibration_strat",    t_("ARTNUM_CALIBRATION_STRATA_LABEL"), 
  "spectrum_infections_calibration_level", t_("INFECTIONS_CALIBRATION_LEVEL_LABEL"),
  "spectrum_infections_calibration_strat",  t_("INFECTIONS_CALIBRATION_STRATA_LABEL"), 
  "calibrate_method",                      t_("CALIBRATE_METHOD_LABEL")) %>%
  dplyr::left_join(calibration_df, by = c("key" = "ind")) %>%
  dplyr::mutate(values = tidyr::replace_na(values, "None"))


# Filter out strata options if calibration not selected
if(is.null(calibration_options$spectrum_plhiv_calibration_level)){
  text <- dplyr::filter(text, !grepl("plhiv", key)) }

if(is.null(calibration_options$spectrum_aware_calibration_level)){
  text <- dplyr::filter(text, !grepl("aware", key)) }

if(is.null(calibration_options$spectrum_artnum_calibration_level)){
  text <- dplyr::filter(text, !grepl("artnum", key)) }

if(is.null(calibration_options$spectrum_infections_calibration_level)){
  text <- dplyr::filter(text, !grepl("infections", key)) }

if(nrow(text) > 0) {
  cat(paste0("* ", text$prefix, " _", text$values, "_"), sep = "\n")
} else {
  if (print_en) {no_calibration <- "No calibration selected"}
  if (print_fr) {no_calibration <- "Aucun étalonnage sélectionné"}
  if (print_pt) {no_calibration <- "Nenhuma calibração selecionada"}
  cat(paste0("* ", no_calibration), sep = "\n")
}
if ("true" %in% include$art_attend) {

  cat(paste0("ART coverage is estimated accounting for patient mobility between
             neighbouring districts (for ", art_attend, ").
             \n This takes into account 
             where patients reside as opposed to the location of the clinic they attended.
             \n Further technical information about this allocation method
             and the Naomi model is available at the end of this report."))
} else {

  cat(paste0("Further technical information about the Naomi model is available 
             at the end of this report."))
}
if ("true" %in% include$art_attend) {

  cat(paste0("La couverture du TARV est estimée en tenant compte de la mobilité 
  des patients entre les districts voisins (pour ", art_attend, "). 
  \n Cela prend en compte leur lieu de résidence par opposition à
  l'emplacement de la clinique qu'ils ont fréquentée
  \n De plus amples informations techniques sur cette méthode 
  d'allocation et le modèle Naomi sont disponibles à la fin de ce rapport."))
} else {

  cat(paste0("De plus amples informations techniques sur cette méthode 
             d'allocation et le modèle Naomi sont disponibles à la fin de ce rapport."))
}
if ("true" %in% include$art_attend) {

  cat(paste0("A cobertura de TARV é estimada considerando a mobilidade dos 
              pacientes entre distritos vizinhos (para ", art_attend, ").
             \n Isto tem em conta o seu local de residência e não a 
             localização da clínica que frequentavam.
             \n Mais informações técnicas sobre este método de alocação e o 
             modelo Naomi estão disponíveis no final deste relatório."))
} else {

  cat(paste0("Mais informações técnicas sobre este método de alocação e o 
             modelo Naomi estão disponíveis no final deste relatório."))
}
if (print_en) { cat("### **Geographic distribution of PLHIV**") }
if (print_fr) { cat("### **Répartition géographique des PVVIH**") }
if (print_pt) { cat("### **Distribuição geográfica de PVVIH**") }
#-------------------------------------------------------------------------------
# Map: PLHIV (mean)
# # By lowest area_level
#-------------------------------------------------------------------------------
p1 <- naomi::map_outputs(indicators_geom, 
                         indicator = "plhiv",
                         age = "Y015_999", 
                         calendar_quarter = options$calendar_quarter_t2,
                         sex_disag = "both", 
                         colour_palette = "red",
                         fig_title = t_("PLHIV_MAP_PLOT_TITLE"),
                         legend_title = t_("PLHIV"))

#-------------------------------------------------------------------------------
# Map: on ART
# # By lowest area_level
#-------------------------------------------------------------------------------
p2 <- naomi::map_outputs(indicators_geom, 
                         indicator = "art_current_residents",
                         age = "Y015_999",                          
                         calendar_quarter = options$calendar_quarter_t2,
                         sex_disag = "both", 
                         colour_palette = "green",
                         fig_title = t_("ART_CURRENT_MAP_PLOT_TITLE"),
                         legend_title = t_("ART_NUMBER_RESIDENTS"))

#-------------------------------------------------------------------------------
# Map: new infections (mean)
# # By lowest area_level
#-------------------------------------------------------------------------------
p3 <- naomi::map_outputs(indicators_geom, 
                         indicator = "infections",
                         age = "Y015_999", 
                         calendar_quarter = options$calendar_quarter_t2,
                         sex_disag = "both", 
                         colour_palette = "blue",
                         fig_title = t_("INFECTIONS_MAP_PLOT_TITLE"),
                         legend_title = t_("NEW_INFECTIONS"))


grid::grid.draw(cbind(ggplot2::ggplotGrob(p1), ggplot2::ggplotGrob(p2), 
                      ggplot2::ggplotGrob(p3)))
if (print_en) {cat("### **Geographic distribution of rates of HIV infection**")}
if (print_fr) {cat("### **Répartition géographique des taux d'infection par le VIH**")}
if (print_pt) {cat("### **Distribuição geográfica das taxas de infeção pelo VIH**")}
#-------------------------------------------------------------------------------
# Map: Prevalence (mean)
# # By lowest area_level
#-------------------------------------------------------------------------------
p4 <- naomi::map_outputs(indicators_geom, 
                         indicator = "prevalence",
                         age = "Y015_049", 
                         sex_disag = "both", 
                         calendar_quarter = options$calendar_quarter_t2,
                         colour_palette = "red",
                         legend_label = scales::percent_format(1L), 
                         fig_title = t_("PREVALENCE_MAP_PLOT_TITLE"),
                         legend_title = t_("HIV_PREVALENCE"))

#-------------------------------------------------------------------------------
# Map: ART coverage (mean)
# # By lowest area_level
#-------------------------------------------------------------------------------
p5 <- naomi::map_outputs(indicators_geom, 
                         indicator = "art_coverage",
                         age = "Y015_999", 
                         sex_disag = "both", 
                         calendar_quarter = options$calendar_quarter_t2,
                         colour_palette = "green",
                         legend_label = scales::percent_format(accuracy = 1L), 
                         fig_title = t_("ART_COVERAGE_MAP_PLOT_TITLE"),
                         legend_title = t_("ART_COVERAGE")
)

#-------------------------------------------------------------------------------
# Map: Incidence
# # By lowest area_level
#-------------------------------------------------------------------------------
p6 <- naomi::map_outputs(indicators_geom, 
                         indicator = "incidence",
                         age = "Y015_049", 
                         sex_disag = "both", 
                         calendar_quarter = options$calendar_quarter_t2,
                         colour_palette = "blue",
                         legend_label = scales::label_number(0.1, 1000), 
                         fig_title = t_("INCIDENCE_MAP_PLOT_TITLE"),
                         legend_title = t_("INCIDENCE_MAP_LEGEND_TITLE"))

grid::grid.draw(cbind(ggplot2::ggplotGrob(p4), ggplot2::ggplotGrob(p5), 
                      ggplot2::ggplotGrob(p6)))
if (print_en) {cat("### **Distribution of HIV by age and sex**")}
if (print_fr) {cat("### **Répartition du VIH par âge et par sexe**")}
if (print_pt) {cat("### **Distribuição do VIH por idade e género**")}
#-------------------------------------------------------------------------------
# Pop Pyramid: PLHIV (mean)
# # By age and sex (15-49)
#-------------------------------------------------------------------------------
p7 <- pop_pyramid_outputs(naomi_output = outputs,
                          indicator = "plhiv",
                          colour_palette = "red",
                          x_title = t_("PLHIV"),
                          fig_title = t_("PLHIV_POP_PYRAMID_PLOT_TITLE"))


#-------------------------------------------------------------------------------
# Pop Pyramid: On ART (mean)
# # By age and sex (15-49)
#-------------------------------------------------------------------------------
p8 <- pop_pyramid_outputs(naomi_output = outputs, 
                          indicator = "art_current_residents",
                          colour_palette = "green",
                          x_title = t_("ART_POP_PYRAMID_X_AXIS"),
                          fig_title = t_("ART_POP_PYRAMID_PLOT_TITLE"))

p8 <- p8 + ggplot2::theme(
  axis.title.y = ggplot2::element_blank(),
  axis.text.y = ggplot2::element_blank(),
  axis.ticks.y = ggplot2::element_blank())

#-------------------------------------------------------------------------------
# Pop Pyramid: New Infections
# # By age and sex (15-49)
#-------------------------------------------------------------------------------
p9 <- pop_pyramid_outputs(naomi_output = outputs,
                          indicator = "infections",
                          colour_palette = "blue",
                          x_title = t_("INFECTIONS_POP_PYRAMID_X_AXIS"),
                          fig_title = t_("INFECTIONS_POP_PYRAMID_PLOT_TITLE"))

p9 <- p9 + ggplot2::theme(
  axis.title.y = ggplot2::element_blank(),
  axis.text.y = ggplot2::element_blank(),
  axis.ticks.y = ggplot2::element_blank())

# Plot figs together
 grid::grid.draw(cbind(ggplot2::ggplotGrob(p7), ggplot2::ggplotGrob(p8), 
                      ggplot2::ggplotGrob(p9)))
if(print_en){cat(paste0("### **", area_level_label, "-level HIV trends**"))}
if(print_fr){cat(paste0("### **Tendances du VIH au niveau ", area_level_label, "**"))}
if(print_pt){cat(paste0("### **Tendências de VIH de nível ", area_level_label, "**"))}
## Dynamically size plot based on number of districts

if (district_count <= 35) {height <- 8}
if (district_count > 35 && district_count <= 65) {height <- 10}
if (district_count > 65 && district_count <= 125) {height <- 14}
if (district_count > 125 && district_count <= 160) {height <- 20}
if (district_count > 160) {height <- 24}

``` {r, echo=FALSE, warning = FALSE, result = "asis", fig.height = height, fig.width = 12}

-----------------------------------------------------------------------------

Barplot: Prevalence

# By lowest area_level, descending, compared to national indicator

-----------------------------------------------------------------------------

p13 <- district_barplot(naomi_output = outputs, indicator = "prevalence", age = "Y015_049", sex_disag = "both", label_format = scales::percent_format(1), colour_palette = "red", x_title = t_("HIV_PREVALENCE"), fig_title = t_("PREVALENCE_DISTRICT_BARPLOT_PLOT_TITLE"), legend_title = t_("PREVALENCE_LEGEND_TITLE"))

-------------------------------------------------------------------------------

Barplot: ART coverage

# By lowest area_level, descending, compared to national indicator

--------------------------------------------------------------------------------

p14 <- district_barplot(naomi_output = outputs, indicator = "art_coverage", age = "Y015_999", sex_disag = "both", label_format = scales::percent_format(1), colour_palette = "green", x_title = t_("ART_COVERAGE"), fig_title = t_("ART_DISTRICT_BARPLOT_PLOT_TITLE"), legend_title = t_("ART_LEGEND_TITLE"))

-----------------------------------------------------------------------------

Barplot: Incidence per 1000

# By lowest area_level, descending, compared to national indicator

-----------------------------------------------------------------------------

p15 <- district_barplot(naomi_output = outputs, indicator = "incidence", age = "Y015_049", sex_disag = "both", label_format = scales::percent_format(0.01, 1000), colour_palette = "blue", x_title = t_("INCIDENCE"), fig_title = t_("INCIDENCE_DISTRICT_BARPLOT_PLOT_TITLE"), legend_title = t_("INCIDENCE_LEGEND_TITLE"))

Plot figs together

grid::grid.draw(cbind(ggplot2::ggplotGrob(p13), ggplot2::ggplotGrob(p14), ggplot2::ggplotGrob(p15)))

```r
if (print_en) {cat(paste0("### **", area_level_label, "-level indicators**"))}
if (print_fr) {cat(paste0("### **Indicateurs de niveau ", area_level_label, "**"))}
if (print_pt) {cat(paste0("### **Indicadores de nível ", area_level_label, "**"))}

``` {r, echo = FALSE, warning = FALSE, results = 'asis'}

# Format data for table

percent_indicators <- c("prevalence", "art_coverage") whole_indicators <- c("plhiv", "infections", "art_current", "art_current_residents")

Scaling factor

display_scale <- c("prevalence" = 100, "art_coverage" = 100, "incidence" = 1000, "plhiv" = 1, "infections" = 1, "art_current" = 1, "art_current_residents" = 1)

Number of digits to round by; applied after scaling.

display_digits <- c("prevalence" = 1, "art_coverage" = 1, "incidence" = 1, "plhiv" = -2, "infections" = -1, "art_current" = -2, "art_current_residents" = -2)

display_suffix <- c("prevalence" = "%", "art_coverage" = "%", "incidence" = "", "plhiv" = "", "infections" = "", "art_current" = "", "art_current_residents" = "")

This controls whether uncertainty range is shown

display_fmt <- c("prevalence" = "%s%s (%s-%s%s)", "art_coverage" = "%s%s (%s-%s%s)", "incidence" = "%s%s (%s-%s%s)", "plhiv" = "%s%s (%s-%s%s)", "infections" = "%s%s (%s-%s%s)", "art_current_residents" = "%s%s (%s-%s%s)", "art_current" = "%s%s")

indicators_15to49 <- c("prevalence", "incidence") indicators_15plus <- c("art_coverage", "plhiv", "infections", "art_current", "art_current_residents")

x1 <- indicators %>% dplyr::filter(calendar_quarter == t2) %>% dplyr::filter( sex == "both", age_group == "Y015_049" & indicator %in% indicators_15to49 | age_group == "Y015_999" & indicator %in% indicators_15plus ) %>% dplyr::left_join( sf::st_drop_geometry(outputs$meta_area) %>% dplyr::select(area_id, area_sort_order), by = "area_id" ) %>% dplyr::mutate(area_id = forcats::fct_reorder(area_id, area_sort_order)) %>% dplyr::select(area_id, area_level_label, area_level, area_name, mean, lower, upper, indicator)

Format values

format_value <- function(x, indicator) { val <- round(x * display_scale[indicator], display_digits[indicator]) mapply(format, val, trim = TRUE, scientific = FALSE, nsmall = pmax(display_digits[indicator], 0), big.mark = ",") }

x1$mean <- format_value(x1$mean, x1$indicator) x1$lower <- format_value(x1$lower, x1$indicator) x1$upper <- format_value(x1$upper, x1$indicator) x1$suffix <- display_suffix[x1$indicator] x1$fmt <- display_fmt[x1$indicator]

x1$val <- sprintf(x1$fmt, x1$mean, x1$suffix, x1$lower, x1$upper, x1$suffix)

Melt data in table

x2 <- x1 %>% dplyr::select(area_id, area_level_label, area_level, area_name, val, indicator) %>% tidyr::spread(indicator, val) %>% dplyr::select(area_level_label, area_level, area_name, plhiv, prevalence, infections, incidence, art_coverage, art_current_residents, art_current )

``` {r, echo = FALSE, warning = FALSE, results = 'asis'}
# #-----------------------------------------------------------------------------
# # Table: ART
# # # By lowest area_level, indicators defined above
# #-----------------------------------------------------------------------------

 x2 %>%
  dplyr::group_by(area_level_label) %>%
  dplyr::arrange(area_level, area_name) %>%
  dplyr::select(-c(area_level)) %>%
  gt::gt(rowname_col = "area_name") %>%
  gt::tab_stubhead(label = gt::md(t_("AREA_TABLE_HEADING"))) %>%
  gt::tab_options(
    table.align = "left",
    heading.align = "centre",
    column_labels.font.size = "small",
    column_labels.background.color = "grey",
    table.font.size = "smaller",
    data_row.padding = gt::px(3),
    row_group.background.color = "lightgrey"
  ) %>%
  gt::tab_spanner(
    label = gt::md(t_("HIV_DISTRIBUTION_TABLE_HEADING")),
    columns = c('plhiv', 'prevalence')) %>%
  gt::tab_spanner(
    label = gt::md(t_("INFECTION_TABLE_HEADING")),
    columns = c('incidence', 'infections')) %>%
  gt::tab_spanner(
    label = gt::md(t_("ART_TABLE_HEADING")),
    columns = c('art_coverage', 'art_current_residents', 'art_current')) %>%
  gt::cols_label(
    plhiv = gt::md(t_("PLHIV_TABLE_HEADING")),
    prevalence = gt::md(t_("HIV_PREVALENCE_TABLE_HEADING")),
    infections = gt::md(t_("INFECTION_TABLE_SUBHEADING")),
    incidence = gt::md(t_("INCIDENCE_TABLE_SUBHEADING")),
    art_coverage = gt::md(t_("ART_TABLE_SUBHEADING")),
    art_current = gt::md(t_("ART_CLIENT_TABLE_SUBHEADING")),
    art_current_residents = gt::md(t_("ART_RESIDENT_TABLE_SUBHEADING"))
  ) %>%
  gt::cols_align(align = "center") %>%
  gt::cols_width(everything()~ px(155))

::: {#translate lang="en"}

Methods

Naomi is a small-area estimation model for estimating HIV prevalence and PLHIV, ART coverage, and new HIV infections at district level by sex and five-year age group. The model combines district-level data about multiple outcomes from several sources in a Bayesian statistical model to produce robust indicators of subnational HIV burden.

The model produces estimates at three time points: the year of the most recent population-based survey, the current period at which the most recent ART and ANC programme data are available, and short-term one-year ahead projections for HIV programme planning purposes. Subnational population estimates by sex and age group are sourced from consensus sources in each country and adjusted to match the populations used within Spectrum by sex and age group.

Survey data

Cross-sectional estimates for HIV prevalence, ART coverage, and HIV incidence are produced at the mid-point of the most recent nationally representative household survey. For HIV prevalence, the model is calibrated to survey data about HIV prevalence by subnational level, sex, and five-year age group from the most recent population-based survey (for example Population HIV Impact Assessment survey or Demographic and Health Survey). Since the survey sample size in each district is relatively small, routinely reported data about HIV prevalence among pregnant women attending their first antenatal care visit, extracted from the national health information system, are used to improve estimates of the spatial pattern of HIV.

ART Coverage

Antiretroviral therapy coverage by district, age, and sex is estimated from household survey data about the presence of antiretroviral biomarkers in HIV-positive survey respondents. Routinely reported antiretroviral therapy coverage among pregnant women prior to first antenatal care visit is used as a covariate for the spatial pattern of antiretroviral therapy coverage. The antiretroviral therapy coverage and HIV prevalence are also calibrated so that total number on antiretroviral therapy matches that report in the Spectrum national file. :::

::: {#translate lang="fr"}

Méthodes

Naomi est un modèle d'estimation à petite échelle permettant d'estimer la prévalence du VIH et des PVVIH, la couverture TARV et les nouvelles infections par le VIH au niveau du district par sexe et par groupe d'âge de cinq ans. Le modèle combine des données au niveau du district sur des résultats multiples provenant de plusieurs sources dans un modèle statistique bayésien pour produire des indicateurs robustes de la charge du VIH au niveau sous-national.

Le modèle produit des estimations à trois moments : l'année de l'enquête démographique la plus récente, la période actuelle à laquelle les données les plus récentes sur les programmes de traitement antirétroviral et de soins prénatals sont disponibles, et des projections à court terme, un an à l'avance, à des fins de planification des programmes de lutte contre le VIH. Les estimations de la population infranationale par sexe et groupe d'âge proviennent de sources consensuelles dans chaque pays et sont ajustées pour correspondre aux populations utilisées dans Spectrum par sexe et groupe d'âge.

Données d'enquête

Les estimations transversales de la prévalence du VIH, de la couverture du traitement antirétroviral et de l'incidence du VIH sont produites à mi-parcours de l'enquête sur les ménages la plus récente et la plus représentative au niveau national. Pour la prévalence du VIH, le modèle est calibré à partir des données d'enquête sur la prévalence du VIH par niveau sous-national, par sexe et par groupe d'âge de cinq ans de l'enquête la plus récente auprès de la population (par exemple l'enquête d'évaluation de l'impact du VIH sur la population ou l'enquête démographique et sanitaire). Étant donné que la taille de l'échantillon de l'enquête dans chaque district est relativement faible, les données régulièrement communiquées sur la prévalence du VIH parmi les femmes enceintes qui se rendent à leur première visite de soins prénatals, extraites du système national d'information sanitaire, sont utilisées pour améliorer les estimations de la répartition spatiale du VIH.

Couverture TARV

La couverture de la thérapie antirétrovirale par district, âge et sexe est estimée à partir des données de l'enquête sur les ménages concernant la présence de biomarqueurs antirétroviraux chez les répondants séropositifs. La couverture de la thérapie antirétrovirale signalée de façon routinière chez les femmes enceintes avant la première visite de soins prénatals est utilisée comme covariable pour le modèle spatial de la couverture de la thérapie antirétrovirale. La couverture de la thérapie antirétrovirale et la prévalence du VIH sont également calibrées de manière à ce que le nombre total de personnes sous thérapie antirétrovirale corresponde à celui déclaré dans le fichier national Spectrum. :::

::: {#translate lang="pt"}

Métodos

Naomi{target="_blank"} é um modelo de estimativa de pequena área para estimar a prevalência de VIH e o número de PVVIH, cobertura de TARV e novas infeções por VIH a nível distrital por género e grupo etário de cinco anos. O modelo combina dados de nível distrital sobre resultados múltiplos de várias fontes num modelo estatístico Bayesiano para produzir indicadores robustos da carga subnacional do VIH.

O modelo produz estimativas em três momentos: o ano do inquérito mais recente com base na população, o período atual em que os dados mais recentes dos programas de TARV e CPN estão disponíveis e projeções a curto prazo com um ano de antecedência para fins de planeamento do programa do VIH. As estimativas da população subnacional por género e grupo etário são obtidas de fontes consensuais em cada país e ajustadas para corresponder às populações utilizadas no âmbito do Spectrum por género e grupo etário.

Dados de inquérito

As estimativas transversais da prevalência de VIH, cobertura de TARV e incidência de VIH são produzidas no ponto médio do mais recente inquérito a agregados familiares nacionalmente representativo. Para a prevalência de VIH, o modelo é calibrado para obter dados sobre a prevalência de VIH por nível subnacional, género e grupo etário de cinco anos do inquérito mais recente com base na população (por exemplo Population HIV Impact Assessment survey ou Demographic and Health Survey). Uma vez que o tamanho da amostra do inquérito em cada distrito é relativamente pequeno, os dados rotineiramente relatados sobre a prevalência de VIH entre as mulheres grávidas que vão à sua primeira consulta pré-natal, extraídos do sistema nacional de informação de saúde, são usados para melhorar as estimativas do padrão espacial do VIH.

Cobertura de TARV

A cobertura da terapia antirretroviral por distrito, idade e género é estimada a partir de dados de inquéritos a agregados familiares sobre a presença de biomarcadores antirretrovirais nos inquiridos seropositivos. A cobertura da terapia antirretroviral relatada rotineiramente entre mulheres grávidas antes da primeira consulta pré-natal é utilizada como covariável para o padrão espacial de cobertura da terapia antirretroviral. A cobertura da terapia antirretroviral e a prevalência do VIH também são calibradas de modo a que o número total de pessoas em terapia antirretroviral corresponda ao que consta do ficheiro nacional Spectrum. :::

if("true" %in% include$art_attend) {

  cat(paste0("
_ART attendance in neighbouring districts_\n 

A challenge for estimating treatment coverage at district level is that persons may access antiretroviral therapy services in a different district than their residence, for example if facilities are closer or perceived to provide better services. The model allows for a probability that resident people living with HIV access antiretroviral therapy in a neighbouring district. The prior assumption is that the large majority of people living with HIV will access antiretroviral therapy in their district of residence, but this probability can vary based on district data about the number receiving antiretroviral therapy compared to HIV prevalence, antiretroviral therapy coverage and population.


             "))
}
if("true" %in% include$art_attend) {

  cat(paste0("
_Fréquentation du TARV dans les districts voisins_\n 

Un défi dans la estimation de la couverture du traitement au niveau du district est que les personnes peuvent accéder les services de thérapie antirétrovirale dans un district différent de leur résidence, par exemple si les établissements sont plus proches ou perçus comme offrant de meilleurs services. Le modèle tient compte de la probabilité que les résidents vivant avec le VIH aient accès à une thérapie antirétrovirale dans un district voisin. L'hypothèse antérieure est que la grande majorité des personnes vivant avec le VIH auront accès au traitement antirétroviral dans leur district de résidence, mais cette probabilité peut varier en fonction des données du district concernant le nombre de personnes recevant un traitement antirétroviral par rapport à la prévalence du VIH, à la couverture du traitement antirétroviral et à la population.


             "))
}
if("true" %in% include$art_attend) {

  cat(paste0("
_Participação em TARV em distritos vizinhos_\n 

Um desafio para estimar a cobertura de tratamento a nível distrital é o facto de as pessoas poderem aceder a serviços de terapia antirretroviral num distrito diferente daquele em que residem, por exemplo, se as instalações ficarem mais próximas ou forem consideradas prestadoras de melhores serviços. O modelo permite a probabilidade de as pessoas residentes que vivem com VIH terem acesso a terapia antirretroviral num distrito vizinho. O pressuposto é que a grande maioria das pessoas que vivem com VIH terão acesso a terapia antirretroviral no seu distrito de residência, mas esta probabilidade pode variar com base nos dados distritais sobre o número de pessoas que recebem terapia antirretroviral em comparação com a prevalência de VIH, cobertura da terapia antirretroviral e população..


             "))
}

::: {#translate lang="en"} HIV incidence

Direct estimates of HIV incidence are not available at subnational levels. While some recent household surveys have measured HIV incidence at the national level based on biomarker measures for recent HIV infections, too few recent infections are observed in any district to make a robust estimate. Therefore, to estimate HIV incidence at the subnational level, the HIV transmission rate from Spectrum estimates is calculated and applied to small area estimates of HIV prevalence and ART coverage in each subnational area. The sex and age distribution in each subnational area are based on HIV incidence rate ratios from Spectrum applied to the population structure in each area.

Current estimates and one-year ahead projection

The update estimates from the most recent household survey to the current period, the model conducts a one-step projection of the population the most recent survey to the current period. Population estimates are updated with official population estimates. The number of PLHIV is projected forward based on survival estimates by province, sex, and age group from Spectrum over the same period (which accounts for HIV disease progression and effects of ART scale up on reducing AIDS mortality). ART coverage is updated based on the number currently reported on ART from service provision data.

To extrapolate estimates a further one-year ahead for HIV planning purposes, the number of new infections and PLHIV are calculated based on the transmission rate from national or subnational Spectrum estimates. The number on ART are projected by calculating the increased in odds of ART coverage by age and sex based on ART projections input to Spectrum and applying this change in odds to each subnational area.

Version

The Naomi model is supported by UNAIDS and developed and maintained by the MRC Centre for Global Infectious Disease Analysis at Imperial College London. The model receives technical guidance from the UNAIDS Reference Group on Estimates, Modelling, and Projections. The model was first used in 2020 and continues to be developed responsive to new data and HIV strategic information needs. :::

::: {#translate lang="fr"} Incidence du VIH

Les estimations directes de l'incidence du VIH ne sont pas disponibles aux niveaux sous-nationaux. Bien que certaines enquêtes récentes auprès des ménages aient mesuré l'incidence du VIH au niveau national sur la base de mesures de biomarqueurs pour les infections récentes au VIH, trop peu d'infections récentes sont observées dans un district quelconque pour faire une estimation robuste. Par conséquent, pour estimer l'incidence du VIH au niveau sous-national, le taux de transmission du VIH à partir des estimations du Spectrum est calculé et appliqué aux estimations de la prévalence du VIH et de la couverture du TAR dans chaque zone sous-nationale. La répartition par sexe et par âge dans chaque zone infranationale est basée sur les ratios de taux d'incidence du VIH de Spectrum appliqués à la structure de la population dans chaque zone.

Estimations actuelles et projection à un an

Pour mettre à jour les estimations de l'enquête la plus récente auprès des ménages jusqu'à la période actuelle, le modèle effectue une projection en une étape de la population de l'enquête la plus récente jusqu'à la période actuelle. Les estimations de la population sont mises à jour avec les estimations officielles de la population. Le nombre de PLHIV est projeté vers l'avant sur la base des estimations de survie par province, sexe et groupe d'âge de Spectrum sur la même période (ce qui tient compte de la progression de la maladie du VIH et des effets de l'intensification du TARV sur la réduction de la mortalité due au SIDA). La couverture du traitement antirétroviral est mise à jour sur la base du nombre de personnes actuellement déclarées sous traitement antirétroviral à partir des données sur la prestation de services.

Pour extrapoler les estimations un an à l'avance à des fins de planification de la lutte contre le VIH, le nombre de nouvelles infections et de personnes vivant avec le VIH est calculé sur la base du taux de transmission à partir des estimations nationales ou sous-nationales de Spectrum. Le nombre de personnes sous traitement antirétroviral est projeté en calculant l'augmentation des chances de bénéficier d'un traitement antirétroviral par âge et par sexe, sur la base des projections relatives au traitement antirétroviral introduites dans Spectrum, et en appliquant cette variation des chances à chaque région infranationale.

Version

Le modèle Naomi est soutenu par l'ONUSIDA et développé et maintenu par le MRC Centre for Global Infectious Disease Analysis à l'Imperial College London. Le modèle reçoit des conseils techniques du Groupe de référence de l'ONUSIDA sur les estimations, la modélisation et les projections. Le modèle a été utilisé pour la première fois en 2020 et continue d'être développé en fonction des nouvelles données et des besoins en informations stratégiques sur le VIH. :::

::: {#translate lang="pt"} Incidência do VIH

Não estão disponíveis estimativas diretas da incidência do VIH a níveis subnacionais. Embora alguns inquéritos recentes a agregados familiares tenham medido a incidência do VIH a nível nacional com base em medidas de biomarcadores para infeções recentes pelo VIH, são observadas muito poucas infeções recentes em qualquer distrito para se fazer uma estimativa robusta. Portanto, para estimar a incidência do VIH a nível subnacional, a taxa de transmissão do VIH a partir das estimativas do Spectrum é calculada e aplicada a estimativas de pequena área da prevalência do VIH e da cobertura do TARV em cada área subnacional. A distribuição por género e idade em cada área subnacional é baseada na taxa de incidência do VIH do Spectrum aplicada à estrutura da população em cada área.

Estimativas atuais e projeção com um ano de antecedência

Para atualizar as estimativas a partir do inquérito mais recente aos agregados familiares até ao período atual, o modelo realiza uma projeção de uma etapa da população do inquérito mais recente até ao período atual. As estimativas da população são atualizadas com estimativas oficiais da população. O número de PVVIH é projetado com base em estimativas de sobrevivência por província, género e grupo etário do Spectrum durante o mesmo período (o que explica a progressão da doença por VIH e os efeitos da escala de TARV na redução da mortalidade por SIDA). A cobertura de TARV é atualizada com base no número atualmente reportado sobre a TARV a partir de dados de prestação de serviços.

Para extrapolar as estimativas com um ano de antecedência para efeitos de planeamento da luta contra o VIH, o número de novas infeções e de PVVIH é calculado com base na taxa de transmissão das estimativas nacionais ou subnacionais do Spectrum. O número de pessoas em TARV é projetado através do cálculo do aumento da probabilidade de cobertura de TARV por idade e género com base nas projeções de TARV introduzidas no Spectrum e aplicando esta alteração às probabilidades para cada área subnacional.

Versão

O modelo Naomi é apoiado pela UNAIDS e desenvolvido e mantido pelo [MRC Centre for Global Infectious Disease Analysis] (https://www.imperial.ac.uk/mrc-global-infectious-disease-analysis) no Imperial College London. O modelo recebe orientação técnica do UNAIDS Reference Group on Estimates, Modelling, and Projections. O modelo foi usado pela primeira vez em 2020 e continua a ser desenvolvido em resposta a novos dados e necessidades de informação estratégica sobre o VIH. :::



mrc-ide/naomi documentation built on April 10, 2024, 2:13 p.m.