6

(How) can you index a BAM file using pysam?

When I tried the intuitive pysam.index I got:

import pysam
my_bam = pysam.AlignmentFile("regular_bwamem_mapping.bam", "rb")
pysam.index(my_bam)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-a0b3a04ecb2c> in <module>
----> 1 pysam.index(L_bam)

~/miniconda3/lib/python3.7/site-packages/pysam/utils.py in __call__(self, *args, **kwargs)
     59             args,
     60             catch_stdout=kwargs.get("catch_stdout", True),
---> 61             save_stdout=kwargs.get("save_stdout", None))
     62
     63         if kwargs.get("split_lines", False):

pysam/libcutils.pyx in pysam.libcutils._pysam_dispatch()

TypeError: object of type 'pysam.libcalignmentfile.AlignmentFile' has no len()
Kamil S Jaron
  • 5,542
  • 2
  • 25
  • 59
  • 1
    disclaimer: when I post a question and answer, it's because I figure the answer while I write the question. – Kamil S Jaron Feb 13 '20 at 16:15
  • I have tried same command... error [E::hts_idx_push] Unsorted positions on sequence #8: 3411049 followed by 3378665 [E::sam_index] Read 'A00404:40:HFGYNDSXX:4:1258:24623:27633' with ref_name='chr8', ref_length=145138636, flags=1107, pos=3378665 cannot be indexed Traceback (most recent call last): File "Insertx.py", line 283, in main() File "Insertx.py", line 263, in main pysam.index(str(''.join( data))) File "/usr/local/lib/python3.8/dist-packages/pysam/utils.py", line 69, in call raise SamtoolsError( pysam.utils.SamtoolsError: 'samtools returned with error 1: stdout=, stderr=samt – anju Nov 26 '23 at 02:28
  • @anju there must have been something that gone wrong with sorting the file. Otherwise it would not complain about it. – Kamil S Jaron Dec 15 '23 at 14:14

1 Answers1

11

Oh you silly sausage, pysam.index takes a bam file name, not a python object.

import pysam
pysam.index("regular_bwamem_mapping.bam")

will index your .bam file.

Kamil S Jaron
  • 5,542
  • 2
  • 25
  • 59