---
title: "PMScanR: An R Package for the large-scale identification, analysis, and visualization of protein motifs"
author:
  - Jan Pawel Jastrzebski
  - Damian Czopek
  - Monika Gawronska
  - Wiktor Babis
  - Miriana Quaranta
date: "`r Sys.Date()`"
output: BiocStyle::html_document
vignette: >
  %\VignetteIndexEntry{PMScanR: Protein Motif Scanning and Analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=TRUE}
# Standard setup chunk
knitr::opts_chunk$set(echo = TRUE, collapse = TRUE)
# Load libraries required for the vignette to build
library(PMScanR)
library(ggseqlogo)
library(seqinr)
library(plotly)
```

# 1 Introduction

The `PMScanR` package provides large-scale identification, analysis and visualization of protein motifs. The package integrates various methods to facilitate motif identification, characterization, and visualization. It includes functions for running PS-Scan, a PROSITE database tool. Additionally, `PMScanR` supports format conversion to GFF, enhancing downstream analyses such as graphical representation and database integration. The library offers multiple visualization tools, including heatmaps, sequence logos, and pie charts, enabling a deeper understanding of motif distribution and conservation. Through its integration with PROSITE, `PMScanR` provides access to up-to-date motif data.

Proteins play a crucial role in biological processes, with their functions closely related to structure. Protein functions are often associated with the presence of specific motifs, which are short, sometimes repetitive amino acid sequences essential for distinctive molecular interactions or modifications. Most of the existing bioinformatics tools focus mainly on the identification of known motifs and often do not provide during motif extraction, interactive analysis and visualization tools. Moreover, they do not take into account the effect of single variations on an entire domain or protein motif. These limitations highlight the need for a tool that can automate and scale the analysis. To address this, we have developed `PMScanR`, an R-based package. Designed to facilitate and automate the prediction and the evaluation of the effect of single amino acid substitutions on the occurrence of protein motifs on a large scale of both motifs and sequences. However, existing tools lacked the capability to perform comparative analysis of multiple motifs across multiple sequences, a gap that `PMScanR` was particularly developed to fill.

## 1.1 Instalation and loading
To install this package, start R (version "4.4" or higher) and enter:

```{r installation-loading, eval=FALSE}
if (!require("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("PMScanR")

library(PMScanR)
```
# 2 Data manipulation and overall usage

## 2.1 GUI

If the user prefers to perform the analysis using a graphical user interface (GUI), they can simply run the function `runPMScanRShiny()`. This will launch a Shiny app that opens an interactive window. The window can be used both within R and in a web browser, providing a clickable, user-friendly interface that allows the entire analysis, including visualizations, to be carried out without needing to write code.
If you want you can use shiny to use all the features of the library with user friendly GUI helping to follow all the steps which are contained in this library.

```{r run-shiny-app, eval=FALSE}
# This command launches the interactive Shiny app
runPMScanRShiny()
```

## 2.2 Command Line

Alternatively, if the user wishes to work directly with the code, the library provides a set of functions to perform the full analysis, including protein motif identification and visualization. This can be done through an R script, where users can execute and customize the analysis programmatically. Each function included in the package is described below, along with an explanation of its purpose and functionality.

### 2.2.1 List of functions and their description

The following list of commands provides a step-by-step description of the functions that ensure the complete analysis provided by the `PMScanR` package.

The first step of the analyses is to establish the working environment through the use of functions:

```{r set-working-directory}
# Setting working directory is user-specific,
# setwd("disc:/your/path/to/working/directory")
```

The next step is to load the data for the analysis (more example input files are given in the repository on Github, and below is one example file just from this repository):

```{r load-example-fasta}
# Load example FASTA file included with the package
fasta_file <- system.file("extdata", "hemoglobins.fasta", package = "PMScanR")
```

Once the previous steps have been completed, you can move on to the relevant part of the analysis. Below is a description of the function, together with an example of its use.

#### `runPsScan()`

This function runs the ps_scan tool from the user's operating system to find protein motifs. It requires in_file, out_format, and out_file arguments. The function automatically detects the operating system and uses a cached version of the required PROSITE files.

```{r runPsScan, eval=FALSE}
# This command is not evaluated in the vignette as it requires an external
# dependency (Perl) and can be time-consuming.
runPsScan(in_file = fasta_file, out_format = 'gff', out_file = "results_pfscan.gff")
```

This function is an automatic form of analysis loading, which searches the sequence for protein motifs present on it, but there is also an alternative option where the user can manually point the path to each of the files and the version of the operation system.

After running the scan, the output files can be converted into a GFF-like format for downstream analysis.

#### `readPsa()` and `readProsite()`

These functions are used to parse the output files generated by `runPsScan`. They convert the raw text output into a standardized GFF-like data frame, which is a structured format required by the other analysis and visualization functions in the package.

The following example shows how to parse a sample PSA output file that is included with the `PMScanR` package.

```{r read-example-psa}
# Load the path to an example PSA output file
motifs_psa_file <- system.file("extdata", "out_Hb_psa.txt", package = "PMScanR")

# Use readPsa to convert the file to a GFF-like data frame
gff_data <- readPsa(motifs_psa_file)

# Display the first few rows of the resulting data frame
head(gff_data)
```

Once the analysis output files have been converted to GFF format, the next step is to create the matrix from this file needed for further visualisation in the form of heatmap generation. That can me make by using:

#### `gff2matrix()`

This function converts the GFF-like data frame into a binary motif-occurrence matrix. This matrix format is compact and is the required input for the heatmap visualization functions. Each row represents a unique motif, each column represents a sequence, and a `1` indicates the presence of that motif in that sequence.

```{r convert-gff-to-matrix}
# The 'gff_data' is used from the previous chunk
motif_matrix <- gff2matrix(gff_data)

# Display the first few rows of the resulting matrix
head(motif_matrix)
```

After using this function a heatmap can be generate by using:

#### `matrix2hm()` and `matrixToSquareHeatmap()`

These functions generate interactive heatmaps from the motif-occurrence matrix, which is an effective way to visualize the presence or absence of motifs across many sequences simultaneously. `matrix2hm` creates a standard rectangular heatmap, while `matrixToSquareHeatmap` creates one with a square aspect ratio, which can be useful for comparing motifs.

```{r generate-heatmap-1}
# Generate a standard heatmap from the motif_matrix
heatmap1 <- matrix2hm(input = motif_matrix)
heatmap1
```

```{r generate-heatmap-2, eval=FALSE}
# Generate a square heatmap from the motif_matrix
heatmap2 <- matrixToSquareHeatmap(input = motif_matrix)
heatmap2
```

Heatmap is the first option to visualise the data (shown above), the next option is to generate a seqlogo, after preparing the protein motifs for their generation using the functions described below:

#### `extractSegments()` and `extractProteinMotifs()`

These functions are used to prepare data for sequence logo visualizations. A sequence logo provides a graphical representation of the conservation of nucleotides or amino acids in a set of aligned sequences.

`extractSegments` is used to pull out a specific region (e.g., from position 10 to 20) from a list of raw sequences. `extractProteinMotifs` is used to extract all occurrences of a specific, defined motif from a PSA scan result file.

The example below demonstrates how to extract a segment from our sample hemoglobin sequences and generate a logo.

```{r extract-segments-from-fasta, fig.show='hold'}
# Read the FASTA file into a list of sequences
sequences <- seqinr::read.fasta(file = fasta_file, seqtype = "AA")

# Extract segments from position 10 to 20 from all sequences
segments <- extractSegments(sequences, from = 10, to = 20)

# Generate the sequence logo from the extracted segments
ggseqlogo::ggseqlogo(unlist(segments), seq_type = "aa")
```

### `extractProteinMotifs()`

This function is used to extract all protein motifs belonging to specific PROSITE IDs from a PSA-formatted file. It returns a list where each element is named by a PROSITE ID (e.g., "PS00223") and contains all the sequence instances found for that motif. This is used for sequence logo visualizations of specific motifs.

```{r extract-motifs-from-psa, fig.show='hold'}
# Extract all protein motifs into a list
protein_motifs <- extractProteinMotifs(motifs_psa_file)

# Generate the sequence logo from the extracted protein motifs
ggseqlogo::ggseqlogo(protein_motifs$PS60007, seq_type='aa') # Sequence logo for motif 'PS60007' (example motif ID)
ggseqlogo::ggseqlogo(protein_motifs[1], seq_type='aa')       # Sequence logo for the first motif in the list
ggseqlogo::ggseqlogo(protein_motifs[5], seq_type='aa')       # Sequence logo for the fifth motif in the list
```

#### `freqPie()`

This function generates a pie chart to visualize the frequency distribution of each motif type found in the analysis. It takes the GFF-like data frame as input and provides a quick, high-level overview of which motifs are most common in the dataset.

```{r generate-pie-chart, eval=TRUE}
# The 'gff_data'  from a previous chunk is used here
pie_chart <- freqPie(gff_data)
print(pie_chart)
```

# References

Sigrist C.J.A., de Castro E., Cerutti L., Cuche B.A., Hulo N., Bridge A., Bougueleret L., Xenarios I. (2012). New and continuing developments at PROSITE. *Nucleic Acids Res.*

# Session Information

```{r session-info}
sessionInfo()
