Skill Tracer
Skills › Scientific Agent Skills › pysam › api_reference.md

api_reference.md

439 lines · skills/pysam/references/api_reference.md at 5f2bc03

Open on GitHub
1# Pysam 0.24 API Quick Reference
2
3This is a compact navigation aid, not a replacement for the official API
4documentation. Signatures and defaults below are for pysam 0.24.1.
5

Pysam 0.24 API Quick Reference

This is a compact navigation aid, not a replacement for the official API documentation. Signatures and defaults below are for pysam 0.24.1.

Raw lines 1 to 5
6## Alignment Files
7

Alignment Files

Raw lines 6 to 7
8### Constructor
9
10```python
11pysam.AlignmentFile(
12 filepath_or_object,
13 mode=None, # pass the remaining options by keyword
14 template=None,
15 reference_names=None,
16 reference_lengths=None,
17 text=None,
18 header=None,
19 add_sq_text=True,
20 add_sam_header=True,
21 check_header=True,
22 check_sq=True,
23 reference_filename=None,
24 index_filename=None,
25 filepath_index=None,
26 require_index=False,
27 duplicate_filehandle=True,
28 ignore_truncation=False,
29 format_options=None,
30 threads=1,
32```
34Core methods:
36```python
37AlignmentFile.fetch(
38 contig=None,
39 start=None,
40 stop=None,
41 region=None,
42 tid=None,
43 until_eof=False,
44 multiple_iterators=False,
45 reference=None, # compatibility alias
46 end=None, # compatibility alias
49AlignmentFile.count(
50 contig=None,
51 start=None,
52 stop=None,
53 region=None,
54 until_eof=False,
55 read_callback="nofilter",
56 reference=None,
57 end=None,
60AlignmentFile.count_coverage(
61 contig,
62 start=None,
63 stop=None,
64 region=None,
65 quality_threshold=15,
66 read_callback="all",
67 reference=None,
68 end=None,
71AlignmentFile.pileup(
72 contig=None,
73 start=None,
74 stop=None,
75 region=None,
76 reference=None,
77 end=None,
78 **kwargs,
80```
82Important pileup kwargs/defaults:
84| Option | Default | Meaning |
85|---|---:|---|
86| `truncate` | `False` | limit columns to exact query interval |
87| `max_depth` | `8000` | maximum depth |
88| `stepper` | `"samtools"` in current implementation/docs context | read filtering/processing mode |
89| `fastafile` | `None` | reference for BAQ/samtools behavior |
90| `ignore_overlaps` | `True` | adjust qualities of overlapping paired bases |
91| `ignore_orphans` | `True` | exclude improper paired orphans |
92| `flag_filter` | unmapped, secondary, QC-fail, duplicate | excluded flags |
93| `flag_require` | `0` | required flags |
94| `min_base_quality` | `13` | base-quality threshold |
95| `min_mapping_quality` | `0` | mapping-quality threshold |
96| `compute_baq` | `True` | compute BAQ when reference is available |
97| `redo_baq` | `False` | recompute existing BAQ |
99For `count_coverage`, pass numeric `contig`, `start`, `stop` within contig
100bounds; the accepted `region`/`end` aliases do not size its arrays correctly
101in 0.24.1.
103Always pass important pileup semantics explicitly rather than depending on
104defaults. `get_num_aligned()` is a quality-filtered pileup-entry count in
1050.24.1 and can include D/N entries. Count non-deletion/non-refskip entries
106explicitly for observed base depth.
108Other useful methods/properties:
110- `write(read)`
111- `has_index()` / `check_index()`
112- `get_index_statistics()`
113- `get_reference_name(tid)` / `get_tid(name)`
114- `get_reference_length(name)`
115- `find_introns(read_iterator)`
116- `head(n, multiple_iterators=True)`
117- `references`, `lengths`, `nreferences`
118- `mapped`, `unmapped`, `nocoordinate` when index statistics support them;
119 CRAI returns zeros because it stores no such counts

Constructor

pysam.AlignmentFile(
    filepath_or_object,
    mode=None,  # pass the remaining options by keyword
    template=None,
    reference_names=None,
    reference_lengths=None,
    text=None,
    header=None,
    add_sq_text=True,
    add_sam_header=True,
    check_header=True,
    check_sq=True,
    reference_filename=None,
    index_filename=None,
    filepath_index=None,
    require_index=False,
    duplicate_filehandle=True,
    ignore_truncation=False,
    format_options=None,
    threads=1,
)

Core methods:

AlignmentFile.fetch(
    contig=None,
    start=None,
    stop=None,
    region=None,
    tid=None,
    until_eof=False,
    multiple_iterators=False,
    reference=None,  # compatibility alias
    end=None,        # compatibility alias
)

AlignmentFile.count(
    contig=None,
    start=None,
    stop=None,
    region=None,
    until_eof=False,
    read_callback="nofilter",
    reference=None,
    end=None,
)

AlignmentFile.count_coverage(
    contig,
    start=None,
    stop=None,
    region=None,
    quality_threshold=15,
    read_callback="all",
    reference=None,
    end=None,
)

AlignmentFile.pileup(
    contig=None,
    start=None,
    stop=None,
    region=None,
    reference=None,
    end=None,
    **kwargs,
)

Important pileup kwargs/defaults:

OptionDefaultMeaning
truncateFalselimit columns to exact query interval
max_depth8000maximum depth
stepper"samtools" in current implementation/docs contextread filtering/processing mode
fastafileNonereference for BAQ/samtools behavior
ignore_overlapsTrueadjust qualities of overlapping paired bases
ignore_orphansTrueexclude improper paired orphans
flag_filterunmapped, secondary, QC-fail, duplicateexcluded flags
flag_require0required flags
min_base_quality13base-quality threshold
min_mapping_quality0mapping-quality threshold
compute_baqTruecompute BAQ when reference is available
redo_baqFalserecompute existing BAQ

For count_coverage, pass numeric contig, start, stop within contig bounds; the accepted region/end aliases do not size its arrays correctly in 0.24.1.

Always pass important pileup semantics explicitly rather than depending on defaults. get_num_aligned() is a quality-filtered pileup-entry count in 0.24.1 and can include D/N entries. Count non-deletion/non-refskip entries explicitly for observed base depth.

Other useful methods/properties:

  • write(read)
  • has_index() / check_index()
  • get_index_statistics()
  • get_reference_name(tid) / get_tid(name)
  • get_reference_length(name)
  • find_introns(read_iterator)
  • head(n, multiple_iterators=True)
  • references, lengths, nreferences
  • mapped, unmapped, nocoordinate when index statistics support them; CRAI returns zeros because it stores no such counts
Raw lines 8 to 120
121## `AlignedSegment`
123Construction:
125```python
126read = pysam.AlignedSegment(header=None)
127```
129Prefer passing the destination `AlignmentHeader`.
131Frequently used attributes:
133- identity: `query_name`, `query_sequence`, `query_qualities`
134- query spans: `query_length`, `query_alignment_start`,
135 `query_alignment_end`, `query_alignment_length`
136- reference: `reference_id`, `reference_name`, `reference_start`,
137 `reference_end`, `reference_length`
138- mapping: `mapping_quality`, `cigarstring`, `cigartuples`
139- mate: `next_reference_id`, `next_reference_name`,
140 `next_reference_start`, `template_length`
141- flags: `flag` and `is_*` boolean properties
143Methods:
145- `get_tag(tag, with_value_type=False)`
146- `set_tag(tag, value, value_type=None, replace=True)`
147- `has_tag(tag)`
148- `get_tags(with_value_type=False)`
149- `set_tags(tags)`
150- `get_aligned_pairs(matches_only=False, with_seq=False, with_cigar=False)`
151- `get_blocks()`
152- `get_reference_positions(full_length=False)`
153- `get_reference_sequence()` (requires MD)
154- `get_forward_sequence()` / `get_forward_qualities()`
155- `infer_query_length()` / `infer_read_length()`
157Modified-base properties:
159- `modified_bases`
160- `modified_bases_forward`
162They return mappings from `(canonical_base, strand, modification)` to
163`(query_position, quality)` calls.

AlignedSegment

Construction:

read = pysam.AlignedSegment(header=None)

Prefer passing the destination AlignmentHeader.

Frequently used attributes:

  • identity: query_name, query_sequence, query_qualities
  • query spans: query_length, query_alignment_start, query_alignment_end, query_alignment_length
  • reference: reference_id, reference_name, reference_start, reference_end, reference_length
  • mapping: mapping_quality, cigarstring, cigartuples
  • mate: next_reference_id, next_reference_name, next_reference_start, template_length
  • flags: flag and is_* boolean properties

Methods:

  • get_tag(tag, with_value_type=False)
  • set_tag(tag, value, value_type=None, replace=True)
  • has_tag(tag)
  • get_tags(with_value_type=False)
  • set_tags(tags)
  • get_aligned_pairs(matches_only=False, with_seq=False, with_cigar=False)
  • get_blocks()
  • get_reference_positions(full_length=False)
  • get_reference_sequence() (requires MD)
  • get_forward_sequence() / get_forward_qualities()
  • infer_query_length() / infer_read_length()

Modified-base properties:

  • modified_bases
  • modified_bases_forward

They return mappings from (canonical_base, strand, modification) to (query_position, quality) calls.

Raw lines 121 to 164
165## Pileup Objects
167`PileupColumn`:
169- `reference_id`, `reference_name`, `reference_pos`
170- `nsegments`
171- `pileups`
172- `get_num_aligned()`
173- `get_query_sequences(...)`
174- `get_query_qualities()`
175- `get_mapping_qualities()`
177`PileupRead`:
179- `alignment`
180- `query_position`
181- `query_position_or_next`
182- `is_del`
183- `is_refskip`
184- `indel`
185- `level`
187Read column values before the iterator advances; the buffer is reused.
188`PileupRead.level` is exposed but is not currently computed.

Pileup Objects

PileupColumn:

  • reference_id, reference_name, reference_pos
  • nsegments
  • pileups
  • get_num_aligned()
  • get_query_sequences(...)
  • get_query_qualities()
  • get_mapping_qualities()

PileupRead:

  • alignment
  • query_position
  • query_position_or_next
  • is_del
  • is_refskip
  • indel
  • level

Read column values before the iterator advances; the buffer is reused. PileupRead.level is exposed but is not currently computed.

Raw lines 165 to 189
190## Variant Files
192### Constructor
194```python
195pysam.VariantFile(
196 filename,
197 mode=None,
198 index_filename=None,
199 header=None,
200 drop_samples=False,
201 duplicate_filehandle=True,
202 ignore_truncation=False,
203 threads=1,
205```
207Core methods:
209```python
210VariantFile.fetch(
211 contig=None,
212 start=None,
213 stop=None,
214 region=None,
215 reopen=False,
216 end=None,
217 reference=None,
220VariantFile.subset_samples(include_samples)
221VariantFile.new_record(*args, **kwargs)
222VariantFile.write(record)
223```
225Numeric fetch coordinates are 0-based, half-open. `reopen=True` supports
226multiple simultaneous iterators. Use `contig`, not the legacy `reference`
227alias: without `contig` or `region`, 0.24.1 selects the sequential-rewind path
228before interpreting that alias.
230`VariantHeader`:
232```python
233header.copy()
234header.add_meta(key, value=None, items=None)
235header.add_line(line)
236header.add_sample(sample)
237header.new_record(
238 contig=None,
239 start=0,
240 stop=0,
241 alleles=None,
242 id=None,
243 qual=None,
244 filter=None,
245 info=None,
246 samples=None,
247 **kwargs,
249```
251Metadata collections:
253- `contigs`
254- `samples`
255- `filters`
256- `info`
257- `formats`
258- `records`
260`VariantRecord`:
262- location: `contig`, `chrom`, `pos`, `start`, `stop`, `rlen`
263- alleles: `ref`, `alts`, `alleles`, `alleles_variant_types`
264- metadata: `id`, `qual`, `filter`, `info`
265- samples: `samples`
266- methods: `copy()`, `translate(destination_header)`

Constructor

pysam.VariantFile(
    filename,
    mode=None,
    index_filename=None,
    header=None,
    drop_samples=False,
    duplicate_filehandle=True,
    ignore_truncation=False,
    threads=1,
)

Core methods:

VariantFile.fetch(
    contig=None,
    start=None,
    stop=None,
    region=None,
    reopen=False,
    end=None,
    reference=None,
)

VariantFile.subset_samples(include_samples)
VariantFile.new_record(*args, **kwargs)
VariantFile.write(record)

Numeric fetch coordinates are 0-based, half-open. reopen=True supports multiple simultaneous iterators. Use contig, not the legacy reference alias: without contig or region, 0.24.1 selects the sequential-rewind path before interpreting that alias.

VariantHeader:

header.copy()
header.add_meta(key, value=None, items=None)
header.add_line(line)
header.add_sample(sample)
header.new_record(
    contig=None,
    start=0,
    stop=0,
    alleles=None,
    id=None,
    qual=None,
    filter=None,
    info=None,
    samples=None,
    **kwargs,
)

Metadata collections:

  • contigs
  • samples
  • filters
  • info
  • formats
  • records

VariantRecord:

  • location: contig, chrom, pos, start, stop, rlen
  • alleles: ref, alts, alleles, alleles_variant_types
  • metadata: id, qual, filter, info
  • samples: samples
  • methods: copy(), translate(destination_header)
Raw lines 192 to 267
268## FASTA and FASTX
270```python
271pysam.FastaFile(
272 filename,
273 filepath_index=None,
274 filepath_index_compressed=None,
277FastaFile.fetch(
278 reference=None,
279 start=None,
280 end=None,
281 region=None,
284FastaFile.get_reference_length(reference)
285```
287Properties: `references`, `lengths`, `nreferences`.
289```python
290pysam.FastxFile(filename, persist=True)
291```
293Yielded records expose:
295- `name`
296- `comment`
297- `sequence`
298- `quality`
299- `get_quality_array()`
301`persist=False` is faster but returns temporary read-only proxies.

FASTA and FASTX

pysam.FastaFile(
    filename,
    filepath_index=None,
    filepath_index_compressed=None,
)

FastaFile.fetch(
    reference=None,
    start=None,
    end=None,
    region=None,
)

FastaFile.get_reference_length(reference)

Properties: references, lengths, nreferences.

pysam.FastxFile(filename, persist=True)

Yielded records expose:

  • name
  • comment
  • sequence
  • quality
  • get_quality_array()

persist=False is faster but returns temporary read-only proxies.

Raw lines 268 to 302
303## Tabix
305```python
306pysam.TabixFile(
307 filename,
308 mode="r",
309 parser=None,
310 index=None,
311 encoding="ascii",
312 threads=1,
315TabixFile.fetch(
316 reference=None,
317 start=None,
318 end=None,
319 region=None,
320 parser=None,
321 multiple_iterators=False,
323```
325Properties: `contigs`, `header`, `filename`, `filename_index`. Do not use the
326inherited `index_filename` to discover the loaded tabix index (it is `None`
327in the tested release). Supply `index="data.gz.csi"` for CSI; the default
328looks only for `data.gz.tbi`. Although accepted, `threads=` is reset to 1
329by the 0.24.1 TabixFile implementation; do not promise tabix parallel decoding.
331Compression and indexing:
333```python
334pysam.tabix_compress(
335 filename_in,
336 filename_out,
337 force=False,
340pysam.tabix_index(
341 filename,
342 force=False,
343 seq_col=None,
344 start_col=None,
345 end_col=None,
346 preset=None,
347 meta_char="#",
348 line_skip=0,
349 zerobased=False,
350 min_shift=-1,
351 index=None,
352 keep_original=False,
353 csi=False,
355```
357Parsers:
359- `pysam.asTuple()`
360- `pysam.asBed()`
361- `pysam.asGTF()`
362- `pysam.asGFF3()`
363- `pysam.asVCF()` (its `.pos` is 0-based, unlike `VariantRecord.pos`)

Tabix

pysam.TabixFile(
    filename,
    mode="r",
    parser=None,
    index=None,
    encoding="ascii",
    threads=1,
)

TabixFile.fetch(
    reference=None,
    start=None,
    end=None,
    region=None,
    parser=None,
    multiple_iterators=False,
)

Properties: contigs, header, filename, filename_index. Do not use the inherited index_filename to discover the loaded tabix index (it is None in the tested release). Supply index="data.gz.csi" for CSI; the default looks only for data.gz.tbi. Although accepted, threads= is reset to 1 by the 0.24.1 TabixFile implementation; do not promise tabix parallel decoding.

Compression and indexing:

pysam.tabix_compress(
    filename_in,
    filename_out,
    force=False,
)

pysam.tabix_index(
    filename,
    force=False,
    seq_col=None,
    start_col=None,
    end_col=None,
    preset=None,
    meta_char="#",
    line_skip=0,
    zerobased=False,
    min_shift=-1,
    index=None,
    keep_original=False,
    csi=False,
)

Parsers:

  • pysam.asTuple()
  • pysam.asBed()
  • pysam.asGTF()
  • pysam.asGFF3()
  • pysam.asVCF() (its .pos is 0-based, unlike VariantRecord.pos)
Raw lines 303 to 364
365## Wrapped Commands
367Explicit imports:
369```python
370import pysam.samtools
371import pysam.bcftools
372```
374Each dispatcher has:
376```python
377command(
378 *args: str,
379 catch_stdout=True,
380 save_stdout=None,
381 split_lines=False,
384command.get_messages()
385command.usage()
386```
388- command-line tokens are separate strings
389- stdout is returned by default
390- `save_stdout=path` writes captured stdout to a file
391- `catch_stdout=False` discards stdout and avoids overriding a command's `-o`
392- after success, stderr is available from `get_messages()`; after failure,
393 use the raised exception because 0.24.1 can leave that cache unchanged
394- a nonzero exit raises `pysam.SamtoolsError`
396Top-level samtools aliases such as `pysam.sort` exist, but explicit module
397imports make provenance clearer. Bcftools should be explicitly imported as
398`pysam.bcftools`.

Wrapped Commands

Explicit imports:

import pysam.samtools
import pysam.bcftools

Each dispatcher has:

command(
    *args: str,
    catch_stdout=True,
    save_stdout=None,
    split_lines=False,
)

command.get_messages()
command.usage()
  • command-line tokens are separate strings
  • stdout is returned by default
  • save_stdout=path writes captured stdout to a file
  • catch_stdout=False discards stdout and avoids overriding a command's -o
  • after success, stderr is available from get_messages(); after failure, use the raised exception because 0.24.1 can leave that cache unchanged
  • a nonzero exit raises pysam.SamtoolsError

Top-level samtools aliases such as pysam.sort exist, but explicit module imports make provenance clearer. Bcftools should be explicitly imported as pysam.bcftools.

Raw lines 365 to 399
400## Convenience Functions
402- `pysam.qualitystring_to_array(text)`
403- `pysam.array_to_qualitystring(values)`
404- `pysam.index(*samtools_args, **dispatcher_kwargs)`
405- `pysam.faidx(*samtools_args, **dispatcher_kwargs)`
406- `pysam.tabix_compress(...)`
407- `pysam.tabix_index(...)`
408- `pysam.set_verbosity(level)`
409- `pysam.reverse_complement(sequence)` (new in 0.24.1; preserves input type)
410- `pysam.reverse_complement_inplace(bytearray_sequence)` (new in 0.24.1)
412Pysam 0.24 substantially optimized `array_to_qualitystring()`.

Convenience Functions

  • pysam.qualitystring_to_array(text)
  • pysam.array_to_qualitystring(values)
  • pysam.index(*samtools_args, **dispatcher_kwargs)
  • pysam.faidx(*samtools_args, **dispatcher_kwargs)
  • pysam.tabix_compress(...)
  • pysam.tabix_index(...)
  • pysam.set_verbosity(level)
  • pysam.reverse_complement(sequence) (new in 0.24.1; preserves input type)
  • pysam.reverse_complement_inplace(bytearray_sequence) (new in 0.24.1)

Pysam 0.24 substantially optimized array_to_qualitystring().

Raw lines 400 to 413
414## Exceptions
416Expect and handle narrowly:
418- `ValueError`: invalid coordinates, header/record errors, unusable index
419- `OSError` / `IOError`: file, compression, and HTSlib I/O problems
420- `IndexError`: some invalid coordinates and sequence access; FASTA end
421 overruns can instead clip or return an empty string, so validate bounds
422- `KeyError`: missing headers, samples, tags, or fields when accessed directly
423- `pysam.SamtoolsError`: wrapped command failure
425Do not use `ignore_truncation=True` as general error suppression.

Exceptions

Expect and handle narrowly:

  • ValueError: invalid coordinates, header/record errors, unusable index
  • OSError / IOError: file, compression, and HTSlib I/O problems
  • IndexError: some invalid coordinates and sequence access; FASTA end overruns can instead clip or return an empty string, so validate bounds
  • KeyError: missing headers, samples, tags, or fields when accessed directly
  • pysam.SamtoolsError: wrapped command failure

Do not use ignore_truncation=True as general error suppression.

Raw lines 414 to 426
427## Compatibility Names to Avoid in New Code
429Prefer:
431- `AlignmentFile`, not `Samfile`
432- `AlignedSegment`, not `AlignedRead`
433- `FastxFile`, not `FastqFile`
434- `get_tag()` / `set_tag()`, not `opt()` / `setTag()`
435- `get_reference_name()` / `get_tid()`, not old PEP8-incompatible names
436- `pysam.CIGAR_OPS.CMATCH` and related enum members, not top-level aliases
438Compatibility aliases can remain in 0.24 but are poor foundations for new
439work.

Compatibility Names to Avoid in New Code

Prefer:

  • AlignmentFile, not Samfile
  • AlignedSegment, not AlignedRead
  • FastxFile, not FastqFile
  • get_tag() / set_tag(), not opt() / setTag()
  • get_reference_name() / get_tid(), not old PEP8-incompatible names
  • pysam.CIGAR_OPS.CMATCH and related enum members, not top-level aliases

Compatibility aliases can remain in 0.24 but are poor foundations for new work.

Raw lines 427 to 439