---
title: "geneClusterPattern Vignette: overview"
author: "Jianhong Ou"
date: "`r BiocStyle::doc_date()`"
package: "`r BiocStyle::pkg_ver('geneClusterPattern')`"
abstract: >
  Visualize conserved gene clusters in multiple genomes
vignette: >
  %\VignetteIndexEntry{geneClusterPattern Vignette: overview}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
output:
  html_document:
    theme: simplex
    toc: true
    toc_float: true
    toc_depth: 4
    fig_caption: true
---

```{r, echo=FALSE, results="hide", warning=FALSE}
suppressPackageStartupMessages({
    library(org.Dr.eg.db)
    library(geneClusterPattern)
    library(GenomeInfoDb)
    fish <- readRDS(system.file('extdata', 'fish.rds',
                            package = 'geneClusterPattern'))
    homologs <- readRDS(system.file('extdata', 'homologs.rds',
                                package = 'geneClusterPattern'))
})
knitr::opts_chunk$set(warning=FALSE, message=FALSE)
```

# Introduction


Understanding the conservation of gene neighborhoods across species provides important insights into genome organization, functional linkage, and evolutionary processes. **geneClusterPattern** is a package developed to facilitate the systematic characterization of orthologous gene arrangements surrounding a focal gene across multiple species.

Given a gene of interest, the package supports two complementary strategies to define orthology relationships. It can retrieve homologous genes directly from Ensembl (via Compara), or it can incorporate user-provided ortholog group assignments generated by [OrthoFinder](https://github.com/davidemms/OrthoFinder). These flexible input options allow users to integrate gene homology information from widely used comparative genomics pipelines.

Based on the orthology information, **geneClusterPattern** constructs an ordered representation of genes within a configurable genomic window upstream and downstream of the focal gene. The resulting ortholog gene pattern captures the relative arrangement of ortholog groups across species, enabling direct comparison of local genomic structure.

This framework is particularly useful for investigating conserved synteny, identifying lineage-specific rearrangements, and exploring the evolutionary stability of gene clusters. The package outputs are designed to be analysis- and visualization-friendly, supporting downstream statistical analysis and graphical representation of gene neighborhood conservation.


# Installation

```{r installation, eval=FALSE}
if (!require("BiocManager", quietly = TRUE)) {
    install.packages("BiocManager")
}
BiocManager::install('geneClusterPattern')
# or install from github
BiocManager::install('jianhong/geneClusterPattern')
```

# Quick start

There are main steps to create the gene cluster pattern for a given gene.

Step 1. Load the required libraries.

Step 2. Prepare homolog information for the reference species. Homologs can be
retrieved from the Ensembl database or obtained from ortholog group assignments.
In this example, we use a pre-saved homolog dataset downloaded from Ensembl.

Step 3. Define the gene cluster.

Step 4. Visualize the gene cluster.

```{r quickstart}
## load library
library(geneClusterPattern)
library(org.Dr.eg.db)
library(GenomeInfoDb)
## prepare all the ensembl ids
ids <- as.list(org.Dr.egENSEMBL)
ensembl_gene_ids <- sort(unique(unlist(ids)))
```
```{r guessmart, eval=FALSE}
## extract gene information via biomaRt
fish_mart <- guessSpecies('zebrafish', output='mart', version=112)
fish <- grangesFromEnsemblIDs(mart = fish_mart,
                              ensembl_gene_ids = ensembl_gene_ids)
## if failed, try load presaved data
# fish <- readRDS(system.file('extdata', 'fish.rds',
#                             package = 'geneClusterPattern'))
```
```{r loadSpecies}
## subset the ensembl_gene_ids to save time
ensembl_gene_ids <- names(fish[seqnames(fish)=='24'])
## keep the standard sequence only
fish <- pruningSequences(fish)
## define the species scientific name
species <- guessSpecies(c('human', 'house mouse', 'Japanese medaka', 'turquoise killifish', 'gaculeatus'), version=112) # three-spined stickleback
species
```
```{r retrieveDataFromEnsembl, eval=FALSE}
## retrieve homologs from Ensembl
homologs <- getHomologGeneList(species, fish_mart, ensembl_gene_ids)
homologs <- pruningSequences(homologs)
## if failed, try to load pre-saved data
# homologs <- readRDS(system.file('extdata', 'homologs.rds',
#                                 package = 'geneClusterPattern'))
```
```{r getGeneCluster}
## get gene cluster for target gene
queryGene <- 'pcolce2b'
## define the gene cluster
nearest10neighbors <- getGeneCluster(fish, queryGene, homologs, k=10)

## prepare the gene annotations for all homologs for plot
genesList <- c(drerio=fish, homologs)[
  c("hsapiens", "mmusculus", "drerio", "olatipes", "nfurzeri", "gaculeatus")]

## plot the cluster
pgp <- plotGeneClusterPatterns(genesList, nearest10neighbors)
```

The plot consists of two panels. The top panel shows the **Gene Pattern** plot,
while the bottom panel displays the actual genomic coordinates of the genes in
the cluster for each species. By default, the reference gene is positioned at
the center of the plot. Homologous genes across different species are displayed
using the same fill color.

In the **Gene Pattern** plot, gene lengths are shown schematically rather than
to scale, making the gene order and orientation easier to visualize. In
contrast, the genomic tracks in the bottom panel represent the true genomic
coordinates and actual gene lengths.

# From OrthoFinder results

Homolog information can also be obtained from ortholog group assignments. 
For example, you can start from the orthogroup table generated by OrthoFinder, 
which groups homologous genes across multiple species into orthologous groups.
These group assignments can be used directly as input for
downstream gene cluster analysis.

```{r orthofinder}
## import the ortholog groups
path <- system.file('extdata/orthofinder/Danio_rerio.GRCz11.pep.all.tsv.gz',
                    package='geneClusterPattern')
orthologs <- orthologPairsFromOrthoFinder(path)
## annotations
annoGR_list <- readRDS(
    system.file('extdata/orthofinder/grange.obj.rds',
                 package='geneClusterPattern'))
## reformat to meet the requirement of the package
homologs <- getHomologListForOrthoFinder(orthologs, annoGR_list[-1])
## set reference species
queryGR <- annoGR_list[["Danio rerio"]]
## define the gene cluster
nearest10neighbors <- getGeneCluster(queryGR, queryGene, homologs, k=10)
pgp <- plotGeneClusterPatterns(c('zebrafish'=queryGR, homologs),
                               nearest10neighbors)
```


# Session Info
```{r sessionInfo, results='asis'}
sessionInfo()
```

