This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Pysam fetch for records not exists in VCF files
f1 = pysam.VariantFile("test.vcf.gz")

for f in f1.fetch(str(chr), int(start), int(end)):

            if f:
                    print "yes"  
            else :
                    print "hello"

In the above example Its not printing "hello" even for cases which doesn't have entry into VCF. I want to print program "hello" for cases where VariantFile doesn't have variants records.

Its their a way to do this ?

Thanks

pysam fetch

Try:

if not f1.fetch(str(chr), int(start), int(end)):
    print("hello")

instead of the for loop.

Thanks Ryan, Its not working. I tried this earlier as well.

What do you get if you print f for positions which are not in the vcf?

There shouldn't be an else condition, since there shouldn't be a for loop in this case in question.

And looking at how f looks like doesn't depend on if else statement, you just need to now what fetch returns for a position you think isn't included in the vcf.

     if f1.fetch(str(chr), int(start), int(end)):
                print "hello"
     else:
                print "no"

Even this is not working as well.

What do you get if you print f1.fetch(str(chr), int(start), int(end)) for positions which are not in the vcf?

>>> print f1.fetch('2', 224629875, 224629876)
<pysam.ctabix.TabixIterator object at 0x7fd7e26101f0>
>>> print f1.fetch('2', 224629873, 224629874)
<pysam.ctabix.TabixIterator object at 0x7fd7e26101f0>

Reagrdless of absence or present its proting iterator object. I checked for object condition as well but no luck.

The TabixIterator is always True, regardless of precense or absence of that variant.

yes and Thats why its never going to else condition.

Exactly. What are you trying to achieve? This issue probably has a better solution.

2 answers

SInce I have a small files need to extracted from VCF file so i jus used hash and then search in hash so finally I was able to accomplished this task but stiil i have no idea why its not printing "hello" even for cases which doesn't have entry into VCF

Pysam returns an iterator for the fetch call, so that condition will be always be true. You can query for an attribute of the VariantRecord (e.g. contig, pos etc.) to check if it's empty.

for f in f1.fetch(str(chr), int(start), int(end)):
      # This will return an empty list if a variant is not present at that location.
      if [r.contig for r in f]:
          print True
      else:
          print False

I'd like to suggest to write python3-compatible code, especially when you are sharing examples. In this case you have to adapt the print statements to print(True) and print(False). As such, users who stumble upon your solution won't have issues running your code.

Log in to answer this question.