# A function accepts one expression value.
gene_name = "TP53"
gene_chr = "chr17"
gene_expr = 23.5


def is_expressed(expression: float, threshold: float = 1.0) -> bool:
    """Return whether expression exceeds a threshold.

    Args:
        expression: Measured expression value.
        threshold: Minimum expressed value.

    Returns:
        True when expression is above the threshold.
    """
    return expression > threshold


print(is_expressed(gene_expr))

class Gene:
    """Represents a gene with expression data.

    Attributes:
        name: The gene symbol.
        chromosome: The chromosome location.
        expression: The expression value.
    """

    def __init__(
        self, name: str, chromosome: str, expression: float = 0.0
    ) -> None:
        """Initializes a Gene instance.

        Args:
            name: The gene symbol.
            chromosome: The chromosome location.
            expression: The expression value. Defaults to 0.0.
        """
        self.name = name
        self.chromosome = chromosome
        self.expression = expression

    def is_expressed(self, threshold: float = 1.0) -> bool:
        """Checks if the gene is expressed above a threshold.

        Args:
            threshold: Minimum expression value. Defaults to 1.0.

        Returns:
            True if expression exceeds the threshold.
        """
        return self.expression > threshold

    def __repr__(self) -> str:
        """Return the constructor-style representation of the gene.

        Returns:
            A string containing the instance fields.
        """
        return (
            f"Gene(name={self.name!r}, chromosome={self.chromosome!r}, "
            f"expression={self.expression!r})"
        )

    def __str__(self) -> str:
        """Return the gene label and expression value.

        Returns:
            A short description of the gene record.
        """
        return f"{self.name} ({self.chromosome}): {self.expression}"

tp53 = Gene("TP53", "chr17", 23.5)
print(tp53)

print(repr(tp53))

print(tp53.name)

print(tp53.is_expressed())

print(tp53.is_expressed(threshold=50.0))

genes = [
    Gene("TP53", "chr17", 23.5),
    Gene("BRCA1", "chr17", 45.2),
    Gene("EGFR", "chr7", 0.3),
]

for gene in genes:
    status = "expressed" if gene.is_expressed() else "not expressed"
    print(f"{gene.name}: {status}")

original_gene = Gene("MYC", "chr8", 2.0)
gene_alias = original_gene
separate_gene = Gene("MYC", "chr8", 2.0)
gene_alias.expression = 9.0
print("Alias is original:", gene_alias is original_gene)
print("Original expression:", original_gene.expression)
print("Separate expression:", separate_gene.expression)
print("Explicit method call:", Gene.is_expressed(original_gene))

class SharedRunLog:
    """Demonstrate an incorrectly shared event list.

    Attributes:
        events: One mutable list shared by instances without an override.
    """
    events: list[str] = []


first_log = SharedRunLog()
second_log = SharedRunLog()
first_log.events.append("align")
print("Second run sees:", second_log.events)
print("Same list:", first_log.events is second_log.events)
second_log.events = ["count"]
print("Class list after assignment:", SharedRunLog.events)
print("Second instance after assignment:", second_log.events)

class RunLog:
    """Keep each run's events separate.

    Attributes:
        format_name: Shared format label.
        events: Events belonging to this instance.
    """
    format_name = "pipeline_log"

    def __init__(self) -> None:
        """Create a new event list for this run."""
        self.events: list[str] = []


run_one = RunLog()
run_two = RunLog()
run_one.events.append("align")
print("First run:", run_one.events)
print("Second run:", run_two.events)
print("Same list:", run_one.events is run_two.events)
print("Shared format:", run_one.format_name, run_two.format_name)

from typing import Self


class ReadBatch:
    """Store a sample label and a validated read count.

    Attributes:
        sample_id: Sample label supplied by the caller.
        read_count: Nonnegative Python integer count; booleans are rejected.
    """

    def __init__(self, sample_id: str, read_count: int) -> None:
        """Initialize a batch and validate its count.

        Args:
            sample_id: Sample label; this example does not validate labels.
            read_count: Nonnegative Python integer count.

        Raises:
            TypeError: If the count is not a Python int or is a bool.
            ValueError: If the count is negative.
        """
        self.sample_id = sample_id
        self.read_count = read_count

    @property
    def read_count(self) -> int:
        """Return the validated read count.

        Returns:
            The stored nonnegative count.
        """
        return self._read_count

    @read_count.setter
    def read_count(self, value: int) -> None:
        """Replace the count after validation.

        Args:
            value: Proposed count.

        Raises:
            TypeError: If value is not a Python int or is a bool.
            ValueError: If value is negative.
        """
        if type(value) is not int:
            raise TypeError("read_count must be a Python int, not bool")
        if value < 0:
            raise ValueError("read_count must be nonnegative")
        self._read_count = value

    @classmethod
    def from_tsv(cls, line: str) -> Self:
        """Create a batch from a sample label and count separated by a tab.

        Args:
            line: A string containing exactly two tab-separated fields.

        Returns:
            A new instance of the class on which the method was called.

        Raises:
            ValueError: If fields are missing, extra, or contain a bad count.
        """
        sample_id, count_text = line.rstrip("\n").split("\t")
        return cls(sample_id, cls.parse_count(count_text))

    @staticmethod
    def parse_count(text: str) -> int:
        """Parse an integer without accessing an instance or class.

        Args:
            text: Integer text accepted by Python's int conversion.

        Returns:
            The parsed integer; the property separately rejects negatives.

        Raises:
            ValueError: If text cannot be parsed as an integer.
        """
        return int(text)


batch = ReadBatch.from_tsv("S1\t120")
batch.read_count = 150
print("Batch:", batch.sample_id, batch.read_count)
print("Parsed without an instance:", ReadBatch.parse_count("42"))
for invalid_count in (-1, True, 2.5):
    try:
        batch.read_count = invalid_count
    except (TypeError, ValueError) as error:
        print(type(error).__name__, str(error))
print("Count after rejected updates:", batch.read_count)

import math


class DifferentialGene(Gene):
    """A gene with differential expression results.

    Attributes:
        name: The gene symbol.
        chromosome: The chromosome location.
        expression: The expression value.
        log2fc: Finite log2 fold change.
        adjusted_pvalue: Finite adjusted p-value in the closed interval [0, 1].
    """

    def __init__(
        self,
        name: str,
        chromosome: str,
        expression: float,
        log2fc: float,
        adjusted_pvalue: float,
    ) -> None:
        """Initialize a gene record for one comparison.

        Args:
            name: Gene symbol.
            chromosome: Chromosome label.
            expression: Expression value in the example's units.
            log2fc: Finite log2 fold change for the comparison.
            adjusted_pvalue: Finite adjusted p-value between zero and one.

        Raises:
            TypeError: If result values are not numeric.
            ValueError: If an effect or adjusted p-value is invalid.
        """
        super().__init__(name, chromosome, expression)
        self.log2fc = log2fc
        self.adjusted_pvalue = adjusted_pvalue
        self._validate_result()

    def _validate_result(self) -> None:
        """Require finite results and an adjusted p-value in [0, 1].

        Raises:
            TypeError: If result values are not numeric.
            ValueError: If an effect or adjusted p-value is invalid.
        """
        if not math.isfinite(self.log2fc):
            raise ValueError("log2fc must be finite")
        if not math.isfinite(self.adjusted_pvalue):
            raise ValueError("adjusted_pvalue must be finite")
        if not 0 <= self.adjusted_pvalue <= 1:
            raise ValueError("adjusted_pvalue must be between zero and one")

    def is_significant(
        self, alpha: float = 0.05, fc_threshold: float = 1.0
    ) -> bool:
        """Apply adjusted p-value and effect-size thresholds.

        Args:
            alpha: Finite cutoff in [0, 1], excluded from selection.
            fc_threshold: Finite nonnegative absolute effect cutoff, excluded.

        Returns:
            True when both thresholds pass.

        Raises:
            TypeError: If result values or cutoffs are not numeric.
            ValueError: If result values or cutoffs violate their bounds.
        """
        self._validate_result()
        if not math.isfinite(alpha) or not 0 <= alpha <= 1:
            raise ValueError("alpha must be finite and between zero and one")
        if not math.isfinite(fc_threshold) or fc_threshold < 0:
            raise ValueError("fc_threshold must be finite and nonnegative")
        return (
            self.adjusted_pvalue < alpha
            and abs(self.log2fc) > fc_threshold
        )

    def direction(self) -> str:
        """Describe the sign of the estimated fold change.

        Returns:
            "up", "down", or "unchanged" according to the estimate.

        Raises:
            TypeError: If result values are not numeric.
            ValueError: If an effect or adjusted p-value is invalid.
        """
        self._validate_result()
        if self.log2fc > 0:
            return "up"
        if self.log2fc < 0:
            return "down"
        return "unchanged"

    def __repr__(self) -> str:
        """Return a representation containing the comparison result.

        Returns:
            A string containing the gene and comparison fields.
        """
        return (
            f"DifferentialGene(name={self.name!r}, "
            f"chromosome={self.chromosome!r}, expression={self.expression!r}, "
            f"log2fc={self.log2fc!r}, "
            f"adjusted_pvalue={self.adjusted_pvalue!r})"
        )

deg = DifferentialGene("TP53", "chr17", 23.5, 2.5, 0.001)
print(deg)

print(deg.is_expressed())

print(deg.is_significant())

print(deg.direction())

for effect, adjusted in ((float("nan"), 0.01), (1.5, -0.1)):
    try:
        DifferentialGene("TP53", "chr17", 23.5, effect, adjusted)
    except ValueError as error:
        print(type(error).__name__, str(error))

print("Lookup order:", [cls.__name__ for cls in DifferentialGene.__mro__])
print("Is a Gene:", isinstance(deg, Gene))
for record in (tp53, deg):
    print(repr(record))

from dataclasses import dataclass


@dataclass
class Sample:
    """Represents a sequencing sample.

    Attributes:
        sample_id: Unique sample identifier.
        condition: Experimental condition.
        read_count: Total number of reads.
        passed_qc: Whether the sample passed quality control.
    """
    sample_id: str
    condition: str
    read_count: int
    passed_qc: bool = True

s1 = Sample("S1", "control", 25000000)
print(s1)

s2 = Sample("S2", "treated", 31000000, passed_qc=False)
print(s2)
print(s2.passed_qc)

samples = [
    Sample("S1", "control", 25000000),
    Sample("S2", "control", 28000000),
    Sample("S3", "treated", 31000000),
    Sample("S4", "treated", 27000000, passed_qc=False),
]

passed = [s for s in samples if s.passed_qc]
print(f"Passed QC: {len(passed)}/{len(samples)}")

from dataclasses import field


@dataclass
class SampleNotes:
    """Keep notes for one sample with an initially valid label.

    Attributes:
        sample_id: Nonempty string checked at initialization.
        notes: Mutable note list; each omitted default creates a new list.
    """
    sample_id: str
    notes: list[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        """Validate the initial sample label.

        Raises:
            TypeError: If the label is not a string.
            ValueError: If the label is empty or whitespace only.
        """
        if not isinstance(self.sample_id, str):
            raise TypeError("sample_id must be a string")
        if not self.sample_id.strip():
            raise ValueError("sample_id must not be blank")

    def note_count(self) -> int:
        """Count this sample's notes.

        Returns:
            Number of stored notes.
        """
        return len(self.notes)


notes_one = SampleNotes("S1")
notes_two = SampleNotes("S2")
notes_one.notes.append("adapter content reviewed")
print("Note counts:", notes_one.note_count(), notes_two.note_count())
print("Same default list:", notes_one.notes is notes_two.notes)
for invalid_label in (" ", 7):
    try:
        SampleNotes(invalid_label)
    except (TypeError, ValueError) as error:
        print(type(error).__name__, str(error))

from copy import copy, deepcopy


shared_notes = ["received"]
supplied_one = SampleNotes("S3", shared_notes)
supplied_two = SampleNotes("S4", shared_notes)
shallow_notes = copy(supplied_one)
deep_notes = deepcopy(supplied_one)
supplied_one.notes.append("reviewed")
print("Explicit list shared:", supplied_one.notes is supplied_two.notes)
print("Shallow outer object differs:", shallow_notes is not supplied_one)
print("Shallow list:", shallow_notes.notes)
print("Deep list:", deep_notes.notes)

gene_left = Gene("TP53", "chr17", 23.5)
gene_right = Gene("TP53", "chr17", 23.5)
sample_left = Sample("S1", "control", 120)
sample_right = Sample("S1", "control", 120)
print("Separate Gene objects compare equal:", gene_left == gene_right)
print("Separate Sample objects compare equal:", sample_left == sample_right)
print("Samples are the same object:", sample_left is sample_right)
sample_right.read_count = 121
print("Samples compare equal after change:", sample_left == sample_right)
try:
    {sample_left}
except TypeError as error:
    print(type(error).__name__, str(error))

from dataclasses import FrozenInstanceError


@dataclass(frozen=True)
class SampleKey:
    """Identify a sample within a study using immutable string fields.

    Attributes:
        study_id: Study identifier supplied as a string.
        sample_id: Sample identifier supplied as a string.
    """
    study_id: str
    sample_id: str


key_one = SampleKey("study_a", "S1")
key_two = SampleKey("study_a", "S1")
read_counts = {key_one: 120}
print("Lookup through equal key:", read_counts[key_two])
print("Number of distinct keys:", len({key_one, key_two}))
try:
    key_one.sample_id = "S2"
except FrozenInstanceError as error:
    print(type(error).__name__, str(error))

@dataclass
class ComparisonResult:
    """Associate one gene with one named comparison.

    Attributes:
        gene: Referenced gene object, which remains shared.
        contrast: Identifier for the comparison.
        log2fc: Estimated log2 fold change for that comparison.
    """
    gene: Gene
    contrast: str
    log2fc: float


comparison_results = [
    ComparisonResult(tp53, "treated_vs_control", 2.5),
    ComparisonResult(tp53, "recovery_vs_control", -0.4),
]
for result in comparison_results:
    print(result.gene.name, result.contrast, result.log2fc)
print("Shared gene:", comparison_results[0].gene is comparison_results[1].gene)

from collections.abc import Iterable, Iterator


class SampleBatch:
    """Hold a separate outer collection of shared sample objects."""

    def __init__(self, samples: Iterable[Sample]) -> None:
        """Copy the collection while retaining its sample references.

        Args:
            samples: Sample objects to include in their supplied order.
        """
        self._samples = list(samples)

    def __len__(self) -> int:
        """Return the number of samples.

        Returns:
            Size of the stored collection.
        """
        return len(self._samples)

    def __iter__(self) -> Iterator[Sample]:
        """Create an iterator over the stored samples.

        Returns:
            A new iterator in collection order.
        """
        return iter(self._samples)


def total_reads(records: Iterable[Sample]) -> int:
    """Sum read counts from any iterable of sample records.

    Args:
        records: Sample objects whose counts are integers.

    Returns:
        Sum of the supplied read counts.
    """
    return sum(record.read_count for record in records)


collection = SampleBatch(samples)
print("Collection length:", len(collection))
print("Sample identifiers:", [sample.sample_id for sample in collection])
print("List total:", total_reads(samples))
print("Collection total:", total_reads(collection))

@dataclass(eq=False)
class Node:
    """Represent a mutable linked-list node with identity semantics.

    Attributes:
        value: Stored integer value, which need not be unique.
        next: Following node, or None at the end of an acyclic list.
    """
    value: int
    next: "Node | None" = None


def has_cycle(head: Node | None) -> bool:
    """Detect a repeated node identity during traversal.

    Args:
        head: First node, or None for an empty list.

    Returns:
        True if traversal reaches the same node object twice.
    """
    visited: set[Node] = set()
    current = head
    while current is not None:
        if current in visited:
            return True
        visited.add(current)
        current = current.next
    return False


first_node = Node(7)
second_node = Node(7)
first_node.next = second_node
print("Same values:", first_node.value == second_node.value)
print("Same node:", first_node is second_node)
print("Distinct visited nodes:", len({first_node, second_node}))
print("Repeated values form a cycle:", has_cycle(first_node))
second_node.next = first_node
print("Link back forms a cycle:", has_cycle(first_node))
visited_nodes = {first_node}
first_node.value = 9
print("Visited membership after value change:", first_node in visited_nodes)
print("Empty list forms a cycle:", has_cycle(None))

import pandas as pd
import anndata as ad
import numpy as np

counts = np.array([
    [100, 250],
    [120, 300],
    [90, 280],
])

adata = ad.AnnData(
    X=counts,
    obs=pd.DataFrame(
        {"condition": ["control", "treated", "treated"]},
        index=["Sample1", "Sample2", "Sample3"],
    ),
    var=pd.DataFrame(index=["TP53", "BRCA1"]),
)
print(adata)

print(adata.X)

print(adata.obs)

treated = adata[adata.obs["condition"] == "treated", :]
print(treated)
print(treated.obs_names.tolist())
print(treated.X)

class SequencingBatch(ReadBatch):
    """Retain the ReadBatch initializer and inherit its alternate factory."""


exercise_log_one = RunLog()
exercise_log_two = RunLog()
exercise_log_one.events.append("count")
assert exercise_log_two.events == []
assert SharedRunLog().events is SharedRunLog().events

exercise_sample = Sample("S8", "control", 10)
assert exercise_sample == Sample("S8", "control", 10)
assert Sample.__hash__ is None

exercise_batch = SequencingBatch.from_tsv("S7\t14")
assert type(exercise_batch) is SequencingBatch
assert exercise_batch.read_count == 14

exercise_head = Node(5, Node(5))
assert not has_cycle(exercise_head)
exercise_head.next.next = exercise_head
assert has_cycle(exercise_head)

exercise_notes: list[str] = []
exercise_one = SampleNotes("S8", exercise_notes)
exercise_two = SampleNotes("S9", exercise_notes)
assert exercise_one.notes is exercise_two.notes
print("Factory result:", type(exercise_batch).__name__)
print("All five exercise checks passed.")
