Search in sources :

Example 6 with BedLine

use of com.github.lindenb.jvarkit.util.bio.bed.BedLine in project jvarkit by lindenb.

the class BamCmpCoverage method readBedFile.

private void readBedFile(final File bedFile) {
    if (this.intervals == null) {
        intervals = new IntervalTreeMap<Boolean>();
    }
    try {
        LOG.info("Reading " + bedFile);
        final BedLineCodec bedLineCodec = new BedLineCodec();
        BufferedReader r = IOUtils.openFileForBufferedReading(bedFile);
        String line;
        while ((line = r.readLine()) != null) {
            final BedLine bedLine = bedLineCodec.decode(line);
            if (bedLine == null)
                continue;
            this.intervals.put(bedLine.toInterval(), true);
        }
        CloserUtil.close(r);
    } catch (final IOException err) {
        LOG.error(err);
        throw new RuntimeException(err);
    }
}
Also used : BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) BedLineCodec(com.github.lindenb.jvarkit.util.bio.bed.BedLineCodec) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine)

Example 7 with BedLine

use of com.github.lindenb.jvarkit.util.bio.bed.BedLine in project jvarkit by lindenb.

the class BedIndexTabix method run.

protected void run(LineIterator in) throws IOException {
    int bedLineCount = 0;
    File tbi = new File(outputFile.getPath() + TabixUtils.STANDARD_INDEX_EXTENSION);
    BlockCompressedOutputStream writer = null;
    SortingCollection<String> sorter = null;
    final Comparator<String> comparator = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            BedLine bed1 = bedCodec.decode(o1);
            BedLine bed2 = bedCodec.decode(o2);
            int i = bed1.getContig().compareTo(bed2.getContig());
            if (i != 0)
                return i;
            i = bed1.getStart() - bed2.getStart();
            if (i != 0)
                return i;
            i = bed1.getEnd() - bed2.getEnd();
            if (i != 0)
                return i;
            return o1.compareTo(o2);
        }
    };
    CloseableIterator<String> iter = null;
    try {
        TabixIndexCreator indexCreator = new TabixIndexCreator(TabixFormat.BED);
        LOG.info("Opening" + outputFile);
        writer = new BlockCompressedOutputStream(this.outputFile);
        StringBuilder header = new StringBuilder();
        while (in.hasNext()) {
            String h = in.peek();
            if (!BedLine.isBedHeader(h))
                break;
            header.append(in.next()).append('\n');
        }
        // write header
        if (header.length() > 0) {
            LOG.info("Writing header");
            writer.write(header.toString().getBytes());
        }
        if (this.sort) {
            LOG.info("Sorting");
            sorter = SortingCollection.newInstance(String.class, new BedDataCodec(), comparator, this.writingSortingCollection.getMaxRecordsInRam(), this.writingSortingCollection.getTmpPaths());
            while (in.hasNext()) {
                String line = in.next();
                BedLine bed = bedCodec.decode(line);
                if (bed == null)
                    continue;
                sorter.add(line);
            }
            sorter.doneAdding();
            sorter.setDestructiveIteration(true);
            iter = sorter.iterator();
            long filePosition = writer.getFilePointer();
            while (iter.hasNext()) {
                String line = iter.next();
                BedLine bed = this.bedCodec.decode(line);
                writer.write(line.getBytes());
                writer.write('\n');
                indexCreator.addFeature(bed, filePosition);
                filePosition = writer.getFilePointer();
            }
            sorter.cleanup();
        } else {
            long filePosition = writer.getFilePointer();
            while (in.hasNext()) {
                String line = in.next();
                BedLine bed = this.bedCodec.decode(line);
                if (bed == null)
                    continue;
                writer.write(line.getBytes());
                writer.write('\n');
                indexCreator.addFeature(bed, filePosition);
                filePosition = writer.getFilePointer();
            }
        }
        writer.flush();
        LOG.info("Creating index");
        Index index = indexCreator.finalizeIndex(writer.getFilePointer());
        LOG.info("Writing index to " + tbi + " using " + index.getClass());
        index.writeBasedOnFeatureFile(this.outputFile);
        writer.close();
        writer = null;
        LOG.info("Done  N=" + bedLineCount);
    } catch (Exception e) {
        if (this.outputFile.exists() && this.outputFile.isFile()) {
            LOG.warning("Deleting " + this.outputFile);
            this.outputFile.delete();
            if (tbi.exists() && tbi.isFile())
                tbi.delete();
        }
        throw new IOException(e);
    } finally {
        CloserUtil.close(iter);
        CloserUtil.close(sorter);
        CloserUtil.close(writer);
    }
}
Also used : BlockCompressedOutputStream(htsjdk.samtools.util.BlockCompressedOutputStream) TabixIndexCreator(htsjdk.tribble.index.tabix.TabixIndexCreator) Index(htsjdk.tribble.index.Index) IOException(java.io.IOException) IOException(java.io.IOException) Comparator(java.util.Comparator) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) File(java.io.File)

Example 8 with BedLine

use of com.github.lindenb.jvarkit.util.bio.bed.BedLine in project jvarkit by lindenb.

the class SamFindClippedRegions method doWork.

/*private static boolean closeTo(int pos1,int pos2, int max)
		{
		return Math.abs(pos2-pos1)<=max;
		}*/
/*
	private static boolean same(char c1,char c2)
		{
		if(c1=='N' || c2=='N') return false;
		return Character.toUpperCase(c1)==Character.toUpperCase(c2);
		}*/
@Override
public int doWork(List<String> args) {
    int readLength = 150;
    if (args.isEmpty()) {
        LOG.error("illegal.number.of.arguments");
        return -1;
    }
    List<Input> inputs = new ArrayList<Input>();
    VariantContextWriter w = null;
    // SAMFileWriter w=null;
    try {
        SAMSequenceDictionary dict = null;
        /* create input, collect sample names */
        Map<String, Input> sample2input = new HashMap<String, Input>();
        for (final String filename : args) {
            Input input = new Input(new File(filename));
            // input.index=inputs.size();
            inputs.add(input);
            if (sample2input.containsKey(input.sampleName)) {
                LOG.error("Duplicate sample " + input.sampleName + " in " + input.bamFile + " and " + sample2input.get(input.sampleName).bamFile);
                return -1;
            }
            sample2input.put(input.sampleName, input);
            if (dict == null) {
                dict = input.header.getSequenceDictionary();
            } else if (!SequenceUtil.areSequenceDictionariesEqual(dict, input.header.getSequenceDictionary())) {
                LOG.error("Found more than one dictint sequence dictionary");
                return -1;
            }
        }
        LOG.info("Sample N= " + sample2input.size());
        /* create merged iterator */
        List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(sample2input.size());
        for (Input input : inputs) headers.add(input.header);
        SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SortOrder.coordinate, headers, true);
        List<SamReader> readers = new ArrayList<SamReader>(sample2input.size());
        for (Input input : inputs) readers.add(input.samFileReaderScan);
        MergingSamRecordIterator merginIter = new MergingSamRecordIterator(headerMerger, readers, true);
        Allele reference_allele = Allele.create("N", true);
        Allele[] alternate_alleles = new Allele[] { Allele.create("<CLIP5>", false), Allele.create("<CLIP3>", false) };
        Set<VCFHeaderLine> vcfHeaderLines = new HashSet<VCFHeaderLine>();
        for (Allele alt : alternate_alleles) {
            vcfHeaderLines.add(new VCFSimpleHeaderLine("<ID=" + alt.getDisplayString() + ",Description=\"StructVar\">", VCFHeaderVersion.VCF4_1, VCFConstants.ALT_HEADER_START.substring(2), Arrays.asList("ID", "Description")));
        }
        vcfHeaderLines.add(new VCFInfoHeaderLine("COUNT_SAMPLES", 1, VCFHeaderLineType.Integer, "Number of samples with  depth>=" + this.min_depth));
        vcfHeaderLines.add(new VCFInfoHeaderLine(VCFConstants.DEPTH_KEY, 1, VCFHeaderLineType.Integer, "Approximate read depth."));
        vcfHeaderLines.add(new VCFFormatHeaderLine(VCFConstants.GENOTYPE_KEY, 1, VCFHeaderLineType.String, "Genotype"));
        vcfHeaderLines.add(new VCFFormatHeaderLine(VCFConstants.DEPTH_KEY, 1, VCFHeaderLineType.Integer, "Approximate read depth"));
        vcfHeaderLines.add(new VCFHeaderLine(getClass().getSimpleName() + "CmdLine", String.valueOf(getProgramCommandLine())));
        vcfHeaderLines.add(new VCFHeaderLine(getClass().getSimpleName() + "Version", String.valueOf(getVersion())));
        for (int side = 0; side < 2; ++side) {
            vcfHeaderLines.add(new VCFFormatHeaderLine("CN" + (side == 0 ? 5 : 3), 1, VCFHeaderLineType.Integer, "count clipped in " + (side == 0 ? 5 : 3) + "'"));
        }
        if (dict != null) {
            vcfHeaderLines.addAll(VCFUtils.samSequenceDictToVCFContigHeaderLine(dict));
        }
        VCFHeader vcfHeader = new VCFHeader(vcfHeaderLines, sample2input.keySet());
        w = VCFUtils.createVariantContextWriterToStdout();
        w.writeHeader(vcfHeader);
        final IntervalTreeMap<Boolean> intervals = new IntervalTreeMap<>();
        // w=swf.make(header, System.out);
        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict);
        if (bedFile != null) {
            final BedLineCodec bedLineCodec = new BedLineCodec();
            LOG.info("Reading " + bedFile);
            BufferedReader r = IOUtils.openFileForBufferedReading(bedFile);
            String line;
            while ((line = r.readLine()) != null) {
                BedLine bedLine = bedLineCodec.decode(line);
                if (bedLine == null)
                    continue;
                if (dict != null && dict.getSequence(bedLine.getContig()) == null) {
                    LOG.warning("undefined chromosome  in " + bedFile + " " + line);
                    continue;
                }
                intervals.put(bedLine.toInterval(), true);
            }
            CloserUtil.close(r);
        }
        LinkedList<SAMRecord> buffer = new LinkedList<SAMRecord>();
        final Predicate<SAMRecord> filterSamRecords = new Predicate<SAMRecord>() {

            @Override
            public boolean test(SAMRecord rec) {
                if (rec.getReadUnmappedFlag())
                    return false;
                if (rec.isSecondaryOrSupplementary())
                    return false;
                if (rec.getDuplicateReadFlag())
                    return false;
                if (rec.getReadFailsVendorQualityCheckFlag())
                    return false;
                Cigar cigar = rec.getCigar();
                if (cigar == null || cigar.numCigarElements() < 2)
                    return false;
                boolean found_S = false;
                for (int side = 0; side < 2; ++side) {
                    CigarElement ce = cigar.getCigarElement(side == 0 ? 0 : cigar.numCigarElements() - 1);
                    // read must be clipped on 5' or 3' with a good length
                    if (!ce.getOperator().equals(CigarOperator.S))
                        continue;
                    found_S = true;
                    break;
                }
                if (!found_S)
                    return false;
                SAMReadGroupRecord g = rec.getReadGroup();
                if (g == null || g.getSample() == null || g.getSample().isEmpty())
                    return false;
                return true;
            }
        };
        final FilteringIterator<SAMRecord> forwardIterator = new FilteringIterator<SAMRecord>(merginIter, filterSamRecords);
        for (; ; ) {
            SAMRecord rec = null;
            if (forwardIterator.hasNext()) {
                rec = forwardIterator.next();
                progress.watch(rec);
                if (intervals != null && !intervals.containsOverlapping(new Interval(rec.getReferenceName(), rec.getAlignmentStart(), rec.getAlignmentEnd())))
                    continue;
            }
            // need to flush buffer ?
            if (rec == null || (!buffer.isEmpty() && !buffer.getLast().getReferenceIndex().equals(rec.getReferenceIndex())) || (!buffer.isEmpty() && buffer.getLast().getUnclippedEnd() + readLength < rec.getUnclippedStart())) {
                if (!buffer.isEmpty()) {
                    int chromStart = buffer.getFirst().getUnclippedStart();
                    int chromEnd = buffer.getFirst().getUnclippedEnd();
                    for (SAMRecord sam : buffer) {
                        chromStart = Math.min(chromStart, sam.getUnclippedStart());
                        chromEnd = Math.max(chromEnd, sam.getUnclippedEnd());
                    }
                    final int winShift = 5;
                    for (int pos = chromStart; pos + winShift <= chromEnd; pos += winShift) {
                        int[] count_big_clip = new int[] { 0, 0 };
                        // int max_depth[]=new int[]{0,0};
                        List<Genotype> genotypes = new ArrayList<Genotype>();
                        Set<Allele> all_alleles = new HashSet<Allele>();
                        all_alleles.add(reference_allele);
                        boolean found_one_depth_ok = false;
                        int sum_depth = 0;
                        int samples_with_high_depth = 0;
                        for (String sample : sample2input.keySet()) {
                            GenotypeBuilder gb = new GenotypeBuilder(sample);
                            int[] count_clipped = new int[] { 0, 0 };
                            Set<Allele> sample_alleles = new HashSet<Allele>(3);
                            for (int side = 0; side < 2; ++side) {
                                for (SAMRecord sam : buffer) {
                                    if (!sam.getReadGroup().getSample().equals(sample))
                                        continue;
                                    Cigar cigar = sam.getCigar();
                                    CigarElement ce = cigar.getCigarElement(side == 0 ? 0 : cigar.numCigarElements() - 1);
                                    if (!ce.getOperator().equals(CigarOperator.S))
                                        continue;
                                    int clipStart = (side == 0 ? sam.getUnclippedStart() : sam.getAlignmentEnd() + 1);
                                    int clipEnd = (side == 0 ? sam.getAlignmentStart() - 1 : sam.getUnclippedEnd());
                                    if ((pos + winShift < clipStart || pos > clipEnd))
                                        continue;
                                    count_clipped[side]++;
                                    if (ce.getLength() >= this.min_clip_length) {
                                        count_big_clip[side]++;
                                    }
                                    sample_alleles.add(alternate_alleles[side]);
                                    gb.attribute("CN" + (side == 0 ? 5 : 3), count_clipped[side]);
                                }
                            }
                            // if(!(found_one_big_clip[0] || found_one_big_clip[1])) continue;
                            if (count_clipped[0] + count_clipped[1] == 0)
                                continue;
                            if ((count_clipped[0] + count_clipped[1]) > min_depth) {
                                found_one_depth_ok = true;
                                ++samples_with_high_depth;
                            }
                            sum_depth += (count_clipped[0] + count_clipped[1]);
                            gb.alleles(new ArrayList<Allele>(sample_alleles));
                            all_alleles.addAll(sample_alleles);
                            gb.DP(count_clipped[0] + count_clipped[1]);
                            genotypes.add(gb.make());
                        }
                        if (all_alleles.size() == 1) {
                            // all homozygotes
                            continue;
                        }
                        if (!found_one_depth_ok) {
                            continue;
                        }
                        if (!(count_big_clip[0] >= 1 || count_big_clip[1] >= 1)) {
                            continue;
                        }
                        Map<String, Object> atts = new HashMap<String, Object>();
                        atts.put("COUNT_SAMPLES", samples_with_high_depth);
                        atts.put(VCFConstants.DEPTH_KEY, sum_depth);
                        VariantContextBuilder vcb = new VariantContextBuilder();
                        vcb.chr(buffer.getFirst().getReferenceName());
                        vcb.start(pos);
                        vcb.stop(pos + winShift);
                        vcb.alleles(all_alleles);
                        vcb.attributes(atts);
                        vcb.genotypes(genotypes);
                        w.add(vcb.make());
                    }
                    buffer.clear();
                }
                if (rec == null) {
                    break;
                }
            }
            buffer.add(rec);
        }
        merginIter.close();
        progress.finish();
        return 0;
    } catch (Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        for (Input input : inputs) {
            CloserUtil.close(input);
        }
    }
}
Also used : VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VCFSimpleHeaderLine(htsjdk.variant.vcf.VCFSimpleHeaderLine) Predicate(java.util.function.Predicate) HashSet(java.util.HashSet) Genotype(htsjdk.variant.variantcontext.Genotype) GenotypeBuilder(htsjdk.variant.variantcontext.GenotypeBuilder) CigarElement(htsjdk.samtools.CigarElement) LinkedList(java.util.LinkedList) BedLineCodec(com.github.lindenb.jvarkit.util.bio.bed.BedLineCodec) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) SAMRecord(htsjdk.samtools.SAMRecord) SAMFileHeader(htsjdk.samtools.SAMFileHeader) File(java.io.File) Interval(htsjdk.samtools.util.Interval) MergingSamRecordIterator(htsjdk.samtools.MergingSamRecordIterator) SAMReadGroupRecord(htsjdk.samtools.SAMReadGroupRecord) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) SamReader(htsjdk.samtools.SamReader) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFHeader(htsjdk.variant.vcf.VCFHeader) VCFFormatHeaderLine(htsjdk.variant.vcf.VCFFormatHeaderLine) SamFileHeaderMerger(htsjdk.samtools.SamFileHeaderMerger) SAMSequenceDictionaryProgress(com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) IOException(java.io.IOException) Allele(htsjdk.variant.variantcontext.Allele) Cigar(htsjdk.samtools.Cigar) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) BufferedReader(java.io.BufferedReader) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap)

Example 9 with BedLine

use of com.github.lindenb.jvarkit.util.bio.bed.BedLine in project jvarkit by lindenb.

the class PcrSliceReads method doWork.

@Override
public int doWork(List<String> args) {
    if (bedFile == null) {
        LOG.error("undefined bed file");
        return -1;
    }
    BufferedReader r = null;
    SamReader samReader = null;
    try {
        samReader = super.openSamReader(oneFileOrNull(args));
        final BedLineCodec codec = new BedLineCodec();
        r = IOUtils.openFileForBufferedReading(bedFile);
        String line;
        while ((line = r.readLine()) != null) {
            final BedLine bed = codec.decode(line);
            if (bed == null)
                continue;
            final String chrom = bed.getContig();
            int chromStart1 = bed.getStart();
            int chromEnd1 = bed.getEnd();
            if (chromStart1 < 1 || chromStart1 > chromEnd1) {
                LOG.error("Bad bed line " + line);
                return -1;
            }
            final String name = bed.get(3).trim();
            if (name == null || name.isEmpty()) {
                LOG.error("Bad bed line (name missing) in  " + line);
                return -1;
            }
            final Interval i = new Interval(chrom, chromStart1, chromEnd1, false, name);
            this.bedIntervals.put(i, i);
        }
        return run(samReader);
    } catch (Exception e) {
        LOG.error(e);
        return -1;
    } finally {
        CloserUtil.close(r);
        CloserUtil.close(samReader);
    }
}
Also used : SamReader(htsjdk.samtools.SamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) BedLineCodec(com.github.lindenb.jvarkit.util.bio.bed.BedLineCodec) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) Interval(htsjdk.samtools.util.Interval)

Example 10 with BedLine

use of com.github.lindenb.jvarkit.util.bio.bed.BedLine in project jvarkit by lindenb.

the class PcrClipReads method doWork.

@Override
public int doWork(final List<String> args) {
    if (this.bedFile == null) {
        LOG.error("undefined bed file ");
        return -1;
    }
    BufferedReader r = null;
    SamReader samReader = null;
    try {
        final String inputName = oneFileOrNull(args);
        samReader = openSamReader(inputName);
        final SAMFileHeader header = samReader.getFileHeader();
        if (header == null) {
            LOG.error("No SAM header in input");
            return -1;
        }
        final SAMSequenceDictionary dict = header.getSequenceDictionary();
        LOG.info("reading bed File " + this.bedFile);
        r = IOUtils.openFileForBufferedReading(this.bedFile);
        String line;
        final BedLineCodec codec = new BedLineCodec();
        while ((line = r.readLine()) != null) {
            final BedLine bedLine = codec.decode(line);
            if (bedLine == null) {
                LOG.warn("Ignoring bed line " + line);
                continue;
            }
            if (dict != null) {
                if (dict.getSequenceIndex(bedLine.getContig()) == -1) {
                    LOG.warn("unknown contig in " + bedLine + ". Available are " + dict.getSequences().stream().map(SSR -> SSR.getSequenceName()).collect(Collectors.joining(", ")) + ". Skipping.");
                    continue;
                }
            }
            final Interval i = bedLine.toInterval();
            this.bedIntervals.put(i, i);
        }
        CloserUtil.close(r);
        r = null;
        return run(samReader);
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(r);
        CloserUtil.close(samReader);
        this.bedIntervals.clear();
        ;
    }
}
Also used : SamReader(htsjdk.samtools.SamReader) BufferedReader(java.io.BufferedReader) SAMFileHeader(htsjdk.samtools.SAMFileHeader) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) BedLineCodec(com.github.lindenb.jvarkit.util.bio.bed.BedLineCodec) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) Interval(htsjdk.samtools.util.Interval)

Aggregations

BedLine (com.github.lindenb.jvarkit.util.bio.bed.BedLine)19 BedLineCodec (com.github.lindenb.jvarkit.util.bio.bed.BedLineCodec)16 BufferedReader (java.io.BufferedReader)12 Interval (htsjdk.samtools.util.Interval)9 IOException (java.io.IOException)8 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)7 SamReader (htsjdk.samtools.SamReader)7 File (java.io.File)7 ArrayList (java.util.ArrayList)7 SAMFileHeader (htsjdk.samtools.SAMFileHeader)6 SAMSequenceDictionaryProgress (com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress)5 SAMRecord (htsjdk.samtools.SAMRecord)5 Parameter (com.beust.jcommander.Parameter)4 IOUtils (com.github.lindenb.jvarkit.io.IOUtils)4 JvarkitException (com.github.lindenb.jvarkit.lang.JvarkitException)4 Launcher (com.github.lindenb.jvarkit.util.jcommander.Launcher)4 Program (com.github.lindenb.jvarkit.util.jcommander.Program)4 Logger (com.github.lindenb.jvarkit.util.log.Logger)4 Cigar (htsjdk.samtools.Cigar)4 CigarElement (htsjdk.samtools.CigarElement)4