---
title: "09-bismark-post-align"
format: html
editor: visual
---

# Taking BAMS to tables

## Deduplicated

```{bash}
find ../output/08-bismark/*.bam | \
xargs -n 1 basename -s _pe.bam | \
parallel -j 24 deduplicate_bismark \
--bam \
--paired \
--output_dir ../output/09-bismark-post-align \
../output/08-bismark/{}_pe.bam

```

## Sorted

```{bash}
find ../output/09-bismark-post-align/*deduplicated.bam | \
xargs basename -s _pe.deduplicated.bam | \
xargs -I{} samtools \
sort --threads 42 \
../output/09-bismark-post-align/{}_pe.deduplicated.bam \
-o ../output/09-bismark-post-align/{}.sorted.bam
```

## Methylation Extraction

```{bash}
find ../output/09-bismark-post-align/*deduplicated.bam | xargs -n 1 -I{} \
bismark_methylation_extractor --bedGraph --counts --comprehensive --merge_non_CpG \
--multicore 42 --buffer_size 75% --output ../output/09-bismark-post-align "{}"
```

## Methylation call

```{bash}
find ../output/09-bismark-post-align/*deduplicated.bismark.cov.gz | \
xargs -n 1 basename -s _pe.deduplicated.bismark.cov.gz | \
parallel -j 24 coverage2cytosine \
--genome_folder ../data/Mchi/ \
-o ../output/09-bismark-post-align/{} \
--merge_CpG \
--zero_based \
../output/09-bismark-post-align/{}_pe.deduplicated.bismark.cov.gz
```

## Rename cov files

``` bash
# Read the CSV file and create an associative array - hand edited 3 filenames first
declare -A sample_map
while IFS=, read -r col1 sample_name col3 col4 azenta_sample_name col6; do
  sample_map["$azenta_sample_name"]="$sample_name"
done < ../../M-multi-species/data/e5_DNA_Azenta_metadata.csv

cd ../output/15.5-Apul-bismark/

# Iterate over all *.cov files and rename them
for file in *.cov; do
  # Extract the portion before the first underscore
  prefix="${file%%_*}"
  if [[ -n "${sample_map[$prefix]}" ]]; then
    new_file="${file//$prefix/${sample_map[$prefix]}}"
    mv "$file" "$new_file"
  fi
done
```

## Made bedgraph

``` bash
cd ../output/15.5-Apul-bismark/

for f in *merged_CpG_evidence.cov
do
  STEM=$(basename "${f}" _R1_001.fastp-trim_bismark_bt2.CpG_report.merged_CpG_evidence.cov)
  cat "${f}" | awk -F $'\t' 'BEGIN {OFS = FS} {if ($5+$6 >= 10) {print $1, $2, $3, $4}}' \
  > "${STEM}"_10x.bedgraph
done
```

## Created modified tables

``` bash
for file in ../output/15.5-Apul-bismark/*10x.bedgraph; do
    awk '{print "CpG_"_$1"_"$2, $4}' "$file" > "${file%.bedgraph}_processed.txt"
done
```

```{bash}

```
