Добавил:
kiopkiopkiop18@yandex.ru t.me/Prokururor I Вовсе не секретарь, но почту проверяю Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Ординатура / Хирургия / Библиотека им академика М.И. Перельмана / Книга_5529_Библиотеки_им_академика_М_И_Перельмана

.pdf
Скачиваний:
0
Добавлен:
31.08.2026
Размер:
26 Мб
Скачать
Variant Analysis
6
6.1 VARIANTS AND AUTOIMMUNE DISEASES
Mutations and genetic variants play a crucial role in the development and progression of autoim­mune diseases, which arise when the immune system mistakenly targets the body’s own tissues. A mutation is a permanent alteration in the nucleotide sequence of the genome of an organism. It can occur spontaneously during DNA replication or be induced by external factors such as radiation, chemicals, or viruses. They may be neutral, benecial, or deleterious, depending on their impact on gene function and organismal tness. Deleterious mutations can affect immune signaling path­ways, antigen processing, or tolerance mechanisms, thereby increasing an individual’s susceptibility to various autoimmune conditions. Broadly, the types of mutations and variants involved include single nucleotide polymorphisms (SNPs), insertions and deletions (indels), copy number variations (CNVs), and larger structural variations. Each of these can have diverse effects on gene expression or protein function, contributing in complex ways to disease phenotypes. Advances in genome-wide association studies (GWAS), next-generation sequencing, and integrative omics have uncovered numerous genetic variants implicated in autoimmune diseases, expanding our understanding of genetic predisposition.
SNPs are the most extensively studied class of variants. They represent a single base change at a specic locus and are cataloged in databases such as dbSNP. For example, the SNP rs2476601 in the PTPN22 gene is one of the most well-established variants associated with multiple autoimmune disorders, including rheumatoid arthritis (RA), type 1 diabetes, and systemic lupus erythematosus (SLE). This variant results in arginine (R) at position 620, in PTPN22 protein, is replaced by trypto­phan (W) (this can be abbreviated as R620W amino acid substitution), which alters T-cell receptor signaling and contributes to autoreactivity. Another notable SNP is rs689 in the INS gene, linked to type 1 diabetes, inuencing insulin expression in the thymus and affecting central tolerance. In the context of multiple sclerosis (MS), SNPs in the HLA-DRB1 gene, such as rs3135388, have been strongly associated with disease risk, underscoring the central role of the human leukocyte antigen (HLA) system in autoimmune pathogenesis.
Beyond SNPs, structural variations like CNVs, recorded in databases such as dbVar, have emerged as important contributors to autoimmune disease susceptibility. Copy number gains or losses can lead to altered gene dosage, dysregulation of immune-related genes, or disruption of gene architecture. For instance, CNVs in the FCGR3B gene, which encodes a receptor involved in the clearance of immune complexes, have been implicated in SLE. Decreased copy number of FCGR3B reduces the efciency of immune complex clearance, promoting chronic inammation and autoantibody formation. Similarly, a CNV involving the C4 gene in the complement system is associated with SLE and schizophrenia, demonstrating pleiotropic effects. Individuals with fewer copies of C4A tend to have increased SLE risk, highlighting the role of complement in immune regulation and disease susceptibility.
Recent studies also emphasize the signicance of non-coding and regulatory variants, including those affecting enhancers, promoters, or non-coding RNAs. These variants may not alter protein sequence but can modulate gene expression in a tissue-specic manner. For example, enhancer vari­ants affecting the expression of IL2RA, the gene encoding the interleukin-2 receptor alpha chain, are linked to type 1 diabetes and MS. Such regulatory variants are often identied through integra­tive analyses of GWAS signals and epigenomic data, including chromatin accessibility and histone modication patterns. In RA, variants near the STAT4 and TR AF1-C5 loci have been shown to inu­ence gene expression in immune cells, correlating with disease susceptibility and clinical severity.
204 DO I: 10.1201/ 97810 03685 432- 6
205 Variant Analysis
In addition to germline variants, somatic mutations in immune cells have also been implicated in certain autoimmune disorders, particularly those with late-onset or clonal features, such as autoim­mune lymphoproliferative syndromes. Moreover, polygenic risk scores (PRS), which aggregate the effects of multiple SNPs, are increasingly used to estimate an individual’s genetic predisposition to autoimmune diseases. While the genetic architecture of these diseases is complex and involves gene–environment interactions, the integration of variant databases like d bS N P, dbVa r, C li nVa r, and gnomAD with functional genomics is shedding light on pathogenic mechanisms. This ongoing research not only deepens our understanding of autoimmune diseases but also opens avenues for personalized diagnostics and therapeutics based on genetic risk proling.
Var ia nt calling from high-throughput sequencing data is a critical computational process in genomics that involves identifying differences between a sequenced genome and a reference genome. The process begins with the generation of raw sequencing reads, typically in the form of paired-end short reads from platforms such as Illumina. These reads undergo quality control steps to remove low-quality bases, adapter contamination, and other sequencing artifacts. The cleaned reads are then aligned or mapped to a reference genome using efcient alignment algorithms like BWA or Bowtie2. This step generates alignment les in SAM or BAM format, where each read is placed at its most likely origin in the reference genome.
Once reads are aligned, the next step involves preprocessing to ensure accurate variant detec­tion. This includes sorting the alignments, marking duplicate reads (which may arise during PCR amplication), and performing base quality score recalibration to correct systematic sequencing errors. Tools like Picard and GATK are commonly used in this phase. After preprocessing, the variant calling algorithms scan the alignments to identify sites where the sequenced data differs from the reference. These differences can include single nucleotide variants (SNVs), insertions and deletions (indels), and, in some workows, larger structural variants. Variant callers such as GATK HaplotypeCaller, FreeBayes, or SAMtools mpileup use probabilistic models to assess the likelihood of a variant being present, taking into account read depth, base quality, and allele balance.
The output of variant calling is typically a Variant Call Format (VCF) le, which contains detailed information about each candidate variant, including its position, reference and alterna­tive alleles, genotype likelihoods, and quality metrics. To distinguish true biological variants from sequencing artifacts, additional ltering is applied based on quality thresholds or machine learn­ing models trained on known variant datasets. For example, the GATK framework uses a process called variant quality score recalibration (VQSR) to assign condence scores and classify variants into high- and low-quality categories. In cases where multiple samples are analyzed simultaneously, joint genotyping can be performed to increase accuracy and consistency across individuals.
The accuracy of variant calling can be inuenced by several factors, including sequencing depth, genome complexity, the presence of repetitive regions, and the quality of the reference genome. Therefore, variant callers often include specic strategies to handle complex regions or low­frequency variants, particularly important in cancer genomics or studies of rare genetic disorders. Following variant calling, annotation tools such as ANNOVAR or SnpEff are used to interpret the biological signicance of each variant, linking them to genes, known polymorphisms in databases like dbSNP or ClinVar, or predicted functional consequences. Overall, variant calling is a corner­stone of modern genomics, enabling discoveries in disease research, population genetics, and per­sonalized medicine by translating raw sequence data into meaningful genetic insights.
In the context of autoimmune diseases, variant calling from high-throughput sequencing data serves as a foundational step in autoimmune disease research, enabling the detection of genetic variations that may underlie disease susceptibility, progression, and therapeutic response. One of the primary goals is the identication of both common and rare variants that contribute to disease predisposition. While GWAS have historically focused on common variants with modest effect sizes, variant calling from whole-genome and whole-exome sequencing (WES) allows researchers to uncover rare variants with potentially stronger, more penetrant effects in coding or regulatory
206 Bioinformatics of Autoimmune Diseases
regions. These variants can provide critical insights into disease mechanisms that are not detectable through traditional genotyping arrays.
Another key objective is the comprehensive proling of variants across diverse genomic con­texts, including coding regions, untranslated regions (UTRs), introns, promoters, enhancers, and other regulatory elements. In autoimmune diseases, non-coding variants often play a substantial role by modulating gene expression in immune cells. Accurate variant calling enables researchers to map these functional non-coding variants and integrate them with expression quantitative trait loci (eQTL) analyses, epigenomic annotations, and chromatin interaction data to determine their regula­tory impact. This integration can reveal how genetic variants inuence gene expression networks and immune pathways that drive autoimmunity.
Var ia nt calling also aims to characterize somatic mutations in immune cells, particularly in disorders where clonal expansion or mosaicism is suspected. This is especially relevant for late­onset autoimmune diseases or conditions with atypical features, where somatic variants may affect immune signaling or tolerance mechanisms. Detecting these low-frequency variants requires high­depth sequencing and sensitive bioinformatic pipelines capable of distinguishing true somatic muta­tions from sequencing artifacts. These ndings help elucidate how acquired mutations contribute to immune dysregulation and may inform future precision medicine strategies.
Furthermore, a critical goal is the detection of structural variants such as insertions, deletions, inver­sions, and CNVs. These larger genomic alterations can disrupt gene function or dosage, and variant calling pipelines are increasingly incorporating specialized tools and algorithms designed to capture such complex events. In autoimmune disease research, structural variants in genes related to the com­plement system, immunoglobulin loci, or HLA regions have been shown to signicantly affect disease risk and phenotype. High-throughput variant calling facilitates a more holistic view of the genome, allowing researchers to assess both sequence-level and structural changes contributing to disease.
Last, variant calling supports the construction of personalized genomic proles and PRS for autoimmune diseases. By aggregating variant data from large cohorts and integrating it with clini­cal phenotypes, researchers can stratify individuals based on their genetic risk. This not only aids in early detection and diagnosis but also guides the development of targeted therapies and individual­ized treatment plans. As sequencing technologies continue to advance, the goals of variant calling are expanding beyond discovery toward clinical application, offering the potential for precision medicine in autoimmune disease management.
Variant detection relies on several types of high-throughput sequencing data, each tailored to specic research or clinical objectives. Whole-genome sequencing (WGS) provides the most com­prehensive view of the genome, covering both coding and non-coding regions. It allows for the detection of a wide range of variants, including SNVs, insertions and deletions (indels), structural variants, and CNVs across the entire genome. This depth of information makes WGS particularly valuable for discovering novel variants and studying complex traits or diseases with heterogeneous genetic bases. However, the high cost and data storage requirements make it less common in routine clinical use compared to more targeted approaches.
WES, in contrast, focuses only on the protein-coding regions of the genome, which comprise about 1–2% of the genome but account for a signicant proportion of known disease-causing muta­tions. Because of its lower cost and data volume, WES is widely used in both research and diagnos­tics to identify coding variants linked to Mendelian disorders and other phenotypes. While WES misses regulatory and intergenic variants, it provides high coverage of exons, allowing for accurate variant detection in coding regions. RNA sequencing (RNA-Seq), while primarily used for tran­scriptome proling, can also be employed for variant calling. Variants detected from RNA-Seq data reect only the transcribed portion of the genome, which adds a layer of functional context, espe­cially in studies of gene expression, splicing, and allele-specic expression in disease states such as cancer and autoimmune conditions.
Long-read sequencing technologies, such as those from Oxford Nanopore and Pacic Biosciences, have transformed variant analysis by enabling the detection of large structural variants and complex
207 Variant Analysis
genomic rearrangements that are difcult to resolve with short-read platforms. Long reads span repetitive or Guanine-Cytosine (GC)-rich regions more effectively and can provide phased haplo­types, revealing the cis or trans conguration of variants. These capabilities are particularly useful in resolving ambiguities in immune loci, such as the HLA region, which is highly polymorphic and relevant to many autoimmune diseases. While long-read sequencing has historically had higher error rates, improvements in base calling and consensus algorithms are making it increasingly reli­able for both research and clinical applications.
After variant calling, the resulting data is stored in standardized le formats, with the VCF being the most widely used. A VCF le encodes each variant with details, including its genomic position, reference and alternate alleles, quality scores, read depth, and genotype information for each sample. The format is extensible and includes metadata lines for annotations such as gene names, predicted functional effects, and population frequencies. For multi-sample projects, the VCF format supports the storage of genotype calls across many individuals in a compact and structured way. Binary versions of VCF les, known as BCF, are also used to save space and allow for faster computation.
In addition to VCF and BCF, structural variants and complex rearrangements are often stored in formats such as BED, which represents genomic intervals, or specialized formats like GVF (Genome Variation Format) and GFF3 for annotated features. Annotation tools may output variant data with added functional or clinical information in custom formats or as augmented VCFs. These les can be indexed and visualized in genome browsers or integrated into databases for downstream analysis. As sequencing technologies and variant detection algorithms evolve, maintaining interop­erability and efciency in le formats remains essential for the scalable analysis and sharing of genomic data.
6.2 EXPERIMENTAL DESIGN FOR VARIANT CALLING
The accuracy and interpretability of variant calling heavily depend on careful experimental design and rigorous sample preparation protocols. At the earliest stages, choosing the appropriate sequenc­ing platform, coverage depth, and sample type are critical decisions shaped by the research ques­tion. For instance, high-coverage WGS is often necessary for detecting rare variants or structural rearrangements, whereas whole-exome or targeted sequencing might sufce for identifying known disease-associated mutations. DNA is the most common starting material for variant calling, and its extraction must ensure high integrity and purity, free from contaminants such as proteins, RNA, or chemical residues. The quality of extracted DNA is typically assessed using spectrophotometric methods and fragment analysis, as degraded or low-concentration samples can introduce artifacts in downstream variant analysis.
Different study designs offer distinct advantages depending on the hypothesis being tested. Case-control studies are among the most widely used for identifying variants associated with auto­immune diseases. They compare allele frequencies between individuals with the disease (cases) and without it (controls) to identify statistically signicant associations. However, such studies must carefully match controls based on population background to avoid confounding due to population stratication. Family-based designs, such as trio or pedigree studies, are powerful for identifying inherited variants and de novo mutations, particularly in early-onset or rare autoimmune conditions. Longitudinal studies, while more resource-intensive, provide temporal data and allow researchers to assess how genetic variants interact with environmental factors over time or inuence disease progression and response to treatment. The choice of design signicantly inuences the statistical power, variant interpretation, and generalizability of the results.
While DNA remains the primary source material for variant calling, RNA-Seq is increasingly used to detect variants in the transcribed portion of the genome. RNA-based variant calling pro­vides insights into the functional impact of variants by linking them directly to gene expression. It is especially useful in cancer and autoimmune research where gene expression patterns are often dys­regulated. For example, RNA-Seq can identify allele-specic expression or splicing defects, which
208 Bioinformatics of Autoimmune Diseases
might not be apparent in DNA sequencing. However, RNA-Seq variant calling presents unique challenges, such as variable transcript abundance, RNA editing, and intron–exon boundaries, which can complicate accurate alignment and variant calling. Therefore, RNA-Seq variant calls are often used in combination with DNA-based calls for validation and interpretation.
Sample quality control is essential to ensure reliable results across sequencing runs. This includes conrming DNA/RNA purity, integrity, and concentration before library preparation. In large-scale studies, consistency in sample handling, storage conditions, and sequencing protocols reduces tech­nical variability. In addition to biological quality control, robust metadata collection is critical. Metadata includes demographic information, clinical diagnosis, treatment history, environmental exposures, and comorbid conditions, all of which can inuence variant interpretation. In autoim­mune disease studies, where heterogeneity is common, richly annotated metadata enables stratica­tion of samples and improves the precision of genotype–phenotype correlations.
Ethical considerations are paramount in studies involving genetic data, especially in diseases like autoimmunity where lifelong health information is implicated. Informed consent must clearly communicate the scope of data usage, potential ndings, data sharing policies, and the rights of par­ticipants to withdraw. Researchers must also address the possibility of incidental ndings, genetic variants unrelated to the study but potentially relevant to a participant’s health. Biobanking, which involves the long-term storage of biological samples and associated data, has become a key com­ponent of autoimmune research. Modern biobanks incorporate secure data systems, standardized protocols for sample preservation, and governance models that enable responsible data access while protecting privacy. With increasing international collaboration, harmonization of ethical frame­works and data-sharing agreements is essential to maximize the impact of variant calling in under­standing and treating autoimmune diseases.
6.3 VARIANT CALLING BEST PRACTICES FOR AUTOIMMUNE DISEASES
The variant calling workow (Figure 6.1) begins with the acquisition of high-quality sequencing data, which forms the foundation for accurate detection of genetic variants. For studies on autoim­mune diseases, WGS or WES is typically employed, depending on the research objectives and avail­able resources. WGS is preferred when non-coding regulatory regions are of interest, while WES offers a cost-effective alternative focused on coding regions where many disease-associated vari­ants are known to reside. Once sequencing is complete, raw data in FASTQ format undergo quality
FIGURE 6.1 The general variant calling owchart.
209 Variant Analysis
control to assess read quality, GC content, and potential adapter contamination. Tools like FastQC and Trimmomatic are commonly used in this stage to remove low-quality reads and artifacts, ensur­ing cleaner data for alignment.
Following quality control, the reads are aligned to a reference genome, usually the latest GRCh38 build, using a highly accurate aligner such as BWA-MEM. The output is a SAM/BAM le, which records the position of each read on the reference genome. This alignment step is crucial, especially for autoimmune disease-associated loci, many of which reside in complex genomic regions like the HLA cluster, where high sequence similarity and polymorphism can complicate mapping. To address this, best practices include using specialized aligners or reference graphs that better handle variabil­ity in immune loci. Once aligned, post-processing steps such as sorting, marking duplicates, and base quality score recalibration are conducted to improve data reliability. These steps are vital for reduc­ing false positives and are standardized in frameworks such as the GATK best practices pipeline.
Var ia nt calling itself is carried out using tools like GATK HaplotypeCaller, FreeBayes, or DeepVariant, which apply probabilistic models or machine learning to identify potential variants. These tools evaluate the evidence for differences at each genomic position, taking into account base quality, allele balance, and depth of coverage. For autoimmune studies, joint genotyping across all samples is often recommended to improve variant detection sensitivity and consistency, especially for identifying shared variants among cases. The resulting output is a VCF le, containing the posi­tion, type, and genotype of each variant. The variant calls are then subjected to quality ltering using hard thresholds or more advanced techniques like VQSR, which uses training sets of known variants to distinguish true positives from sequencing artifacts.
Annotation of the ltered variants is the next critical step. Tools like A NNOVA R, SnpEff, or VEP (Variant Effect Predictor) are used to assign biological meaning to each variant by predicting func­tional effects, mapping variants to genes, and cross-referencing databases such as dbS NP, ClinVa r, gnomAD, and autoimmune-specic resources. For autoimmune disease research, this step is partic­ularly informative, as it helps highlight variants affecting immune-related genes, such as PTPN22, STAT4, IL23R, and HLA-DRB1. Annotation can also include predictions of pathogenicity—using algorithms like CADD or REVEL, and integration with expression data can help determine whether variants have regulatory impacts.
Best practices for autoimmune disease variant calling also emphasize the importance of integrat­ing genetic data with phenotypic and environmental metadata. Because autoimmune disorders often involve gene–environment interactions and present heterogeneously across individuals, statistical models that account for covariates such as age, sex, ancestry, and exposure history enhance the power of association analyses. Furthermore, combining DNA- and RNA-based variant calls can provide a functional context for interpreting disease-associated variants, especially those affecting gene expression or splicing. In particular, RNA-Seq can be used to identify allele-specic expres­sion patterns or aberrant transcripts linked to variants detected in DNA data.
Finally, validation of key variants through independent technologies, such as Sanger sequenc­ing or qPCR, is a recommended best practice, especially when variants are considered for clini­cal interpretation or therapeutic targeting. Data sharing through repositories like dbGaP or EGA, adherence to FAIR data principles, and ethical management of participant information are also crit­ical in ensuring the long-term impact and reproducibility of variant calling studies in autoimmune diseases. As methods continue to evolve, incorporating multi-omic data and leveraging machine learning will further rene variant interpretation and accelerate discoveries in autoimmune disease genetics.
6.4 VARIANT CALLING PIPELINE
In this section, we will walk through the pipeline step by step. The workow has been modular­ized into Python functions for clarity and ease of management. The pipeline requires two primary inputs: (1) paired-end FASTQ les stored in a designated directory, and (2) a CSV le containing
210 Bioinformatics of Autoimmune Diseases
TABLE 6.1 Study Metadata used for Variant Calling
runID RF
ERR9539328 Negative ERR9539251 Negative ERR9539353 Negative ERR9539358 Positive ERR9539313 Positive ERR9539319 Positive
the study design metadata, including the sample SRA run IDs and rheumatoid factor (RF) status (Table 6.1). For demonstration purposes, we will use FASTQ data from six individuals: three with positive RF and three with negative RF. This analysis is intended to demonstrate the process of conducting variant analysis, rather than to draw any scientic conclusions.
To begin the demonstration, we rst need to download the raw data from the NCBI SRA data­base. Start by creating a text le containing the run IDs, with one ID per line, and name this le id s.t xt . For better organization, create a dedicated project directory. Within this directory, copy the run IDs from Table 6.1 into a new le and save it as id s.t xt . Next, copy the download _ fa stq.p y script into the same directory and execute it. The script will automatically create a subdirectory named d ata/raw and download the corresponding FASTQ les into it.
Please note that the download process may take some time depending on your internet speed and system performance. Also, ensure that you have sufcient disk space to store both the raw data and the les generated during subsequent analysis steps. Once the les have been downloaded, you can use the gzip command to compress them and conserve storage space.
The second step is to create a directory named meta, and within that directory, create a le called metadata.txt. This le should be in CSV format and contain the following information:
run ID,RF ERR9539328,negative ERR9539251,negative ERR9539353,negative ERR9539358,positive ERR9539313,positive ERR9539319,positive
The complete pipeline is implemented in the script variant _ calling _ pipeline.py. In the following sections, we will provide a detailed discussion of the functions that constitute this pipeline.
6.4.1 DOWNLOADING AND INDEXING A REFERENCE GENOME
def run_command(command):
print(f"Running: {command}") subprocess.run(command, shell=True, check=True)
def download_and_index_reference(reference_url, output_dir):
os.makedirs(output_dir, exist_ok=True) compressed_path = os.path.join(output_dir, "reference.fasta.gz") ref_fasta = os.path.join(output_dir, "reference.fasta") ref_dict = ref_fasta.replace(".fasta", ".dict") run_command(f"wget -O {compressed_path} {reference_url}") run_command(f"gunzip -c {compressed_path} > {ref_fasta}")
211 Variant Analysis
run_command(f"samtools faidx {ref_fasta}") # Delete. dict if it exists if os.path.exists(ref_dict):
os.remove(ref_dict)
run_command(
f"gatk CreateSequenceDictionary "
f"-R {ref_fasta} "
f"-O {ref_dict}" ) run_command(f"bwa index {ref_fasta}") return ref_fasta
The download _ and _ index _ reference function initiates and prepares the reference genome, a fundamental requirement for any read alignment and variant calling pipeline. It begins by creating the output directory if it does not already exist, ensuring that the necessary workspace is available. The function then downloads a compressed reference genome le from a given URL using wget and decompresses it into a standard FASTA format using gunzip. This FASTA le will serve as the primary reference sequence for mapping reads and identifying genetic variants.
Once the FASTA le is prepared, the function runs samtools faidx to create a FASTA index le, which enables rapid random access to any part of the reference genome. This index is required by many downstream tools that process genomic data. Before generating a new sequence dictionary with GATK’s CreateSequenceDictionary, the function checks whether a .dict le already exists and removes it to avoid conicts or using outdated metadata. The sequence dictionary is a necessary input for GATK-based tools, ensuring that the reference genome is correctly interpreted during analysis. Finally, the function runs bwa index to generate alignment indices specically for BWA, enabling fast and accurate read alignment to the reference.
This function’s impact on the variant calling pipeline is foundational. It ensures that the reference genome is correctly formatted and indexed for use across a variety of bioinformatics tools. Without these indexing steps, the pipeline would fail or operate inefciently during alignment, quality reca­libration, and variant calling. By automating the entire setup process, this function also reduces user error and standardizes the environment, contributing to the accuracy and reproducibility of the pipeline.
6.4.2 QUALITY CONTROL
def quality_control(fastq_files, output_dir):
os.makedirs(output_dir, exist_ok=True) for fq in fastq_files:
run_command(f"fastqc {fq} -o {output_dir}")
def trim_reads(sample_name, r1, r2, output_dir):
os.makedirs(output_dir, exist_ok=True) out_r1 = os.path.join(output_dir, f"{sample_name}_R1_trimmed.fastq.gz") out_r2 = os.path.join(output_dir, f"{sample_name}_R2_trimmed.fastq.gz")
run_command(
f"trimmomatic PE {r1} {r2} {out_r1} /dev/null "
f"{out_r2} /dev/null SLIDINGWINDOW:4:20 MINLEN:50" ) return out_r1, out_r2
The quality _ control function will assess the quality of raw sequencing reads before any further processing takes place in the variant calling pipeline. It takes a list of FASTQ les and an output directory as inputs. The function rst ensures that the specied output directory exists or creates it if it doesn’t. Then, for each FASTQ le provided, it runs the fastqc command-line tool,
212 Bioinformatics of Autoimmune Diseases
which generates a comprehensive quality report. These reports include important metrics such as per-base sequence quality, GC content, sequence duplication levels, and potential contamination. The outputs are saved in the designated directory, allowing users to visually inspect and evaluate the data quality before proceeding with trimming and alignment steps. This helps to identify prob­lematic samples early in the analysis and guides decisions on how to preprocess the data.
The trim _ reads function focuses on improving read quality by trimming low-quality bases and ltering out short reads using the trimmomatic tool. It is specically designed to handle paired­end reads, accepting a sample name and two FASTQ les representing the forward (R1) and reverse (R2) reads, along with an output directory. The function constructs le paths for the trimmed out­puts using the sample name, then invokes trimmomatic in paired-end mode. The trimming set­tings include a sliding window lter that removes low-quality regions (with a window size of 4 and minimum average quality of 20) and a minimum length lter that discards reads shorter than 50 bp. Output les for the successfully paired, trimmed reads are retained, while unpaired reads are discarded by redirecting them to /dev/null. The function returns the paths to the cleaned and compressed FASTQ les, which are then ready for alignment to the reference genome. This step is essential for improving mapping accuracy and reducing noise in downstream variant calling.
6.4.3 READ MAPPING
def align_reads(sample_name, ref_genome, r1_trimmed, r2_trimmed, output_dir):
os.makedirs(output_dir, exist_ok=True) sam_file = os.path.join(output_dir, f"{sample_name}.sam") bam_file = os.path.join(output_dir, f"{sample_name}.bam") rg_bam_file = os.path.join(output_dir, f"{sample_name}_rg.bam") # Step 1: Align without read group run_command(
f"bwa mem {ref_genome} " f"{r1_trimmed} {r2_trimmed} "
f"> {sam_file}" ) # Step 2: Convert to BAM run_command(f"samtools view -Sb {sam_file} > {bam_file}") # Step 3: Add proper read group run_command( (
f"picard AddOrReplaceReadGroups " f"I={bam_file} " f"O={rg_bam_file} " f"RGID={sample_name} " f"RGLB=lib1 " f"RGPL=ILLUMINA " f"RGPU=unit1 " f"RGSM={sample_name} " f"VALIDATION_STRINGENCY=LENIENT"
) ) return rg_bam_file
The align _ reads function carries out a critical step in the variant calling pipeline by align- ing high-quality, trimmed paired-end reads to a reference genome and preparing them with stan­dardized metadata for downstream processing. It takes a sample name, reference genome path, the paths to the trimmed forward and reverse reads, and an output directory. The function rst ensures that the output directory exists and then denes the paths for the intermediate SAM le, an initial BAM le, and the nal BAM le that includes proper read group information.
213 Variant Analysis
The function proceeds in three stages. First, it uses BWA-MEM to align the paired reads to the ref­erence genome, generating a SAM le that contains alignment information for each read. This le is in human-readable format but not optimized for storage or processing, so in the second step, the function converts the SAM le to a binary BAM format using samtools view. The BAM format is more compact and efcient for analysis tools to handle. In the third and nal step, the function uses Picard‘s AddOrReplaceReadGroups tool to attach standardized metadata to each read, including sample ID, library, platform, platform unit, and sample name. These read group tags are essential for tools such as GATK to correctly distinguish between different samples and sequencing runs, and they enable important steps like duplicate marking and base quality score recalibration to operate correctly.
By producing a BAM le that contains both accurate alignment information and complete read group metadata, this function ensures that each sample is traceable and properly formatted for the variant calling workow. This step signicantly contributes to the reliability of downstream analy­ses by enabling the pipeline to process multiple samples in a consistent and reproducible manner. It ensures compatibility with industry-standard tools and provides the structural backbone for the rest of the pipeline’s data processing.
6.4.4 MARKING DUPLICATE READS
def convert_sort_mark_duplicates(sample_name, bam_file, output_dir):
os.makedirs(output_dir, exist_ok=True) sorted_bam = os.path.join(output_dir, f"{sample_name}_sorted.bam") dedup_bam = os.path.join(output_dir, f"{sample_name}_dedup.bam") metrics_file = os.path.join(output_dir, f"{sample_name}_metrics.txt") run_command(f"samtools sort {bam_file} -o {sorted_bam}") run_command(
f"gatk MarkDuplicates " f"-I {sorted_bam} " f"-O {dedup_bam} "
f"-M {metrics_file}" ) return dedup_bam
The convert _ sort _ mark _ duplicates function is responsible for preparing raw alignment data for accurate variant analysis by sorting the alignments and identifying duplicate reads. It takes a sample name, a BAM le (typically produced from aligning sequencing reads to a reference genome), and an output directory. The function ensures the output directory exists before proceeding with further processing. It denes the le paths for the sorted BAM le, the dedupli­cated BAM le, and a metrics le that will contain statistics about the duplication process.
The function begins by sorting the input BAM le using samtools sort. Sorting the reads by their genomic coordinates is an essential prerequisite for many downstream tools in the variant calling pipeline, particularly those that rely on the positional context of reads to function correctly. After sorting, the function runs GATK’s MarkDuplicates tool to identify and label duplicate reads. These duplicates often arise during PCR amplication steps in library preparation and can lead to articial ination of read depth and false variant calls if left unaddressed. The deduplicated output le contains all reads, but those identied as duplicates are agged accordingly so that vari­ant callers can ignore them during analysis.
This function is vital for ensuring the integrity of the data passed on to variant callers. By sorting and marking duplicates, it minimizes technical artifacts and enhances the reliability of variant detection. The deduplicated BAM le it produces becomes a clean and accurate represen­tation of the sample’s aligned reads, suitable for base quality recalibration and condent variant calling.