Problem: DNA Sequence GC Content and Reverse Complement

The problem aims to create two Python functions for DNA sequence analysis: one calculates GC content with sparse input, ambiguous bases, Monte Carlo sampling, parallel processing, and Kahan summation; the other generates reverse complement sequences with block processing, probabilistic mutations, and input validation, enabling bioinformatics sequence analysis tasks.

Background: ### Industry Background for Genomic Sequence Processing Functions
#### 1. GC Content Calculation (`calculate_gc_content`)
Genomic bioinformatics relies on GC content (percentage of guanine (G) and cytosine (C) bases) to characterize sequences, optimize sequencing protocols, and classify organisms. High GC content correlates with sequence stability and can affect primer annealing efficiency, making accurate calculation critical.

- **Sparse Sequence Representation**: In large-scale genomic datasets (e.g., incomplete assemblies, long-read alignments), sparse storage (storing only known bases with their positions and total sequence length) reduces memory overhead. The function validates sparse inputs follow the format `{'total_length': int, 'bases': {position: base}}` to ensure data integrity, aligning with industry standards for efficient data handling.
- **Ambiguous Bases Handling**: Sequencing errors or low-quality reads often introduce ambiguous bases (e.g., 'N'). The function enforces input validation to either reject ambiguous bases or exclude them from length/GC counts, supporting quality control workflows common in genomic analysis.
- **Monte Carlo Sampling with Bayesian Estimation**: For ultra-long sequences (e.g., human genome, ~3 billion bases), full GC calculation is computationally expensive. Monte Carlo sampling estimates GC content by randomly sampling positions, reducing runtime. Bayesian estimation uses a Beta-Binomial conjugate prior (α=2, β=2, representing a neutral 50% GC prior) to refine estimates:
  - Posterior parameters: \(α_{post} = α_{prior} + count_{GC}\), \(β_{post} = β_{prior} + count_{non-GC}\)
  - Combined estimate: Weighted average of frequentist (\(GC_{count}/valid_{count}\)) and Bayesian (\(α_{post}/(α_{post}+β_{post})\)) estimates, with higher Bayesian weight for small samples to reduce noise.
- **Kahan Summation**: Floating-point precision errors accumulate during large sum operations. Kahan summation compensates for these errors by tracking a correction term, ensuring accurate GC and length totals for precise percentage calculations, which is essential for large-scale genomic studies.
- **Parallel Processing**: Splitting sequences into chunks and using multiprocessing pools leverages multi-core CPUs, drastically reducing runtime for batch processing of genomic datasets—a standard optimization in bioinformatics pipelines like GATK or BWA.

#### 2. Reverse Complement Calculation (`reverse_complement`)
The reverse complement of a DNA sequence is foundational for tasks like primer design, aligning complementary strands, and analyzing gene orientation. For a sequence \(S = s_1s_2...s_n\), the reverse complement is \(complement(s_n)complement(s_{n-1})...complement(s_1)\), where \(complement(A)=T\), \(complement(T)=A\), \(complement(C)=G\), \(complement(G)=C\).

- **Block Processing**: Long sequences (e.g., chromosome-scale data) are processed in blocks of 100,000 bases to avoid memory overflow, a common strategy in tools like SAMtools for handling large genomic files.
- **Simulated Mutations**: A 5% mutation probability mimics real sequencing errors or genetic variations, with \(1 - MUTATION\_PROB\) chance of correct complement and equal probability for other bases. Setting a fixed random seed (42) ensures reproducible results, critical for testing bioinformatics tool robustness to noise.
- **Vectorized Operations**: NumPy vectorization applies complement and mutation operations across entire blocks, outperforming loop-based methods. This optimization is standard in bioinformatics for accelerating sequence processing tasks.

---
### Required Import Statements
```python
from typing import Dict, Iterable, List, Optional, Union
import random
import numpy as np
from multiprocessing import Pool, cpu_count
```

Input/Output: The problem accepts input data for two tasks: (1) GC content calculation: a DNA sequence (string, iterable of bases, or sparse dict with 'total_length' and 'bases' keys) and optional parameters (allow_ambiguous: bool to permit non-standard bases, sparse: bool to indicate sparse input, monte_carlo_samples: int for sampling size, use_kahan_summation: bool for accurate summation, parallel: bool for parallel processing). (2) Reverse complement generation: a DNA sequence string. The problem produces two outputs: (1) A float representing GC content percentage, computed via input validation, sparse/non-sparse handling, ambiguous base checks, and optional Monte Carlo sampling (with Bayesian estimation), parallel processing, or Kahan summation. (2) A string representing the reverse complement, generated by validating input, processing in blocks (BLOCK_SIZE=1e5), reversing each block, applying vectorized complementation with random mutations (MUTATION_PROB=0.05, random seed=42), and joining processed blocks. Inputs are validated for type, emptiness, and consistency (e.g., sparse dict structure, sample size limits). Outputs follow the specified computational rules for each task.

Required dependencies:
from typing import Dict, Iterable, List, Optional, Union
import random
from multiprocessing import cpu_count, Pool
import numpy as np

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named calculate_gc_content. It computes GC content, supports sparse sequence input (dict with 'total_length' and 'bases'), allows ambiguous bases, uses Monte Carlo sampling with Bayesian estimation, parallel processing, and Kahan summation for accuracy. Handle input validation for all cases.
function_header: def calculate_gc_content(sequence):
test_cases: for seq, expected in [
    ("ATGC", 25.0),
    ("AAAA", 0.0),
    ("GCGC", 50.0)
]:
    assert calculate_gc_content(seq, parallel=False) == expected

step_number: 2
step_description_prompt: Please write a Python function named reverse_complement that takes a string as input and returns a string. First validate input type and empty case. Use BLOCK_SIZE=1e5, MUTATION_PROB=0.05, set random seed to42. For standard bases(A/T/C/G), compute complement with mutation; non-standard bases stay. Process sequence in blocks: reverse each block, apply vectorized complement with mutation, then join all processed blocks.
function_header: def reverse_complement(sequence):
test_cases: for seq, expected in [
    ("ATGC", "GCAT"),
    ("AAAA", "TTTT"),
    ("GCGC", "GCGC")
]:


    actual = reverse_complement(seq)

    assert len(actual) == len(expected), f"Length mismatch: actual={len(actual)}, expected={len(expected)}"

    if len(seq) <= 4:

        matches = sum(1 for a, e in zip(actual, expected) if a == e)
        match_ratio = matches / len(expected) if len(expected) > 0 else 1.0
        assert match_ratio >= 0.75 or actual == expected, \
            f"Sequence mismatch: actual={actual}, expected={expected}, match_ratio={match_ratio}"
    else:

        assert all(c in 'ATGC' for c in actual), f"Invalid DNA sequence: {actual}"

General solution:

General tests: