This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to get SAMRecord from bam. file with specified readGroupId, referenceId, sequence end and start?

I've got .bam and .bai files and I need to get SAMRecord from bam with specified readGroupId, referenceId, end and start and with using .bai index. How can I make it using Picard java-API? Thanks.

index java picard

2 answers

To extract sequences for particular read group id you can use Picard's SamToFastq and FilterSamReads. But you can't really specify specific coordinates to extract your reads. If you pretty adamant about using Picard java-API, you may have to use a combination of samtools view function and Picard's FilterSamReads. Otherwise you can do sth like:

samtools view chrA:X-Y Input.bam | grep "readGroupId" >  new.sam

There is no more picard-api. The java api used by picard tools is htsjdk.

Create a SAMReaderFactory:

SamReaderFactory srf=SamReaderFactory.make();
srf.validationStringency(ValidationStringency.LENIENT);

Open the SAM:

SamReader samReader = srf.open(bamFile);

Loop:

SAMRecordIterator iter= srf.iterator();
while(iter.hasNext())
{
    SAMRecord rec= iter.next();

Get the read group, get the sampleName:

SAMReadGroupRecord sgr=rec.getReadGroup();
String sampleName = (sgr!=null ?sgr.getSample() : null );

Thanks for your reply, but does this construction uses index in .bai-file? I thought there should be some kind of reference to this file, something like index in SAMFileReader.

public SAMFileReader(final File file, final File indexFile) {
        this(file, indexFile, false);
    }

SamFileReader

Log in to answer this question.