6
$\begingroup$

(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()
$\endgroup$
3
  • 1
    $\begingroup$ disclaimer: when I post a question and answer, it's because I figure the answer while I write the question. $\endgroup$ Feb 13, 2020 at 16:15
  • $\begingroup$ 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 <module> 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 $\endgroup$
    – anju
    Nov 26, 2023 at 2:28
  • $\begingroup$ @anju there must have been something that gone wrong with sorting the file. Otherwise it would not complain about it. $\endgroup$ Dec 15, 2023 at 14:14

1 Answer 1

11
$\begingroup$

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.

$\endgroup$
1
  • 5
    $\begingroup$ I should print "Oh you silly sausage" and tape it above my monitor. $\endgroup$ Feb 14, 2020 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.