---
title: "Instability pipeline"
format: html
---

# Setup

```{r}
library(trace)

```

# About this file

Welcome to the template file. To use this document, you need to fill out the section in the inputs and step through each code section adjusting function parameters as needed. This pipeline assumes full use of the optional functionality from the metadata of batch correction using common samples across fragment analysis runs and grouping samples for index peak assignment. If not using that functionality, pay attention to `batch_correction` in `call_repeats()` and `grouped` in `assign_index_peaks()`, respectively. Once you're satisfied that pipeline is good to go, you can render to generate a report.

In each code chuck, access the help file for more information on how to use it (eg type ?find_ladders into the console).

This document is a quarto file, which is a mix of written text and code that can be rendered to produce a report. See the following links below for more info and how it works.

-   https://quarto.org/
-   https://r4ds.hadley.nz/quarto

# Inputs

```{r inputs}

#fill out these paths
## folder where fsa files live. If they are across several folders, point to the upper directory and use option recursive in list.files
fsa_folder <- ""
fsa_file_list = list.files(fsa_folder, full.names = TRUE, pattern = ".fsa")
fsa_raw <- read_fsa(fsa_file_list)

## import metadata file. You may need to change the function below to read in your type of file. eg readxl::read_excel() for excel file. See add_metadata() for more info on what's required
metadata <- read.csv("")

# or uncomment out the lines below to run an example
## note: to make this example render without errors, comment out the inputs above in this chunk
# fsa_raw <- lapply(cell_line_fsa_list, function(x) x$clone())
# metadata <- trace::metadata

```

# Check data channels


```{r}
plot_data_channels(fsa_raw[1])

```


# Assign Ladders

```{r Assign Ladders}


ladder_sizes <- c(50, 75, 100, 139, 150, 160, 200, 250, 300, 340, 350, 400, 450, 490, 500)

find_ladders(
  # main parameters to set, see help documentation for more info
  fragments_trace = fsa_raw,
  ladder_channel = "DATA.105",
  signal_channel = "DATA.1",
  ladder_sizes = ladder_sizes,
  # advanced parameters for fine tuning
  ladder_start_scan = NULL,
  minimum_peak_signal = NULL,
  zero_floor = FALSE,
  scan_subset = NULL,
  ladder_selection_window = 5,
  max_combinations = 2500000,
  smoothing_window = 21,
  show_progress_bar = FALSE)


```

# Find peaks

```{r Find peaks}
fragments_list <- find_fragments(
  # main parameters to set, see help documentation for more info
  fragments_trace_list = fsa_raw,
  min_bp_size = 300,
  # advanced parameters for fine tuning
  max_bp_size = 1000,
  smoothing_window = 21,
  minimum_peak_signal = 20,
)
```

# Add metadata

```{r Add metadata}

add_metadata(
  # main parameters to set, see help documentation for more info
  fragments_list = fragments_list,
  metadata_data.frame = metadata,
  unique_id = "unique_id",
  metrics_group_id = "metrics_group_id",
  metrics_baseline_control = "metrics_baseline_control",
  batch_run_id = "batch_run_id",
  batch_sample_id = "batch_sample_id",
  batch_sample_modal_repeat = NA
 )

```

# Find alleles

```{r Find alleles}
find_alleles(
  # main parameters to set, see help documentation for more info
  fragments_list = fragments_list,
  # advanced parameters for fine tuning
  peak_region_size_gap_threshold = 6,
  peak_region_signal_threshold_multiplier = 1)
```

# Call repeats

```{r Find repeats}
call_repeats(
  # main parameters to set, see help documentation for more info
  fragments_list = fragments_list,
  assay_size_without_repeat = 87,
  repeat_size = 3,
  force_whole_repeat_units = TRUE,
  correction = "batch",
  # advanced parameters for fine tuning
  force_repeat_pattern = FALSE,
  force_repeat_pattern_size_window = 3,
  force_repeat_pattern_size_period = 3 * 0.93
)

```

# Assign index peaks

```{r Assign index peaks}
assign_index_peaks(
  # main parameters to set, see help documentation for more info
  fragments_list = fragments_list,
  grouped = TRUE,
  # advanced parameters for fine tuning
  index_override_dataframe = NULL
)

```


# Calculate instability metrics

```{r Calculate instability metrics}
metrics_df <- calculate_instability_metrics(
  fragments_list = fragments_list,
  peak_threshold = 0.05,
  window_around_index_peak = c(-50, 50)
)
```

# save outputs

## Create Output Folders

creates outputs folder

```{r Create Output Folders}

if (!dir.exists("outputs")) dir.create("outputs")

```

## ladders
This code generates a PDF file of all the ladders with a customisable plot title.

```{r ladders}

ladder_info <- extract_ladder_summary(fsa_raw)

# Create a PDF to save plots
pdf("outputs/ladders.pdf", height = 5, width = 10)

# Loop through each ladder in the subset
for (ladder in fsa_raw) {
  plot_title <- paste0(
    ladder$unique_id, "\n",
    "avg_rsq: ", round(ladder_info[which(ladder_info$unique_id == ladder$unique_id), "avg_rsq"], 4)
  )
  
  ladder$plot_ladder(plot_title = plot_title)
}

# Close the PDF device
dev.off()




```

## sample traces


```{r sample traces}
pdf("outputs/traces.pdf", height = 5, width = 10)
  
# Loop through each repeat in the subset
for (i in seq_along(fragments_list)) {
  
  # Plot trace with title and sample name
  fragments_list[[i]]$plot_trace(
    xlim = c(80, 250)
  )
  
  # Add text annotation for allele_repeat
  text(
    x = fragments_list[[i]]$get_allele_peak()$allele_repeat, 
    y = fragments_list[[i]]$get_allele_peak()$allele_signal * 1.02, 
    labels = round(fragments_list[[i]]$get_allele_peak()$allele_repeat)
  )
}
  
# Close the PDF device
dev.off()



```

## processed repeats object as RDS file

This can be useful for downstream aggregation of experiments. For example, we could read in the fragments_list back into R in another script to calculate instability metrics.

```{r saveRDS}

saveRDS(fragments_list,
        file = "outputs/processed_repeats_fragments_list.rds")
```

## instability metrics

```{r export instability metrics}
write.table(metrics_df, "outputs/instability_metrics_df.txt",
            row.names=FALSE, sep="\t")

```
