<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fatma Zehra Sarı on Medium]]></title>
        <description><![CDATA[Stories by Fatma Zehra Sarı on Medium]]></description>
        <link>https://medium.com/@fzehrasari?source=rss-29084d33b030------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eAGgCL9d7Lqbc-op4-To4Q.jpeg</url>
            <title>Stories by Fatma Zehra Sarı on Medium</title>
            <link>https://medium.com/@fzehrasari?source=rss-29084d33b030------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:28:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fzehrasari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[‍From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data…]]></title>
            <link>https://medium.com/@fzehrasari/from-raw-reads-to-high-quality-variants-a-bioinformatics-guide-to-genomic-data-cf67b6009e9c?source=rss-29084d33b030------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf67b6009e9c</guid>
            <category><![CDATA[gatk]]></category>
            <category><![CDATA[variant-calling]]></category>
            <category><![CDATA[gvcf]]></category>
            <category><![CDATA[vcf]]></category>
            <dc:creator><![CDATA[Fatma Zehra Sarı]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 14:29:35 GMT</pubDate>
            <atom:updated>2025-07-09T12:00:51.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧬👩🏻‍💻From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data Processing, Quality Control, and Analysis -4-</h3><p>In the previous step, we applied <strong>Base Quality Score Recalibration (BQSR)</strong> to correct systematic errors in sequencing quality scores. This produced the file NA12878.recalibrated.bam, which serves as the input for variant calling.</p><p>To detect variants, we use <strong>GATK’s HaplotypeCaller</strong> — a tool that analyzes the BAM file to identify differences between the sample and the reference genome. It can produce output in different formats depending on the analysis goal. If we are analyzing <strong>a single sample</strong>, HaplotypeCaller can directly generate a standard <strong>VCF</strong> file that lists only the positions where variants are found. However, if we plan to analyze <strong>multiple samples together</strong>, the recommended approach is to use <strong>gVCF mode</strong> by setting the -ERC GVCF option.</p><h3>Chapter 1. What is a gVCF?</h3><p>A <strong>gVCF (genomic VCF)</strong> file contains not only the variant positions but also summarizes regions where no variants were found. Instead of listing every single matching base, it groups long stretches of reference-matching bases into <strong>reference blocks</strong>. These are compactly represented using special fields such as &lt;NON_REF&gt; and END.</p><p>For example, if a 1,000-base region in the genome is identical to the reference, the gVCF stores it as <strong>one single record</strong> instead of 1,000 separate entries. This significantly reduces file size and makes downstream <strong>joint genotyping</strong> across multiple samples much more efficient.</p><h3>1.1.Reference Confidence Modes (-ERC)</h3><p>HaplotypeCaller supports two reference confidence modes, which are controlled by the -ERC option:</p><ul><li>GVCF: Recommended for multi-sample workflows. Compresses non-variant regions into blocks.</li><li>BP_RESOLUTION: Outputs a separate line for every base, whether variant or not — this gives full detail but creates much larger files.</li></ul><p>In most cases, <strong>-ERC GVCF</strong> is the preferred option because it strikes a good balance: it includes both variant and reference information while keeping the file size manageable:</p><pre># Run the GATK HaplotypeCaller in a Docker container with timing and nohup (non-interactive)<br>nohup time docker run --rm -v /path/to/project_data:/workspace broadinstitute/gatk:latest \<br>  <br>  # Execute GATK&#39;s HaplotypeCaller with 8GB of Java memory<br>  gatk --java-options &quot;-Xmx8G&quot; HaplotypeCaller \<br>  <br>  # Reference genome<br>  -R /workspace/hg38_v0_Homo_sapiens_assembly38.fasta \  <br>    <br>  # Input BAM file<br>  -I /workspace/NA12878.recalibrated.bam \               <br>      <br>  # Output gVCF file<br>  -O /workspace/NA12878.g.vcf.gz \                       <br>      <br>  # Emit Reference Confidence mode: GVCF<br>  -ERC GVCF \ # To be able to produce VCF from bam file, remove this line and -O /workspace/NA12878.vcf.gz                                            <br>    <br>  # Redirect output to log file and run in background<br>  &gt; nohup_haplotypecaller.log 2&gt;&amp;1 &amp;</pre><p><strong><em>Note</em></strong><em>:</em> To produce a standard VCF instead, simply remove the -ERC GVCF line and adjust the output path (e.g., -O NA12878.vcf.gz). This will emit only variant sites.</p><p>This command generates a compressed gVCF file (.g.vcf.gz) that includes both variant sites and reference blocks. In our case, <strong>HaplotypeCaller took around 48 hours to complete on a single CPU</strong>. Adding more CPU cores speeds up the process at first, but the benefit levels off after <strong>4 to 8 threads</strong>, showing <strong>diminishing returns</strong> (Ref: <a href="https://hpc.nih.gov/training/gatk_tutorial/haplotype-caller.html">https://hpc.nih.gov/training/gatk_tutorial/haplotype-caller.html</a>).</p><p>The log file from this command provides useful runtime details such as:</p><ul><li>Elapsed time</li><li>Number of genomic regions processed</li><li>Processing speed per interval</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sF5HlQ3UjKEO1ZeXm4yJ1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSSqVOXYOpPXGuzRKyiy-g.png" /><figcaption>Top and bottom sections of the <strong>nohup_haplotypecaller.log</strong>.</figcaption></figure><p>We can inspect a gVCF using bcftools to view either non-variant reference blocks or true variant sites:</p><pre># Displays gVCF records where &lt;NON_REF&gt; is the only alternate allele, representing non-variant reference blocks<br>bcftools view -H /workspace/NA12878.g.vcf.gz | awk &#39;$5==&quot;&lt;NON_REF&gt;&quot;&#39; | head<br><br># Displays gVCF records containing true alternate alleles (SNPs or indels), which may also include &lt;NON_REF&gt;, representing variant sites<br>bcftools view -v snps,indels -H NA12878.g.vcf.gz | head</pre><p>In the first case, we see non-variant regions; in the second, we capture true variants, typically shown with &lt;NON_REF&gt; alongside a real alternate allele like T,&lt;NON_REF&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPF06coelhH77S9rlhoGyQ.png" /><figcaption>Output of <strong>bcftools view -H NA12878.g.vcf.gz | awk ‘$5==”&lt;NON_REF&gt;”’ | head</strong>. These records represent non-variant reference blocks in the gVCF, where &lt;NON_REF&gt; is the only alternate allele. They indicate regions with no observed variation, which are compressed into intervals using the END field to reduce file size while retaining reference confidence information for joint genotyping.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_NdtKSsIuqsFTksjyc1lw.png" /><figcaption>Output of <strong>bcftools view -v snps,indels -H NA12878.g.vcf.gz | head</strong>. These records correspond to <strong>variant sites in gVCF format</strong> where a true alternate allele (e.g., T or G) is reported alongside &lt;NON_REF&gt;. This structure reflects the gVCF&#39;s design to retain reference confidence information at all sites while indicating real variation. Such entries are typical in single-sample gVCFs and support accurate joint genotyping downstream.</figcaption></figure><h3><strong>Chapter 2. Converting gVCF to VCF</strong></h3><p>Once gVCF files are generated for all samples, we use <strong>GATK’s GenotypeGVCFs</strong> to merge and genotype them, producing a final .vcf.gz file with definitive genotype calls. This step interprets the reference confidence data in the gVCFs and outputs a fully genotyped VCF.</p><pre># Run the GATK GenotypeGVCFs tool in Docker to call final genotypes from the gVCF<br>nohup time docker run --rm -v /path/to/project_data:/workspace broadinstitute/gatk:latest \<br>  <br>gatk GenotypeGVCFs \<br><br>    -R /workspace/hg38_v0_Homo_sapiens_assembly38.fasta \  <br><br>    # Input gVCF file<br>    -V /workspace/NA12878.g.vcf.gz \   <br><br>    # Output final VCF with genotypes            <br>    -O /workspace/NA12878.vcf.gz \  <br>                       <br>  &gt; genotypegvcfs.log 2&gt;&amp;1 &amp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xtm_DtW6_K24bCoHBfNs7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eU-ItasYp3FHD_hxCYnd-w.png" /><figcaption>Top and bottom sections of the <strong>genotypegvcfs.log</strong> file.</figcaption></figure><p>The genotypegvcfs.log file includes runtime details and warnings. For example, messages like <strong>&quot;Annotation MLEAC=[1,0] was not found in the header (chr1:14115)&quot;</strong> are harmless and do not affect results. In our case, the tool completed successfully in about <strong>2 hours and 40 minutes</strong>, processing over <strong>581 million gVCF records</strong>, including both variant sites and reference blocks. The resulting VCF file is now ready for downstream filtering and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOFtldayBr04oo-jPfcrYg.png" /><figcaption>Output of <strong>bcftools view -H NA12878.vcf.gz | head | column -t</strong>.</figcaption></figure><h3><strong>Chapter 3. </strong>Comparing Variant Representation in gVCF and VCF Formats</h3><p>Let’s compare the <strong>same variant position (chr1:14115)</strong> in gVCF and VCF formats:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkqUtppy5ZDRQTfY76Julg.png" /></figure><p>Both show the A→T variant, but the gVCF also includes &lt;NON_REF&gt; to capture reference confidence. INFO and FORMAT fields differ slightly, with gVCF containing extra tags (e.g., SB) to support joint genotyping.</p><p>Key columns:</p><ul><li>Chromosome &amp; position (cols 1–2)</li><li>Variant ID (col 3, often missing)</li><li>Reference &amp; alternate alleles (cols 4–5; gVCF may include &lt;NON_REF&gt;)</li><li>Quality score (col 6)</li><li>Filter status (col 7)</li><li>INFO annotations like depth and allele frequency (col 8)</li><li>FORMAT (col 9) and sample genotype data follow</li></ul><p>In summary, VCF lists only confirmed variants, while gVCF captures both variant and non-variant sites, enabling accurate multi-sample joint genotyping.</p><h3>Chapter 4. What Is the Algorithm Behind HaplotypeCaller?</h3><p>A BAM file is essentially a vast dataset containing millions of short DNA sequences called reads, which have been aligned to a reference genome. The purpose of <strong>GATK HaplotypeCaller</strong> is to identify small differences — known as <strong>variants</strong> — within this dataset that deviate from the reference sequence.</p><p>The variant calling process in HaplotypeCaller involves four main steps. Here’s an overview, imagining how it analyzes the reads in a BAM file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*Z9JITMvJCI1dUO0V" /><figcaption>The four-step workflow of GATK’s HaplotypeCaller variant calling process.</figcaption></figure><h3><strong>4.1. Flag Suspicious Areas: Finding Active Regions</strong></h3><p>HaplotypeCaller scans the BAM file thoroughly, similar to a careful editor reviewing a text. It focuses on regions where the reads consistently differ from the reference genome. For example, if the reference genome has an ‘A’ at position 100, but 8 out of 10 aligned reads show a ‘G’, HaplotypeCaller flags this position as an <strong>active region</strong>. This signals a potential variant site that requires deeper analysis.</p><h3><strong>4.2. Create Possible DNA Scenarios: Haplotype Assembly</strong></h3><p>For each active region flagged in the previous step, HaplotypeCaller doesn’t simply consider single base changes. Instead, it reconstructs all plausible DNA sequences (called <strong>haplotypes</strong>) spanning that region by assembling overlapping read fragments. This is achieved using a data structure known as a <strong>de Bruijn graph</strong>, which effectively pieces together short sequences from the reads into longer candidate haplotypes.</p><p>For example, suppose the <strong>reference </strong>sequence in a region is:</p><p>...TAGC<strong>A</strong>TACG...</p><p>While many reads show:</p><p>...TAGC<strong>G</strong>TACG...</p><p>Rather than only testing an ‘A’ to ‘G’ substitution at a single position, HaplotypeCaller builds several possible haplotypes such as:</p><ul><li><strong>Haplotype 1</strong> (Reference): ...TAGCATACG...</li><li><strong>Haplotype 2</strong> (Common variant): ...TAGCGTACG...</li><li><strong>Haplotype 3</strong> (Less frequent alternative): ...TAGCTACTG...</li></ul><h3><strong>4.3. Evaluate Each DNA Piece Against Every Scenario: Calculating Read Likelihoods</strong></h3><p>Next, HaplotypeCaller compares each read aligned to the active region against all candidate haplotypes generated earlier. It uses a sophisticated probabilistic model called <strong>Pair Hidden Markov Model (PairHMM)</strong> to calculate how likely each read originated from each haplotype. This model also incorporates sequencing errors to provide accurate likelihood estimates.</p><p>For example, consider a read sequence: AGCGT</p><ul><li>Compared to Haplotype 1 (AGCAT), PairHMM might estimate a 50% likelihood due to one base mismatch.</li><li>Compared to Haplotype 2 (AGCGT), the likelihood could be 99%, reflecting near-perfect alignment.</li></ul><p>By computing these likelihoods for every read and haplotype, HaplotypeCaller quantifies how well each candidate sequence explains the observed data in the region.</p><h3><strong>4.4. Determine the Most Likely True DNA State: Assigning Genotypes</strong></h3><p>After computing read likelihoods for all candidate haplotypes, HaplotypeCaller applies a rigorous statistical model to determine the most probable genotype at the active region. It evaluates which combination of haplotypes best explains the observed sequencing data.</p><p>For example, if 20 reads cover position 100:</p><ul><li>18 reads strongly support Haplotype 2 (...TAGCGTACG...)</li><li>2 reads support Haplotype 1 (...TAGCATACG...)</li></ul><p>Based on this evidence, HaplotypeCaller will likely call the genotype as <strong>‘GG’</strong> (both alleles carry the variant), even though the reference base is ‘A’. Along with the genotype call, it reports confidence metrics such as genotype likelihoods (GL), providing a quantitative measure of certainty.</p><h3><strong>Chapter 5. </strong>Counting SNPs and Indels in the VCF</h3><p>We can check the number of SNP and Indel variants present in the generated VCF file using bcftools stats:</p><pre># Generate stats for all variants once<br>bcftools stats /workspace/NA12878.vcf.gz | \<br># Filter summary lines starting with &quot;SN&quot;<br>grep -E &quot;^SN&quot; | \<br># Extract lines containing SNPs, indels, or total record counts<br>grep -E &quot;number of SNPs|number of indels|number of records&quot; | \<br># Print the 3rd and 4th tab-separated fields (label and count)<br>awk -F &#39;\t&#39; &#39;{print $3 &quot;\t&quot; $4}&#39; | \<br># Align columns nicely into a table<br>column -t</pre><p>The VCF file contains nearly 5 million variant records, including approximately 4 million SNPs and 850 thousand indels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*fI-hq6royzfihWBEGaUVhQ.png" /></figure><p>In the following sections, we will cover the quality control steps applied to the VCF data, including Variant Quality Score Recalibration (VQSR), to ensure the accuracy and reliability of the variant calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf67b6009e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data…]]></title>
            <link>https://medium.com/@fzehrasari/from-raw-reads-to-high-quality-variants-a-bioinformatics-guide-to-genomic-data-23596a177f86?source=rss-29084d33b030------2</link>
            <guid isPermaLink="false">https://medium.com/p/23596a177f86</guid>
            <category><![CDATA[gatk]]></category>
            <category><![CDATA[bqsr]]></category>
            <dc:creator><![CDATA[Fatma Zehra Sarı]]></dc:creator>
            <pubDate>Mon, 26 May 2025 12:16:20 GMT</pubDate>
            <atom:updated>2025-05-26T20:32:29.167Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧬👩🏻‍💻From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data Processing, Quality Control, and Analysis -3-</h3><p>In the previous step, we aligned sequencing reads to the reference genome and marked duplicate reads using Picard. We now proceed to <strong>Base Quality Score Recalibration (BQSR)</strong>, a critical step in the GATK Best Practices pipeline. BQSR is a statistical method that identifies and corrects <strong>systematic errors</strong> in base quality scores — the probabilities assigned by the sequencer to indicate how confidently each base was called. These scores are crucial for downstream tools, particularly variant callers, which use them to evaluate the reliability of individual base calls.</p><p>Sequencing instruments often produce biased quality scores due to factors such as <strong>sequencing</strong> <strong>cycle or</strong> <strong>sequence context</strong>. BQSR addresses these biases by leveraging a database of <strong>known polymorphic sites</strong> (e.g., dbSNP) to distinguish <strong>true genetic variants</strong> from <strong>sequencing errors</strong>. It uses machine learning to model the relationship between observed error rates and features like read position and local sequence context, recalibrating the scores accordingly.</p><p>By adjusting for these biases, BQSR enhances both the <strong>sensitivity</strong> and <strong>specificity</strong> of downstream analyses. It is particularly beneficial in high-accuracy settings — such<strong> </strong>as clinical genomics or da<strong>t</strong>asets from <strong>older Illumina platforms</strong> — where base quality scores may require correction. However, in <strong>low-coverage</strong> or <strong>long-read</strong> datasets, where error profiles differ and training data may be limited, BQSR’s impact can be minimal. In such cases, it may be reasonable to skip this step to save computational resources without substantially compromising variant calling accuracy.</p><p>Let’s now explore how to perform BQSR in practice.</p><h3>Base Quality Score Recalibration (BQSR)</h3><p>Base Quality Score Recalibration (BQSR) is a two-step process:</p><ol><li><strong>BaseRecalibrator</strong>: Builds a statistical model of covariation between quality scores and various covariates using the input BAM file and a database of known variant sites. It produces a <strong>recalibration table</strong> summarizing empirical error rates.</li><li><strong>ApplyBQSR</strong>: Applies the model to adjust base quality scores in the BAM file, yielding a <strong>recalibrated BAM</strong> suitable for high-confidence variant discovery.</li></ol><p>Known variant sites (e.g., dbSNP) are used to mask expected polymorphisms, so that genuine variants are not mistakenly counted as sequencing errors. Outside these masked regions, mismatches between the reads and the reference are assumed to be errors. This assumption is generally valid for human sequencing data, where the availability of comprehensive variant databases ensures that most remaining mismatches reflect technical artifacts rather than biological variation.</p><h3><strong>Chapter 1. BaseRecalibrator</strong></h3><p>The BaseRecalibrator tool scans all reads and tabulates error patterns across multiple covariates:</p><ul><li><strong>Read group</strong></li><li><strong>Reported quality score</strong></li><li><strong>Sequencing cycle</strong> (base position within the read)</li><li><strong>Dinucleotide context</strong> (current base + preceding base)</li></ul><p>The model is additive, meaning a base’s quality score may be adjusted up or down depending on multiple covariate effects. This process applies to data from any sequencing platform that produces base quality scores on a Phred scale. The following script runs BaseRecalibrator inside a Docker container using a retry loop and nohup to ensure robust execution:</p><pre># Run GATK BaseRecalibrator with retry logic in a Docker container using nohup<br># Output recalibration table to be used in ApplyBQSR<br><br>nohup bash -c &#39;<br><br>  # Initialize retry attempt counter<br>  attempt=1<br><br>  # Retry loop until the command completes successfully<br>  while true; do<br><br>    # Run GATK BaseRecalibrator inside Docker<br>    # Mount project directory to /workspace<br>    docker run --rm -v /path/to/project_data:/workspace broadinstitute/gatk:latest \<br><br>      # GATK with Java options for optimized performance<br>      gatk --java-options &quot;-XX:ParallelGCThreads=8 -Dsamjdk.use_async_io_read_samtools=true -Dsamjdk.use_async_io_write_samtools=true -Dsamjdk.use_async_io_write_tribble=true&quot; \<br><br>      # GATK tool for creating base quality recalibration model<br>      BaseRecalibrator \<br><br>      # Input BAM file with duplicates marked<br>      -I /workspace/NA12878.markdup.bam \<br><br>      # Reference genome FASTA file (GRCh38 version from Broad)<br>      -R /workspace/hg38_v0_Homo_sapiens_assembly38.fasta \<br><br>      # Known variant sites used to avoid penalizing true variants<br>      --known-sites /workspace/resources_broad_hg38_v0_Homo_sapiens_assembly38.dbsnp138.vcf \<br><br>      # Output recalibration table to be used in ApplyBQSR<br>      -O /workspace/recal_data.table &amp;&amp; break<br><br>    # Log retry if BaseRecalibrator fails<br>    echo &quot;[$(date)] Attempt $attempt failed. Retrying in 30 seconds...&quot; &gt;&gt; /workspace/nohup_base_recal_retry.log<br><br>    # Wait before retrying<br>    sleep 30<br><br>    # Increment retry attempt counter<br>    ((attempt++))<br><br>  done<br>&#39; &gt; /workspace/nohup_base_recal_retry.log 2&gt;&amp;1 &amp;</pre><h3><strong>Chapter 2. ApplyBQSR</strong></h3><p>Once the model is generated, the ApplyBQSR tool recalibrates the base quality scores by adjusting each base’s reported score to reflect its empirical error probability more accurately. This improves the reliability of downstream variant calling (e.g., using HaplotypeCaller).</p><pre># Apply the base quality recalibration model using ApplyBQSR inside a Docker container<br># Run in background using nohup and log the output<br><br>nohup docker run --rm -v /path/to/project_data:/workspace broadinstitute/gatk:latest \<br><br>  # Java tuning options for performance<br>  gatk --java-options &quot;-XX:ParallelGCThreads=10 -Dsamjdk.use_async_io_read_samtools=true -Dsamjdk.use_async_io_write_samtools=true -Dsamjdk.use_async_io_write_tribble=true&quot; \<br><br>  # GATK ApplyBQSR tool to apply recalibration to BAM file<br>  ApplyBQSR \<br><br>  # Reference genome (must be identical to the one used in BaseRecalibrator)<br>  -R /workspace/hg38_v0_Homo_sapiens_assembly38.fasta \<br><br>  # Input BAM file (same as BaseRecalibrator input)<br>  -I /workspace/NA12878.markdup.bam \<br><br>  # Recalibration model output from previous step<br>  --bqsr-recal-file /workspace/recal_data.table \<br><br>  # Final output BAM file with adjusted base quality scores<br>  -O /workspace/NA12878.recalibrated.bam \<br><br>  # Redirect output and error streams to log file<br>  &gt; /workspace/nohup_apply_bqsr.log 2&gt;&amp;1 &amp;</pre><p>Optionally, we can rerun BaseRecalibrator on the recalibrated BAM to generate <strong>post-BQSR metrics</strong>, allowing visual comparison between pre- and post-recalibration quality profiles:</p><pre># Run a Docker container using the GATK image, mounting your project directory to /data inside the container<br>docker run --rm -v /path/to/project_data:/data broadinstitute/gatk:latest \<br><br># Execute the GATK tool with Java options optimized for parallel garbage collection and async I/O for better performance<br>gatk --java-options &quot;-XX:ParallelGCThreads=8 -Dsamjdk.use_async_io_read_samtools=true -Dsamjdk.use_async_io_write_samtools=true -Dsamjdk.use_async_io_write_tribble=true&quot; \<br><br># Run the BaseRecalibrator tool to generate base quality score recalibration metrics<br>BaseRecalibrator \<br><br>  # Input BAM file that has already undergone BQSR<br>  -I /data/NA12878.recalibrated.bam \<br><br>  # Reference genome FASTA file<br>  -R /data/hg38_v0_Homo_sapiens_assembly38.fasta \<br><br>  # Known sites of variation (e.g., dbSNP) used to avoid penalizing real variants<br>  --known-sites /data/resources_broad_hg38_v0_Homo_sapiens_assembly38.dbsnp138.vcf \<br><br>  # Output recalibration table for post-BQSR metrics<br>  -O /data/post_recal_data.table<br><br>########################################################################################################################################<br><br></pre><h3><strong>Chapter 3. Visualize with AnalyzeCovariates</strong></h3><p>Finally, we can use AnalyzeCovariates to generate a diagnostic PDF comparing the recalibration metrics before and after applying BQSR:</p><pre># Run a Docker container again with the same mounted directory<br>docker run --rm -v /path/to/project_data:/data broadinstitute/gatk:latest \<br><br># Run the AnalyzeCovariates tool to generate visual diagnostics of recalibration<br>gatk AnalyzeCovariates \<br><br>  # Input table generated from the original (pre-BQSR) BaseRecalibrator run<br>  -before /data/recal_data.table \<br><br>  # Input table generated from the post-BQSR BaseRecalibrator run<br>  -after /data/post_recal_data.table \<br><br>  # Output PDF file containing plots comparing pre- and post-recalibration metrics<br>  -plots /data/bqsr_plots.pdf</pre><p>At the top of the bqsr_plots.pdf file produced by GATK&#39;s BaseRecalibrator, we&#39;ll find a summary of the arguments and settings used during the base quality score recalibration step. This section is important for understanding how the model was built and for ensuring that the process can be reproduced later if needed.</p><p>Here are some key fields explained:</p><ul><li><strong>covariate</strong>: Lists the features used to detect patterns in sequencing errors. Common covariates include ReadGroup, QualityScore, Context (local sequence), and Cycle (position of the base in the read).</li><li><strong>quantizing_levels</strong>: Controls how many quality score levels are used after recalibration. The default is 16, which works well in most cases.</li><li><strong>run_without_dbsnp</strong>: This indicates whether known variant sites (like dbSNP) were used. If set to true, the tool treats all mismatches as errors, which can lead to overcorrection. In human genome analysis, this should usually be false, so true variants aren&#39;t mistakenly treated as sequencing mistakes.</li><li><strong>no_standard_covs</strong>: If true, disables the default covariates. This is rarely needed and usually left as false.</li><li><strong>solid_recal_mode</strong> and <strong>solid_nocall_strategy</strong>: These are specific to SOLiD sequencing data and are not used with Illumina platforms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqhvXJaQpBFhX5HydRmFMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZ370v3zeiTuGUlrNQ_Awg.png" /><figcaption><strong>Top Panel </strong>— Empirical vs. Reported Quality Score: Reported base quality scores before recalibration (pink) systematically overestimate accuracy. After recalibration (blue), scores are better aligned with empirical error rates, indicating improved calibration. <strong>Middle Panel </strong>— Quality Score Accuracy by Cycle: This plot shows how base quality score accuracy varies across sequencing cycles (read position). Before recalibration (pink), clear position-specific biases are observed — particularly at the beginning and end of reads. After recalibration (blue), these biases are substantially reduced, resulting in more consistent and accurate quality estimates across the read. The X-axis represents the sequencing cycle, with negative values indicating bases on the reverse strand and positive values on the forward strand. <strong>Bottom Panel </strong>— Quality Score Accuracy by Sequence Context: Effect of local sequence context (dinucleotide + base) on quality score accuracy. Recalibration reduces context-specific distortions present before (pink), leading to more uniform and reliable quality estimates (blue).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcUqvhNWB1hJEkPNfhNAog.png" /><figcaption><strong>Top Panel — </strong>Quality Score Distribution (QualityScore Covariate): Histogram showing the distribution of reported quality scores before (pink) and after (blue) recalibration. After BQSR, the distribution shifts toward more conservative and realistic quality scores, reducing overestimation of high-confidence base calls. <strong>Middle Panel — </strong>Mean Quality Score by Cycle: Plot showing the average quality score at each position in the read (cycle). Before recalibration (pink), quality scores fluctuate and are overestimated at several positions, particularly near the middle of the read. After recalibration (blue), scores are more stable and consistent across all cycles. Negative values represent bases on the reverse strand, and positive values on the forward strand. <strong>Bottom Panel — </strong>Mean Quality Score by Sequence Context: Base quality score accuracy as a function of local sequence context (dinucleotide + base). Before recalibration (pink), some contexts show lower mean scores due to systematic errors. After recalibration (blue), scores are more uniform, reflecting correction of context-specific quality score biases.</figcaption></figure><p>The report also shows how many base positions were analyzed — approximately <strong>68.4 billion</strong> in this case — for potential mismatches. The <strong>Errors</strong> field indicates how many actual mismatches were observed among those positions, which here amounts to <strong>179 million</strong> (1.79e+08).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*rPpgcp0GtKDHv4KwRhwZBQ.png" /></figure><p>Since we used data from a <strong>single sequencing lane</strong> of the <a href="https://ftp-trace.ncbi.nlm.nih.gov/giab/ftp/data/NA12878/NIST_NA12878_HG001_HiSeq_300x/">NA12878 300×</a> dataset, all reads were assigned to a <strong>single read group</strong> (BH814YADXX.1). As a result, the recalibration table displays entries only for this read group, with each row corresponding to a different <strong>reported base quality score</strong>.</p><p>The table summarizes BQSR metrics across four dimensions:</p><ul><li><strong>QualityScore</strong>: The original base quality score assigned by the sequencing instrument, representing the machine’s estimated probability that a given base was called correctly.</li><li><strong>Observations</strong>: The total number of base calls observed with that specific quality score.</li><li><strong>Errors</strong>: The number of mismatches (putative sequencing errors) detected among those calls, excluding known polymorphic sites to avoid penalizing true variants.</li><li><strong>EmpiricalQuality</strong>: A Phred-scaled value derived from the observed error rate (<em>−10 × log₁₀(Errors / Observations)</em>), reflecting how accurate that quality score is based on actual sequencing data.</li></ul><p>Empirical quality scores are calculated because Phred quality scores are, by definition, log-transformed probabilities of sequencing error. If the observed error rate for a given score deviates from what the sequencer originally assigned, it suggests systematic bias. GATK uses these empirical estimates to adjust the original scores accordingly, ensuring that the recalibrated quality values more accurately reflect true sequencing performance. This correction improves the accuracy and reliability of downstream analyses, particularly variant calling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUa9bb8xy766j9wP6giFSg.png" /></figure><p>Now that we’ve corrected base quality scores, we’re ready to proceed to <strong>variant calling</strong> using <strong>HaplotypeCaller</strong>, which will generate a GVCF file for our sample.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23596a177f86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data…]]></title>
            <link>https://medium.com/@fzehrasari/from-raw-reads-to-high-quality-variants-a-bioinformatics-guide-to-genomic-data-fe1de254074f?source=rss-29084d33b030------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe1de254074f</guid>
            <category><![CDATA[alignment]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[quality-control]]></category>
            <category><![CDATA[next-generation-sequence]]></category>
            <dc:creator><![CDATA[Fatma Zehra Sarı]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 14:28:06 GMT</pubDate>
            <atom:updated>2025-04-29T18:31:59.393Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧬👩🏻‍💻From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data Processing, Quality Control, and Analysis -2-</h3><p>In the first part of this series, we retrieved <a href="https://ftp-trace.ncbi.nlm.nih.gov/giab/ftp/data/NA12878/NIST_NA12878_HG001_HiSeq_300x/131219_D00360_005_BH814YADXX/">a subset of the 300× coverage FASTQ files for the NA12878 </a>sample via FTP. After performing quality checks on the reads and base qualities, we merged data from multiple sequencing lanes into a single paired-end dataset — one file for Read 1 (R1) and another for Read 2 (R2).</p><p>In this second part, we use the quality-checked and merged FASTQ files to align the reads to the human reference genome. After alignment, we evaluate the quality of the resulting files to ensure they meet the standards required for reliable downstream analysis. Throughout this series, we are following the steps outlined in the <a href="https://github.com/broadinstitute/gatk-docs/blob/master/gatk3-tutorials/Appendix_to_(howto)_Discover_variants_with_GATK.md">GATK Best Practices workflow</a>. Before we dive into the alignment process, let’s briefly review the reference genome that will serve as the template for the mapping step.</p><h3><strong>Human Reference Genome (</strong>GRCh38 — hg38<strong>)</strong></h3><p><a href="https://www.genome.gov/human-genome-project">The Human Genome Project</a> was launched in 1990 with the goal of decoding the entire human genome. It was completed in 2003, marking a breakthrough in the field of genomics. During its early phases, the UCSC Genome Browser produced a series of preliminary assemblies (hg1–hg6) based on partial sequencing data. As the quality and completeness of the genome improved, official assemblies began to be released by NCBI, such as Build 34 (hg16), followed by Build 35 (hg17) and Build 36 (hg18). The most widely used reference today is <strong>GRCh38 (hg38)</strong>, released in 2013. It includes better coverage of complex regions and fewer gaps. Although the T2T-CHM13 assembly (hs1) is the most complete version to date, it is not yet widely used because many tools and databases still depend on GRCh38.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdXndEqu3K6Ov62SUTO-_w.png" /><figcaption>Timeline of <a href="https://genome.ucsc.edu/FAQ/FAQreleases.html#release3">human genome assemblies from UCSC</a>, showing major releases from early UCSC-assembled drafts to GRCh37 (hg19) and GRCh38 (hg38), with CHM13v2.0 as the most recent complete reference genome.</figcaption></figure><p><a href="https://console.cloud.google.com/storage/browser/genomics-public-data/resources/broad/hg38/v0;tab=objects?prefix=&amp;forceOnObjectsSortingFiltering=true">A repository hosted on Google Cloud</a> provides publicly accessible versions of the GRCh38 reference genome curated by the Broad Institute. It includes the primary FASTA file, index files, and other essential resources commonly used in genomic workflows. These datasets are particularly well-suited for pipelines that follow GATK Best Practices, making them ideal for our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DnQR6lGPItRHnZEe.png" /><figcaption>Ideogram of the GRCh38/hg38 human reference genome from the <a href="https://www.ncbi.nlm.nih.gov/gdv/browser/genome/?id=GCF_000001405.40">NCBI Genome Data Viewer</a>, displaying characteristic banding patterns (black, grey, white), with gaps and partially assembled regions highlighted in blue and pink.</figcaption></figure><h3><strong>Chapter 1. Short-Read Alignment to the Human Reference Genome</strong></h3><p>Aligning short sequencing reads to the corresponding positions on the reference genome allows us to infer the original genomic location of each read. Several tools are available for aligning short reads to the human genome. Among them, <strong>GATK recommends BWA-MEM for germline variant discovery</strong> due to its high accuracy, especially around indels and in repetitive regions. Bowtie2 may offer faster performance for small genomes but lacks the same level of precision. STAR and HISAT2 are splice-aware, making them ideal for RNA-seq but unnecessary for DNA-seq. BWA-MEM handles paired-end reads and read group information with ease. In addition, it is designed to work well with large datasets by using a memory-efficient indexing method (FM-index).</p><p>To download and compile the BWA (Burrows-Wheeler Aligner) tool from GitHub and make it accessible from anywhere in the terminal, we start by cloning the source code using git clone, then compile it with make. The resulting executable is copied to the ~/bin directory. To enable system-wide access, we add export PATH=&quot;$HOME/bin:$PATH&quot; to the .bashrc file, and apply the changes by running source ~/.bashrc:</p><pre># Clone the BWA source code from the official GitHub repository<br>git clone https://github.com/lh3/bwa.git<br><br># Change into the bwa directory and compile the program<br>cd bwa<br>make<br><br># Create a local bin directory in your home folder if it doesn&#39;t exist<br>mkdir -p ~/bin<br><br># Copy the compiled BWA executable to your local bin directory<br>cp bwa ~/bin/<br><br># Open your .bashrc file to add the bin directory to your PATH<br>nano ~/.bashrc<br><br># (Inside .bashrc) Add the following line at the end of the file:<br>export PATH=&quot;$HOME/bin:$PATH&quot;<br><br># Reload .bashrc to apply the updated PATH immediately<br>source ~/.bashrc</pre><p>BWA-MEM identifies the reference genome using the FASTA filename and looks for index files (.amb, .ann, .bwt, .pac, .sa) in the same directory. These files enable fast searching during alignment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*SwjMaZo8eHKdtYU8LjfI7w.png" /></figure><p>After downloading the reference genome, we can generate these index files using the following command:</p><pre>bwa index hg38_v0_Homo_sapiens_assembly38.fasta</pre><p>Now that the reference FASTA file, the merged read files, and the BWA-MEM index files are all located in the same directory, we can proceed with the alignment and sorting steps. The alignment is performed using the following command:</p><pre># Run BWA-MEM for read alignment using 8 threads<br>bwa mem -t 8 \<br><br># Add read group information (required for GATK and proper downstream processing)<br>  -R &quot;@RG\tID:BH814YADXX\tSM:NA12878\tPL:ILLUMINA\tLB:RM8398\tPU:BH814YADXX.1&quot; \<br><br># Path to the reference genome in FASTA format<br>  hg38_v0_Homo_sapiens_assembly38.fasta \<br><br># Paired-end FASTQ files to be aligned (R1 and R2)<br>  merged_total_R1.fastq.gz merged_total_R2.fastq.gz | \<br><br># Pipe the alignment output (SAM format) directly to samtools for sorting<br># Sort the aligned reads by genomic coordinates using 10 threads and write output to BAM<br>  samtools sort -@ 10 -o NA12878.bam</pre><p>The -R flag is used to add read group information to each alignment. This metadata includes the sample ID (SM), platform (PL), library (LB), and sequencing unit (PU). Including read group information is essential, as many downstream tools—such as those used in variant calling—rely on it to differentiate between samples or sequencing runs within a BAM file. Below is a breakdown of the read group string used in our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*gZpOT6-xU4ieAJBJvv95EQ.png" /></figure><p>bwa mem generates alignment output in <strong>SAM format</strong>, which is streamed directly via a pipe (|) into the samtools sort command. This command converts the SAM output into a <strong>coordinate-sorted BAM file</strong>. Sorting is a crucial step, as many downstream tools—such as those used for duplicate marking and variant calling—require BAM files to be sorted by genomic coordinates in order to function correctly and efficiently. The SAM <strong>(Sequence Alignment/Map)</strong> format is a human-readable text file that stores alignment information. BAM is the <strong>binary</strong>, compressed version of SAM — optimized for storage efficiency and faster processing by downstream tools.</p><p>We can view the header and the first alignment line of a BAM file using samtools. The samtools view -h command outputs the BAM file in SAM format, including the header. Then, awk is used to print all header lines (those starting with @) and extract the first alignment line right after them.</p><pre>samtools view -h NA12878.bam | awk &#39;BEGIN {header=1} /^@/ {print; next} {if (header) {print; header=0; exit}}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1ixSj5nut9jrsdlAY82YA.png" /><figcaption>Example of a SAM header and a single aligned read from the NA12878 BAM file</figcaption></figure><p>In the SAM/BAM header, the first line typically begins with @HD, which defines the SAM format version and the sorting order. For example, VN:1.5 indicates that the file follows SAM format version 1.5, while SO:coordinate specifies that the alignments are sorted by genomic coordinates. The next line is a sequence dictionary entry that begins with @SQ. In this case, SN:chr1 refers to the name of the reference sequence (chromosome 1), and LN:248956422 indicates its length in base pairs. After the sequence dictionary lines, the read group line appears, starting with @RG. In our example, @RG ID:BH814YADXX SM:NA12878 PL:ILLUMINA LB:RM8398 PU:BH814YADXX.1, the read group is defined as follows: ID is the read group identifier (here, BH814YADXX, usually representing the flowcell ID), SM is the sample name (NA12878), PL indicates the sequencing platform (ILLUMINA), LB refers to the library ID (RM8398), and PU represents the platform unit, which is often a combination of flowcell ID and lane number. This is followed by @PG lines, which indicate the programs used to process the data. The line @PG ID:bwa ... shows that the alignment was performed using BWA-MEM version 0.7.19, and the CL field provides the full command that was run. The next program line, @PG ID:samtools ..., indicates that samtools sort version 1.21 was used to sort the alignments, and the PP:bwa tag shows that this step followed the BWA alignment. Finally, @PG ID:samtools.1 ... reveals that samtools view was used to view or extract the contents of the BAM file.</p><p>The first alignment entry begins with a read ID such as HWI-D00360.... This is a paired-end read aligned to chromosome 1 at position 9999. Its CIGAR string is 30S66M52S, which means 30 bases were soft clipped at the start, 66 bases were aligned (matched or mismatched), and 52 bases were soft clipped at the end. The SA:Z: tag indicates that this read has supplementary alignments on chromosome 5, suggesting a split alignment that may be caused by a structural variant or a repetitive region. This is followed by the read sequence and its corresponding base quality scores. Then, additional tags provide further alignment details: NM:i:0 indicates zero mismatches, MQ:i:60 gives the mapping quality, and RG:Z:BH814YADXX confirms the read group to which this read belongs. The second read has a CIGAR string of 103H45M, meaning that 103 bases were hard clipped and 45 bases were aligned. It is also aligned to chromosome 1 at position 9999 and has supplementary alignments on chromosome 5. To better interpret the alignment information, let’s take a look at what each <strong>CIGAR </strong>operation represents:</p><ul><li><strong>M</strong> — Match or mismatch (alignment match; <em>does not</em> distinguish exact matches from mismatches)</li><li><strong>I</strong> — Insertion to the reference</li><li><strong>D</strong> — Deletion from the reference</li><li><strong>S</strong> — Soft clipping (at the ends of reads)</li><li><strong>H</strong> — Hard clipping (rare; usually for supplementary alignments)</li><li><strong>N</strong> — Skipped region (only in special cases like RNA-seq mode; <em>not in standard DNA-seq</em>)</li></ul><p>As the next step, we’ll explore how to check the quality of the alignment file we have generated.</p><h3><strong>Chapter 2. Quality Control of Binary Alignment/Map (BAM) File</strong></h3><p>For quality control steps, we’ll be using <strong>Mosdepth, Picard and Qualimap</strong>. Before running Mosdepth, the BAM file must be indexed. This can be done using samtools:</p><pre>samtools index --threads 12 NA12878.bam</pre><p>Mosdepth can be installed via Bioconda:</p><pre>conda install bioconda::mosdepth</pre><p><strong>Note</strong>: Picard requires Java to run. To install Picard from source:</p><pre># Clone the Picard source code from the official GitHub repository<br>git clone https://github.com/broadinstitute/picard.git<br><br># Move into the cloned picard directory<br>cd picard/<br><br># Build the executable jar file using the Gradle wrapper<br>./gradlew shadowJar<br><br># The compiled Picard JAR file will be located in the build/libs/ directory.<br># To run Picard from the command line, use:<br>java -jar build/libs/picard-&lt;version&gt;-all.jar</pre><p>To install Qualimap, we can create a separate conda environment and install it via Bioconda:</p><pre># Create a new conda environment named &#39;qualimap_env&#39; with Python 3.9<br>conda create -n qualimap_env python=3.9<br><br># Activate the newly created environment<br>conda activate qualimap_env<br><br># Install Qualimap from the Bioconda channel<br>conda install -c bioconda qualimap</pre><h3><strong>2.1. Average Depth and Breadth of Coverage</strong></h3><p>Coverage and depth are key metrics for evaluating the reliability of variant calls. Low or uneven read depth may lead to false positives, while insufficient coverage across genomic regions increases the risk of missing true variants. These metrics are also essential for setting effective filtering thresholds and identifying regions affected by technical artifacts.</p><p>Below, we walk through the commands, outputs, and interpretation steps used to evaluate depth and coverage using <strong>Mosdepth, Picard, and Qualimap</strong>. Now, let’s calculate the depth of coverage and determine the percentage of the genome covered at a specific depth threshold. This can be done efficiently using Mosdepth as follows:</p><pre># Calculate overall depth coverage without generating per-base output.<br># Uses 8 threads for faster processing.<br># The output files (e.g., summary and region-level depth) will be prefixed with &quot;na12878_output&quot;.<br>time mosdepth -t 8 --no-per-base na12878_output NA12878.bam<br><br># Calculate quantized coverage based on depth thresholds:<br># 0–1x (very low or no coverage), 1–10x (low), 10–20x (moderate), and &gt;20x (high).<br># Per-base output is still disabled to reduce file size.<br># The output files will be prefixed with &quot;na12878_quant&quot;.<br>time mosdepth -t 8 --no-per-base --quantize 0:1:10:20: na12878_quant NA12878.bam</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*kFOX3NDHqghrvTqaxPIXog.png" /><figcaption>This image shows the output of the time command for Mosdepth runs. “Real” refers to the total wall-clock time — the actual time the command took to run from start to finish. “User” represents the total amount of CPU time spent executing the program’s own code in user mode. “Sys” indicates the CPU time used by system-level operations like file input/output. When user + sys is bigger than real, it typically means the task was executed in parallel using multiple CPU cores.</figcaption></figure><p>Both commands finished in around 4 minutes using 8 threads. From the first command, we obtained two main output files: na12878_output.mosdepth.summary.txt and na12878_output.mosdepth.global.dist.txt. To inspect the first 10 lines of each file, we can use the cat and head commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*wg2_-UyjK6hmvXTcqLaiWg.png" /><figcaption>Overview of Mosdepth output files: na12878_output.mosdepth.summary.txt (top left and center) provides mean, min, and max coverage per chromosome and region, with a total mean coverage of 23.08×. na12878_output.mosdepth.global.dist.txt (right) displays the global depth distribution, showing the number of bases at each exact coverage depth (e.g., 4702x).</figcaption></figure><p>The file na12878_quant.mosdepth.global.dist.txt shows how sequencing depth is distributed across the genome. Each line indicates a specific depth (e.g., 4702x) and the fraction of bases with that exact coverage. A value of 0.00 means no bases were covered at that depth. na12878_output.mosdepth.summary.txt provides summary statistics per chromosome, including total length, mean coverage, and minimum/maximum depth. For example, chromosome 1 has an average coverage of 24.68x, with some regions reaching over 80,000x and others with no coverage at all. Together, these files offer a detailed view of genome-wide sequencing coverage — both in depth and distribution.</p><p>The second command, which included quantization, produced the following files: na12878_quant.quantized.bed.gz, na12878_quant.mosdepth.summary.txt, and na12878_quant.mosdepth.global.dist.txt. Let’s take a quick look at the first 10 lines of the na12878_quant.quantized.bed.gz file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*UYNR13gvh5RbMoVy9AbRFw.png" /><figcaption>First 10 lines of na12878_quant.quantized.bed.gz</figcaption></figure><p>Each row corresponds to a genomic interval and a value range assigned to that interval. Here’s what each column indicates:</p><p><strong>Column 1 (chr):</strong> Chromosome name (e.g., chr1)</p><p><strong>Column 2 (start):</strong> Start position of the genomic region (0-based)</p><p><strong>Column 3 (end):</strong> End position of the genomic region (0-based, exclusive)</p><p><strong>Column 4 (range):</strong> The quantized value range observed in that region (e.g., 0:1, 10:20, 20:inf)</p><p>The fourth column typically represents coverage depth or another continuous metric that has been grouped into predefined value ranges. For example, a line like chr1 10000 10527 20:inf indicates that the coverage in that region exceeds 20× — as is the case in our example.</p><p>Knowing how much of the genome is covered by at least one read (≥1× depth) is important because regions without any coverage cannot be analyzed for variants. These uncovered areas represent gaps in sequencing and can limit the reliability of downstream analyses. To calculate the percentage of the genome covered by at least one read (≥1x depth), we first need to determine the total number of bases in the reference genome. This information is stored in the .fai index file generated from the reference FASTA. In this file, the second column contains the length of each chromosome. By summing these values using awk, we can obtain the total genome size in base pairs:</p><pre># Generate the FASTA index file required for retrieving reference sequence lengths<br>samtools faidx hg38_v0_Homo_sapiens_assembly38.fasta<br><br># Calculate the total length of the reference genome from the .fai index file<br>refLength=$(awk &#39;{sum += $2} END {print sum}&#39; hg38_v0_Homo_sapiens_assembly38.fasta.fai)</pre><p>Next, we use the quantized BED file generated by Mosdepth to compute how many bases fall into each depth range of interest:</p><pre># Sum the number of bases with depth between 1x and 10x<br>val1=$(zcat na12878_quant.quantized.bed.gz | awk &#39;$4 == &quot;1:10&quot; {sum += $3 - $2} END {print sum}&#39;)<br><br># Sum the number of bases with depth between 10x and 20x<br>val2=$(zcat na12878_quant.quantized.bed.gz | awk &#39;$4 == &quot;10:20&quot; {sum += $3 - $2} END {print sum}&#39;)<br><br># Sum the number of bases with depth greater than 20x (i.e., in the 20–1000 bin)<br>val3=$(zcat na12878_quant.quantized.bed.gz | awk &#39;$4 == &quot;20:inf&quot; {sum += $3 - $2} END {print sum}&#39;)<br></pre><p>Finally, we add all bases covered by at least 1x and divide by the total genome length to calculate the coverage percentage. The bc tool is used to handle floating-point arithmetic:</p><pre># Calculate the percentage of the genome covered at ≥1x depth<br>echo &quot;scale=2; (($val1 + $val2 + $val3) / $refLength) * 100&quot; | bc</pre><p>In our example, the <strong>mean depth of coverage</strong> was 23.08×, and 93% of the genome was covered by at least one read. A similar calculation can also be performed using <strong>Picard’s</strong> CollectWgsMetrics tool, which provides the PCT_1X metric among others. This step, run with 8 threads, took approximately 50 minutes to complete and produced the picard_metrics.txt file as output.</p><pre>time \<br># Run Picard&#39;s CollectWgsMetrics tool using Java, allowing up to 8 threads for garbage collection<br>java -XX:ParallelGCThreads=8 -jar /home/zehra/tools/picard/picard.jar CollectWgsMetrics \<br><br># Input BAM file containing aligned reads<br>  I=NA12878.bam \<br><br># Output file to write WGS metrics summary<br>  O=picard_metrics.txt \<br><br># Reference genome in FASTA format (must have .dict and .fai files in the same directory)<br>  R=hg38_v0_Homo_sapiens_assembly38.fasta \<br><br># Include a histogram of base quality scores in the output<br>  INCLUDE_BQ_HISTOGRAM=true \<br><br># Use a faster algorithm for estimating coverage (approximated)<br>  USE_FAST_ALGORITHM=true<br><br># Extract the main WGS coverage metrics from the Picard output file.<br># This command finds the header line starting with &quot;GENOME_TERRITORY&quot; and includes the next line (the data row).<br># Then it formats the result into a readable table using `column -t`.<br>grep -A1 &quot;^GENOME_TERRITORY&quot; picard_metrics.txt | column -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*om7wKf-xcmQKmZfaKx6-zg.png" /><figcaption>Output of Picard’s CollectWgsMetrics, showing whole-genome coverage statistics including mean and median coverage, coverage breadth at various thresholds (e.g., PCT_1X, PCT_10X), and percentages of reads excluded for quality-related reasons (e.g., MAPQ, duplicates, adapters).</figcaption></figure><p>According to Picard, the mean depth of coverage was 21.47× and the PCT_1X value was 0.928, indicating that 92.8% of the genome was covered by at least 1×—closely aligning with the result obtained using Mosdepth.</p><p>To complement these command-line tools, <strong>Qualimap </strong>provides a graphical HTML report that summarizes alignment and coverage metrics in an interactive format. Qualimap completes in approximately 27 minutes when run with 8 threads. Similar to FastQC, it generates an HTML report that summarizes key alignment quality metrics. During its BAMQC analysis, Qualimap also provides the option to exclude duplicated reads from the evaluation using the --skip-duplicated flag. <em>(We will cover how duplicates are marked using Picard&#39;s MarkDuplicates in Section 2.6.)</em> When this option is used alongside a BAM file in which duplicates have already been marked, duplicated reads are omitted from the analysis—resulting in a more accurate assessment of library complexity and overall sequencing quality:</p><pre><br># Measure execution time for the entire process<br>time qualimap bamqc \<br>  <br>  # Input BAM file with duplicates already marked<br>  -bam NA12878.markdup.bam \<br><br>  # Output directory where the QC report will be saved<br>  -outdir qc_out_skipDup \<br><br>  # Set the maximum amount of Java heap memory to 20 GB<br>  --java-mem-size=20000M \<br><br>  # Use 8 threads for faster processing<br>  --nt 8 \<br><br>  # Exclude reads that are marked as duplicates from the analysis<br>  --skip-duplicated</pre><p>The generated HTML report can be viewed in a web browser using the xdg-open qualimapReport.html command. Below, we see two Qualimap BAMQC reports: one generated without the --skip-duplicated parameter, and another generated after duplicate reads were marked and the --skip-duplicated flag was applied. In addition to the figures shown below, Qualimap’s bamqc function also reports per-chromosome average depth, similar to Mosdepth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz_Nami0mWOfeYBXyimY5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dq7WE55f17Pn7Zela90FHQ.png" /><figcaption><strong>Left</strong>: summary without --skip-duplicated. <strong>Right</strong>: after marking duplicates and applying the flag.</figcaption></figure><p>In BAM files, duplicate reads are identified using the 0x400 flag. When the --skip-duplicated option is enabled in Qualimap, these flagged reads are entirely excluded from the analysis. As a result, no metrics—such as coverage, GC content, or insert size—are calculated from them. In the HTML report, Qualimap clearly distinguishes between <strong>“duplicated reads (flagged)”</strong> and <strong>“duplicated reads skipped”</strong>, indicating how many reads were marked as duplicates and how many were excluded from metric calculations. Since skipped reads are omitted from all downstream analyses, the reported duplication rate reflects only the remaining, unique alignments. Activating --skip-duplicated leads to a substantial reduction in the number of reported duplicated reads—from 66.6 million (12.89%) to 2.76 million (0.53%)—and lowers the overall duplication rate from 9.43% to 4.03%. This decrease occurs because, after marking duplicates (e.g., using Picard), only one representative read from each duplicate group is retained, while the rest are flagged and excluded from analysis.</p><p>Although the average coverage remains nearly unchanged (~23.3×), the standard deviation drops significantly — from 199.6 to 105.3 — indicating a more uniform distribution of reads across the genome. Other metrics, such as mapping quality and insert size, remain stable, as duplicate removal does not affect alignment positions or fragment characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhStPLJRUiHmxX73H-2lFg.png" /><figcaption>Additional depth-related figures from the Qualimap BAMQC HTML report, generated after marking duplicates and applying the --skip-duplicated flag.</figcaption></figure><p>Additional depth-related figures in the HTML report illustrate how reads are distributed across the genome once duplicates have been excluded. The <strong>“Coverage across reference”</strong> plot (top left) shows relatively consistent depth across most genomic regions, with a few localized drops likely corresponding to repetitive or poorly mappable areas. The <strong>Coverage Histogram</strong> (top right) indicates that the majority of bases fall within the 20–30× range, which is consistent with the results obtained from Mosdepth and Picard.</p><p>The more detailed <strong>0–50× Coverage Histogram</strong> (bottom left) illustrates a smooth, near-normal distribution centered around ~24×, indicating uniform depth across the genome following duplicate removal. Notably, the prominent spike at 0× coverage suggests the presence of genomic regions that remain entirely uncovered. These gaps may result from sequencing biases, low-complexity or repetitive sequences, or technical limitations during library preparation or alignment.</p><p>Lastly, the <strong>Genome Fraction Coverage</strong> plot (bottom right) shows that over 90% of the genome is covered at ≥10×, indicating high-quality data sufficient for reliable variant detection.</p><h3><strong>2.2. Sex Chromosome Aneuploidies (SCAs)</strong></h3><p>To assess potential sex chromosome aneuploidy, we can refer to the na12878_output.mosdepth.summary.txt file, which provides per-chromosome coverage statistics generated by Mosdepth. This includes the total number of bases covered and the mean depth for each chromosome. Similar chromosome-level depth information is also available in the output of Qualimap’s BAMQC analysis.</p><pre># Print the header and the coverage summary for chromosomes X and Y from the mosdepth output file.<br># The header is extracted using &#39;head -n 1&#39;, and the rows for chrX and chrY are filtered using grep.<br># The output is formatted into aligned columns using &#39;column -t&#39; for better readability.<br><br>(head -n 1 &amp;&amp; grep -E &#39;chrX|chrY&#39; na12878_output.mosdepth.summary.txt) &lt; na12878_output.mosdepth.summary.txt | column -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Opl-8-lNK-dLOjn7-MfwzQ.png" /></figure><p>In our NA12878 sample, the mean depth for chrX is ~23.6× and for chrY is ~0.9×, consistent with a 46,XX female karyotype — characterized by full diploid coverage on chrX and the absence of chrY. The small but non-zero depth observed on chrY is likely due to reads aligning to pseudoautosomal regions (PARs), which are homologous between chrX and chrY and may result in ambiguous mappings.</p><p>A similar result was obtained using Qualimap, which reported an average depth of ~23.8× for chrX and ~0.9× for chrY, in agreement with the Mosdepth analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*14Hsd5V07RT_JJ_mWPr6tw.png" /><figcaption>Chromosome-level depth information from the Qualimap BAMQC HTML report, generated after marking duplicates and applying the --skip-duplicated flag.</figcaption></figure><h3><strong>2.3. Insert Size Distribution</strong></h3><p>After assessing overall sequencing depth, another key quality metric to examine is <strong>insert size</strong> — the distance between paired-end reads in the genome. Deviations from the expected distribution may indicate technical artifacts, structural variants (e.g., deletions or insertions), or contamination. A sharp, unimodal distribution centered around the expected fragment length suggests high-quality library preparation and reliable paired-end sequencing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*o40flGpQTRjwGmB9.jpg" /><figcaption>Illustration of paired-end sequencing and insert structure. Adapted from: <a href="https://www.frontiersin.org/articles/10.3389/fgene.2014.00005/full">https://www.frontiersin.org/articles/10.3389/fgene.2014.00005/full</a></figcaption></figure><p>We’ll use <strong>Picard’s</strong> CollectInsertSizeMetrics function for this step. It produces a PDF plot showing the distribution of insert sizes. The function completes in about 12 minutes.</p><pre># Run Picard&#39;s CollectInsertSizeMetrics tool<br>picard CollectInsertSizeMetrics \<br><br>    # I = Input BAM file (must be sorted by coordinate)<br>    I=NA12878.bam \<br><br>    # O = Output file for insert size summary statistics<br>    O=insert_size_metrics.txt \<br><br>    # H = Histogram plot of insert size distribution (PDF format)<br>    H=insert_size_histogram.pdf \<br><br>    # M = Minimum percentage (as a decimal) of read pairs required to include in the histogram<br>    # (e.g., 0.5 = at least 50% of paired reads must be usable for generating the histogram)<br>    M=0.5<br><br># Open the generated PDF histogram using the system’s default PDF viewer<br>xdg-open insert_size_histogram.pdf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*tzEHQz13lSuoJNXqStlZkQ.png" /><figcaption>Insert size distribution plot generated by Picard’s CollectInsertSizeMetrics for sample NA12878. The x-axis shows the insert size in base pairs, while the y-axis (left) indicates the number of read pairs with that insert size. The red histogram represents the frequency of observed insert sizes, and the dashed line shows the cumulative fraction of read pairs with inserts greater than a given size (right y-axis). The peak around ~500 bp suggests a well-prepared library with consistent fragment lengths.</figcaption></figure><p>Similarly, Qualimap BAMQC produces insert size plots that confirm the findings from Picard. The <strong>Insert Size Histogram</strong> (right) shows a unimodal distribution centered around ~500 bp, closely matching the peak observed in Picard’s plot. This consistency further supports the conclusion that the library was well-prepared with uniform fragment sizes. The <strong>Insert Size Across Reference</strong> plot (left) illustrates stable insert size values across most of the genome, with occasional spikes likely reflecting repetitive regions or alignment artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BXY0YY3UUnXpDVmQTpeng.png" /><figcaption>Insert size distribution plots from the Qualimap BAMQC HTML report, generated after marking duplicates and applying the --skip-duplicated flag. The histogram shows a unimodal distribution centered around ~500 bp, consistent with Picard’s results, while the genome-wide plot displays overall insert size stability across the reference genome.</figcaption></figure><h3><strong>2.4. Read Depth Distribution</strong></h3><p>We looked at the average depth of coverage — while this number is useful, it only gives us a general overview. It doesn’t tell us how that coverage is distributed across the genome. For that, we need the read depth distribution, which shows how many bases are covered at different depths and helps us spot uneven regions or potential issues in sequencing. To explore this in more detail, we can use <strong>Mosdepth</strong>, which lets us calculate coverage across the genome in fixed-size windows. For example, the following command calculates coverage in 1,000 bp bins:</p><pre># Calculate sequencing depth in fixed 1,000 bp windows across the genome.<br># This will generate region-level coverage output with a .regions.bed.gz file.<br>mosdepth --by 1000 na12878_readdepth NA12878.bam<br><br># Uncompress the per-base coverage file produced by mosdepth,<br># extract the depth values from the 4th column,<br># sort them numerically, and count the frequency of each depth value.<br># The output is written to a histogram file showing how often each depth occurs.<br>zcat na12878_readdepth.per-base.bed.gz | awk &#39;{print $4}&#39; | sort -n | uniq -c &gt; depth_histogram.txt</pre><p>We can visualize the generated depth_histogram.txt data using <strong>matplotlib:</strong></p><pre>import matplotlib.pyplot as plt<br><br>depths = []<br>counts = []<br><br>with open(&quot;depth_histogram.txt&quot;) as f:<br>    for line in f:<br>        line = line.strip()<br>        if not line:<br>            continue<br>        count, depth = line.split()<br>        depths.append(int(depth))<br>        counts.append(int(count))<br><br># Filter: show only depths &lt;= 100 for readability<br>filtered_depths = []<br>filtered_counts = []<br>for d, c in zip(depths, counts):<br>    if d &lt;= 100:<br>        filtered_depths.append(d)<br>        filtered_counts.append(c)<br><br># Plot as bar chart (histogram style)<br>plt.figure(figsize=(10, 5))<br>plt.bar(filtered_depths, filtered_counts, width=1.0, color=&#39;steelblue&#39;)<br>plt.xlabel(&quot;Depth (X)&quot;)<br>plt.ylabel(&quot;Number of bases&quot;)<br>plt.title(&quot;Read Depth Histogram&quot;)<br>plt.xlim(0, 100)<br>plt.tight_layout()<br>plt.savefig(&quot;read_depth_histogram.pdf&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFc4jMlcuGqPoLmkG5QCAA.png" /><figcaption>This histogram visualizes the number of bases (y-axis) covered at different sequencing depths (x-axis). Most bases are concentrated around the 20–30× range, indicating consistent and sufficient coverage for variant calling.</figcaption></figure><h3><strong>2.5. Properly Paired Reads</strong></h3><p>In paired-end sequencing, we expect each read pair to map to the reference genome in a specific configuration: both reads should align to the same chromosome, with Read 1 in the forward direction and Read 2 in the reverse direction, facing each other, and the distance between them (insert size) should fall within a defined range determined during library preparation. This configuration is referred to as <em>proper alignment</em>. When these expectations are not met — for example, if the reads align in the same direction, are too far apart, or map to different chromosomes — the pair is considered <em>improperly aligned</em>.</p><p>A <em>uniquely aligned</em> read is one that maps confidently to a single genomic location, whereas a <em>non-uniquely aligned</em> (or <em>multi-mapped</em>) read aligns to multiple locations, often due to repetitive sequences. Among properly aligned pairs, <em>concordant alignments</em> follow the expected orientation and insert size, indicating high-confidence pairing. <em>Discordant alignments</em>, on the other hand, occur when both reads are mapped but their orientation or distance violates the expected configuration, which may suggest structural variation or mapping artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hC-sMS9vXv17rZyH3By69Q.png" /></figure><p>Picard’s CollectAlignmentSummaryMetrics tool generates a summary table of alignment statistics for mapped reads, including metrics such as alignment rate, and error rate:</p><pre># Specify the reference genome fasta file used for alignment<br>R=hg38_v0_Homo_sapiens_assembly38.fasta \<br><br># Provide the input BAM file containing aligned reads<br>I=NA12878.bam \<br><br># Set the output file where the alignment summary metrics will be written<br>O=picard_alignment_metrics.txt</pre><p>We can visualize the resulting picard_alignment_metrics.txt file as a table using the following Python script:</p><pre>import pandas as pd<br><br># Ensure all columns are shown when printing the DataFrame<br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br># Initialize a list to store relevant lines from the metrics file<br>lines = []<br>start = False<br><br># Open and read the Picard output metrics file<br>with open(&quot;picard_alignment_metrics.txt&quot;) as f:<br>    for line in f:<br>        # Start collecting lines once the header (&quot;CATEGORY&quot;) is found<br>        if line.startswith(&quot;CATEGORY&quot;):<br>            start = True<br>        # Stop collecting lines when the histogram section begins<br>        elif line.startswith(&quot;## HISTOGRAM&quot;):<br>            break<br>        # If in the relevant section and the line is not empty, store it<br>        if start and line.strip():<br>            lines.append(line.strip())<br><br># Split each line into columns using tab as delimiter<br>data = [l.split(&#39;\t&#39;) for l in lines]<br>header = data[0]   # First line is the column header<br>rows = data[1:]    # Remaining lines are the data rows<br><br># Normalize the rows: fill missing columns (if any) with empty strings<br>normalized_rows = [row + [&#39;&#39;] * (len(header) - len(row)) for row in rows]<br><br># Convert the data into a pandas DataFrame<br>df = pd.DataFrame(normalized_rows, columns=header)<br><br># Print the first few rows of the DataFrame<br>print(df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*M6hvyjfxyyqv0HMvlH-Gpg.png" /></figure><p>The NA12878 dataset we analyzed contains a total of approximately 514 million paired-end reads, all of which passed quality filters (PCT_PF_READS = 1.0), indicating high-quality data. Nearly all reads were successfully aligned to the reference genome, with an overall alignment rate of approximately 99.5% (PCT_PF_READS_ALIGNED = 0.99479). The base-level error rates are low, with a mismatch rate of 0.0043 and a high-quality (HQ) error rate of 0.0037. These values reflect accurate read mapping. Additionally, a large proportion of aligned bases have a quality score of Q20 or higher, indicating reliable base calls. The mean read length is consistent at 148 bp, and most reads are <strong>properly </strong>paired, as shown by the high percentage of reads aligned in pairs (PCT_READS_ALIGNED_IN_PAIRS = 0.997). The proportion of <strong>improperly </strong>paired reads remains low (~2.3%), and chimeric reads make up less than 1% of the dataset. Overall, the alignment metrics suggest high-quality sequencing and mapping performance.</p><p>We can also assess the percentage of properly paired reads using the samtools flagstat command.</p><h3><strong>2.6. Marking Duplicates</strong></h3><p>Duplicate marking is an essential step in BAM file quality control. Duplicate reads commonly arise from PCR amplification, but they can also occur in PCR-free workflows due to optical duplicates or cluster-generation artifacts. If duplicates are not marked, variant callers may mistakenly interpret these redundant reads as true variants, increasing the risk of false positives. Marking duplicates helps prevent this by allowing variant callers to ignore redundant evidence, thereby improving the accuracy of variant calls.</p><p>GATK Best Practices recommend using <strong>Picard’s </strong>MarkDuplicates to perform this task. MarkDuplicates identifies duplicate reads based on alignment coordinates and fragment structure. In paired-end data, it detects duplicates by comparing read start positions, insert sizes, and orientations. Within each duplicate set, the read with the highest cumulative base quality score is retained, while the rest are flagged as duplicates. Notably, these quality scores are uncalibrated, since MarkDuplicates is typically executed <strong>before</strong> base quality score recalibration (BQSR). We can run MarkDuplicates using the command below:</p><pre># Run Picard MarkDuplicates tool to identify and mark duplicate reads in BAM file<br>picard MarkDuplicates \<br><br># Input file: original aligned BAM file<br>I=NA12878.bam \<br><br># Output file: BAM file with duplicates marked<br>O=NA12878.markdup.bam \<br><br># Metrics output file: text file containing duplicate metrics and statistics<br>M=NA12878.dup_metrics.txt \<br><br># Create BAM index file (.bai) for quick random access<br>CREATE_INDEX=true \<br><br># Ignore minor formatting issues in BAM file without aborting<br>VALIDATION_STRINGENCY=SILENT</pre><p><strong>Note:</strong> Although Picard MarkDuplicates can accept either query name-sorted or coordinate-sorted BAM files, it is strongly recommended — and commonly practiced in GATK Best Practices — to provide a BAM file sorted by chromosome coordinates, as we previously did using samtools sort -@ 10 -o NA12878.bam.</p><p>To convert the generated NA12878.dup_metrics.txt file into a readable table, the following command extracts the header and the corresponding values, and formats them into aligned columns:</p><pre>grep -A 2 &quot;^## METRICS CLASS&quot; NA12878.dup_metrics.txt | tail -n 2 | column -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vf3NSBhRAC01hmfpQsSRGg.png" /></figure><p>From the NA12878.dup_metrics.txt file, we observe that the duplication metrics reflect a high-quality sequencing dataset. The overall percent duplication is very low (0.54%), suggesting minimal PCR or optical artifacts. Over 255 million read pairs were examined, with approximately 1.3 million duplicates detected, primarily as paired reads.</p><p>To assess optical duplicates specifically, we can inspect the histogram section of the dup_metrics file:</p><pre># Extract the duplication histogram section from the Picard MarkDuplicates output<br># This starts at the line containing &#39;## HISTOGRAM&#39; and continues to the end of the file<br># Then, format the output into aligned columns for better readability<br>awk &#39;/^## HISTOGRAM/,0&#39; NA12878.dup_metrics.txt | column -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*6Ku0JklDuJKG4LWpVSR5aQ.png" /></figure><p>This table gives us an idea of how many duplicate read sets were found and how often each original DNA fragment was sequenced. Most reads were seen just once (CoverageMult ~1), which means they’re unique. Some fragments showed up two or more times — that’s where duplicates come in. For example, in the second row (CoverageMult ~2), about 688,000 duplicate sets were found, and around 27,000 of them were optical duplicates. Since that number is pretty low, it’s a good sign that the sequencing quality is high.</p><p>In line with the overall percent duplication reported by Picard being very low (0.54%), the duplication rate histograms from Qualimap BAMQC appear nearly identical before and after duplicate marking. In the top row, the left plot shows the original BAM file, and the right one shows the marked version. Since the --skip-duplicated flag was applied, duplicates were excluded from both analyses, resulting in similarly skewed distributions dominated by unique reads.</p><p>Qualimap’s HTML report also includes detailed plots related to mapping quality, in addition to coverage, insert size and duplication metrics. The bottom-left plot shows a sharp peak at mapping quality (MAPQ) 60 —<a href="https://github.com/lh3/bwa/blob/master/bwamem.c"> the highest score assigned by BWA-MEM</a> — indicating that most reads are confidently and uniquely aligned to the reference genome. This pattern is typical of high-quality whole-genome sequencing data. The bottom-right plot displays mapping quality across the genome, showing consistently high scores overall. Occasional drops likely correspond to repetitive or low-complexity regions where alignment confidence decreases. Together, these plots confirm the strong alignment quality of the NA12878 dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lioS0B9YWxbRWGheewN9JQ.png" /><figcaption>Duplication and mapping quality plots from the Qualimap BAMQC HTML report. The top row compares duplication rate histograms for the original BAM (left) and the duplicate-marked BAM with the --skip-duplicated flag applied (right). The bottom row shows mapping quality metrics for the marked BAM file analyzed with --skip-duplicated: a histogram of MAPQ scores (left) with a sharp peak at 60, and a genome-wide profile (right) showing consistently high mapping quality with localized drops in complex or repetitive regions.</figcaption></figure><p>Now that we’ve completed our post-alignment quality checks (BAMQC), the next step is base quality score recalibration (BQSR). In the GATK Best Practices workflow, BQSR is typically the last major data preprocessing step before germline variant calling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe1de254074f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data…]]></title>
            <link>https://medium.com/@fzehrasari/from-raw-reads-to-high-quality-variants-a-bioinformatics-guide-to-genomic-data-013d674b396a?source=rss-29084d33b030------2</link>
            <guid isPermaLink="false">https://medium.com/p/013d674b396a</guid>
            <category><![CDATA[quality-control]]></category>
            <category><![CDATA[giab]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[na12878]]></category>
            <category><![CDATA[gw]]></category>
            <dc:creator><![CDATA[Fatma Zehra Sarı]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 17:06:18 GMT</pubDate>
            <atom:updated>2025-04-23T07:17:11.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧬👩🏻‍💻From Raw Reads to High-Quality Variants: A Bioinformatics Guide to Genomic Data Processing, Quality Control, and Analysis -1-</h3><p>In this series of articles, we’ll explore how to use basic Linux commands and bioinformatics tools to analyze genomic file formats including FASTQ, BAM, VCF, and gVCF. We’ll also cover quality control processes for these files, and walk through key bioinformatics steps, from raw sequencing data to variant discovery. Throughout this process, we will follow the <a href="https://github.com/broadinstitute/gatk-docs/blob/master/gatk3-tutorials/Appendix_to_(howto)_Discover_variants_with_GATK.md">GATK Best Practices for Germline Short Variant Discovery.</a> The GATK Best Practices pipeline is one of the most trusted workflows for identifying germline SNPs and indels from sequencing data. It includes three main steps: <strong>pre-processing</strong>, <strong>variant discovery</strong>, and <strong>callset refinement</strong>. First, raw reads are aligned to the reference genome and duplicate reads are marked. Then, base quality scores are recalibrated to improve accuracy. In the variant discovery step, potential variants are identified using tools like HaplotypeCaller. If analyzing multiple samples, joint genotyping can be used to combine data across samples. Finally, variants are filtered, annotated, and reviewed to ensure they are reliable and ready for research or clinical use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfQ1KYuEsMb07oDT4-sqhA.png" /><figcaption>GATK Best Practices workflow for germline SNP and Indel discovery in whole-genomes and exomes.</figcaption></figure><p>As a case study, we will use the NA12878 dataset from the <a href="https://www.nist.gov/programs-projects/genome-bottle">GIAB</a> project, a well-established reference for evaluating sequencing technologies. Our analysis will focus on a subset of the <a href="https://ftp-trace.ncbi.nlm.nih.gov/giab/ftp/data/NA12878/NIST_NA12878_HG001_HiSeq_300x/">300x depth short-read data from the NA12878 sample</a>, specifically from the 131219_D00360_005_BH814YADXX portion. To download these files to our local machine, we will use <strong>lftp</strong>, a command-line tool for transferring files between local and remote servers. lftp supports various protocols, including FTP, SFTP, HTTP, and HTTPS, and is particularly useful for recursive downloads, directory synchronization, and efficient file transfers. To install lftp on a Linux system, we can use the following command in the terminal:</p><pre>sudo apt-get install lftp</pre><pre> nohup lftp -e &quot;mirror --include-glob &#39;*.fastq.gz&#39; --only-newer --continue; quit&quot; ftp://ftp-trace.ncbi.nlm.nih.gov/giab/ftp/data/NA12878/NIST_NA12878_HG001_HiSeq_300x/131219_D00360_005_BH814YADXX/Project_RM8398/ &gt; nohup.out 2&gt;&amp;1 &amp;</pre><h3>Breakdown of the Parameters Used in the lftp Command</h3><ul><li><strong>nohup</strong>: Ensures the command continues running even if the user logs out or the session is closed.</li><li><strong>lftp</strong>: A command-line tool for transferring files between local and remote servers.</li><li><strong>-e</strong>: Executes the specified commands after connecting to the server.</li><li><strong>mirror</strong>: Recursively downloads files from the remote server.</li><li><strong>--include-glob &#39;*.fastq.gz&#39;</strong>: Filters downloads to include only .fastq.gz files.</li><li><strong>--only-newer</strong>: Downloads only files that are newer than existing ones.</li><li><strong>; quit</strong>: Exits lftp after completing the download.</li><li><strong>FTP URL</strong>: Specifies the remote server location of the files.</li><li><strong>&gt; nohup.out 2&gt;&amp;1</strong>:</li></ul><p><strong>nohup.out</strong>: Redirects output to a file named nohup.out. <strong>2&gt;&amp;1</strong>: Redirects error messages to the same file.</p><ul><li><strong>&amp;</strong>: Runs the command in the background, allowing other tasks to be performed in the terminal.</li></ul><p>The directory 131219_D00360_005_BH814YADXX/ contains sequencing data from the NA12878 sample. Within this directory, there are subdirectories corresponding to different flow cells and lanes, such as 131219_D00360_006_AH81VLADXX/ and 131223_D00360_007_BH88WKADXX/. Each flow cell directory contains sample-specific subdirectories like Sample_U0a/ and Sample_U0b/, which house the sequencing read files. These files include forward (R1) and reverse (R2) reads, named according to their lane and read number, such as U0a_CGATGT_L001_R1_001.fastq.gz and U0a_CGATGT_L001_R2_001.fastq.gz.</p><p>To verify that the downloaded files are properly compressed, we can use the <strong>gzip</strong> command with the<strong> -t</strong> option. This option performs a test to check if the .gz file is valid and not corrupted. If the file is intact, gzip will produce no output and return an exit status of 0. In case of corruption, an error message will be displayed.</p><pre>gzip -t U0a_CGATGT_L001_R1_001.fastq.gz</pre><h3>Chapter 1. FASTQ, FastQC and MultiQC</h3><h3><strong>1.1. FASTQ Content</strong></h3><p>Let’s inspect the structure of the FASTQ data within one of the downloaded .fastq.gz files. We can use the <strong>zcat </strong>command to display the contents directly in the terminal without extracting the file. To view the first 10 lines of the file:</p><pre>zcat U0a_CGATGT_L001_R1_001.fastq.gz | head -n 10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ars1bRvKRFYMxzc7LPCh6g.png" /><figcaption>The first 10 rows of one of the FASTQ files used in our analysis.</figcaption></figure><p>Each entry in a typical FASTQ file consists of four lines, as described below:</p><p><strong>Line 1 (Header line):</strong></p><p>@HWI-D00360:5:H814YADXX:1:1101:1205:2142 1:N:0:CGATGT<br> The “@” symbol at the beginning marks the sequence identifier. This identifier contains information about the sequencing run, including the instrument ID, run number, lane, and other sequencing details. The last part (e.g., CGATGT) represents the index or barcode used to identify the sample within the sequencing run.</p><p><strong>Line 2 (Sequence):</strong></p><p>CTGGTCCTAACATCTGTTGACCATAGCCATATTTTTCAGAAAAGTCACATGCTCAAGATACAAAACTAATTAACATTGAAAACTATATCAAAAGACTTCTGGTTCTGGCATAATGTGAGATAAGATAACTCGAAATTTCTCTTACTGC<br> This line contains the nucleotide sequence (A, T, C, G) that was read during sequencing. It represents the raw sequence data.</p><p><strong>Line 3 (Plus line):</strong></p><p>+</p><p>The “+” line separates the sequence from the quality scores. It is mandatory in FASTQ format but does not contain any actual data.</p><p><strong>Line 4 (Quality scores):</strong></p><p>CCCFFFFFHHHHHJJJJJJJJJJJJJJJJJJJJJJJJJIJJJJJIJJJJJJJJJJJJJJJJJJJJIJJJJJJJJJJJJJJHHHHHHFFFFFFFEDEEEDDDDDDDDDDDDDDDDDDDEDDDDDDDDDDDDDDDDDDDDDEDDDDDDDD<br> This line provides the <strong>Phred</strong> <strong>quality </strong>scores (Q-score) for each nucleotide in the sequence. These scores are encoded in FASTQ files using <strong>ASCII </strong>characters for compact storage. Each character corresponds to a numerical Phred score, which is derived from its ASCII value using the formula:</p><p><em>Phred quality score = ASCII_value — 33</em></p><p>For example:</p><ul><li><strong>C:</strong> The ASCII value for ‘C’ is 67. Subtracting 33 gives a Phred score of 34.</li><li><strong>F:</strong> The ASCII value for ‘F’ is 70. Subtracting 33 gives a Phred score of 37.</li><li><strong>H:</strong> The ASCII value for ‘H’ is 72. Subtracting 33 gives a Phred score of 39.</li><li><strong>J:</strong> The ASCII value for ‘J’ is 74. Subtracting 33 gives a Phred score of 41.</li></ul><p>We can manually calculate the Phred scores for each base using Python. Here’s a code snippet to do that:</p><pre># Define the sequence of quality scores as a string<br>quality_str = &quot;CCCFFFFFHHHHHJJJJJJJJJJJJJJJJJJJJJJJJJIJJJJJIJJJJJJJJJJJJJJJJJJJJIJJJJJJJJJJJJJJHHHHHHFFFFFFFEDEEEDDDDDDDDDDDDDDDDDDDEDDDDDDDDDDDDDDDDDDDDDEDDDDDDDD&quot;<br># Create a set to get unique characters<br>unique_chars = set(quality_str)<br># Calculate the Phred quality score for each unique character<br>phred_scores = {char: ord(char) - 33 for char in unique_chars}<br>phred_scores</pre><p>Phred quality scores (Q-scores) indicate sequencing accuracy, with higher values reflecting lower error probabilities and greater confidence. The scores follow a negative logarithmic scale:</p><p><em>Q = -10 * log10(P(incorrect))</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*eBO8FoICGoPQeIpRKSCxkw.png" /></figure><h3><strong>1.2. </strong>Using FastQC for Quality Control and Corruption Detection</h3><p>To ensure data integrity and assess sequencing quality, we can use <a href="https://www.bioinformatics.babraham.ac.uk/projects/fastqc/">FastQC, a tool developed by the Babraham Institute</a>. While FASTQ files store base quality scores, FastQC analyzes and visualizes this information, generating a detailed graphical report. It identifies potential issues such as low-quality bases, adapter contamination, and overrepresented sequences, helping users quickly evaluate sequencing reliability. FastQC can be used in two ways:</p><ul><li>We can load our FASTQ files into the Graphical User Interface (GUI), and FastQC will automatically generate a report. The report uses color-coded results to indicate potential problems with the data, making it easy to identify quality issues at a glance.</li><li>Alternatively, FastQC can be run directly from the terminal. To do so, we can execute following commands:</li></ul><p><strong>Note</strong>: FastQC requires Java to run. Ensure that you have Java installed before using FastQC.</p><pre># Update the package list and install FastQC<br>sudo apt-get update<br>sudo apt-get install fastqc</pre><pre># This will run FastQC in headless mode and generate the output (HTML and .zip files) <br># in the current directory without requiring a graphical environment.<br>#!/bin/bash<br># Start timer for total execution time<br>start_time=$(date +%s)<br># Directory where the files are located<br>directory=&quot;/path/to/Sample_U0a&quot;<br># Output file to store the times (absolute path to the output file)<br>output_file=&quot;/path/to/Sample_U0a/execution_time.txt&quot;<br># Create or clear the output file before starting<br>&gt; &quot;$output_file&quot;<br># Go to the specified directory<br>cd &quot;$directory&quot;<br># Loop through each fastq.gz file in the directory<br>for file in *.fastq.gz; do<br>    echo &quot;Running FastQC for $file...&quot;<br># Start timer for each file<br>    file_start_time=$(date +%s)<br># Run FastQC on the file<br>    fastqc --noextract &quot;$file&quot; -o &quot;$directory&quot;<br># Calculate file analysis time<br>    file_end_time=$(date +%s)<br>    file_duration=$((file_end_time - file_start_time))<br>    echo &quot;$file analysis completed in $file_duration seconds.&quot;<br># Log file analysis time to the output file<br>    echo &quot;$file: $file_duration seconds&quot; &gt;&gt; &quot;$output_file&quot;<br>done<br># End timer for total execution time<br>end_time=$(date +%s)<br>total_duration=$((end_time - start_time))<br># Display total execution time<br>echo &quot;Total time for FastQC analysis: $total_duration seconds.&quot;<br># Log total time to the output file<br>echo &quot;Total time for FastQC analysis: $total_duration seconds&quot; &gt;&gt; &quot;$output_file&quot;</pre><ul><li>If any files are detected as corrupted during the FastQC analysis and errors are encountered, the corrupted files can be manually re-downloaded from the FTP address and replaced with the correct versions.</li></ul><h3><strong>1.3. MultiQC</strong></h3><p>As stated on its <a href="https://github.com/MultiQC/MultiQC">GitHub page</a>, “MultiQC is a tool to create a single report with interactive plots for multiple bioinformatics analyses across many samples.” To combine all the FastQC results into a single report, we will use MultiQC. For the <strong>144 </strong>fastq.gz files located in the 131219_D00360_005_BH814YADXX/ directory under the samples Sample_U0a, Sample_U0b, Sample_U0c, Sample_U5a, Sample_U5b, and Sample_U5c, we will generate a MultiQC report by merging the FastQC results from all these files. The final MultiQC report will be generated as shown below: (MultiQC can be installed via Conda using the following command)</p><pre>conda install multiqc<br>multiqc .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMjqj_blpSEMlCN9axBuxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1XdB0X7tUVlhwyvwqiRNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcUJ-hFKuvLY0Gy8RRj28A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brgY1EuXpmJpXJagcmI_0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2JzJbDJ8EI4Hd3gYtVLoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsmW89W3qouweXv2G-kcpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YElEQeY4p28phSXRNWATyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sxR2BQLc50SjlJy8y3DPg.png" /><figcaption>MultiQC report for 144 fastq.gz files associated with the NA12878 sample.</figcaption></figure><p>Now, let’s take a look at how these plots can be interpreted:</p><p><strong>General Statistics:</strong></p><ul><li>FastQC Duplication: The duplication rate is very close to 0%, indicating minimal redundancy in the sequences.</li><li>FastQC GC Content: The GC content is around 40%, <a href="https://www.nature.com/articles/35057062/figures/12">which is typical for human genome</a>, suggesting no significant bias in base composition.</li><li>FastQC Average Read Length: The average read length is 148 bp, which is consistent and typical for short-read sequencing technologies.</li><li>FastQC Median Read Length: The median read length is also 148 bp, showing uniformity in read lengths across the dataset.</li><li>FastQC Failed Sequences: 0% of the sequences failed, indicating high-quality data with no significant issues.</li><li>FastQC Total Sequences: While some samples contain fewer than 1 million sequences, the majority have around 4 million reads.</li></ul><p><strong>Per Sequence GC Content:</strong> We see a peak around 40% GC content which is typical for human genomes and suggests that the dataset has a balanced distribution of GC content, with no significant GC bias. The 4% on the Y-axis at the 40% GC point represents the percentage of sequences that fall within the GC content range around 40%.</p><p><strong>Adapter Content: </strong>The plot shows some samples with values approaching 2% on the Y-axis, meaning that up to 2% of the reads in those samples contain adapter sequences. According to the FastQC Adapter Content module, a warning is issued only if an adapter sequence is found in more than 10% of all reads (<a href="https://www.bioinformatics.babraham.ac.uk/projects/fastqc/Help/3%20Analysis%20Modules/">https://www.bioinformatics.babraham.ac.uk/projects/fastqc/Help/3%20Analysis%20Modules/</a>).</p><p>Since 2% is well below this threshold, it is generally considered acceptable and does not pose a significant issue. Therefore, we can proceed with these values without concern.</p><p><strong>Per Base N Content</strong>: For all samples remains below 1%, indicating that the proportion of unidentified bases (“N”) in the sequencing data is very low. This suggests high sequencing accuracy and good data quality, with minimal issues related to base calling.</p><p><strong>Mean Quality Scores: </strong>In the Mean Quality Scores plot, all samples have quality scores above Q28 (P (incorrect) = 0.158%), staying within the green (high-quality) region. Toward 140 bp, the scores approach the lower boundary of the green zone, which is expected due to the natural decline in quality toward the end of reads in Illumina sequencing. However, the overall quality remains high and does not indicate significant concerns.</p><p><strong>Per Sequence Quality Scores:</strong> The X-axis represents the Mean Sequence Quality (Phred score), and all samples peak around Q35, indicating that most reads have high-quality scores with very low error rates. However, on the Y-axis, which represents the number of reads, the peak heights vary across samples. While most samples have peaks above 1M reads, with some reaching 1.8M reads, others show lower peaks between 0.4M and 0.2M reads. This suggests differences in sequencing depth across samples, but overall, the consistently high-quality scores indicate that the data is of good quality.</p><p><strong>Sequence Counts: </strong>In the plot, duplicate reads are represented by very small lines in all samples, indicating a low level of duplication. On the X-axis, the total number of reads varies across samples — some reach 4M reads, while others are around 3M, and some fall below 2M. This variation suggests differences in sequencing depth across samples, but the low duplication levels indicate that the data is of good quality without excessive redundancy.</p><p><strong>Sequence Duplication Levels</strong>: The Y-axis represents the percentage of the library, while the X-axis shows the duplication level. The sharp drop at duplication level 2 suggests that the vast majority of sequences are unique, with only a small portion appearing more than once. This indicates low duplication rates, which is a good sign for sequencing quality, as it suggests minimal over-sequencing and a well-complex library.</p><h3><strong>*Merging R1 and R2 Files into Single R1 and R2 Files*</strong></h3><p>To create a single R1 and R2 file for bioinformatics analysis, we will merge the R1 files and R2 files separately for each sample using the <strong>cat </strong>command. This process combines all R1 reads into one file and all R2 reads into another, ensuring they are grouped correctly for further analysis:</p><pre>#!/bin/bash<br><br># Change to the directory where the Sample_ files are located<br>cd &quot;/path/to/131219_D00360_005_BH814YADXX/&quot;<br><br># Loop through all sample directories<br>for sample in Sample_U0a Sample_U0b Sample_U0c Sample_U5a Sample_U5b Sample_U5c<br>do<br>  echo &quot;Merging files for $sample ...&quot;<br><br>  # Merge R1 files<br>  cat ${sample}/*_R1_*.fastq.gz &gt; ${sample}/${sample}_merged_R1.fastq.gz<br><br>  # Merge R2 files<br>  cat ${sample}/*_R2_*.fastq.gz &gt; ${sample}/${sample}_merged_R2.fastq.gz<br><br>  echo &quot;Finished merging $sample&quot;<br>done</pre><p>To verify that the merge process has been done correctly, we will compare the total file sizes of the R1 and R2 files in each sample with the size of the merged R1 and R2 files. The combined size of the individual R1 and R2 files should match the size of the merged files, confirming the correctness of the merge:</p><pre>#!/bin/bash<br><br>cd &quot;/path/to/131219_D00360_005_BH814YADXX/&quot;<br><br>for sample in Sample_U0a Sample_U0b Sample_U0c Sample_U5a Sample_U5b Sample_U5c<br>do<br>  echo &quot;Checking file sizes for $sample ...&quot;<br><br>  # Calculate total size of all R1 files before merging<br>  total_R1_size=$(du -ch ${sample}/*_R1_*.fastq.gz | grep total | awk &#39;{print $1}&#39;)<br>  <br>  # Get the size of the merged R1 file<br>  merged_R1_size=$(du -h ${sample}/${sample}_merged_R1.fastq.gz | awk &#39;{print $1}&#39;)<br>  <br>  echo &quot;Total R1 size before merge: $total_R1_size&quot;<br>  echo &quot;Merged R1 file size: $merged_R1_size&quot;<br>  <br>  echo &quot;-----------------------------------&quot;<br><br>done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*87ZX9hb8YwTb3-utZmLC1A.png" /></figure><p>Now, let’s merge individual R1 and R2 FASTQ files from multiple samples into one combined R1 file and one combined R2 file for further analysis.</p><pre>#!/bin/bash<br><br># Change to the directory where the downloaded files are located<br>cd &quot;/path/to/131219_D00360_005_BH814YADXX/&quot;<br><br>echo &quot;Merging all merged R1 files into a single file...&quot;<br><br># Calculate total size of individual merged R1 files<br>total_R1_size=$(du -ch Sample_U0a/Sample_U0a_merged_R1.fastq.gz \<br>    Sample_U0b/Sample_U0b_merged_R1.fastq.gz \<br>    Sample_U0c/Sample_U0c_merged_R1.fastq.gz \<br>    Sample_U5a/Sample_U5a_merged_R1.fastq.gz \<br>    Sample_U5b/Sample_U5b_merged_R1.fastq.gz \<br>    Sample_U5c/Sample_U5c_merged_R1.fastq.gz | grep total | awk &#39;{print $1}&#39;)<br><br># Merge R1 files<br>cat Sample_U0a/Sample_U0a_merged_R1.fastq.gz \<br>    Sample_U0b/Sample_U0b_merged_R1.fastq.gz \<br>    Sample_U0c/Sample_U0c_merged_R1.fastq.gz \<br>    Sample_U5a/Sample_U5a_merged_R1.fastq.gz \<br>    Sample_U5b/Sample_U5b_merged_R1.fastq.gz \<br>    Sample_U5c/Sample_U5c_merged_R1.fastq.gz &gt; merged_total_R1.fastq.gz<br><br># Get the size of the merged R1 file<br>merged_R1_size=$(du -h merged_total_R1.fastq.gz | awk &#39;{print $1}&#39;)<br><br>echo &quot;Total size of individual merged R1 files: $total_R1_size&quot;<br>echo &quot;Size of final merged R1 file: $merged_R1_size&quot;<br><br>echo &quot;-----------------------------------&quot;<br><br>echo &quot;Merging all merged R2 files into a single file...&quot;<br><br># Calculate total size of individual merged R2 files<br>total_R2_size=$(du -ch Sample_U0a/Sample_U0a_merged_R2.fastq.gz \<br>    Sample_U0b/Sample_U0b_merged_R2.fastq.gz \<br>    Sample_U0c/Sample_U0c_merged_R2.fastq.gz \<br>    Sample_U5a/Sample_U5a_merged_R2.fastq.gz \<br>    Sample_U5b/Sample_U5b_merged_R2.fastq.gz \<br>    Sample_U5c/Sample_U5c_merged_R2.fastq.gz | grep total | awk &#39;{print $1}&#39;)<br><br># Merge R2 files<br>cat Sample_U0a/Sample_U0a_merged_R2.fastq.gz \<br>    Sample_U0b/Sample_U0b_merged_R2.fastq.gz \<br>    Sample_U0c/Sample_U0c_merged_R2.fastq.gz \<br>    Sample_U5a/Sample_U5a_merged_R2.fastq.gz \<br>    Sample_U5b/Sample_U5b_merged_R2.fastq.gz \<br>    Sample_U5c/Sample_U5c_merged_R2.fastq.gz &gt; merged_total_R2.fastq.gz<br><br># Get the size of the merged R2 file<br>merged_R2_size=$(du -h merged_total_R2.fastq.gz | awk &#39;{print $1}&#39;)<br><br>echo &quot;Total size of individual merged R2 files: $total_R2_size&quot;<br>echo &quot;Size of final merged R2 file: $merged_R2_size&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*xcw73-JyeYBh7T7i_VC90g.png" /><figcaption>Merging individual R1 and R2 FASTQ files from multiple samples into one combined R1 file and one combined R2 file.</figcaption></figure><p>In the next section, we will align the merged R1 and R2 FASTQ files to the human reference genome. We will also discuss the tools and methods used for quality control of the resulting BAM files after alignment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=013d674b396a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Web Scraping to Linear Regression Model]]></title>
            <link>https://medium.com/i%CC%87stanbuldatascienceacademy/from-web-scraping-to-linear-regression-model-96c01169a305?source=rss-29084d33b030------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c01169a305</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Fatma Zehra Sarı]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 17:15:47 GMT</pubDate>
            <atom:updated>2022-09-19T23:07:24.228Z</atom:updated>
            <content:encoded><![CDATA[<p>The internet is full of data waiting to be harvested. One of the main tools to obtain the specific data we want to use is the <strong>Beautiful Soup</strong> library. In this article I will explain the basic steps to extract the data from our target website using “<strong>requests</strong>” and “<strong>Beautiful Soup</strong>” libraries, build a basic machine learning model, and check the model’s accuracy.</p><h4>Step 0: URL and HTML elements</h4><p>Before starting to scrape, we need priori knowledge of a website’s structure which is usually defined with <strong>HTML </strong>(HyperText Markup Language). HTML is a “markup” language because it uses a set of symbols to annotate text, images, and other content for display in a web browser. These symbols help us to find where the data are. HyperText in HTML refers to links that connect web pages to one another.</p><p>I chose <a href="https://www.kitapyurdu.com/"><strong>kitapyurdu.com</strong></a> website which is a popular online bookstore in Turkiye as the website I will focus on. <a href="https://www.kitapyurdu.com/">kitapyurdu.com</a> website contains a browser section for searching the books and several sub-categories like best sellers or new releases. We will extract the data from the annual best sellers list in the literary-fiction (edebiyat) and non-literary sub-categories. There are 22 and 21 pages in literary-fiction and non-literary sub-categories, respectively. If we look at the <strong>URL </strong>of the first page, second page, third page, etc. in the literary-fiction category, we see the constant and changing parts of these URLs. Changing parts of URL from page to page in kitapyurdu.com are page numbers.</p><p>URL of the first page: <a href="https://www.kitapyurdu.com/index.php?route=product/best_sellers&amp;page=1&amp;list_id=6&amp;filter_in_stock=1&amp;filter_in_stock=1">https://www.kitapyurdu.com/index.php?route=product/best_sellers&amp;page=1&amp;list_id=18&amp;filter_in_stock=1&amp;filter_in_stock=1</a></p><p>URL of the second page: <a href="https://www.kitapyurdu.com/index.php?route=product/best_sellers&amp;page=2&amp;list_id=6&amp;filter_in_stock=1&amp;filter_in_stock=1">https://www.kitapyurdu.com/index.php?route=product/best_sellers&amp;page=2&amp;list_id=18&amp;filter_in_stock=1&amp;filter_in_stock=1</a></p><p>We’ll use this information to access all pages of the aforementioned sub-categories. Now let’s look at the HTML code that creates the web page. We can inspect a website using Developer Tools which can be accessed by right-clicking on the page and selecting the Inspect option. When we look at the <em>Elements</em> tab in the developer tools, we see a structure with clickable HTML elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79nhSWYqPI2-BuCH1xvNHQ.jpeg" /><figcaption>HTML elements of the webpage</figcaption></figure><p>An HTML element starts with the &lt;tagname&gt; and end with &lt;/tagname&gt;. Some of the basic tags are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*yLd0f4r2nj7zL-qFwvxq6A.png" /><figcaption>From <a href="https://www.codebrainer.com/blog/top-10-html-tags">https://www.codebrainer.com/blog/top-10-html-tags</a></figcaption></figure><p>After this brief introduction, we can start to scrape our website.</p><h4>Step 1: Web Scraping via Beautiful Soup</h4><p>To get the website’s HTML code into our Python script, we use the requests library. Before starting web scraping, we download and import this library along with other libraries we’ll employ.</p><pre>import requests<br>from bs4 import BeautifulSoup as bts<br>import pandas as pd<br>import numpy as np</pre><p>Now, we’ll define a function “<strong>getAndParseURL(url)</strong>” that takes the URL of the webpage and issues an HTTP GET request to the given URL. It retrieves the HTML data that the server sends back and stores that data in the “result” object.</p><p>The “result” object contains HTML elements and attributes scattered around. We can parse it to make the data more accessible via Beautiful Soup (bts) library. “bts” takes HTML content we scraped earlier as its input, and returns parsed HTML content.</p><pre>def getAndParseURL(url):<br>    result = requests.get(url, headers={&quot;User-Agent&quot;:&quot;Chrome/103.0.0.0&quot;}) # Safari/537.36. Mozilla/5.0<br>    soup = bts(result.text, &quot;html.parser&quot;)<br>    return soup</pre><p>The next step is accessing the URL of each book on the each page. URL of a book is located under &lt;div&gt; with a class attribute that has the value “cover”. &lt;a&gt; tag under this attribute defines a hyperlink that contains the URL of the book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q0JUZrNYMQxC4uxF4S9-w.png" /><figcaption>href attribute : URL of the page the link goes to.</figcaption></figure><p>For each of the 22 pages (literary sub-category of bestsellers), we’ll use “getAndParseURL(page)” function to get parsed HTML content of each page and “<strong>findAll()</strong>” to access the links of the books inside the parsed HTML.</p><pre>products = []<br>for page in pages:<br>    html = getAndParseURL(page)<br>    for product in html.findAll(&quot;div&quot;,{&quot;class&quot;:&quot;cover&quot;}):<br>        products.append(product.a.get(&quot;href&quot;))<br>print(products[:25])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfqRfxsyadOceMyL0N3TPQ.png" /><figcaption>Links of the first 25 books under the literary-fiction sub-category</figcaption></figure><p>We will employ “find()” to access the information inside other HTML tags. We can get the text in HTML code by writing “.text”, and remove the empty space at the beginning and at the end of the string with “.strip()”.</p><pre>name = html.find(&quot;h1&quot;,{&quot;class&quot;:&quot;pr_header__heading&quot;}).text.strip()<br>print(&quot;Name of the Book: &quot;, name)<br>author = html.find(&quot;a&quot;,{&quot;class&quot;:&quot;pr_producers__link&quot;}).text.strip()<br>print(&quot;Author: &quot;, author)<br>publisher = html.find(&quot;div&quot;,{&quot;class&quot;:&quot;pr_producers__publisher&quot;}).text.strip()<br>print(&quot;Publisher: &quot;, publisher)<br>release_date = html.find(&quot;div&quot;,{&quot;class&quot;:&quot;attributes&quot;}).find(text=re.compile(&quot;Yayın Tarihi&quot;)).findNext().text.strip().replace(&quot;.&quot;,&quot;/&quot;)<br>print(&quot;Release Date: &quot;, release_date)<br>purchase_info = html.find(&quot;div&quot;,{&quot;class&quot;:&quot;purchase-info&quot;}).text.strip().replace(&quot;.&quot;,&quot;&quot;)<br>print(&quot;Purchase Info: &quot;, purchase_info)<br>page_num = html.find(&quot;div&quot;,{&quot;class&quot;:&quot;attributes&quot;}).find(text=re.compile(&quot;Sayfa Sayısı:&quot;)).findNext().text.strip()<br>print(&quot;Number of Pages: &quot;, int(page_num))<br>cover =  html.find(&quot;div&quot;,{&quot;class&quot;:&quot;attributes&quot;}).find(text=re.compile(&quot;Cilt Tipi:&quot;)).findNext().text.strip()<br>print(&quot;Type of the Book Cover: &quot;, cover)<br>paper_type = html.find(&quot;div&quot;,{&quot;class&quot;:&quot;attributes&quot;}).find(text=re.compile(&quot;Kağıt Cinsi:&quot;)).findNext().text.strip()<br>print(&quot;Type of the Paper: &quot;, paper_type)<br>rating = float(html.find(&quot;meta&quot;, itemprop=&quot;ratingValue&quot;).attrs[&quot;content&quot;].replace(&quot;.&quot;,&quot;&quot;))<br>print(&quot;Rate: &quot;, rating)<br>rating_count = int(html.find(&quot;meta&quot;, itemprop=&quot;ratingCount&quot;).attrs[&quot;content&quot;].replace(&quot;.&quot;,&quot;&quot;))<br>print(&quot;Rating Count: &quot;, rating_count)<br>review_count = int(html.find(&quot;meta&quot;, itemprop=&quot;reviewCount&quot;).attrs[&quot;content&quot;].replace(&quot;.&quot;,&quot;&quot;))<br>print(&quot;Review Count: &quot;, review_count)<br>fav_count = int(html.find(&quot;span&quot;,{&quot;id&quot;:&quot;favorite-count&quot;}).text.strip().replace(&quot;.&quot;,&quot;&quot;))<br>print(&quot;Fav Count: &quot;, fav_count)<br>to_read_list = html.find(&quot;li&quot;,{&quot;class&quot;:&quot;readlists__item&quot;}).text.strip(&quot;\n&quot;).strip().replace(&quot;.&quot;,&quot;&quot;)<br>print(&quot;To-Read List Count: &quot;, to_read_list)<br>price = float(html.find(&quot;div&quot;,{&quot;class&quot;:&quot;price__item&quot;}).text.strip().replace(&quot;,&quot;,&quot;.&quot;))<br>print(&quot;Price: &quot;, price)<br>discount = html.find(&quot;p&quot;,{&quot;class&quot;:&quot;info-text&quot;}).text.replace(&quot;,&quot;,&quot;.&quot;)<br>print(&quot;Discount: &quot;, discount)<br>manufacturer_price = float(html.find(&quot;span&quot;,{&quot;class&quot;:&quot;pr_price__strikeout-list&quot;}).text.strip().replace(&quot;,&quot;,&quot;.&quot;))<br>print(&quot;Manufacturer Price: &quot;, manufacturer_price)</pre><pre>df = pd.DataFrame.from_records(features, columns=df_columns)<br>    df.to_pickle(&quot;./kitap_yurdu_literary.pkl&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*ctAfDb1NxkwiyAVj-7d1LQ.png" /><figcaption>Attributes we extracted for one of the books</figcaption></figure><p>We will perform the same steps for the non-literary sub-category of bestsellers, too. Then we’ll <strong>append </strong>the second dataframe we created to the first one. In the regression model we’ll construct, we are planning to predict the <strong>price </strong>of the books. So we need to put the features we get into a form that can be used as input for our model.</p><h4>Step 2: Feature Engineering</h4><p>As we can see, we could not obtain the “number” data for “<strong>purchase_info</strong>” and “<strong>to_read_list</strong>” attributes. To solve this issue, we can write a simple function to split the string we obtained into a list and find the “number” information inside of the list’s elements.</p><pre>for i in purchase_info.split():<br>    try:<br>        purchase_num = int(i)<br>        return purchase_num<br>    except ValueError:<br>        pass</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKyHcvXyPK3JNXVOvv0s7g.png" /><figcaption>The first 5 rows of the dataframe</figcaption></figure><p>After obtaining the attributes for each one of the books under “literary-fiction” and “non-literary” sub-categories, we construct a dataframe to hold all the data and can save this dataframe as a pickle object using “<strong>.to_pickle()</strong>” function of pandas library.</p><p>The “<strong>release_date</strong>” attribute is not very useful in this form. We can use it to obtain the number of days passed since the release date of the book. To do that, we’ll convert the type of release date from string to datetime object. Then we’ll obtain today’s date in the same format and find the difference between them.</p><pre>today = datetime.now().date()<br>def time_passed(release_date):   <br>    rd = datetime.strptime(release_date, &quot;%d/%m/%Y&quot;).date()<br>    time_since_publ = (today-rd).days<br>    return(time_since_publ)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB38DAeJm23nmaJGf-5Hvg.png" /><figcaption>The first 5 rows of the dataframe with “Time Passed Since Publication” column</figcaption></figure><p>Different types of<strong> covers </strong>and <strong>papers </strong>may effect the price of the book. There are 2 types of covers and 5 types of papers in our dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*GIvRkxXfJ4Puchc8fGnOww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*7JIryjRiTlgDyUwyMp1gsg.png" /></figure><p>Types of Cover of the Book -&gt; Karton Kapak : softcover &amp; Ciltli: hardcover</p><p>Types of Paper -&gt; Kitap Kağıdı: Uncooated paper &amp; 3. Hm. Kağıt: 3. Grade Pulp Paper &amp; 2. Hm. Kağıt: 2. Grade Pulp Paper &amp; 1. Hm. Kağıt: 1. Grade Pulp Paper &amp; Kuşe Kağıt: Coated paper</p><p>We can use <strong>label encoding</strong> to convert the types of covers and papers into the numeric form so as to machine-readable form. Firstly we create dictionaries that match each cover or paper type with a number, then map columns of our dataframe with these dictionaries. By the way, the numbers we assign are not randomly assigned, but based on the quality of the cover or the paper type.</p><pre>book_cover_dict = { &#39;Karton Kapak&#39;:1, &#39;Ciltli&#39;:2}</pre><pre>paper_dict = { &#39;Kitap Kağıdı&#39;:2,<br>                &#39;2. Hm. Kağıt&#39;:2,<br>                &#39;1. Hm. Kağıt&#39;:3,                  <br>                &#39;3. Hm. Kağıt&#39;:1,<br>                &#39;Kuşe Kağıt&#39;:4 }<br>ky[&quot;Cover of Book&quot;] = ky[&quot;Cover of Book&quot;].map(book_cover_dict)<br>ky[&#39;Paper Type&#39;] = ky[&#39;Paper Type&#39;].map(paper_dict)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJ9YQaTM332CL0pvMm9FoQ.png" /><figcaption>The first 5 rows of the dataframe after label encoding step</figcaption></figure><p>Before the construction of the machine learning model, we’ll drop duplicate rows and the first 3 non-numeric columns from the dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcKY32ZWb4fBXHQr7HihRA.png" /><figcaption>The first 5 rows of the dataframe after removing the first 3 non-numeric columns</figcaption></figure><p>We also need to check empty rows of the columns before further steps.<strong> </strong>We can prefer to remove the empty rows or fill them with mean, median etc. of that specific column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*WyJsLzAjfPHgYqo44RzLlw.png" /><figcaption>Summary of the dataframe</figcaption></figure><p>I prefer to remove 10 empty rows of <strong>Number of Pages </strong>and 2<strong> </strong>empty rows of <strong>Time Passed Since Publication.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*kZxQrPp791bk5OfCfztP7Q.png" /><figcaption>Dataframe after removal of empty rows</figcaption></figure><p>For filling the empty rows of the <strong>Manufacturer Price</strong> column we can use numbers selected from a uniform distribution over [0, mean + standard deviation) interval of the column.</p><pre>def mean_std_filling(column_name):    <br>    mean = column_name.mean()<br>    std = column_name.std()<br>    is_null = column_name.isna().sum()<br>    print(&#39;Mean:&#39;, mean, &#39;Std:&#39;, std, &#39;Null:&#39;, is_null)<br>    rand_float = np.random.uniform(0, mean + std, size = is_null)<br>    print(&#39;Numbers:&#39;, rand_float[:25])</pre><pre>    column_name[np.isnan(column_name)] = rand_float<br>    column_name = column_name.astype(float)</pre><p>For filling one empty row of the <strong>Type of the Paper</strong> column, we can use “2” which is the standard type of book paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*We2VIQDRVLljsmSg3DqR4w.png" /><figcaption>The last version of the dataframe after feature engineering steps</figcaption></figure><h4>Step 3: Building a linear regression model</h4><p>We start with the split of dataframe as train, validation, and test sets. We use the train set for training step, then test the accuracy of the model with the validation and test sets. <strong>Scikit-learn</strong> is a famous Python library that can be used to create machine learning models. We’ll use this library for both to split the dataset and to build our model.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X = ky_lr.loc[:,ky_lr.columns != &quot;Price&quot;]<br>y = ky_lr.Price</pre><pre># Train/Test split<br>X_train, x_test, Y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><pre># Train/Validation split<br>x_train, x_cv, y_train, y_cv = train_test_split(X_train, Y_train, test_size=0.2, random_state=42)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*cHBp5q3KHAwKbQ6xGzBEkg.png" /><figcaption>Sizes of the datasets</figcaption></figure><p>After importing the library, let’s train our model with the training set and check the accuracy by calculating R² and Mean Square Error metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*I-hhhYTgpW6GboU0Ubuv0w.png" /></figure><p>R² shows the goodness of fit. In our case, R² is too high and it means that there may be an overfitting problem. Let’s check the distribution of the 6 columns of the dataframe with <strong>Seaborn </strong>library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXocwQ4zP9odR5l_V9sJ2w.png" /><figcaption>Distribution of the dataframe’s columns</figcaption></figure><p>We can see that all 6 columns exhibit a right-skewed distribution. We’ll use the upper-quartile values of the columns to remove the outliers and try to obtain a distribution similar to the normal distribution. (Upper-quartile is the value under which 75% of data points are found when arranged in increasing order.)</p><pre>def extract_whiskers(data):<br>    median_value = np.median(data) # Median<br>    upper_quartile = np.percentile(data, 75) # 75%<br>    lower_quartile = np.percentile(data, 25) # 25%</pre><pre>iqr = upper_quartile - lower_quartile # Interquartile Range<br>    upper = data[data&lt;=upper_quartile+1.5*iqr].max()<br>    print(&quot;Upper Whisker:&quot;, data[data&lt;=upper_quartile+1.5*iqr].max()) # Max<br>    #print(&quot;Lower Whisker:&quot;, data[data&gt;=lower_quartile-1.5*iqr].min()) # Min<br>    return upper2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcxOSvtKs5yKP0G4ntIvSw.png" /><figcaption>Distribution of the dataframe’s columns after removal of outliers</figcaption></figure><p>We can use the log-transformation to transform skewed data to approximately conform to normality. We’ll employ the <strong>Numpy </strong>library to transform Purchase Info, Rating Count, Review Count, and Fav Count columns into log-transformed versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmAsUn3AXi2_QZFQoHNczg.png" /><figcaption>Log-transformed columns (features)</figcaption></figure><p>After the transformation step, let’s check the correlation between the features in our dataframe. If two features show a high correlation, change in one of them would cause change to another and so the model results to fluctuate significantly. We need to identify highly correlated features and remove them before the model training step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6-DKvHVfKfBMs7N1OkRKw.png" /><figcaption>Correlation heatmap of the features after log transformation</figcaption></figure><p>To determine the features that show high corr with other features :</p><pre>corr_matrix = ky_lr.corr().abs()</pre><pre># Select upper triangle of correlation matrix<br>upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))</pre><pre># Find features with correlation greater than 0.85<br>to_drop = [column for column in upper.columns if any(upper[column] &gt; 0.85)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*xddUBG7YtzEaLaeQry6yGA.png" /><figcaption>Features that show high correlation with other features</figcaption></figure><p>Let’s drop the “Manufacturer Price”, “Review Count Log” and “Rating Count Log” columns, and train our model again, then check the accuracy for both validation and test sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*YqQwiuvihryUZRp08s9eTA.png" /></figure><p>We can say that we have overcome the overfitting problem, because the accuracy of the validation set is reasonable, and the accuracy of our holdout set (test set) is high enough to continue with this model. So our model generalizes well. As a final step, let’s find out how much each feature contributes to the model prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlOhRPI28d8vOojTpMmhHg.png" /></figure><p>“<strong>Type of the Book Cover</strong>” is the feature that has the most impact on the “<strong>Price</strong>” prediction.</p><p><strong>You can view the codes of this project at:</strong></p><p><a href="https://github.com/FatmaZehraSari/webScraping_linearRegression/blob/main/webScraping_linearReg_kitapyurdu.ipynb"><strong>https://github.com/FatmaZehraSari/webScraping_linearRegression/blob/main/webScraping_linearReg_kitapyurdu.ipynb</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c01169a305" width="1" height="1" alt=""><hr><p><a href="https://medium.com/i%CC%87stanbuldatascienceacademy/from-web-scraping-to-linear-regression-model-96c01169a305">From Web Scraping to Linear Regression Model</a> was originally published in <a href="https://medium.com/i%CC%87stanbuldatascienceacademy">İstanbul Data Science Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>