Skip to content

Python API

tinymapper is a command line first: tinymapper and tinymapper-report. These modules are what scripts use: a run's specification and its runner, and the report of a run, written or read back.

from tinymapper.models import JobSpec
from tinymapper.runner import TinyMapperRunner
from tinymapper.report import read_report

spec = JobSpec(
    mode="ChIP", sample="reads/JS001", genome="genomes/R64-1-1/R64-1-1", output="results"
)
TinyMapperRunner(spec).run()  # 0 when the run went to its end
sections, tables = read_report("results/JS001.report.txt")
sections["reads"]["kept_pct"]  # '50.74': values are text

tinymapper.models

Typed job specification for tinyMapper.

All parameters map 1-to-1 to tinyMapper.sh CLI flags.

TinyMapperMode

Bases: str, Enum

Supported mapping modes (matches tinyMapper.sh case-sensitive values).

Source code in src/tinymapper/models.py
class TinyMapperMode(str, Enum):
    """Supported mapping modes (matches tinyMapper.sh case-sensitive values)."""

    chip = "ChIP"
    rna = "RNA"
    atac = "ATAC"
    mnase = "MNase"
    hic = "HiC"
    shotgun = "shotgun"

JobSpec

Bases: BaseModel

Complete specification for a single tinyMapper run.

All field names and defaults mirror tinyMapper.sh variables.

Source code in src/tinymapper/models.py
class JobSpec(BaseModel):
    """Complete specification for a single tinyMapper run.

    All field names and defaults mirror tinyMapper.sh variables.
    """

    model_config = {"populate_by_name": True}

    # ---- Required ----
    mode: TinyMapperMode
    sample: str
    genome: str

    # ---- Core optional ----
    output: Path = Path("results")
    input: str = ""  # --input / -i
    calibration: str = ""  # --calibration / -c  (spikein genome prefix)
    threads: int = 8

    # ---- Alignment / filtering ----
    alignment: str = ""
    filter_opts: str = "-f 0x001 -f 0x002 -F 0x004 -F 0x008 -q 10"
    blacklist: str = ""
    gsize: str = "13000000"
    keep_duplicates: bool = False  # --duplicates flag
    keep_intermediate: bool = False  # --keepIntermediate flag

    # ---- HiC-specific ----
    # hicstuff's 5spm mapping (bwa mem -5SPM), the default since 0.15.0:
    # hicstuff 4.1.0 added it, and builds bwa's index when a genome has none.
    hicstuff_opts: str = "--mapping 5spm --duplicates --filter --plot --no-cleanup"
    restriction: str = "HpaII,HinfI"
    binning: str = "500"
    # cooler balance's arguments, as hicstuff's --balancing-args: none by
    # default, cooler balance's defaults (unused before 0.15.0).
    balance_opts: str = ""

    # ---- MNase-specific ----
    mnase_sizes: str = "130,200"

    # ---- Track generation ----
    extend_reads_len: int | None = None  # --extendReads value for single-end bamCoverage/bamCompare

    # ---- Shotgun-specific ----
    as_single_end: bool = False  # --as-single-end: cat R1+R2 and map as SE (legacy shotgun)

    # ---- Runtime (not CLI flags) ----
    hash: str = ""  # populated in model_post_init
    dry_run: bool = False

    def model_post_init(self, __context: object) -> None:
        if not self.hash:
            object.__setattr__(self, "hash", _generate_hash())

    # ------------------------------------------------------------------ #
    #  Validators                                                          #
    # ------------------------------------------------------------------ #

    @field_validator("mode", mode="before")
    @classmethod
    def normalise_mode(cls, v: str) -> str:
        """Accept case-insensitive mode names (chip → ChIP, hic → HiC, etc.)."""
        return _MODE_ALIASES.get(str(v).lower(), v)

    @model_validator(mode="after")
    def _check_calibration_requires_input(self) -> JobSpec:
        if self.calibration and not self.input:
            raise ValueError("--calibration requires --input to also be provided")
        return self

    # ------------------------------------------------------------------ #
    #  Derived properties                                                  #
    # ------------------------------------------------------------------ #

    @property
    def sample_base(self) -> str:
        return Path(self.sample).name

    @property
    def input_base(self) -> str:
        return Path(self.input).name if self.input else ""

    @property
    def genome_base(self) -> str:
        return Path(self.genome).name

    @property
    def spikein_base(self) -> str:
        return Path(self.calibration).name if self.calibration else ""

    @property
    def do_input(self) -> bool:
        return bool(self.input)

    @property
    def do_calibration(self) -> bool:
        return bool(self.calibration)

    @property
    def do_peaks(self) -> bool:
        return self.mode in (TinyMapperMode.chip, TinyMapperMode.atac)

    @property
    def remove_duplicates_flag(self) -> str:
        """samtools markdup -r flag (empty string when keeping dups)."""
        return "" if self.keep_duplicates else "-r"

    @property
    def exclude_duplicates_flag(self) -> str:
        """deepTools option skipping reads flagged as duplicates (empty when keeping dups).

        Replaces ``--ignoreDuplicates``, which deepTools 4.0 removed.  Every BAM
        reaching a track step has been through ``samtools markdup`` first:
        paired-end BAMs have their duplicates removed (so this is a no-op),
        single-end and RNA BAMs have them flagged (0x400) and this skips them.
        """
        return "" if self.keep_duplicates else "--samFlagExclude 1024"

    @property
    def blacklist_options(self) -> str:
        """bamCoverage --blackListFileName option."""
        return f"--blackListFileName {self.blacklist}" if self.blacklist else ""

    @property
    def samtools_thread_opts(self) -> str:
        return f"-@ {self.threads} --output-fmt bam"

    @property
    def mnase_min_size(self) -> str:
        return self.mnase_sizes.split(",")[0]

    @property
    def mnase_max_size(self) -> str:
        return self.mnase_sizes.split(",")[1]

    @property
    def hic_base_rez(self) -> str:
        """Lowest resolution bin for HiC (first value in comma-separated list)."""
        return self.binning.split(",")[0]

    # ------------------------------------------------------------------ #
    #  Round-trip serialisation                                            #
    # ------------------------------------------------------------------ #

    def to_cli_args(self) -> list[str]:
        """Return the equivalent tinyMapper.sh long-form argument list."""
        args: list[str] = [
            "--mode",
            self.mode.value,
            "--sample",
            self.sample,
            "--genome",
            self.genome,
            "--output",
            str(self.output),
            "--threads",
            str(self.threads),
        ]
        if self.input:
            args += ["--input", self.input]
        if self.calibration:
            args += ["--calibration", self.calibration]
        if self.alignment:
            args += ["--alignment", self.alignment]
        if self.filter_opts != "-f 0x001 -f 0x002 -F 0x004 -F 0x008 -q 10":
            args += ["--filter", self.filter_opts]
        if self.blacklist:
            args += ["--blacklist", self.blacklist]
        if self.gsize != "13000000":
            args += ["--gsize", self.gsize]
        if self.keep_duplicates:
            args.append("--duplicates")
        if self.keep_intermediate:
            args.append("--keepIntermediate")
        if self.mode == TinyMapperMode.hic:
            args += ["--hicstuff", self.hicstuff_opts]
            args += ["--restriction", self.restriction]
            args += ["--binning", self.binning]
            if self.balance_opts:
                args += ["--balance", self.balance_opts]
        if self.mode == TinyMapperMode.mnase:
            args += ["--MNaseSizes", self.mnase_sizes]
        if self.extend_reads_len is not None:
            args += ["--extend-reads", str(self.extend_reads_len)]
        if self.as_single_end:
            args.append("--as-single-end")
        return args

remove_duplicates_flag property

remove_duplicates_flag: str

samtools markdup -r flag (empty string when keeping dups).

exclude_duplicates_flag property

exclude_duplicates_flag: str

deepTools option skipping reads flagged as duplicates (empty when keeping dups).

Replaces --ignoreDuplicates, which deepTools 4.0 removed. Every BAM reaching a track step has been through samtools markdup first: paired-end BAMs have their duplicates removed (so this is a no-op), single-end and RNA BAMs have them flagged (0x400) and this skips them.

blacklist_options property

blacklist_options: str

bamCoverage --blackListFileName option.

hic_base_rez property

hic_base_rez: str

Lowest resolution bin for HiC (first value in comma-separated list).

normalise_mode classmethod

normalise_mode(v: str) -> str

Accept case-insensitive mode names (chip → ChIP, hic → HiC, etc.).

Source code in src/tinymapper/models.py
@field_validator("mode", mode="before")
@classmethod
def normalise_mode(cls, v: str) -> str:
    """Accept case-insensitive mode names (chip → ChIP, hic → HiC, etc.)."""
    return _MODE_ALIASES.get(str(v).lower(), v)

to_cli_args

to_cli_args() -> list[str]

Return the equivalent tinyMapper.sh long-form argument list.

Source code in src/tinymapper/models.py
def to_cli_args(self) -> list[str]:
    """Return the equivalent tinyMapper.sh long-form argument list."""
    args: list[str] = [
        "--mode",
        self.mode.value,
        "--sample",
        self.sample,
        "--genome",
        self.genome,
        "--output",
        str(self.output),
        "--threads",
        str(self.threads),
    ]
    if self.input:
        args += ["--input", self.input]
    if self.calibration:
        args += ["--calibration", self.calibration]
    if self.alignment:
        args += ["--alignment", self.alignment]
    if self.filter_opts != "-f 0x001 -f 0x002 -F 0x004 -F 0x008 -q 10":
        args += ["--filter", self.filter_opts]
    if self.blacklist:
        args += ["--blacklist", self.blacklist]
    if self.gsize != "13000000":
        args += ["--gsize", self.gsize]
    if self.keep_duplicates:
        args.append("--duplicates")
    if self.keep_intermediate:
        args.append("--keepIntermediate")
    if self.mode == TinyMapperMode.hic:
        args += ["--hicstuff", self.hicstuff_opts]
        args += ["--restriction", self.restriction]
        args += ["--binning", self.binning]
        if self.balance_opts:
            args += ["--balance", self.balance_opts]
    if self.mode == TinyMapperMode.mnase:
        args += ["--MNaseSizes", self.mnase_sizes]
    if self.extend_reads_len is not None:
        args += ["--extend-reads", str(self.extend_reads_len)]
    if self.as_single_end:
        args.append("--as-single-end")
    return args

tinymapper.runner

TinyMapperRunner — validates inputs and dispatches to mode modules.

TinyMapperRunner

Orchestrates validation, directory setup and mode dispatch.

Parameters:

Name Type Description Default
spec JobSpec

The run.

required
command str

The command line that started it, which the log's header writes; by default, the one spec gives.

None
Source code in src/tinymapper/runner.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
class TinyMapperRunner:
    """Orchestrates validation, directory setup and mode dispatch.

    Parameters
    ----------
    spec : JobSpec
        The run.
    command : str
        The command line that started it, which the log's header writes; by
        default, the one ``spec`` gives.
    """

    def __init__(self, spec: JobSpec, command: str | None = None) -> None:
        self.spec = spec
        self.command = command or shlex.join(["tinymapper", *spec.to_cli_args()])
        self.paths = RunPaths(
            outdir=spec.output,
            sample_base=spec.sample_base,
            genome=spec.genome_base,
            hash_=spec.hash,
            input_base=spec.input_base,
            spikein=spec.spikein_base,
            mnase_min=spec.mnase_min_size,
            mnase_max=spec.mnase_max_size,
            mode=spec.mode.value,
            hic_base_rez=spec.hic_base_rez,
        )

    # ------------------------------------------------------------------ #
    #  Public interface                                                    #
    # ------------------------------------------------------------------ #

    def run(self) -> int:
        """Execute the full pipeline.  Returns 0 on success, 1 on failure."""
        spec = self.spec
        paths = self.paths

        self._setup_dirs()
        while paths.logfile.exists():
            # The log is named after the second the run started: another run of
            # the sample started in this one, so this run starts in the next.
            time.sleep(1 - datetime.now().microsecond / 1e6)
            paths.started = datetime.now()
        _logging.write_header(
            paths.logfile,
            version=VERSION,
            started=paths.started,
            cmd=self.command,
            parameters=header_parameters(spec),
        )
        paths.errfile.touch()
        paths.tmpfile.touch()

        from tinymapper._shell import configure_err_file

        configure_err_file(paths.errfile)
        handler = _logging.attach(paths.logfile)
        clock = time.monotonic()

        try:
            self._validate_tools()
            self._validate_genome_index()
            if spec.do_calibration:
                self._validate_genome_index(is_spikein=True)

            sample_r1, sample_r2 = self._resolve_fastq(spec.sample, "sample")
            input_r1: Path | None = None
            input_r2: Path | None = None
            if spec.do_input:
                input_r1, input_r2 = self._resolve_fastq(spec.input, "input")

            paired = sample_r2 is not None
            if not paired:
                if spec.mode == TinyMapperMode.hic:
                    raise RuntimeError(
                        "HiC mode requires paired-end reads (R2 not found for sample prefix)."
                    )
                if spec.do_calibration:
                    raise RuntimeError(
                        "Spikein calibration requires paired-end reads "
                        "(R2 not found for sample prefix)."
                    )
                if spec.mode != TinyMapperMode.rna and spec.extend_reads_len is None:
                    raise RuntimeError(
                        "Single-end reads detected but --extend-reads was not set.  "
                        "Provide a fragment length (e.g. --extend-reads 200) so that "
                        "bamCoverage can extend single-end reads to the correct size."
                    )
                logger.warning(
                    "Single-end reads detected. "
                    "Fragment-size filtering (MNase) and spikein calibration "
                    "are not available in SE mode."
                )
            elif (
                spec.as_single_end
                and spec.mode == TinyMapperMode.shotgun
                and spec.extend_reads_len is None
            ):
                raise RuntimeError(
                    "--as-single-end requires --extend-reads to be set.  "
                    "Provide a fragment length (e.g. --extend-reads 200) so that "
                    "bamCoverage can extend single-end reads to the correct size."
                )

            self._log_startup(sample_r1, sample_r2)

            from tinymapper.modes import atac, chip, hic, mnase, rna, shotgun

            _MODE_MAP = {
                TinyMapperMode.chip: chip.run,
                TinyMapperMode.rna: rna.run,
                TinyMapperMode.atac: atac.run,
                TinyMapperMode.mnase: mnase.run,
                TinyMapperMode.hic: hic.run,
                TinyMapperMode.shotgun: shotgun.run,
            }
            _MODE_MAP[spec.mode](
                spec=spec,
                paths=paths,
                sample_r1=sample_r1,
                sample_r2=sample_r2,
                input_r1=input_r1,
                input_r2=input_r2,
                log_file=paths.logfile,
            )

            from tinymapper._stats import write_statistics

            write_statistics(spec, paths, paths.logfile)
            self._cleanup_intermediates()
            self._write_report(time.monotonic() - clock)
            written = "nothing written (dry run)" if spec.dry_run else _WRITTEN[spec.mode]
            logger.info(
                "Pipeline completed successfully: %s after %s",
                written,
                _logging.duration(time.monotonic() - clock),
            )
            return 0

        except Exception as exc:
            logger.error("Pipeline failed: %s", exc)
            self._cleanup_on_failure()
            return 1
        finally:
            _logging.detach(handler)
            paths.tmpfile.unlink(missing_ok=True)
            self._remove_empty_dirs()

    def _write_report(self, seconds: float) -> None:
        """Write the run's report (CONVENTIONS.md § 12). A report that cannot be
        written leaves the run's outputs as they are: it is a warning."""
        if self.spec.dry_run:
            logger.info("Dry run: no report")
            return
        from tinymapper.report import write_report

        try:
            write_report(
                self.spec.output,
                log=self.paths.logfile,
                force=True,
                duration_s=round(seconds),
            )
        except Exception as exc:  # the outputs stand without it
            logger.warning("The report could not be written: %s", exc)

    # ------------------------------------------------------------------ #
    #  Directory setup                                                     #
    # ------------------------------------------------------------------ #

    def _setup_dirs(self) -> None:
        spec = self.spec
        outdir = spec.output
        subdirs = [
            "fastq/genome",
            "fastq/spikein",
            "bam/genome",
            "bam/spikein",
            "tracks",
            "peaks",
            "matrices",
            "pairs",
            "plots",
            "stats",
            "logs",
        ]
        for d in subdirs:
            (outdir / d).mkdir(parents=True, exist_ok=True)

        for name in [spec.sample_base, spec.input_base]:
            if not name:
                continue
            for d in [
                f"fastq/genome/{name}",
                f"fastq/spikein/{name}",
                f"bam/genome/{name}",
                f"bam/spikein/{name}",
                f"tracks/{name}",
                f"peaks/{name}",
                f"matrices/{name}",
                f"pairs/{name}",
                f"plots/{name}",
            ]:
                (outdir / d).mkdir(parents=True, exist_ok=True)

    # ------------------------------------------------------------------ #
    #  Validation                                                          #
    # ------------------------------------------------------------------ #

    def _validate_tools(self) -> None:
        spec = self.spec
        if spec.mode == TinyMapperMode.rna:
            required = ["STAR", "samtools", "bamCoverage"]
        elif spec.mode == TinyMapperMode.hic:
            required = ["hicstuff", "samtools", "bedtools", "bedGraphToBigWig"]
        elif spec.mode == TinyMapperMode.shotgun:
            required = ["bwa-mem2", "samtools", "bamCoverage"]
        else:
            required = ["bwa-mem2", "samtools", "bamCoverage"]

        for tool in required:
            if not shutil.which(tool):
                raise RuntimeError(
                    f"{tool} not found in PATH. "
                    f"Install it via: micromamba install -c bioconda {tool}"
                )
        if spec.do_peaks and not shutil.which("macs3"):
            raise RuntimeError(
                "macs3 not found in PATH. Install it via: micromamba install -c bioconda macs3"
            )
        if spec.mode == TinyMapperMode.hic:
            from tinymapper.modes.hic import check_hicstuff

            check_hicstuff(spec)

    def _validate_genome_index(self, is_spikein: bool = False) -> None:
        spec = self.spec
        genome_prefix = spec.calibration if is_spikein else spec.genome
        genome_base = Path(genome_prefix)
        genome_fa = Path(str(genome_base) + ".fa")
        label = "spikein" if is_spikein else "reference"

        if not genome_fa.exists():
            raise FileNotFoundError(f"{label.capitalize()} genome FASTA not found: {genome_fa}")

        if spec.mode == TinyMapperMode.rna and not is_spikein:
            star_dir = Path(str(genome_base) + "/STAR/")
            if not star_dir.is_dir():
                raise RuntimeError(
                    f"STAR genome index directory not found: {star_dir}\n"
                    f"Build it with: STAR --runMode genomeGenerate "
                    f"--genomeFastaFiles {genome_fa} --genomeDir {star_dir}"
                )
        elif spec.mode == TinyMapperMode.hic:
            from tinymapper.modes.hic import BOWTIE2_INDEX, hicstuff_aligner

            # hicstuff aligns with bowtie2 unless its options say otherwise
            # (mapping mode 5spm aligns with bwa, and builds bwa's index if
            # the genome has none).
            if hicstuff_aligner(spec.hicstuff_opts) == "bowtie2":
                for ext in BOWTIE2_INDEX:
                    idx = Path(str(genome_base) + ext)
                    if not idx.exists():
                        raise RuntimeError(
                            f"bowtie2 {label} index file missing: {idx}\n"
                            f"Build it with: bowtie2-build {genome_fa} {genome_base}"
                        )
        else:
            # bwa-mem2 index files are named after the FASTA file.
            for ext in [".0123", ".bwt.2bit.64", ".amb", ".ann", ".pac"]:
                idx = Path(str(genome_fa) + ext)
                if not idx.exists():
                    raise RuntimeError(
                        f"bwa-mem2 {label} index file missing: {idx}\n"
                        f"Build it with: bwa-mem2 index {genome_fa}"
                    )

        # Generate chrom.sizes if missing (non-fatal)
        sizes = Path(str(genome_base) + ".chrom.sizes")
        if not sizes.exists():
            logger.warning("%s chrom.sizes not found; generating from FASTA index", label)
            fai = Path(str(genome_fa) + ".fai")
            subprocess.run(
                f"samtools faidx {genome_fa} && cut -f1-2 {fai} > {sizes}",
                shell=True,
                check=True,
            )

    @staticmethod
    def _resolve_fastq(sample_prefix: str, label: str) -> tuple[Path, Path | None]:
        """Return (R1, R2) paths by trying known FASTQ naming patterns.

        Tries paired-end patterns first.  Falls back to single-end patterns
        (R2 = None) if no paired files are found.
        """
        prefix = Path(sample_prefix)
        for r1_suf, r2_suf in _FASTQ_PATTERNS:
            r1 = prefix.parent / f"{prefix.name}{r1_suf}"
            r2 = prefix.parent / f"{prefix.name}{r2_suf}"
            if r1.exists() and r2.exists():
                if (r1_suf, r2_suf) != _FASTQ_PATTERNS[0]:
                    logger.warning("Found %s FASTQ files: %s & %s", label, r1, r2)
                return r1, r2

        # Try Illumina S## naming pattern
        r1_candidates = [
            f
            for f in glob.glob(str(prefix.parent / f"{prefix.name}*_R1*.gz"))
            if re.search(r"_S\d{1,2}_R1", f)
        ]
        r2_candidates = [
            f
            for f in glob.glob(str(prefix.parent / f"{prefix.name}*_R2*.gz"))
            if re.search(r"_S\d{1,2}_R2", f)
        ]
        if len(r1_candidates) == 1 and len(r2_candidates) == 1:
            logger.warning(
                "Found %s FASTQ files via S## pattern: %s & %s",
                label,
                r1_candidates[0],
                r2_candidates[0],
            )
            return Path(r1_candidates[0]), Path(r2_candidates[0])

        # Fall back to single-end patterns
        for suffix in _SINGLE_FASTQ_PATTERNS:
            r1 = prefix.parent / f"{prefix.name}{suffix}"
            if r1.exists():
                logger.warning(
                    "Found single-end %s FASTQ file: %s (no paired R2 found)",
                    label,
                    r1,
                )
                return r1, None

        raise FileNotFoundError(
            f"{label.capitalize()} FASTQ files not found for prefix: {sample_prefix}\n"
            f"Files must be named e.g. {prefix.name}_R1.fq.gz & {prefix.name}_R2.fq.gz "
            f"(paired-end) or {prefix.name}_R1.fq.gz (single-end)"
        )

    # ------------------------------------------------------------------ #
    #  Logging                                                             #
    # ------------------------------------------------------------------ #

    def _log_startup(self, sample_r1: Path, sample_r2: Path | None) -> None:
        """The run's first records: its log's header has its parameters."""
        spec = self.spec
        logger.info(
            "tinymapper v%s: %s run %s of %s", VERSION, spec.mode.value, spec.hash, spec.sample
        )
        if sample_r2 is None or (spec.as_single_end and spec.mode == TinyMapperMode.shotgun):
            logger.info("Reads: %s (single-end)", sample_r1)
        else:
            logger.info("Reads: %s and %s", sample_r1, sample_r2)
        logger.info(
            "Log file: %s; errors of the programs: %s", self.paths.logfile, self.paths.errfile
        )

    # ------------------------------------------------------------------ #
    #  Cleanup                                                             #
    # ------------------------------------------------------------------ #

    def _cleanup_intermediates(self) -> None:
        """Remove intermediate SAM/unmapped files when keep_intermediate is False."""
        if self.spec.keep_intermediate:
            return
        p = self.paths
        for path in [
            p.sample_aligned_genome,
            p.sample_aligned_calibration,
            p.sample_non_aligned_calibration,
            p.sample_non_aligned_genome_aligned_calibration,
            p.sample_non_aligned_calibration_aligned_genome,
            p.input_aligned_genome,
            p.input_aligned_calibration,
            p.input_non_aligned_calibration,
            p.input_non_aligned_genome_aligned_calibration,
            p.input_non_aligned_calibration_aligned_genome,
        ]:
            if path.exists():
                path.unlink(missing_ok=True)

        # Unmapped FASTQ gz pairs
        for prefix in [
            p.sample_non_aligned_genome,
            p.sample_non_aligned_calibration,
            p.input_non_aligned_genome,
            p.input_non_aligned_calibration,
        ]:
            for gz in [Path(f"{prefix}.1.gz"), Path(f"{prefix}.2.gz")]:
                gz.unlink(missing_ok=True)

    def _cleanup_on_failure(self) -> None:
        """Remove any files matching this run's hash on failure (skipped with -k)."""
        if self.spec.mode == TinyMapperMode.hic:
            from tinymapper.modes.hic import remove_hicstuff_tmp

            remove_hicstuff_tmp(self.spec, self.paths)
        if self.spec.keep_intermediate:
            return
        for path in self.spec.output.rglob(f"*{self.spec.hash}*"):
            if path.suffix not in (".log", ".err") and path.is_file():
                path.unlink(missing_ok=True)

    def _remove_empty_dirs(self) -> None:
        for d in sorted(self.spec.output.rglob("*"), reverse=True):
            if d.is_dir():
                with contextlib.suppress(OSError):
                    d.rmdir()

run

run() -> int

Execute the full pipeline. Returns 0 on success, 1 on failure.

Source code in src/tinymapper/runner.py
def run(self) -> int:
    """Execute the full pipeline.  Returns 0 on success, 1 on failure."""
    spec = self.spec
    paths = self.paths

    self._setup_dirs()
    while paths.logfile.exists():
        # The log is named after the second the run started: another run of
        # the sample started in this one, so this run starts in the next.
        time.sleep(1 - datetime.now().microsecond / 1e6)
        paths.started = datetime.now()
    _logging.write_header(
        paths.logfile,
        version=VERSION,
        started=paths.started,
        cmd=self.command,
        parameters=header_parameters(spec),
    )
    paths.errfile.touch()
    paths.tmpfile.touch()

    from tinymapper._shell import configure_err_file

    configure_err_file(paths.errfile)
    handler = _logging.attach(paths.logfile)
    clock = time.monotonic()

    try:
        self._validate_tools()
        self._validate_genome_index()
        if spec.do_calibration:
            self._validate_genome_index(is_spikein=True)

        sample_r1, sample_r2 = self._resolve_fastq(spec.sample, "sample")
        input_r1: Path | None = None
        input_r2: Path | None = None
        if spec.do_input:
            input_r1, input_r2 = self._resolve_fastq(spec.input, "input")

        paired = sample_r2 is not None
        if not paired:
            if spec.mode == TinyMapperMode.hic:
                raise RuntimeError(
                    "HiC mode requires paired-end reads (R2 not found for sample prefix)."
                )
            if spec.do_calibration:
                raise RuntimeError(
                    "Spikein calibration requires paired-end reads "
                    "(R2 not found for sample prefix)."
                )
            if spec.mode != TinyMapperMode.rna and spec.extend_reads_len is None:
                raise RuntimeError(
                    "Single-end reads detected but --extend-reads was not set.  "
                    "Provide a fragment length (e.g. --extend-reads 200) so that "
                    "bamCoverage can extend single-end reads to the correct size."
                )
            logger.warning(
                "Single-end reads detected. "
                "Fragment-size filtering (MNase) and spikein calibration "
                "are not available in SE mode."
            )
        elif (
            spec.as_single_end
            and spec.mode == TinyMapperMode.shotgun
            and spec.extend_reads_len is None
        ):
            raise RuntimeError(
                "--as-single-end requires --extend-reads to be set.  "
                "Provide a fragment length (e.g. --extend-reads 200) so that "
                "bamCoverage can extend single-end reads to the correct size."
            )

        self._log_startup(sample_r1, sample_r2)

        from tinymapper.modes import atac, chip, hic, mnase, rna, shotgun

        _MODE_MAP = {
            TinyMapperMode.chip: chip.run,
            TinyMapperMode.rna: rna.run,
            TinyMapperMode.atac: atac.run,
            TinyMapperMode.mnase: mnase.run,
            TinyMapperMode.hic: hic.run,
            TinyMapperMode.shotgun: shotgun.run,
        }
        _MODE_MAP[spec.mode](
            spec=spec,
            paths=paths,
            sample_r1=sample_r1,
            sample_r2=sample_r2,
            input_r1=input_r1,
            input_r2=input_r2,
            log_file=paths.logfile,
        )

        from tinymapper._stats import write_statistics

        write_statistics(spec, paths, paths.logfile)
        self._cleanup_intermediates()
        self._write_report(time.monotonic() - clock)
        written = "nothing written (dry run)" if spec.dry_run else _WRITTEN[spec.mode]
        logger.info(
            "Pipeline completed successfully: %s after %s",
            written,
            _logging.duration(time.monotonic() - clock),
        )
        return 0

    except Exception as exc:
        logger.error("Pipeline failed: %s", exc)
        self._cleanup_on_failure()
        return 1
    finally:
        _logging.detach(handler)
        paths.tmpfile.unlink(missing_ok=True)
        self._remove_empty_dirs()

header_parameters

header_parameters(spec: JobSpec) -> dict[str, object]

The run's parameters, as its log's header writes them: the run's hash, then each option of the command line, by its long name, as given or by default.

Source code in src/tinymapper/runner.py
def header_parameters(spec: JobSpec) -> dict[str, object]:
    """The run's parameters, as its log's header writes them: the run's hash,
    then each option of the command line, by its long name, as given or by
    default."""
    return {
        "hash": spec.hash,
        "mode": spec.mode.value,
        "sample": spec.sample,
        "genome": spec.genome,
        "output": spec.output,
        "input": spec.input,
        "calibration": spec.calibration,
        "threads": spec.threads,
        "alignment": spec.alignment,
        "filter": spec.filter_opts,
        "blacklist": spec.blacklist,
        "gsize": spec.gsize,
        "duplicates": spec.keep_duplicates,
        "extend-reads": spec.extend_reads_len,
        "hicstuff": spec.hicstuff_opts,
        "restriction": spec.restriction,
        "binning": spec.binning,
        "balance": spec.balance_opts,
        "MNaseSizes": spec.mnase_sizes,
        "as-single-end": spec.as_single_end,
        "keepIntermediate": spec.keep_intermediate,
        "dry-run": spec.dry_run,
    }

tinymapper.report

The report of a run: its numbers, its MultiQC row and its page.

The report of one run of tinymapper, for one sample (CONVENTIONS.md § 12), in the run's output directory, named after the sample:

  • <sample>.report.txt: every number of the report, for scripts, which :func:read_report reads back;
  • <sample>.report_mqc.yaml: the run's row of MultiQC's General Statistics table;
  • <sample>.report.html: a page to read the run with.

:func:collect gathers it from what the run left in its output directory, and never runs a program: its log's header (the run's parameters), the statistics it keeps in stats/<sample>/ (samtools flagstat, stats and markdup, STAR's log, tinymapper's counts), its peaks and its spike-in counts. A Hi-C run takes its numbers from hicstuff's report, which tinymapper writes under the sample's name in matrices/<sample>/, and links to it. chromokit's report kit (tinymapper._report) writes the files. A run writes its report at its end, and tinymapper-report writes it again from the run's directory.

The report's format is :data:FORMAT_VERSION: a key, a column, a unit or a MultiQC column that changes or goes raises it; one that comes does not. docs/formats.md documents every key.

Run dataclass

A run, as its log describes it.

Attributes:

Name Type Description
outdir Path

The run's output directory.

log Path

Its log, logs/<sample>.tinymapper_<date>.log.

header dict

The log's header: the version, the date, the command line and each parameter, as text.

spec JobSpec

The run's parameters, its output directory being outdir.

duration_s int or None

How long it took, from its log's last line.

Source code in src/tinymapper/report.py
@dataclass(frozen=True)
class Run:
    """A run, as its log describes it.

    Attributes
    ----------
    outdir : Path
        The run's output directory.
    log : Path
        Its log, ``logs/<sample>.tinymapper_<date>.log``.
    header : dict
        The log's header: the version, the date, the command line and each
        parameter, as text.
    spec : JobSpec
        The run's parameters, its output directory being outdir.
    duration_s : int or None
        How long it took, from its log's last line.
    """

    outdir: Path
    log: Path
    header: dict[str, str]
    spec: JobSpec
    duration_s: int | None = None

    @property
    def sample(self) -> str:
        """The sample's name: the base name of its reads' prefix."""
        return self.spec.sample_base

    @property
    def paths(self) -> RunPaths:
        """The run's files."""
        spec = self.spec
        return RunPaths(
            outdir=self.outdir,
            sample_base=spec.sample_base,
            genome=spec.genome_base,
            hash_=spec.hash,
            input_base=spec.input_base,
            spikein=spec.spikein_base,
            mnase_min=spec.mnase_min_size,
            mnase_max=spec.mnase_max_size,
            mode=spec.mode.value,
            hic_base_rez=spec.hic_base_rez,
        )

sample property

sample: str

The sample's name: the base name of its reads' prefix.

paths property

paths: RunPaths

The run's files.

Collected dataclass

The report of a run, and what its page takes besides.

Attributes:

Name Type Description
report Report

The report: its sections.

figures dict

The page's plots, by the id of their place in it.

inputs dict

What the page's header names: the reads, the genome, the input and the spike-in genome.

links dict

The run's outputs that the page links to: links["files"], and for a Hi-C run links["hicstuff"], hicstuff's page.

Source code in src/tinymapper/report.py
@dataclass
class Collected:
    """The report of a run, and what its page takes besides.

    Attributes
    ----------
    report : tinymapper._report.Report
        The report: its sections.
    figures : dict
        The page's plots, by the id of their place in it.
    inputs : dict
        What the page's header names: the reads, the genome, the input and
        the spike-in genome.
    links : dict
        The run's outputs that the page links to: links["files"], and for a
        Hi-C run links["hicstuff"], hicstuff's page.
    """

    report: object
    figures: dict = field(default_factory=dict)
    inputs: dict = field(default_factory=dict)
    links: dict = field(default_factory=dict)

tool

tool()

tinymapper, as its reports name it: its version, the report's format, its MultiQC columns and its page's template.

Source code in src/tinymapper/report.py
def tool():
    """tinymapper, as its reports name it: its version, the report's format, its
    MultiQC columns and its page's template."""
    from tinymapper._report import Tool

    return Tool(
        name="tinymapper",
        version=__version__,
        format_version=FORMAT_VERSION,
        columns=MQC_COLUMNS,
        description="tinymapper runs: the reads, the shares mapped, kept and duplicated, "
        "the peaks and the share of the reads in them",
        docs=DOCS,
        template=TEMPLATE,
    )

read_report

read_report(path)

Read a report.txt back: its sections, by name, each its keys and their values as text, and its tables, as pandas.DataFrame of text; None where a value is NA. Needs pandas.

Source code in src/tinymapper/report.py
def read_report(path):
    """Read a report.txt back: its sections, by name, each its keys and their
    values as text, and its tables, as pandas.DataFrame of text; None where a
    value is NA. Needs pandas."""
    from tinymapper._report import read_txt

    return read_txt(path)

report_paths

report_paths(outdir: Path, sample: str) -> list[Path]

The files of the report of sample in outdir: its report.txt, its page and its report_mqc.yaml, in that order.

Source code in src/tinymapper/report.py
def report_paths(outdir: Path, sample: str) -> list[Path]:
    """The files of the report of sample in outdir: its report.txt, its page
    and its report_mqc.yaml, in that order."""
    from tinymapper._report import report_files

    return [Path(outdir) / name for name in report_files(sample)]

spec_from_header

spec_from_header(header: dict[str, str], outdir: Path) -> JobSpec

The run's parameters, from its log's header, its output directory being outdir (the header's may be relative to where the run started).

Source code in src/tinymapper/report.py
def spec_from_header(header: dict[str, str], outdir: Path) -> JobSpec:
    """The run's parameters, from its log's header, its output directory being
    outdir (the header's may be relative to where the run started)."""
    for key in ("mode", "sample", "genome", "hash"):
        if not header.get(key):
            raise ValueError(f"The log's header has no {key}: is it a tinymapper log?")

    def flag(key: str) -> bool:
        return header.get(key, "").lower() == "true"

    fields: dict[str, object] = {
        "mode": header["mode"],
        "sample": header["sample"],
        "genome": header["genome"],
        "output": outdir,
        "hash": header["hash"],
        "keep_duplicates": flag("duplicates"),
        "as_single_end": flag("as-single-end"),
        "keep_intermediate": flag("keepIntermediate"),
    }
    texts = {
        "input": "input",
        "calibration": "calibration",
        "alignment": "alignment",
        "filter": "filter_opts",
        "blacklist": "blacklist",
        "gsize": "gsize",
        "hicstuff": "hicstuff_opts",
        "restriction": "restriction",
        "binning": "binning",
        "balance": "balance_opts",
        "MNaseSizes": "mnase_sizes",
    }
    for key, name in texts.items():
        if key in header:
            fields[name] = header[key]
    if header.get("threads"):
        fields["threads"] = int(header["threads"])
    if header.get("extend-reads"):
        fields["extend_reads_len"] = int(header["extend-reads"])
    return JobSpec.model_validate(fields)

read_run

read_run(outdir: Path, log: Path) -> Run

The run of log, whose outputs are in outdir.

Raises:

Type Description
ValueError

If log is not a tinymapper log, or the log of a dry run.

Source code in src/tinymapper/report.py
def read_run(outdir: Path, log: Path) -> Run:
    """The run of log, whose outputs are in outdir.

    Raises
    ------
    ValueError
        If log is not a tinymapper log, or the log of a dry run.
    """
    header = read_header(log)
    if header.get("dry-run", "").lower() == "true":
        raise ValueError(f"{log} is the log of a dry run, which has no report.")
    outdir = Path(outdir).absolute()
    spec = spec_from_header(header, outdir)
    match = _COMPLETED.search(_last_line(log))
    duration = to_seconds(match[1]) if match else None
    return Run(
        outdir=outdir, log=Path(log).absolute(), header=header, spec=spec, duration_s=duration
    )

find_runs

find_runs(outdir: Path, *, sample: str | None = None, log: Path | None = None) -> list[Run]

The runs whose report is written: the run of log; or else the newest run of each sample (of sample alone, if given) that went to its end, by the date in its log's name.

Parameters:

Name Type Description Default
outdir Path

The runs' output directory, whose logs/ holds their logs.

required
sample str

A sample's name, or the path prefix given to tinymapper --sample.

None
log Path

A run's log.

None

Raises:

Type Description
FileNotFoundError

If outdir holds no log of a run that went to its end (of sample).

ValueError

If log is not the newest run of its sample in outdir that went to its end: stats/<sample>/ holds that run's statistics.

Source code in src/tinymapper/report.py
def find_runs(outdir: Path, *, sample: str | None = None, log: Path | None = None) -> list[Run]:
    """The runs whose report is written: the run of log; or else the newest
    run of each sample (of sample alone, if given) that went to its end, by
    the date in its log's name.

    Parameters
    ----------
    outdir : Path
        The runs' output directory, whose ``logs/`` holds their logs.
    sample : str
        A sample's name, or the path prefix given to ``tinymapper --sample``.
    log : Path
        A run's log.

    Raises
    ------
    FileNotFoundError
        If outdir holds no log of a run that went to its end (of sample).
    ValueError
        If log is not the newest run of its sample in outdir that went to
        its end: ``stats/<sample>/`` holds that run's statistics.
    """
    outdir = Path(outdir).absolute()
    logs = outdir / "logs"
    if log is not None:
        run = read_run(outdir, Path(log))
        _refuse_older(run, _newest_runs(logs, run.sample).get(run.sample))
        return [run]
    wanted = Path(sample).name if sample else None
    newest = _newest_runs(logs, wanted)
    if not newest:
        of = f" of {wanted}" if wanted else ""
        raise FileNotFoundError(
            f"No log{of} of a run that went to its end in {logs}: "
            "<sample>.tinymapper_<date>.log, which tinymapper 0.15.0 and newer write."
        )
    return [read_run(outdir, path) for _, (_, path) in sorted(newest.items())]

read_flagstat

read_flagstat(path: Path) -> dict[str, int]

samtools flagstat's counts, by their description ("primary", "primary mapped", "paired in sequencing"…): the reads that passed QC and those that failed it, together. Empty if path does not exist.

Source code in src/tinymapper/report.py
def read_flagstat(path: Path) -> dict[str, int]:
    """``samtools flagstat``'s counts, by their description ("primary",
    "primary mapped", "paired in sequencing"…): the reads that passed QC and
    those that failed it, together. Empty if path does not exist."""
    counts: dict[str, int] = {}
    if not path.is_file():
        return counts
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        match = re.match(r"(\d+) \+ (\d+) ([^(]+)", line)
        if match:
            counts.setdefault(match[3].strip(), int(match[1]) + int(match[2]))
    return counts

read_samtools_stats

read_samtools_stats(path: Path) -> tuple[dict[str, int | float], list[tuple[int, int]]]

samtools stats' summary numbers (its SN lines), by their name without the colon ("reads mapped"…), and its insert sizes (IS lines): (size, pairs). Empty if path does not exist.

Source code in src/tinymapper/report.py
def read_samtools_stats(path: Path) -> tuple[dict[str, int | float], list[tuple[int, int]]]:
    """``samtools stats``' summary numbers (its SN lines), by their name
    without the colon ("reads mapped"…), and its insert sizes (IS lines):
    (size, pairs). Empty if path does not exist."""
    summary: dict[str, int | float] = {}
    sizes: list[tuple[int, int]] = []
    if not path.is_file():
        return summary, sizes
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        fields = line.split("\t")
        if fields[0] == "SN" and len(fields) >= 3:
            value = _number(fields[2])
            if value is not None:
                summary[fields[1].rstrip(":")] = value
        elif fields[0] == "IS" and len(fields) >= 3:
            sizes.append((int(fields[1]), int(fields[2])))
    return summary, sizes

read_markdup

read_markdup(path: Path) -> dict[str, int]

samtools markdup -f's counts, by their name ("EXAMINED", "DUPLICATE PRIMARY TOTAL"…). Empty if path does not exist.

Source code in src/tinymapper/report.py
def read_markdup(path: Path) -> dict[str, int]:
    """``samtools markdup -f``'s counts, by their name ("EXAMINED",
    "DUPLICATE PRIMARY TOTAL"…). Empty if path does not exist."""
    counts: dict[str, int] = {}
    if not path.is_file():
        return counts
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        key, _, value = line.partition(":")
        number = _number(value)
        if isinstance(number, int):
            counts[key.strip()] = number
    return counts

read_star_log

read_star_log(path: Path) -> dict[str, int | float]

STAR's Log.final.out, its numbers by their label ("Number of input reads"…). Empty if path does not exist.

Source code in src/tinymapper/report.py
def read_star_log(path: Path) -> dict[str, int | float]:
    """STAR's ``Log.final.out``, its numbers by their label ("Number of input
    reads"…). Empty if path does not exist."""
    numbers: dict[str, int | float] = {}
    if not path.is_file():
        return numbers
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        label, sep, value = line.partition("|")
        number = _number(value) if sep else None
        if number is not None:
            numbers[label.strip()] = number
    return numbers

read_counts

read_counts(path: Path) -> dict[str, int]

tinymapper's counts (<sample>.counts.txt): a name and a number per line. Empty if path does not exist.

Source code in src/tinymapper/report.py
def read_counts(path: Path) -> dict[str, int]:
    """tinymapper's counts (``<sample>.counts.txt``): a name and a number per
    line. Empty if path does not exist."""
    counts: dict[str, int] = {}
    if not path.is_file():
        return counts
    for line in path.read_text(encoding="utf-8").splitlines():
        key, _, value = line.partition("\t")
        if value.strip().isdigit():
            counts[key.strip()] = int(value)
    return counts

read_sections

read_sections(path: Path) -> dict[str, dict[str, str | None]]

The sections of a report.txt (chromokit's format: hicstuff's report), each its keys and their values as text, None for NA; its tables are left out. Empty if path does not exist. Needs no pandas, as read_txt does.

Source code in src/tinymapper/report.py
def read_sections(path: Path) -> dict[str, dict[str, str | None]]:
    """The sections of a report.txt (chromokit's format: hicstuff's report),
    each its keys and their values as text, None for NA; its tables are left
    out. Empty if path does not exist. Needs no pandas, as read_txt does."""
    sections: dict[str, dict[str, str | None]] = {}
    current = None
    if not path.is_file():
        return sections
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line.strip() or line.startswith("#"):
            continue
        match = re.fullmatch(r"\[(table: )?([a-z][a-z0-9_]*)\]", line.strip())
        if match:
            current = None if match[1] else sections.setdefault(match[2], {})
            continue
        if current is not None:
            key, _, value = line.partition(" ")
            value = value.strip()
            current[key] = None if value == "NA" else value
    return sections

run_section

run_section(run: Run) -> dict[str, object]

The run's parameters, as its log's header gives them, and how long it took.

Source code in src/tinymapper/report.py
def run_section(run: Run) -> dict[str, object]:
    """The run's parameters, as its log's header gives them, and how long it
    took."""
    header = run.header
    spec = run.spec
    started = header.get("date")
    return {
        "version": header.get("version"),
        "started": started.replace(" ", "T") if started else None,
        "duration_s": run.duration_s,
        "hash": spec.hash,
        "mode": spec.mode.value,
        "sample": spec.sample,
        "genome": spec.genome,
        "input": spec.input or None,
        "calibration": spec.calibration or None,
        "threads": spec.threads,
        "duplicates_kept": spec.keep_duplicates,
        "alignment": spec.alignment or None,
        "filter": spec.filter_opts or None,
        "blacklist": spec.blacklist or None,
        "gsize": spec.gsize if spec.do_peaks else None,
        "extend_reads": spec.extend_reads_len,
        "mnase_sizes": spec.mnase_sizes if spec.mode == TinyMapperMode.mnase else None,
        "hicstuff": spec.hicstuff_opts if spec.mode == TinyMapperMode.hic else None,
        "restriction": spec.restriction if spec.mode == TinyMapperMode.hic else None,
        "binning": spec.binning if spec.mode == TinyMapperMode.hic else None,
        "as_single_end": spec.as_single_end if spec.mode == TinyMapperMode.shotgun else None,
    }

reads_section

reads_section(run: Run, *, of_input: bool = False) -> dict[str, object]

The reads of the sample (or of the input) and where they went: mapped, kept and duplicated, from the statistics in stats/<name>/.

Source code in src/tinymapper/report.py
def reads_section(run: Run, *, of_input: bool = False) -> dict[str, object]:
    """The reads of the sample (or of the input) and where they went: mapped,
    kept and duplicated, from the statistics in ``stats/<name>/``."""
    spec, paths = run.spec, run.paths
    name = spec.input_base if of_input else spec.sample_base
    flagstat = read_flagstat(paths.stats_file(name, "flagstat"))
    summary, _ = read_samtools_stats(paths.stats_file(name, "stats"))
    markdup = read_markdup(paths.stats_file(name, "markdup"))
    paired = flagstat.get("paired in sequencing", 0) > 0 if flagstat else None
    reads = flagstat.get("primary")
    mapped = flagstat.get("primary mapped")
    if spec.mode == TinyMapperMode.rna:
        # STAR's BAM holds the mapped reads only: its log counts the reads, a
        # pair as one.
        star = read_star_log(paths.stats_file(name, "star"))
        sequenced = star.get("Number of input reads")
        reads = None if sequenced is None else int(sequenced) * (2 if paired else 1)
    in_bam = summary.get("reads mapped")
    flagged = summary.get("reads duplicated", 0) if not spec.keep_duplicates else 0
    kept_reads = None if in_bam is None else int(in_bam - flagged)
    duplicates = markdup.get("DUPLICATE PRIMARY TOTAL", markdup.get("DUPLICATE TOTAL"))
    examined = markdup.get("EXAMINED")
    return {
        "paired": paired,
        "reads": reads,
        "mapped": mapped,
        "mapped_pct": _pct(mapped, reads),
        "kept": kept_reads,
        "kept_pct": _pct(kept_reads, reads),
        "duplicates": duplicates,
        "duplicates_pct": _pct(duplicates, examined),
    }

hicstuff_report_paths

hicstuff_report_paths(run: Run) -> list[Path]

hicstuff's report of a Hi-C run, which tinymapper writes under the sample's name in matrices/<sample>/.

Source code in src/tinymapper/report.py
def hicstuff_report_paths(run: Run) -> list[Path]:
    """hicstuff's report of a Hi-C run, which tinymapper writes under the
    sample's name in ``matrices/<sample>/``."""
    return report_paths(run.paths.hicstuff_report_dir, run.sample)

hic_sections

hic_sections(run: Run) -> tuple[dict[str, object], dict[str, object]]

A Hi-C run's reads (as reads_section counts them: a pair is two reads) and its hicstuff section, from hicstuff's report: its read pairs, the share mapped, the duplicates, the pairs kept and the trans ratio.

Source code in src/tinymapper/report.py
def hic_sections(run: Run) -> tuple[dict[str, object], dict[str, object]]:
    """A Hi-C run's reads (as reads_section counts them: a pair is two reads)
    and its hicstuff section, from hicstuff's report: its read pairs, the
    share mapped, the duplicates, the pairs kept and the trans ratio."""
    txt, html, _ = hicstuff_report_paths(run)
    sections = read_sections(txt)
    pairs = sections.get("pairs", {})
    contacts = sections.get("contacts", {})

    def number(values: dict, key: str) -> int | float | None:
        value = values.get(key)
        return None if value is None else _number(value)

    reads = number(pairs, "reads")
    final_pairs = number(pairs, "final_pairs")
    duplicate_pairs = number(pairs, "duplicates")
    kept_reads = None if final_pairs is None else 2 * final_pairs
    reads_section = {
        "paired": True,
        "reads": reads,
        "mapped": number(pairs, "mapped_reads"),
        "mapped_pct": number(pairs, "mapped_reads_pct"),
        "kept": kept_reads,
        "kept_pct": _pct(kept_reads, reads),
        "duplicates": None if duplicate_pairs is None else 2 * duplicate_pairs,
        "duplicates_pct": number(pairs, "duplicates_pct"),
    }
    hicstuff = {
        "version": sections.get("report", {}).get("hicstuff_version"),
        "read_pairs": number(pairs, "read_pairs"),
        "mapped_pairs": number(pairs, "mapped_pairs"),
        "final_pairs": final_pairs,
        "trans_ratio": number(contacts, "trans_ratio"),
        "report": _relative(html, run.outdir),
    }
    return reads_section, hicstuff

calibration_section

calibration_section(run: Run) -> dict[str, object]

The spike-in calibration of a ChIP-seq run: the reads of the sample and of the input on each genome, filtered, the occupancy ratio and the scaling factor of the scaled track, from the run's counts file.

Source code in src/tinymapper/report.py
def calibration_section(run: Run) -> dict[str, object]:
    """The spike-in calibration of a ChIP-seq run: the reads of the sample and
    of the input on each genome, filtered, the occupancy ratio and the
    scaling factor of the scaled track, from the run's counts file."""
    values: list[str] = []
    statfile = run.paths.statfile
    if statfile.is_file():
        values = [line.split("\t")[1] for line in statfile.read_text().splitlines() if "\t" in line]
    numbers = [_number(value) for value in values] if len(values) == 6 else [None] * 6
    sample_genome, input_genome, sample_spikein, input_spikein, ori, scaling = numbers
    return {
        "spikein": run.spec.spikein_base,
        "sample_genome_reads": sample_genome,
        "sample_spikein_reads": sample_spikein,
        "sample_spikein_pct": _pct(sample_spikein, _sum(sample_genome, sample_spikein)),
        "input_genome_reads": input_genome,
        "input_spikein_reads": input_spikein,
        "input_spikein_pct": _pct(input_spikein, _sum(input_genome, input_spikein)),
        "ori": ori,
        "scaling_factor": scaling,
    }

peaks_section

peaks_section(run: Run) -> dict[str, object]

The peaks MACS3 called, and the share of the kept reads in them (FRiP).

Source code in src/tinymapper/report.py
def peaks_section(run: Run) -> dict[str, object]:
    """The peaks MACS3 called, and the share of the kept reads in them (FRiP)."""
    peaks = peaks_file(run.spec)
    count = None
    if peaks.is_file():
        with open(peaks, encoding="utf-8", errors="replace") as handle:
            count = sum(1 for line in handle if line.strip() and not line.startswith("#"))
    counts = read_counts(run.paths.stats_file(run.sample, "counts"))
    counted, in_peaks = counts.get("reads_counted"), counts.get("reads_in_peaks")
    return {
        "peaks": count,
        "reads_counted": counted,
        "reads_in_peaks": in_peaks,
        "frip_pct": _pct(in_peaks, counted),
        "file": _relative(peaks, run.outdir),
    }

fragments_section

fragments_section(run: Run) -> tuple[dict[str, object], list[tuple[int, int]]]

The sizes of the kept fragments (paired-end runs), from samtools stats: their median, mean and spread, and for MNase-seq the share in the run's size window (--MNaseSizes). Also the sizes, for the plot.

Source code in src/tinymapper/report.py
def fragments_section(run: Run) -> tuple[dict[str, object], list[tuple[int, int]]]:
    """The sizes of the kept fragments (paired-end runs), from ``samtools
    stats``: their median, mean and spread, and for MNase-seq the share in
    the run's size window (--MNaseSizes). Also the sizes, for the plot."""
    summary, sizes = read_samtools_stats(run.paths.stats_file(run.sample, "stats"))
    pairs = sum(count for _, count in sizes) if sizes else None
    section: dict[str, object] = {
        "pairs": pairs,
        "median_bp": _median(sizes),
        "mean_bp": summary.get("insert size average") if sizes else None,
        "sd_bp": summary.get("insert size standard deviation") if sizes else None,
    }
    if run.spec.mode == TinyMapperMode.mnase:
        low, high = int(run.spec.mnase_min_size), int(run.spec.mnase_max_size)
        inside = sum(count for size, count in sizes if low <= size <= high)
        section.update(
            window_min_bp=low,
            window_max_bp=high,
            in_window_pct=_pct(inside, pairs) if sizes else None,
        )
    return section, sizes

strands_section

strands_section(run: Run) -> dict[str, object]

The kept reads of an RNA-seq run on each strand, as the stranded tracks split them (deepTools' --filterRNAstrand, for dUTP libraries).

Source code in src/tinymapper/report.py
def strands_section(run: Run) -> dict[str, object]:
    """The kept reads of an RNA-seq run on each strand, as the stranded tracks
    split them (deepTools' --filterRNAstrand, for dUTP libraries)."""
    counts = read_counts(run.paths.stats_file(run.sample, "counts"))
    forward, reverse = counts.get("forward"), counts.get("reverse")
    return {
        "forward": forward,
        "reverse": reverse,
        "forward_pct": _pct(forward, _sum(forward, reverse)),
    }

files_section

files_section(run: Run) -> dict[str, str | None]

The run's main outputs, relative to its output directory: its log, its BAM, its peaks, its contact maps and hicstuff's report, each None if the run has none.

Source code in src/tinymapper/report.py
def files_section(run: Run) -> dict[str, str | None]:
    """The run's main outputs, relative to its output directory: its log, its
    BAM, its peaks, its contact maps and hicstuff's report, each None if the
    run has none."""
    spec, paths = run.spec, run.paths
    hic = spec.mode == TinyMapperMode.hic
    return {
        "log": _relative(run.log, run.outdir),
        "bam": None if hic else _relative(kept(spec, paths), run.outdir),
        "peaks": _relative(peaks_file(spec), run.outdir) if spec.do_peaks else None,
        "mcool": _relative(paths.sample_mcool, run.outdir) if hic else None,
        "hicstuff_report": _relative(hicstuff_report_paths(run)[1], run.outdir) if hic else None,
    }

collect

collect(run: Run, *, duration_s: int | None = None, report_dir: Path | None = None) -> Collected

Gather the report of a run, from what it left in its directory.

Parameters:

Name Type Description Default
run Run

The run (see find_runs).

required
duration_s int

How long the run took, in seconds, for the run's own report, written before its log's last line; by default, from that line.

None
report_dir Path

Where the page will be, which its links start from; by default, the run's directory.

None

Returns:

Type Description
Collected

The report (see the module's docstring), the page's plots, the inputs its header names and the outputs it links to.

Source code in src/tinymapper/report.py
def collect(
    run: Run, *, duration_s: int | None = None, report_dir: Path | None = None
) -> Collected:
    """Gather the report of a run, from what it left in its directory.

    Parameters
    ----------
    run : Run
        The run (see find_runs).
    duration_s : int
        How long the run took, in seconds, for the run's own report, written
        before its log's last line; by default, from that line.
    report_dir : Path
        Where the page will be, which its links start from; by default, the
        run's directory.

    Returns
    -------
    Collected
        The report (see the module's docstring), the page's plots, the inputs
        its header names and the outputs it links to.
    """
    from tinymapper._report import Report, report_files, report_section

    spec = run.spec
    report_dir = Path(report_dir or run.outdir)
    section_run = run_section(run)
    if duration_s is not None:
        section_run["duration_s"] = duration_s
    sections: dict[str, dict] = {
        "report": report_section(tool(), run.sample, {"outdir": str(run.outdir)}),
        "run": section_run,
        "commands": {"tinymapper": run.header.get("cmd")},
    }
    sizes: list[tuple[int, int]] = []
    if spec.mode == TinyMapperMode.hic:
        sections["reads"], sections["hicstuff"] = hic_sections(run)
    else:
        sections["reads"] = reads_section(run)
        if spec.mode == TinyMapperMode.chip and spec.do_input:
            sections["input"] = reads_section(run, of_input=True)
        if spec.do_calibration:
            sections["calibration"] = calibration_section(run)
        if spec.do_peaks:
            sections["peaks"] = peaks_section(run)
        if spec.mode in _FRAGMENT_MODES:
            sections["fragments"], sizes = fragments_section(run)
        if spec.mode == TinyMapperMode.rna:
            sections["strands"] = strands_section(run)
    sections["files"] = files_section(run)
    report = Report(sections=sections)

    txt, _, mqc = report_files(run.sample)
    outputs = [run.log, *sorted(_outputs(run))]
    links: dict[str, object] = {
        "files": [os.path.relpath(path, report_dir) for path in outputs]
        + [name for name in (txt, mqc) if (report_dir / name).exists()]
    }
    hicstuff_page = hicstuff_report_paths(run)[1]
    if spec.mode == TinyMapperMode.hic and hicstuff_page.is_file():
        links["hicstuff"] = os.path.relpath(hicstuff_page, report_dir)
    inputs = {"Reads": spec.sample, "Genome": spec.genome}
    if spec.input:
        inputs["Input"] = spec.input
    if spec.calibration:
        inputs["Spike-in"] = spec.calibration
    return Collected(report=report, figures=figures(report, sizes), inputs=inputs, links=links)

figures

figures(report, sizes: list[tuple[int, int]]) -> dict[str, dict]

The plots of the page, as Plotly figures (data and layout), by the id of their place: where the reads went (plot-reads), and the fragments' sizes (plot-fragments), each left out when the run gives nothing to draw. A colour left out follows the page's palette.

Source code in src/tinymapper/report.py
def figures(report, sizes: list[tuple[int, int]]) -> dict[str, dict]:
    """The plots of the page, as Plotly figures (data and layout), by the id of
    their place: where the reads went (plot-reads), and the fragments' sizes
    (plot-fragments), each left out when the run gives nothing to draw. A
    colour left out follows the page's palette."""
    plots: dict[str, dict] = {}
    rows = [("Sample", report.sections["reads"])]
    if "input" in report.sections:
        rows.append(("Input", report.sections["input"]))
    labels = ["Mapped", "Kept", "Duplicates"]
    data = []
    for name, reads in rows:
        shares = [reads.get("mapped_pct"), reads.get("kept_pct"), reads.get("duplicates_pct")]
        if all(share is None for share in shares):
            continue
        data.append(
            {
                "type": "bar",
                "orientation": "h",
                "name": name,
                "x": [share or 0 for share in shares],
                "y": labels,
                "text": ["NA" if share is None else f"{share:.1f}%" for share in shares],
                "textposition": "outside",
                "cliponaxis": False,
                "hovertemplate": f"{name}: %{{y}}, %{{x:.2f}}%<extra></extra>",
            }
        )
    if data:
        plots["plot-reads"] = {
            "data": data,
            "layout": {
                **_LAYOUT,
                "height": 260 if len(data) == 1 else 320,
                "barmode": "group",
                "showlegend": len(data) > 1,
                "margin": {"l": 100, "r": 40, "t": 30, "b": 50},
                "xaxis": {"title": {"text": "Share (%)"}, "range": [0, 105]},
                "yaxis": {"autorange": "reversed"},
            },
        }
    shown = [(size, count) for size, count in sorted(sizes) if size <= 1000]
    if shown:
        fragments = report.sections["fragments"]
        layout = {
            **_LAYOUT,
            "height": 320,
            "xaxis": {"title": {"text": "Fragment size (bp)"}, "range": [0, shown[-1][0]]},
            "yaxis": {"title": {"text": "Pairs"}, "rangemode": "tozero"},
        }
        if "window_min_bp" in fragments:
            layout["shapes"] = [
                {
                    "type": "rect",
                    "xref": "x",
                    "yref": "paper",
                    "x0": fragments["window_min_bp"],
                    "x1": fragments["window_max_bp"],
                    "y0": 0,
                    "y1": 1,
                    "opacity": 0.12,
                    "line": {"width": 0},
                    "fillcolor": "#7f7f7f",
                }
            ]
        plots["plot-fragments"] = {
            "data": [
                {
                    "type": "scatter",
                    "mode": "lines",
                    "fill": "tozeroy",
                    "x": [size for size, _ in shown],
                    "y": [count for _, count in shown],
                    "hovertemplate": "%{y:,} pairs of %{x} bp<extra></extra>",
                }
            ],
            "layout": layout,
        }
    return plots

write_report

write_report(outdir: Path, *, log: Path | None = None, sample: str | None = None, report_dir: Path | None = None, force: bool = False, duration_s: int | None = None) -> list[str]

Write the report of a run, from its output directory.

Parameters:

Name Type Description Default
outdir Path

The run's output directory. It is only read.

required
log Path

The run's log; by default, the newest log of sample's runs that went to their end, in outdir/logs.

None
sample str

The sample, when log is not given; by default, the only sample of outdir.

None
report_dir Path

The report's directory, made if missing; by default, outdir.

None
force bool

Replace the report of the same sample in report_dir; without it, an existing one is refused before anything is read.

False
duration_s int

How long the run took, in seconds (see collect).

None

Returns:

Type Description
list of str

The report's files: its report.txt, its page and its report_mqc.yaml.

Raises:

Type Description
FileNotFoundError

If outdir holds no log of a run (of sample) that went to its end.

FileExistsError

If a file of the report exists and force is not set.

ValueError

If outdir holds the runs of several samples and none is named, or log is not a tinymapper log.

Source code in src/tinymapper/report.py
def write_report(
    outdir: Path,
    *,
    log: Path | None = None,
    sample: str | None = None,
    report_dir: Path | None = None,
    force: bool = False,
    duration_s: int | None = None,
) -> list[str]:
    """Write the report of a run, from its output directory.

    Parameters
    ----------
    outdir : Path
        The run's output directory. It is only read.
    log : Path
        The run's log; by default, the newest log of sample's runs that went
        to their end, in ``outdir/logs``.
    sample : str
        The sample, when log is not given; by default, the only sample of
        outdir.
    report_dir : Path
        The report's directory, made if missing; by default, outdir.
    force : bool
        Replace the report of the same sample in report_dir; without it, an
        existing one is refused before anything is read.
    duration_s : int
        How long the run took, in seconds (see collect).

    Returns
    -------
    list of str
        The report's files: its report.txt, its page and its report_mqc.yaml.

    Raises
    ------
    FileNotFoundError
        If outdir holds no log of a run (of sample) that went to its end.
    FileExistsError
        If a file of the report exists and force is not set.
    ValueError
        If outdir holds the runs of several samples and none is named, or log
        is not a tinymapper log.
    """
    runs = find_runs(outdir, sample=sample, log=log)
    if len(runs) > 1:
        names = ", ".join(run.sample for run in runs)
        raise ValueError(f"{outdir} holds the runs of several samples ({names}): name one.")
    return _write(runs[0], report_dir=report_dir, force=force, duration_s=duration_s)

write_reports

write_reports(outdir: Path, *, sample: str | None = None, log: Path | None = None, report_dir: Path | None = None, force: bool = False) -> list[str]

Write the report of each run that find_runs finds in outdir: the run of log, or the newest of each sample (of sample alone, if given). Without force, an existing report refuses them all, before any is written.

Returns:

Type Description
list of str

The files of the reports, three per run.

Source code in src/tinymapper/report.py
def write_reports(
    outdir: Path,
    *,
    sample: str | None = None,
    log: Path | None = None,
    report_dir: Path | None = None,
    force: bool = False,
) -> list[str]:
    """Write the report of each run that find_runs finds in outdir: the run of
    log, or the newest of each sample (of sample alone, if given). Without
    force, an existing report refuses them all, before any is written.

    Returns
    -------
    list of str
        The files of the reports, three per run.
    """
    runs = find_runs(outdir, sample=sample, log=log)
    if not force:
        for run in runs:
            _refuse_existing(report_paths(Path(report_dir or run.outdir), run.sample))
    written: list[str] = []
    for run in runs:
        written += _write(run, report_dir=report_dir, force=True)
    return written