---
title: "10-Apul lncRNA"
author: Steven Roberts
date: "`r format(Sys.time(), '%d %B, %Y')`"  
output: 
  html_document:
    theme: readable
    highlight: zenburn
    toc: true
    toc_float: true
    number_sections: true
    code_folding: show
    code_download: true
---

```{r setup, include=FALSE}
library(knitr)
library(tidyverse)
knitr::opts_chunk$set(
  echo = TRUE,         # Display code chunks
  eval = FALSE,         # Evaluate code chunks
  warning = FALSE,     # Hide warnings
  message = FALSE,     # Hide messages
  fig.width = 6,       # Set plot width in inches
  fig.height = 4,      # Set plot height in inches
  fig.align = "center" # Align plots to the center
)
```



# Run HiSat on RNA-seq

can start with sorted bams from 07-Hisat

```{bash}

```


# StringTie
StringTie uses the sorted BAM files to assemble transcripts for each sample, outputting them as GTF (Gene Transfer Format) files. And then merges all individual GTF assemblies into a single merged GTF file. This step extracts transcript information and merges GTFs from all samples--an important step in creating a canonical list of lncRNAs across all samples included in the pipeline.

Getting gff

```{r, engine='bash'}

cd ../data
wget -O Apulcra-genome.gff "https://osf.io/download/f9dbr/"
```


```{r, engine='bash'}

head ../data/Apulcra-genome.gff

```


# PICK UP HERE FROM )7

# StringTie
StringTie uses the sorted BAM files to assemble transcripts for each sample, outputting them as GTF (Gene Transfer Format) files. And then merges all individual GTF assemblies into a single merged GTF file. This step extracts transcript information and merges GTFs from all samples--an important step in creating a canonical list of lncRNAs across all samples included in the pipeline.

```{r, engine='bash'}
find ../output/07-Apul-Hisat/*sorted.bam \
| xargs basename -s .sorted.bam | xargs -I{} \
/home/shared/stringtie-2.2.1.Linux_x86_64/stringtie \
-p 48 \
-G ../data/Apulcra-genome.gff \
-o ../output/10-Apul-lncRNA/{}.gtf \
../output/07-Apul-Hisat/{}.sorted.bam
```



```{r, engine='bash', eval=TRUE}
wc -l ../output/10-Apul-lncRNA/RNA*.gtf
head ../output/10-Apul-lncRNA/RNA*.gtf
```


Merges all individual GTF assemblies into a single merged GTF file.

This is used to create a non-redundant set of transcripts after running StringTie separately on multiple RNA-Seq datasets.

```{r, engine='bash'}
/home/shared/stringtie-2.2.1.Linux_x86_64/stringtie \
--merge \
-G ../data/Apulcra-genome.gff \
-o ../output/10-Apul-lncRNA/stringtie_merged.gtf \
../output/10-Apul-lncRNA/RNA*.gtf
```



```{r, engine='bash', eval=TRUE}

wc -l ../output/10-Apul-lncRNA/stringtie_merged.gtf
head ../output/10-Apul-lncRNA/stringtie_merged.gtf


echo "what is possible"

grep -v '^#' ../output/10-Apul-lncRNA/stringtie_merged.gtf | cut -f3 | sort | uniq -c


```

# GFFcompare
https://ccb.jhu.edu/software/stringtie/gffcompare.shtml

```{r, engine='bash'}
/home/shared/gffcompare-0.12.6.Linux_x86_64/gffcompare \
-r ../data/Apulcra-genome.gff \
-o ../output/10-Apul-lncRNA/gffcompare_merged \
../output/10-Apul-lncRNA/stringtie_merged.gtf
```


```{r, engine='bash', eval=TRUE}
ls ../output/10-Apul-lncRNA/gffcompare_merged*
```

```{r, engine='bash', eval=TRUE}
cat ../output/10-Apul-lncRNA/gffcompare_merged.stats
```

```{r, engine='bash', eval=TRUE}
head -10 ../output/10-Apul-lncRNA/gffcompare_merged.annotated.gtf
```

![](https://camo.githubusercontent.com/35dc9d9e4be6b49e4393668660be388674f1efa94f543fe44984a1febe19bdf3/687474703a2f2f67616e6e65742e666973682e77617368696e67746f6e2e6564752f7365617368656c6c2f736e6170732f323032332d31312d30335f30392d32352d32342e706e67)


# Filter
Filters the combined GTF output from GFFcompare to select only the lines representing "transcripts" and excluding lines starting with "#" (these are lines in the output format from GFFcompare that don't contain transcript information). This step further filters for a class code of "u", and keep only those with lengths greater than 199 bases. The "u' class code from the GFFcompare step is for "unknown" transcripts, that is those that are not previously annotated in our reference GFF as protein coding. The size filter of +200nt is a common filtering step for isolating lncRNAs.

```{r, engine='bash'}
awk '$3 == "transcript" && $1 !~ /^#/' \
../output/10-Apul-lncRNA/gffcompare_merged.annotated.gtf | grep 'class_code "u"\|class_code "x"|\class_code "i"\|class_code "y"' | awk '($5 - $4 > 199) || ($4 - $5 > 199)' > ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.gtf
```

```{r, engine='bash', eval=TRUE}
wc -l ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.gtf
head ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.gtf
```

# Bedtools
Extracts the sequence data from the `$FASTA` reference file based on the coordinates from the filtered GTF. The resulting sequences represent potential lncRNA candidates.

```{r, engine='bash'}
/home/shared/bedtools2/bin/fastaFromBed \
-fi ../data/Apulcra-genome.fa \
-bed ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.gtf \
-fo ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta \
-name -split
```

```{r, engine='bash'}
fgrep -c ">" ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta 
head ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta 
```



# CPC2
Initializes a conda environment (Anaconda) and runs CPC2, a software to predict whether a transcript is coding or non-coding. The results are saved to the $OUTPUT_DIR. CPC2 uses ORF (Open Reading Frame) Analysis, Isometric Feature Mapping (Isomap), Sequence Homology, RNA Sequence Features, and Quality of Translation to assess coding potential and flag any transcripts we would want to exclude using the FASTA generated in the previous step.

```{r, engine='bash'}
eval "$(/opt/anaconda/anaconda3/bin/conda shell.bash hook)"
python /home/shared/CPC2_standalone-1.0.1/bin/CPC2.py \
-i ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta \
-o ../output/10-Apul-lncRNA/Apul_CPC2
```


```{r, engine='bash', eval=TRUE}
wc -l ../output/10-Apul-lncRNA/Apul_CPC2.txt
head ../output/10-Apul-lncRNA/Apul_CPC2.txt
```

#Filter
Filters the CPC2 results to get only noncoding transcripts (using the class "noncoding" from the CPC2 results) and extracts their IDs and matches these IDs with the sequences from the previous step to generate a GTF of long noncoding transcripts.

Matches these IDs with the sequences from the previous step to generate a GTF of noncoding transcripts.

```{r, engine='bash'}
awk '$8 == "noncoding" {print $1}' ../output/10-Apul-lncRNA/Apul_CPC2.txt > ../output/10-Apul-lncRNA/Apul_noncoding_transcripts_ids.txt
```

```{r, engine='bash'}
wc -l ../output/10-Apul-lncRNA/Apul_noncoding_transcripts_ids.txt
head ../output/10-Apul-lncRNA/Apul_noncoding_transcripts_ids.txt
```


```{r, engine='bash'}
head ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta
fgrep -c ">" ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta
```

# subsetting fasta
```{r, engine='bash'}
/home/shared/samtools-1.12/samtools faidx ../output/10-Apul-lncRNA/Apul_lncRNA_candidates.fasta \
-r ../output/10-Apul-lncRNA/Apul_noncoding_transcripts_ids.txt > ../output/10-Apul-lncRNA/Apul_lncRNA.fasta

```

ddd

```{r, engine='bash'}
fgrep -c ">" ../output/10-Apul-lncRNA/Apul_lncRNA.fasta
fgrep ">" ../output/10-Apul-lncRNA/Apul_lncRNA.fasta | head -5

head ../output/10-Apul-lncRNA/Apul_lncRNA.fasta
```

# Getting genome feature track

```{r, engine='python'}

# Open the input file and the output file
with open('../output/10-Apul-lncRNA/Apul_noncoding_transcripts_ids.txt', 'r') as infile, open('../output/10-Apul-lncRNA/Apul_lncRNA.bed', 'w') as outfile:
    # Process each line in the input file
    for line in infile:
        # Remove 'transcript::' and then split the line by ':' to extract the relevant parts
        parts = line.strip().replace('transcript::', '').split(':')
        chromosome = parts[0]
        # Split the position part by '-' to get start and end positions
        start, end = parts[1].split('-')
        
        # BED format requires the start position to be 0-based
        # Convert the start position to 0-based by subtracting 1
        start = str(int(start) - 1)
        
        # Write the chromosome, start, and end positions to the output file
        # Separate each field with a tab character
        outfile.write(f'{chromosome}\t{start}\t{end}\n')

# After running this script, 'output.bed' will contain the converted data in BED format.

```

```{r, engine='bash', eval=TRUE}
head ../output/10-Apul-lncRNA/Apul_lncRNA.bed
```




# Count Matrix

list format

RNA-ACR-140 ../output/10-Apul-lncRNA/RNA-ACR-140.gtf
RNA-ACR-145 ../output/10-Apul-lncRNA/RNA-ACR-145.gtf
RNA-ACR-173 ../output/10-Apul-lncRNA/RNA-ACR-173.gtf
RNA-ACR-178 ../output/10-Apul-lncRNA/RNA-ACR-178.gtf


```{r, engine='bash'}
head ../output/10-Apul-lncRNA/list01.txt
```



```{r, engine='bash'}
python /home/shared/stringtie-2.2.1.Linux_x86_64/prepDE.py \
-i ../output/10-Apul-lncRNA/list01.txt \
-g ../output/10-Apul-lncRNA/lnc-gene_count_matrix.csv \
-t ../output/10-Apul-lncRNA/lnc-transcript_count_matrix.csv

head ../output/10-Apul-lncRNA/*matrix.csv

```