---
title: "Introduction of 'geneNR'"
author: "Rajamani Nirmalaruban"
date: "2026-07-05"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction of 'geneNR'}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  echo = TRUE
)

```

## Introduction

The **geneNR** package streamlines post-GWAS (Genome-Wide Association Studies) and post-QTL mapping analyses by automating candidate gene identification within custom search windows. It parses genomics files, visualizes marker densities, and targets stress-adaptive traits primarily in wheat and rice, serving as an asset for cereal improvement programs.

---

## Key Features

* **Dual Genome Execution Engines:** Seamlessly switch between online Ensembl live data mining or completely offline custom local GFF3 reference alignments.
* **Genomic Visualization Tools:** Generate clean density maps and frequency charts across chromosomes out-of-the-box.
* **Dynamic Search Windows:** Configure precision asymmetric nucleotide interval sizes (`upstream` and `downstream`) or map uneven custom intervals (like haplotype linkage disequilibrium blocks).
* **Multi-Format File Support:** Built-in helper parsers to ingest standard variant calls directly from HapMap (`.hmp.txt`) and VCF (`.vcf`) files.
* **Fully Clean Workspace Resets:** Internal directory environments automatically clean up behind themselves, protecting files from overlapping temporary extractions.

---

## Technical Pipeline & Parameter Configurations

The package exposes functions for gene identification (`geneSNP()`, `geneQTL()`, `geneSNPcustom()`), file conversion (`import_hmp()`, `import_vcf()`), data summarization (`summariseSNP()`, `summariseSNP_vcf()`), and visualization (`plot_SNP()`, `plot_summariseSNP()`).

### Gene Mining Function Arguments

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| **`data_file`** | `character` | *Required* | Built-in dataset name (e.g., `"sample_data_wheat"`) or path to a custom `.csv` file. |
| **`upstream`** | `numeric` | `1000000` | Search window extension upstream of the variant position (in base pairs). |
| **`downstream`** | `numeric` | `1000000` | Search window extension downstream of the variant position (in base pairs). |
| **`crop`** | `character` | `"wheat"` | Species target selector; choose either `"wheat"` or `"rice"`. |
| **`genome_source`** | `character` | `"online"` | Database routing engine; choose `"online"` (Ensembl server lookup) or `"local"`. |
| **`gff3_file`** | `character` | `NULL` | Complete system file path targeting your local custom `.gff3` reference sheet. |

### Target Reference Genome Assemblies

When using the `genome_source = "online"` engine, `geneNR` automatically queries the most current stable database instances on Ensembl Plants:

* **Wheat:** Mapped directly to the hexaploid bread wheat reference assembly **IWGSC RefSeq v1.0**.
* **Rice:** Mapped directly to the unified **IRGSP-1.0** (Japonica Group cv. Nipponbare) reference sequence.

*Note: If your local input data was called using alternative genome coordinates (e.g., specific pan-genome cultivars, or custom assemblies), switch to `genome_source = "local"` and provide your targeted reference `.gff3` file.*

---

## Step-by-Step Executions

### Workflow 1: Instant Local Tracking Engine (CRAN Safe)

This mode executes completely offline. If `genome_source = "local"` is selected without passing a path, the function automatically loops back to its internal custom package database framework (`sample_crop.gff3`).

```{r local_workflow, eval=TRUE}
library(geneNR)

gff_path <- system.file("extdata", "sample_crop.gff3", package = "geneNR")

# Execute local mapping on sample datasets using the integrated reference sheet
local_results <- geneSNP(
  data_file     = "sample_data_wheat",
  upstream      = 50000,
  downstream    = 50000,
  genome_source = "local",
  gff3_file     = gff_path
)

# Display extracted candidate data matrix output lines
print(utils::head(local_results))

```

### Workflow 2: Online Real-Time Web Scraping Mode

This mode scrapes live genome layers from Ensembl Plants. Because it requires active server responses, it is skipped during check loops to comply with CRAN timing limits.

```r
# Run online extraction tracking across regional rice variants
online_results <- geneSNP(
  data_file     = "sample_data_rice", 
  upstream      = 10000, 
  downstream    = 10000, 
  crop          = "rice",
  genome_source = "online"
)

print(utils::head(online_results))

```

### Workflow 3: Custom Haplotype Range Testing (`geneSNPcustom`)

When dynamic search windows are not uniform across the dataset, use `geneSNPcustom` to read custom coordinate columns (`start` and `stop`) from the input table.

```{r custom_workflow, eval=TRUE}
gff_path <- system.file("extdata", "sample_crop.gff3", package = "geneNR")

# Process dynamic uneven interval segments using the offline template pipeline
custom_range_results <- geneSNPcustom(
  data_file     = "sample_data_wheat_custom",
  crop          = "wheat",
  genome_source = "local",
  gff3_file     = gff_path
)

print(utils::head(custom_range_results))

```

---

## Genomic Data Summarization & Visualization

### Parsing and Summarizing Genotypic Data

You can easily import genomic marker distributions directly from standard formats like HapMap and VCF to compute chromosomal summary frames.

```{r summaries, eval=TRUE}
# Import a sample HapMap tracking dataset
demo_hmp <- system.file("extdata", "demo_SNP.hmp.txt", package = "geneNR")
imported_data <- import_hmp(demo_hmp)

# Summarize variant distributions across chromosomes
snp_summary <- summariseSNP(imported_data)
print(snp_summary)

```

### Mapping Chromosomal Density Charts (`plot_SNP`)

The package features native plotting methods to map physical variant spreads against chromosomal skeletons.

```{r plot_SNP, eval=TRUE, fig.height=5, fig.width=10}
# Load internal mock layout references
chr_details <- read.csv(system.file("extdata", "chromosome_details.csv", package = "geneNR"))
snp_locations <- read.csv(system.file("extdata", "identified_SNP.csv", package = "geneNR"))

# Generate the physical density model distribution map
snp_map <- plot_SNP(
  chromosome_details = chr_details, 
  data               = snp_locations,  
  chromosome_color   = "steelblue",  
  title              = "Chromosome map with SNPs", 
  label_color        = "black"
)

# Render the plot layout
print(snp_map)

```

### Visualizing Frequency Histograms (`plot_summariseSNP`)

To view aggregate chromosomal frequencies side-by-side, use `plot_summariseSNP` to create customized summary charts.

```{r plot_summarise, eval=TRUE, fig.height=5, fig.width=7}
# Generate a summary metric visualization chart
summary_chart <- plot_summariseSNP(
  snp_summary, 
  bar_color   = "skyblue",
  label_size  = 3, 
  label_color = "red"
)

# Render the layout chart
print(summary_chart)

```

---

## System Output Layout

Upon evaluation, matches are structured cleanly and auto-exported into your working folder as a comprehensive Excel report:

* `traits`: The verified agronomic phenotype profile label.
* `SNP` / `QTL`: The designated genetic marker tag identifier.
* `search_window`: Complete tracking coordinate string (`Chr:Start-Stop`).
* `gene_size`: Exact sequence limits matching the gene boundaries.
* `gene_id`: Official Ensembl Accession or GFF reference designation tag.
* `gene_type`: Functional structural biotype annotation classification.

---

## Support & Package Maintenance

For code reporting, genomic coordinate requests, or to report structural workflow issues, contact the author and maintainer:

* **Maintainer:** Rajamani Nirmalaruban
* **Email:** nirmalaruban97@gmail.com

---

## Glossary

* **GWAS:** Genome-Wide Association Studies
* **SNP:** Single Nucleotide Polymorphism
* **QTL:** Quantitative Trait Loci
* **GFF3:** General Feature Format version 3
* **Mbp:** Megabase Pairs (1,000,000 base pairs)
* **VCF:** Variant Call Format


```
