Search in sources :

Example 11 with ContigDictComparator

use of com.github.lindenb.jvarkit.util.samtools.ContigDictComparator in project jvarkit by lindenb.

the class IjgvdToVcf method doWork.

@Override
public int doWork(List<String> args) {
    try {
        final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(this.fai);
        this.ctgNameConverter = ContigNameConverter.fromOneDictionary(dict);
        List<Path> zipPaths = IOUtils.unrollPaths(args);
        List<CloseableIterator<VariantContext>> iterators = new ArrayList<>(zipPaths.size() * 2);
        for (final Path zipPath : zipPaths) {
            if (zipPath.getFileName().toString().endsWith(".tsv")) {
                String fname = zipPath.getFileName().toString();
                if (fname.endsWith("filtered.tsv") && skip_filtered) {
                    continue;
                }
                if (fname.endsWith("_multiallelic.tsv") && skip_multiallelic) {
                    continue;
                }
                final InputStream in = Files.newInputStream(zipPath);
                iterators.add(new ZipIterator(fname, in));
                continue;
            }
            for (int i = 0; i < 2; i++) {
                final ZipInputStream zin = new ZipInputStream(Files.newInputStream(zipPath));
                ZipEntry entry = null;
                ZipIterator zipIter = null;
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.getName().endsWith("filtered.tsv") && skip_filtered) {
                        zin.closeEntry();
                        continue;
                    }
                    if (entry.getName().endsWith("_multiallelic.tsv") && skip_multiallelic) {
                        zin.closeEntry();
                        continue;
                    }
                    if (i == 0 && !(entry.getName().endsWith("passed.tsv") || entry.getName().endsWith("multiallelic.tsv"))) {
                        zin.closeEntry();
                        continue;
                    }
                    if (i == 1 && !entry.getName().endsWith("filtered.tsv")) {
                        zin.closeEntry();
                        continue;
                    }
                    zipIter = new ZipIterator(entry.getName(), zin);
                    break;
                }
                if (zipIter == null) {
                    zin.close();
                } else {
                    iterators.add(zipIter);
                }
            }
        }
        final ContigDictComparator contigDictComparator = new ContigDictComparator(dict);
        final Comparator<VariantContext> comparator = (A, B) -> {
            int i = contigDictComparator.compare(A.getContig(), B.getContig());
            if (i != 0)
                return i;
            i = Integer.compare(A.getStart(), B.getStart());
            if (i != 0)
                return i;
            return A.getReference().compareTo(B.getReference());
        };
        final MergingIterator<VariantContext> iter = new MergingIterator<>(comparator, iterators);
        final VariantContextWriter vcw = writingVariantsDelegate.dictionary(dict).open(out);
        final Set<VCFHeaderLine> metaData = new HashSet<>();
        VCFStandardHeaderLines.addStandardInfoLines(metaData, true, VCFConstants.ALLELE_COUNT_KEY, VCFConstants.ALLELE_FREQUENCY_KEY, VCFConstants.ALLELE_NUMBER_KEY);
        metaData.add(new VCFInfoHeaderLine(REF_ALLELE_FREQ, 1, VCFHeaderLineType.Float, "Ref Allele Freq."));
        metaData.add(new VCFInfoHeaderLine(ALT_ALLELE_FREQ, 1, VCFHeaderLineType.Float, "Alt Allele Freq."));
        metaData.add(new VCFInfoHeaderLine(REF_ALLELE_COUNT, 1, VCFHeaderLineType.Integer, "Ref Allele count"));
        metaData.add(new VCFInfoHeaderLine(ALT_ALLELE_COUNT, 1, VCFHeaderLineType.Integer, "Alt Allele count."));
        metaData.add(new VCFInfoHeaderLine(TOTAL_ALLELES_COUNT, 1, VCFHeaderLineType.Integer, "Total allele count"));
        metaData.add(new VCFInfoHeaderLine(N_SAMPLES, 1, VCFHeaderLineType.Integer, "N samples"));
        metaData.add(new VCFFilterHeaderLine(MULTIALLELIC, "multiallelic"));
        metaData.add(new VCFFilterHeaderLine(FILTER1, "filtered in input"));
        VCFHeader header = new VCFHeader(metaData);
        header.setSequenceDictionary(dict);
        JVarkitVersion.getInstance().addMetaData(this, header);
        vcw.writeHeader(header);
        ProgressFactory.Watcher<VariantContext> progress = ProgressFactory.newInstance().dictionary(dict).logger(LOG).build();
        while (iter.hasNext()) {
            final VariantContext ctx = progress.apply(iter.next());
            vcw.add(ctx);
        }
        vcw.close();
        iter.close();
        progress.close();
        return 0;
    } catch (Exception e) {
        LOG.error(e);
        return -1;
    }
}
Also used : VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) IntStream(java.util.stream.IntStream) WritingVariantsDelegate(com.github.lindenb.jvarkit.variant.variantcontext.writer.WritingVariantsDelegate) CloseableIterator(htsjdk.samtools.util.CloseableIterator) Allele(htsjdk.variant.variantcontext.Allele) Arrays(java.util.Arrays) CharSplitter(com.github.lindenb.jvarkit.lang.CharSplitter) MergingIterator(htsjdk.samtools.util.MergingIterator) ZipInputStream(java.util.zip.ZipInputStream) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Parameter(com.beust.jcommander.Parameter) VCFStandardHeaderLines(htsjdk.variant.vcf.VCFStandardHeaderLines) VCFHeader(htsjdk.variant.vcf.VCFHeader) ParametersDelegate(com.beust.jcommander.ParametersDelegate) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOUtils(com.github.lindenb.jvarkit.io.IOUtils) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) CloserUtil(htsjdk.samtools.util.CloserUtil) VCFConstants(htsjdk.variant.vcf.VCFConstants) AbstractIterator(htsjdk.samtools.util.AbstractIterator) VCFFilterHeaderLine(htsjdk.variant.vcf.VCFFilterHeaderLine) VCFHeaderLineType(htsjdk.variant.vcf.VCFHeaderLineType) SequenceDictionaryUtils(com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils) Files(java.nio.file.Files) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) Logger(com.github.lindenb.jvarkit.util.log.Logger) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) Set(java.util.Set) IOException(java.io.IOException) JVarkitVersion(com.github.lindenb.jvarkit.util.JVarkitVersion) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) List(java.util.List) StringUtils(com.github.lindenb.jvarkit.lang.StringUtils) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) VariantContext(htsjdk.variant.variantcontext.VariantContext) BufferedReader(java.io.BufferedReader) Comparator(java.util.Comparator) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) InputStream(java.io.InputStream) VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) VariantContext(htsjdk.variant.variantcontext.VariantContext) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFFilterHeaderLine(htsjdk.variant.vcf.VCFFilterHeaderLine) VCFHeader(htsjdk.variant.vcf.VCFHeader) HashSet(java.util.HashSet) Path(java.nio.file.Path) CloseableIterator(htsjdk.samtools.util.CloseableIterator) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOException(java.io.IOException) MergingIterator(htsjdk.samtools.util.MergingIterator) ZipInputStream(java.util.zip.ZipInputStream)

Example 12 with ContigDictComparator

use of com.github.lindenb.jvarkit.util.samtools.ContigDictComparator in project jvarkit by lindenb.

the class FaidxSplitter method doWork.

@Override
public int doWork(final List<String> args) {
    try {
        if (this.faidx == null) {
            LOG.error("reference undefined");
            return -1;
        }
        if (window_size <= 0 || overlap_size >= window_size || this.small_size < 0) {
            LOG.info("bad parameters");
            return -1;
        }
        final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(this.faidx);
        final ContigNameConverter contigNameConverter = ContigNameConverter.fromOneDictionary(dict);
        final Pattern excludePat = Pattern.compile(this.excludeChromStr);
        final IntervalTreeMap<Interval> intervals1 = new IntervalTreeMap<>();
        dict.getSequences().stream().filter(R -> !excludePat.matcher(R.getSequenceName()).matches()).map(SSR -> new Interval(SSR)).forEach(I -> intervals1.put(I, I));
        if (intervals1.isEmpty()) {
            LOG.error("No sequence in dict after filtering.");
            return -1;
        }
        final IntervalTreeMap<Interval> geneMap = new IntervalTreeMap<>();
        final Function<Interval, Interval> findGene = I -> {
            final Collection<Interval> coll = geneMap.getOverlapping(I);
            if (coll.isEmpty())
                return null;
            final int min = coll.stream().mapToInt(G -> G.getStart()).min().getAsInt();
            final int max = coll.stream().mapToInt(G -> G.getEnd()).max().getAsInt();
            return new Interval(I.getContig(), min, max + this.overlap_size + 1);
        };
        if (this.geneSource != null) {
            LOG.info("loading genes " + this.geneSource);
            final Set<String> notFound = new HashSet<>();
            try (final BedLineReader br = new BedLineReader(IOUtils.openURIForBufferedReading(this.geneSource), this.geneSource)) {
                while (br.hasNext()) {
                    final BedLine gene = br.next();
                    if (gene == null)
                        continue;
                    final String contig2 = contigNameConverter.apply(gene.getContig());
                    if (StringUtil.isBlank(contig2)) {
                        if (notFound.add(gene.getContig()))
                            LOG.warn("gene contig not found :" + gene.getContig());
                        continue;
                    }
                    if (excludePat.matcher(contig2).matches())
                        continue;
                    final Interval g = new Interval(contig2, gene.getStart(), gene.getEnd());
                    if (geneMap.getOverlapping(g).stream().anyMatch(X -> X.contains(g)))
                        continue;
                    geneMap.put(g, g);
                }
            }
        }
        if (this.gapSource != null) {
            LOG.info("loading gaps " + this.gapSource);
            final Set<String> notFound = new HashSet<>();
            try (final BedLineReader br = new BedLineReader(IOUtils.openURIForBufferedReading(this.gapSource), this.gapSource)) {
                while (br.hasNext()) {
                    final BedLine gap0 = br.next();
                    final String contig2 = contigNameConverter.apply(gap0.getContig());
                    if (StringUtil.isBlank(contig2)) {
                        if (notFound.add(gap0.getContig()))
                            LOG.warn("gap contig not found :" + gap0.getContig());
                        continue;
                    }
                    if (excludePat.matcher(contig2).matches())
                        continue;
                    final Interval gap = new Interval(contig2, gap0.getStart(), gap0.getEnd());
                    final Collection<Interval> genes = geneMap.getOverlapping(gap);
                    for (final Interval gene_interval : genes) {
                        if (!gap.overlaps(gene_interval))
                            throw new IllegalStateException();
                        LOG.warn("gene " + gene_interval + " overlap gap " + gap + " " + this.split(gene_interval, gap));
                        geneMap.remove(gene_interval);
                        this.split(gene_interval, gap).forEach(N -> geneMap.put(N, N));
                    }
                    if (geneMap.containsOverlapping(gap))
                        throw new IllegalStateException();
                    final Collection<Interval> list = intervals1.getOverlapping(gap);
                    for (final Interval i : list) {
                        if (!gap.overlaps(i))
                            throw new IllegalStateException();
                        intervals1.remove(i);
                        this.split(i, gap).forEach(N -> intervals1.put(N, N));
                    }
                }
            }
        }
        final Comparator<String> contigCmp = new ContigDictComparator(dict);
        final List<Interval> intervalsList = new ArrayList<>(intervals1.values());
        intervalsList.sort((A, B) -> {
            final int i = contigCmp.compare(A.getContig(), B.getContig());
            if (i != 0)
                return i;
            return A.getStart() - B.getStart();
        });
        /* start writing output */
        try (PrintWriter pw = super.openPathOrStdoutAsPrintWriter(this.outputFile)) {
            for (final Interval interval : intervalsList) {
                if (interval.length() <= this.window_size) {
                    echo(pw, interval);
                    continue;
                }
                int start = interval.getStart();
                while (start < interval.getEnd()) {
                    int chromEnd = Math.min(interval.getEnd(), start + this.window_size);
                    // extend interval while there is a gene that shouldn't be broken */
                    for (; ; ) {
                        final Interval record = new Interval(interval.getContig(), start, chromEnd);
                        final Interval gene = findGene.apply(record);
                        // no gene
                        if (gene == null || record.contains(gene))
                            break;
                        if (gene.getStart() < record.getStart())
                            throw new IllegalStateException("gene start " + gene.getStart() + " < " + start + " " + "\ngene:\t" + gene + "\ninterval\t" + interval + "\nrecord\t" + record);
                        chromEnd = Math.min(interval.getEnd(), gene.getEnd());
                        if (chromEnd >= interval.getEnd())
                            break;
                    }
                    if (interval.getEnd() - chromEnd <= this.small_size) {
                        chromEnd = interval.getEnd();
                    }
                    echo(pw, new Interval(interval.getContig(), start, chromEnd));
                    if (chromEnd >= interval.getEnd())
                        break;
                    start = chromEnd - this.overlap_size + 1;
                }
            }
            pw.flush();
        }
        LOG.info("Done N=" + this.count_echoed);
        return 0;
    } catch (final Throwable err) {
        LOG.error(err);
        return -1;
    } finally {
    }
}
Also used : ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Parameter(com.beust.jcommander.Parameter) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BedLineReader(com.github.lindenb.jvarkit.bed.BedLineReader) Interval(htsjdk.samtools.util.Interval) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) DistanceParser(com.github.lindenb.jvarkit.util.bio.DistanceParser) NoSplitter(com.github.lindenb.jvarkit.util.jcommander.NoSplitter) StringUtil(htsjdk.samtools.util.StringUtil) IOUtils(com.github.lindenb.jvarkit.io.IOUtils) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) SequenceDictionaryUtils(com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap) Collection(java.util.Collection) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) Logger(com.github.lindenb.jvarkit.util.log.Logger) Set(java.util.Set) List(java.util.List) Pattern(java.util.regex.Pattern) Comparator(java.util.Comparator) Collections(java.util.Collections) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) BedLineReader(com.github.lindenb.jvarkit.bed.BedLineReader) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) BedLine(com.github.lindenb.jvarkit.util.bio.bed.BedLine) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) Collection(java.util.Collection) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap) Interval(htsjdk.samtools.util.Interval) HashSet(java.util.HashSet) PrintWriter(java.io.PrintWriter)

Example 13 with ContigDictComparator

use of com.github.lindenb.jvarkit.util.samtools.ContigDictComparator in project jvarkit by lindenb.

the class StarRetroCopy method doWork.

@Override
public int doWork(final List<String> args) {
    if (this.min_depth < 1) {
        LOG.error("Bad min depth");
        return -1;
    }
    PrintWriter saveInsertionsPw = null;
    SamReader sr = null;
    VariantContextWriter vcw0 = null;
    CloseableIterator<SAMRecord> iter = null;
    SAMFileWriter sfw = null;
    try {
        /* load the reference genome */
        /* create a contig name converter from the REF */
        // open the sam file
        final String input = oneFileOrNull(args);
        final SamReaderFactory srf = super.createSamReaderFactory();
        if (this.faidx != null)
            srf.referenceSequence(this.faidx);
        if (input != null) {
            sr = srf.open(SamInputResource.of(input));
            final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(sr.getFileHeader());
            /* READ KNOWGENES FILES */
            loadGTF(dict);
            if (this.use_bai && !sr.hasIndex()) {
                LOG.warning("Cannot used bai because input is not indexed");
            }
            // if there is a bai, only query the bam in the regions of splicing
            if (this.use_bai && sr.hasIndex()) {
                LOG.info("building intervals...");
                final QueryInterval[] intervals = this.intronTreeMap.keySet().stream().flatMap(intron -> {
                    // we need the reads overlapping the exon bounds
                    final int tid = dict.getSequenceIndex(intron.getContig());
                    final int extend = 1 + Math.max(0, this.minCigarSize);
                    final QueryInterval q1 = new QueryInterval(tid, Math.max(1, intron.getStart() - extend), intron.getStart() + extend);
                    final QueryInterval q2 = new QueryInterval(tid, Math.max(1, intron.getEnd() - extend), intron.getEnd() + extend);
                    return Arrays.stream(new QueryInterval[] { q1, q2 });
                }).sorted().collect(HtsCollectors.optimizedQueryIntervals());
                LOG.debug("Query bam using " + intervals.length + " random access intervals. Please wait...");
                iter = sr.queryOverlapping(intervals);
            } else {
                iter = sr.iterator();
            }
        } else {
            sr = srf.open(SamInputResource.of(stdin()));
            final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(sr.getFileHeader());
            /* READ GTF FILES */
            loadGTF(dict);
            iter = sr.iterator();
        }
        final SAMFileHeader samFileHeader = sr.getFileHeader();
        final SAMSequenceDictionary refDict = SequenceDictionaryUtils.extractRequired(samFileHeader);
        /* save gene writer */
        if (this.saveBedPeTo != null) {
            saveInsertionsPw = super.openPathOrStdoutAsPrintWriter(this.saveBedPeTo);
        } else {
            saveInsertionsPw = NullOuputStream.newPrintWriter();
        }
        if (this.saveBamTo != null) {
            sfw = new SAMFileWriterFactory().makeSAMOrBAMWriter(samFileHeader, true, this.saveBamTo);
        }
        final String sample = samFileHeader.getReadGroups().stream().map(RG -> RG.getSample()).filter(S -> !StringUtils.isBlank(S)).findFirst().orElse("SAMPLE");
        final ProgressFactory.Watcher<SAMRecord> progress = ProgressFactory.newInstance().dictionary(samFileHeader).logger(LOG).build();
        final String SAM_ATT_JI = "jI";
        while (iter.hasNext()) {
            final SAMRecord rec = progress.apply(iter.next());
            if (rec.getReadUnmappedFlag())
                continue;
            if (rec.getMappingQuality() < this.min_read_mapq)
                continue;
            if (rec.isSecondaryOrSupplementary())
                continue;
            if (rec.getDuplicateReadFlag())
                continue;
            if (rec.getReadFailsVendorQualityCheckFlag())
                continue;
            boolean save_read_to_bam = false;
            /* save read if it is not properly mapped (problem with size) and he and his mate surround an intron */
            if (rec.getReadPairedFlag() && !rec.getMateUnmappedFlag() && rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && !rec.getProperPairFlag() && /* MUST NOT be proper pair */
            rec.getReadNegativeStrandFlag() != rec.getMateNegativeStrandFlag()) {
                final SimpleInterval intronInterval;
                if (rec.getEnd() + 1 < rec.getMateAlignmentStart()) {
                    intronInterval = new SimpleInterval(rec.getContig(), rec.getEnd() + 1, rec.getMateAlignmentStart() - 1);
                } else if (SAMUtils.hasMateCigar(rec) && SAMUtils.getMateAlignmentEnd(rec) + 1 < rec.getAlignmentStart()) {
                    intronInterval = new SimpleInterval(rec.getContig(), SAMUtils.getMateAlignmentEnd(rec) + 1, rec.getAlignmentStart() - 1);
                } else {
                    intronInterval = null;
                }
                if (intronInterval != null) {
                    if (this.intronTreeMap.getOverlapping(intronInterval).stream().flatMap(L -> L.stream()).anyMatch(S -> intronInterval.contains(S))) {
                        save_read_to_bam = true;
                    }
                }
            }
            /* WE use STAR DATA */
            if (!this.use_cigar_string) {
                if (!rec.hasAttribute(SAM_ATT_JI))
                    continue;
                final Object tagValue = rec.getAttribute(SAM_ATT_JI);
                paranoid.assertTrue((tagValue instanceof int[]));
                final int[] bounds = (int[]) tagValue;
                // jI:B:i,-1
                if (bounds.length == 1 && bounds[0] < 0)
                    continue;
                if (bounds.length % 2 != 0) {
                    LOG.warn("bound.length%2!=0 with " + rec.getSAMString());
                    continue;
                }
                for (int i = 0; i < bounds.length; i += 2) {
                    int intron_start = bounds[i];
                    int intron_end = bounds[i + 1];
                    final Interval r = new Interval(rec.getContig(), intron_start, intron_end);
                    // don't use overlapping : with STAR it is strictly the intron boundaries
                    final List<Segment> introns = this.intronTreeMap.get(r);
                    if (introns == null)
                        continue;
                    save_read_to_bam = true;
                    for (final Segment intron : introns) {
                        intron.match++;
                    }
                }
            } else /* WE use other bam like bwa-mem */
            {
                final Cigar cigar = rec.getCigar();
                if (cigar == null || cigar.numCigarElements() < 2)
                    continue;
                int ref1 = rec.getAlignmentStart();
                for (final CigarElement ce : cigar.getCigarElements()) {
                    final CigarOperator op = ce.getOperator();
                    final int ref_end = ref1 + (op.consumesReferenceBases() ? ce.getLength() : 0);
                    if (op.equals(CigarOperator.N) || op.equals(CigarOperator.D)) {
                        final Interval r = new Interval(rec.getContig(), ref1, ref_end - 1);
                        final List<Segment> introns = this.intronTreeMap.get(r);
                        if (introns == null)
                            continue;
                        save_read_to_bam = true;
                        for (final Segment intron : introns) {
                            intron.match++;
                        }
                    }
                    ref1 = ref_end;
                }
                /**
                 * 2019-07-29. I tried using SA:Z:tag doesn't work well , so let's look a the clipping only
                 */
                if (cigar.isClipped()) {
                    for (int side = 0; side < 2; side++) {
                        final Interval r;
                        if (side == 0 && cigar.isRightClipped() && cigar.getLastCigarElement().getLength() >= this.minCigarSize) {
                            r = new Interval(rec.getContig(), rec.getEnd() + 1, rec.getEnd() + 1 + this.minCigarSize);
                        } else if (side == 1 && cigar.isLeftClipped() && cigar.getFirstCigarElement().getLength() >= this.minCigarSize) {
                            r = new Interval(rec.getContig(), Math.max(1, rec.getStart() - (1 + this.minCigarSize)), Math.max(1, rec.getStart() - (1)));
                        } else {
                            continue;
                        }
                        final int final_side = side;
                        final List<Segment> introns = this.intronTreeMap.getOverlapping(r).stream().flatMap(L -> L.stream()).filter(SEG -> isWithinIntronBound(SEG, r, final_side)).collect(Collectors.toList());
                        if (introns.isEmpty())
                            continue;
                        // System.err.println("SA for "+r+" "+rec.getReadName()+" "+introns.size());
                        save_read_to_bam = true;
                        for (final Segment intron : introns) {
                            intron.match++;
                        }
                    }
                }
            }
            if (save_read_to_bam) {
                saveInsertion(saveInsertionsPw, rec);
                if (sfw != null)
                    sfw.addAlignment(rec);
            }
        }
        final ContigDictComparator contigCmp = new ContigDictComparator(refDict);
        this.all_transcripts.removeIf(T -> T.segments.stream().noneMatch(S -> S.match >= min_depth));
        final int max_introns = this.all_transcripts.stream().mapToInt(K -> K.segments.size()).max().orElse(1);
        final List<String> intron_names = IntStream.range(0, max_introns).mapToObj(IDX -> String.format("%s_INTRON_%04d", sample, 1 + IDX)).collect(Collectors.toList());
        /**
         * build vcf header
         */
        final Set<VCFHeaderLine> metaData = new HashSet<>();
        metaData.add(VCFStandardHeaderLines.getFormatLine(VCFConstants.GENOTYPE_KEY, true));
        metaData.add(VCFStandardHeaderLines.getFormatLine(VCFConstants.GENOTYPE_QUALITY_KEY, true));
        metaData.add(VCFStandardHeaderLines.getFormatLine(VCFConstants.DEPTH_KEY, true));
        metaData.add(VCFStandardHeaderLines.getFormatLine(VCFConstants.GENOTYPE_ALLELE_DEPTHS, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.DEPTH_KEY, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_NUMBER_KEY, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_COUNT_KEY, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_COUNT_KEY, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_FREQUENCY_KEY, true));
        metaData.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.END_KEY, true));
        metaData.add(new VCFInfoHeaderLine(VCFConstants.SVTYPE, 1, VCFHeaderLineType.String, "Variation type"));
        metaData.add(new VCFInfoHeaderLine("SVLEN", 1, VCFHeaderLineType.Integer, "Variation Length"));
        for (final String att : ENSEMBL_TRANSCRIPT_ATTS) {
            metaData.add(new VCFInfoHeaderLine(att, 1, VCFHeaderLineType.String, "Value for the attribute '" + att + "' in the gtf"));
        }
        // metaData.add(new VCFFormatHeaderLine(ATT_COUNT_SUPPORTING_READS, 2,VCFHeaderLineType.Integer,"Count supporting reads [intron-left/intron-right]"));
        // metaData.add(new VCFInfoHeaderLine(ATT_RETRO_DESC, VCFHeaderLineCount.UNBOUNDED,VCFHeaderLineType.String,
        // "Retrocopy attributes: transcript-id|strand|exon-left|exon-left-bases|exon-right-bases|exon-right"));
        metaData.add(new VCFInfoHeaderLine(ATT_INTRONS_COUNT, 1, VCFHeaderLineType.Integer, "Number of introns for the Transcript"));
        metaData.add(new VCFInfoHeaderLine(ATT_INTRONS_CANDIDATE_COUNT, 1, VCFHeaderLineType.Integer, "Number of introns found retrocopied for the transcript"));
        metaData.add(new VCFInfoHeaderLine(ATT_INTRONS_CANDIDATE_FRACTION, 1, VCFHeaderLineType.Float, "Fraction of introns found retrocopied for the transcript"));
        metaData.add(new VCFFormatHeaderLine(INTRON_START, 1, VCFHeaderLineType.Integer, "Introns start"));
        metaData.add(new VCFFormatHeaderLine(INTRON_END, 1, VCFHeaderLineType.Integer, "Introns end"));
        metaData.add(new VCFFilterHeaderLine(ATT_LOW_DEPTH_FILTER + this.low_depth_threshold, "Number of read is lower than :" + this.min_depth));
        metaData.add(new VCFFilterHeaderLine(ATT_NOT_ALL_INTRONS, "Not all introns were found retrocopied"));
        final VCFHeader header = new VCFHeader(metaData, intron_names);
        JVarkitVersion.getInstance().addMetaData(this, header);
        header.setSequenceDictionary(refDict);
        /* open vcf for writing*/
        vcw0 = super.openVariantContextWriter(this.outputFile);
        final VariantContextWriter vcw = vcw0;
        vcw.writeHeader(header);
        Collections.sort(this.all_transcripts, (A, B) -> {
            int i = contigCmp.compare(A.getContig(), B.getContig());
            if (i != 0)
                return i;
            i = Integer.compare(A.getStart(), B.getStart());
            if (i != 0)
                return i;
            return Integer.compare(A.getEnd(), B.getEnd());
        });
        final Allele ref = Allele.create((byte) 'N', true);
        final Allele alt = Allele.create("<RETROCOPY>", false);
        for (final Transcript kg : this.all_transcripts) {
            // ok good candidate
            final VariantContextBuilder vcb = new VariantContextBuilder();
            vcb.chr(kg.getContig());
            vcb.start(kg.getStart());
            vcb.stop(kg.getEnd());
            vcb.id(kg.transcript_id);
            final List<Allele> alleles = Arrays.asList(ref, alt);
            final int max_depth = kg.segments.stream().mapToInt(X -> X.match).max().orElse(0);
            vcb.attribute(VCFConstants.DEPTH_KEY, max_depth);
            vcb.log10PError(max_depth / -10.0);
            boolean filter_set = false;
            if (max_depth < this.low_depth_threshold) {
                vcb.filter(ATT_LOW_DEPTH_FILTER + this.low_depth_threshold);
                filter_set = true;
            }
            vcb.attribute(VCFConstants.ALLELE_NUMBER_KEY, 2);
            vcb.attribute(VCFConstants.ALLELE_COUNT_KEY, 1);
            vcb.attribute(VCFConstants.ALLELE_FREQUENCY_KEY, 0.5);
            vcb.attribute(VCFConstants.SVTYPE, "DEL");
            vcb.attribute(VCFConstants.END_KEY, kg.getEnd());
            vcb.attribute("SVLEN", kg.getLengthOnReference());
            for (final String att : kg.attributes.keySet()) {
                vcb.attribute(att, VCFUtils.escapeInfoField(kg.attributes.get(att)));
            }
            vcb.alleles(alleles);
            // introns sequences
            vcb.attribute(ATT_INTRONS_CANDIDATE_COUNT, kg.segments.stream().filter(I -> I.match > 0).count());
            vcb.attribute(ATT_INTRONS_COUNT, kg.segments.size());
            vcb.attribute(ATT_INTRONS_CANDIDATE_FRACTION, kg.segments.stream().filter(I -> I.match > 0).count() / (float) kg.segments.size());
            if (kg.segments.stream().filter(I -> I.match > 0).count() != kg.segments.size()) {
                vcb.filter(ATT_NOT_ALL_INTRONS);
                filter_set = true;
            }
            final List<Genotype> genotypes = new ArrayList<>(kg.segments.size());
            /* build genotypes */
            for (int i = 0; i < kg.segments.size(); i++) {
                final Segment intron = kg.segments.get(i);
                final GenotypeBuilder gb = new GenotypeBuilder(intron_names.get(i), Arrays.asList(ref, alt));
                gb.DP(intron.match);
                gb.attribute(INTRON_START, intron.start);
                gb.attribute(INTRON_END, intron.end);
                genotypes.add(gb.make());
            }
            vcb.genotypes(genotypes);
            if (!filter_set) {
                vcb.passFilters();
            }
            vcw.add(vcb.make());
        }
        progress.close();
        vcw.close();
        iter.close();
        iter = null;
        sr.close();
        sr = null;
        saveInsertionsPw.flush();
        saveInsertionsPw.close();
        saveInsertionsPw = null;
        if (sfw != null) {
            sfw.close();
            sfw = null;
        }
        return 0;
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(iter);
        CloserUtil.close(sr);
        CloserUtil.close(vcw0);
        CloserUtil.close(sfw);
        CloserUtil.close(saveInsertionsPw);
    }
}
Also used : Allele(htsjdk.variant.variantcontext.Allele) Arrays(java.util.Arrays) Program(com.github.lindenb.jvarkit.util.jcommander.Program) VCFStandardHeaderLines(htsjdk.variant.vcf.VCFStandardHeaderLines) VCFHeader(htsjdk.variant.vcf.VCFHeader) CigarElement(htsjdk.samtools.CigarElement) CigarOperator(htsjdk.samtools.CigarOperator) SAMFileHeader(htsjdk.samtools.SAMFileHeader) Map(java.util.Map) Path(java.nio.file.Path) CloserUtil(htsjdk.samtools.util.CloserUtil) PrintWriter(java.io.PrintWriter) SimpleInterval(com.github.lindenb.jvarkit.samtools.util.SimpleInterval) SequenceDictionaryUtils(com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap) GenotypeBuilder(htsjdk.variant.variantcontext.GenotypeBuilder) Predicate(java.util.function.Predicate) Logger(com.github.lindenb.jvarkit.util.log.Logger) Set(java.util.Set) SAMFileWriter(htsjdk.samtools.SAMFileWriter) Collectors(java.util.stream.Collectors) GTFCodec(com.github.lindenb.jvarkit.util.bio.gtf.GTFCodec) SAMRecord(htsjdk.samtools.SAMRecord) List(java.util.List) StringUtils(com.github.lindenb.jvarkit.lang.StringUtils) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) SamReaderFactory(htsjdk.samtools.SamReaderFactory) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) IntStream(java.util.stream.IntStream) Genotype(htsjdk.variant.variantcontext.Genotype) VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) VCFUtils(com.github.lindenb.jvarkit.util.vcf.VCFUtils) Cigar(htsjdk.samtools.Cigar) CloseableIterator(htsjdk.samtools.util.CloseableIterator) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) SAMUtils(htsjdk.samtools.SAMUtils) Parameter(com.beust.jcommander.Parameter) NullOuputStream(com.github.lindenb.jvarkit.io.NullOuputStream) HtsCollectors(com.github.lindenb.jvarkit.stream.HtsCollectors) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) Interval(htsjdk.samtools.util.Interval) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOUtils(com.github.lindenb.jvarkit.io.IOUtils) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) VCFConstants(htsjdk.variant.vcf.VCFConstants) Locatable(htsjdk.samtools.util.Locatable) VCFFilterHeaderLine(htsjdk.variant.vcf.VCFFilterHeaderLine) VCFHeaderLineType(htsjdk.variant.vcf.VCFHeaderLineType) SAMFileWriterFactory(htsjdk.samtools.SAMFileWriterFactory) Files(java.nio.file.Files) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) IOException(java.io.IOException) JVarkitVersion(com.github.lindenb.jvarkit.util.JVarkitVersion) SamReader(htsjdk.samtools.SamReader) File(java.io.File) GtfReader(com.github.lindenb.jvarkit.util.bio.structure.GtfReader) SamInputResource(htsjdk.samtools.SamInputResource) QueryInterval(htsjdk.samtools.QueryInterval) VCFFormatHeaderLine(htsjdk.variant.vcf.VCFFormatHeaderLine) Paranoid(com.github.lindenb.jvarkit.lang.Paranoid) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) ArrayList(java.util.ArrayList) QueryInterval(htsjdk.samtools.QueryInterval) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) SamReader(htsjdk.samtools.SamReader) SimpleInterval(com.github.lindenb.jvarkit.samtools.util.SimpleInterval) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFFilterHeaderLine(htsjdk.variant.vcf.VCFFilterHeaderLine) VCFHeader(htsjdk.variant.vcf.VCFHeader) PrintWriter(java.io.PrintWriter) HashSet(java.util.HashSet) VCFFormatHeaderLine(htsjdk.variant.vcf.VCFFormatHeaderLine) SamReaderFactory(htsjdk.samtools.SamReaderFactory) SAMFileWriter(htsjdk.samtools.SAMFileWriter) SAMFileWriterFactory(htsjdk.samtools.SAMFileWriterFactory) Genotype(htsjdk.variant.variantcontext.Genotype) CigarOperator(htsjdk.samtools.CigarOperator) GenotypeBuilder(htsjdk.variant.variantcontext.GenotypeBuilder) CigarElement(htsjdk.samtools.CigarElement) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOException(java.io.IOException) Allele(htsjdk.variant.variantcontext.Allele) Cigar(htsjdk.samtools.Cigar) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) SAMRecord(htsjdk.samtools.SAMRecord) SAMFileHeader(htsjdk.samtools.SAMFileHeader) SimpleInterval(com.github.lindenb.jvarkit.samtools.util.SimpleInterval) Interval(htsjdk.samtools.util.Interval) QueryInterval(htsjdk.samtools.QueryInterval)

Example 14 with ContigDictComparator

use of com.github.lindenb.jvarkit.util.samtools.ContigDictComparator in project jvarkit by lindenb.

the class FindNewSpliceSites method doWork.

@Override
public int doWork(final List<String> args) {
    SamReader sfr = null;
    PrintWriter bedWriter = null;
    SortingCollection<Junction> junctionSorter = null;
    try {
        final SamReaderFactory srf = super.createSamReaderFactory();
        if (this.faidx != null) {
            srf.referenceSequence(this.faidx);
        }
        final String input = oneFileOrNull(args);
        sfr = input == null ? srf.open(SamInputResource.of(stdin())) : srf.open(SamInputResource.of(input));
        final SAMFileHeader header0 = sfr.getFileHeader();
        try (GtfReader gftReader = new GtfReader(this.gtfPath)) {
            SAMSequenceDictionary dict = header0.getSequenceDictionary();
            if (dict != null)
                gftReader.setContigNameConverter(ContigNameConverter.fromOneDictionary(dict));
            gftReader.getAllGenes().stream().flatMap(G -> G.getTranscripts().stream()).filter(T -> T.getExonCount() > 1).flatMap(T -> T.getIntrons().stream()).map(T -> T.toInterval()).forEach(T -> {
                this.intronMap.put(T, T);
            });
        }
        final SAMFileHeader header1 = header0.clone();
        final SAMProgramRecord p = header1.createProgramRecord();
        p.setCommandLine(getProgramCommandLine());
        p.setProgramVersion(getVersion());
        p.setProgramName(getProgramName());
        this.sfw = this.writingBamArgs.openSamWriter(outputFile, header1, true);
        final SAMFileHeader header2 = header0.clone();
        final SAMProgramRecord p2 = header2.createProgramRecord();
        p2.setCommandLine(getProgramCommandLine());
        p2.setProgramVersion(getVersion());
        p2.setProgramName(getProgramName());
        this.weird = this.writingBamArgs.createSAMFileWriterFactory().makeSAMWriter(header2, true, new NullOuputStream());
        if (this.bedOut != null) {
            final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(sfr.getFileHeader());
            this.junctionComparator = new ContigDictComparator(dict).createLocatableComparator();
            junctionSorter = SortingCollection.newInstance(Junction.class, new JunctionCodec(), (A, B) -> A.compare2(B), this.writingSortingCollection.getMaxRecordsInRam(), this.writingSortingCollection.getTmpPaths());
        }
        scan(sfr, p, p2, junctionSorter);
        sfr.close();
        if (this.bedOut != null) {
            junctionSorter.doneAdding();
            bedWriter = super.openPathOrStdoutAsPrintWriter(this.bedOut);
            final String sample = StringUtils.ifBlank(header0.getReadGroups().stream().map(RG -> RG.getSample()).filter(s -> !StringUtils.isBlank(s)).collect(Collectors.toCollection(TreeSet::new)).stream().collect(Collectors.joining(";")), ".");
            try (CloseableIterator<Junction> iter = junctionSorter.iterator()) {
                final EqualRangeIterator<Junction> eq = new EqualRangeIterator<>(iter, (A, B) -> A.compare1(B));
                while (eq.hasNext()) {
                    final List<Junction> row = eq.next();
                    final Junction first = row.get(0);
                    bedWriter.print(first.getContig());
                    bedWriter.print('\t');
                    bedWriter.print(first.getStart() - 1);
                    bedWriter.print('\t');
                    bedWriter.print(first.getEnd());
                    bedWriter.print('\t');
                    bedWriter.print(sample);
                    bedWriter.print('\t');
                    bedWriter.print(first.name);
                    bedWriter.print('\t');
                    bedWriter.print(row.size());
                    bedWriter.println();
                }
                eq.close();
            }
            bedWriter.flush();
            bedWriter.close();
            bedWriter = null;
            junctionSorter.cleanup();
        }
        return 0;
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(sfr);
        CloserUtil.close(this.sfw);
        CloserUtil.close(this.weird);
        CloserUtil.close(bedWriter);
    }
}
Also used : DataInputStream(java.io.DataInputStream) Cigar(htsjdk.samtools.Cigar) CloseableIterator(htsjdk.samtools.util.CloseableIterator) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Parameter(com.beust.jcommander.Parameter) NullOuputStream(com.github.lindenb.jvarkit.io.NullOuputStream) CigarElement(htsjdk.samtools.CigarElement) CigarOperator(htsjdk.samtools.CigarOperator) SAMFileHeader(htsjdk.samtools.SAMFileHeader) TreeSet(java.util.TreeSet) ParametersDelegate(com.beust.jcommander.ParametersDelegate) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) Interval(htsjdk.samtools.util.Interval) DataOutputStream(java.io.DataOutputStream) AbstractDataCodec(com.github.lindenb.jvarkit.util.picard.AbstractDataCodec) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) Path(java.nio.file.Path) CloserUtil(htsjdk.samtools.util.CloserUtil) PrintWriter(java.io.PrintWriter) SequenceDictionaryUtils(com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils) Locatable(htsjdk.samtools.util.Locatable) SortingCollection(htsjdk.samtools.util.SortingCollection) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap) SAMRecordIterator(htsjdk.samtools.SAMRecordIterator) Collection(java.util.Collection) Logger(com.github.lindenb.jvarkit.util.log.Logger) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) IOException(java.io.IOException) SAMFileWriter(htsjdk.samtools.SAMFileWriter) SamReader(htsjdk.samtools.SamReader) EOFException(java.io.EOFException) Collectors(java.util.stream.Collectors) GtfReader(com.github.lindenb.jvarkit.util.bio.structure.GtfReader) SAMRecord(htsjdk.samtools.SAMRecord) List(java.util.List) SamInputResource(htsjdk.samtools.SamInputResource) SAMProgramRecord(htsjdk.samtools.SAMProgramRecord) StringUtils(com.github.lindenb.jvarkit.lang.StringUtils) EqualRangeIterator(com.github.lindenb.jvarkit.util.iterator.EqualRangeIterator) Comparator(java.util.Comparator) SamReaderFactory(htsjdk.samtools.SamReaderFactory) SamReaderFactory(htsjdk.samtools.SamReaderFactory) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) EqualRangeIterator(com.github.lindenb.jvarkit.util.iterator.EqualRangeIterator) SAMProgramRecord(htsjdk.samtools.SAMProgramRecord) IOException(java.io.IOException) EOFException(java.io.EOFException) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) SamReader(htsjdk.samtools.SamReader) GtfReader(com.github.lindenb.jvarkit.util.bio.structure.GtfReader) TreeSet(java.util.TreeSet) NullOuputStream(com.github.lindenb.jvarkit.io.NullOuputStream) SAMFileHeader(htsjdk.samtools.SAMFileHeader) PrintWriter(java.io.PrintWriter)

Example 15 with ContigDictComparator

use of com.github.lindenb.jvarkit.util.samtools.ContigDictComparator in project jvarkit by lindenb.

the class RNASeqPolyA method doWork.

@Override
public int doWork(final List<String> args) {
    final Map<String, GeneInfo> geneToTrancripts = new HashMap<>();
    try {
        final String debugTranscript = dynaParams.getOrDefault("debug.transcript", "");
        final SAMSequenceDictionary dict = SequenceDictionaryUtils.extractRequired(this.faidx);
        if (!StringUtils.isBlank(this.limit_contig) && dict.getSequence(this.limit_contig) == null) {
            throw new JvarkitException.ContigNotFoundInDictionary(this.limit_contig, dict);
        }
        final ContigNameConverter converter = ContigNameConverter.fromOneDictionary(dict);
        final Gff3Codec gff3 = new Gff3Codec(Gff3Codec.DecodeDepth.DEEP);
        try (InputStream is = IOUtils.openPathForReading(this.gffPath)) {
            final AsciiLineReader asciiLineReader = AsciiLineReader.from(is);
            final LineIterator lr = new LineIteratorImpl(asciiLineReader);
            while (!gff3.isDone(lr)) {
                decodeGff3Feature(gff3.decode(lr), converter, geneToTrancripts);
            }
            gff3.close(lr);
            asciiLineReader.close();
        }
        if (geneToTrancripts.isEmpty()) {
            LOG.warn("no transcript was found.");
        // continue , empty VCF must be produced
        }
        final IntervalTreeMap<LastExon> exonMap = new IntervalTreeMap<>();
        // fill exonMap
        geneToTrancripts.values().stream().flatMap(K -> K.transcripts.values().stream()).forEach(X -> exonMap.put(new Interval(X), X));
        final ToIntFunction<String> toTid = C -> {
            final SAMSequenceRecord ssr = dict.getSequence(C);
            if (ssr == null)
                throw new JvarkitException.ContigNotFoundInDictionary(C, dict);
            return ssr.getSequenceIndex();
        };
        final List<Path> inputs = IOUtils.unrollPaths(args);
        final QueryInterval[] intervals = this.disable_bam_index || inputs.isEmpty() ? null : QueryInterval.optimizeIntervals(exonMap.values().stream().map(R -> new QueryInterval(toTid.applyAsInt(R.getContig()), R.getPosition(), R.getPosition())).toArray(N -> new QueryInterval[N]));
        final SamReaderFactory srf = super.createSamReaderFactory().referenceSequence(this.faidx);
        final String primerAAA;
        if (polyA_primer_size > 0) {
            primerAAA = StringUtils.repeat(this.polyA_primer_size, 'A');
        } else {
            primerAAA = null;
        }
        final Set<String> samples = new HashSet<>();
        int bam_index = 0;
        // loop over the bams
        for (; ; ) {
            final Path bamFilename = inputs.isEmpty() ? null : inputs.get(bam_index);
            try (SamReader sr = inputs.isEmpty() ? srf.open(SamInputResource.of(stdin())) : srf.open(bamFilename)) {
                final SAMFileHeader header0 = sr.getFileHeader();
                SequenceUtil.assertSequenceDictionariesEqual(dict, SequenceDictionaryUtils.extractRequired(header0));
                final String sample = header0.getReadGroups().stream().map(RG -> RG.getSample()).filter(S -> !StringUtils.isBlank(S)).findFirst().orElse(bamFilename == null ? "STDIN" : IOUtils.getFilenameWithoutCommonSuffixes(bamFilename));
                if (samples.contains(sample)) {
                    LOG.error("duplicate sample " + sample);
                    return -1;
                }
                samples.add(sample);
                final ProgressFactory.Watcher<SAMRecord> progress = ProgressFactory.newInstance().dictionary(dict).build();
                try (CloseableIterator<SAMRecord> iter = (intervals == null || inputs.isEmpty() ? /*stdin*/
                sr.iterator() : sr.query(intervals, false))) {
                    while (iter.hasNext()) {
                        final SAMRecord rec = progress.apply(iter.next());
                        if (rec.getReadUnmappedFlag())
                            continue;
                        if (!StringUtils.isBlank(this.limit_contig) && !rec.getContig().equals(this.limit_contig))
                            continue;
                        if (this.default_read_filter && !SAMRecordDefaultFilter.accept(rec))
                            continue;
                        final Collection<LastExon> lastExons = exonMap.getOverlapping(rec);
                        if (lastExons.isEmpty())
                            continue;
                        final Cigar cigar = rec.getCigar();
                        if (cigar == null || cigar.isEmpty())
                            continue;
                        final byte[] bases = rec.getReadBases();
                        if (bases == null || SAMRecord.NULL_SEQUENCE.equals(bases))
                            continue;
                        for (LastExon exon : lastExons) {
                            if (!StringUtils.isBlank(debugTranscript) && !exon.transcriptId.equals(debugTranscript)) {
                                continue;
                            }
                            ExonCount count = exon.sample2count.get(sample);
                            if (count == null) {
                                count = new ExonCount();
                                exon.sample2count.put(sample, count);
                            }
                            final StringBuilder sb = new StringBuilder();
                            boolean indel_flag = false;
                            boolean last_exon_in_intron_flag = false;
                            boolean match_last_base = false;
                            int ref1 = rec.getUnclippedStart();
                            int read0 = 0;
                            for (CigarElement ce : cigar) {
                                if (exon.isMinusStrand() && ref1 > exon.start)
                                    break;
                                if (this.ignore_with_indels && indel_flag)
                                    break;
                                final CigarOperator op = ce.getOperator();
                                switch(op) {
                                    case P:
                                        break;
                                    case I:
                                        indel_flag = true;
                                        for (int i = 0; i < ce.getLength(); i++) {
                                            if (exon.isAfterExon(ref1)) {
                                                sb.append((char) Character.toUpperCase(bases[read0]));
                                            }
                                            read0++;
                                        }
                                        break;
                                    case D:
                                    case N:
                                        if ((exon.isPlusStrand() && CoordMath.overlaps(ref1, ref1 + ce.getLength() - 1, exon.getEnd(), exon.getEnd() + 1)) || (exon.isMinusStrand() && CoordMath.overlaps(ref1, ref1 + ce.getLength() - 1, exon.getStart() - 1, exon.getStart()))) {
                                            last_exon_in_intron_flag = true;
                                        }
                                        ref1 += ce.getLength();
                                        indel_flag = true;
                                        break;
                                    case H:
                                        for (int i = 0; i < ce.getLength(); i++) {
                                            if (exon.isAfterExon(ref1)) {
                                                sb.append('N');
                                            }
                                            if (ref1 == exon.getPosition())
                                                match_last_base = true;
                                            ref1++;
                                        }
                                        break;
                                    case S:
                                    case M:
                                    case X:
                                    case EQ:
                                        for (int i = 0; i < ce.getLength(); i++) {
                                            if (exon.isAfterExon(ref1)) {
                                                sb.append((char) Character.toUpperCase(bases[read0]));
                                            }
                                            if (ref1 == exon.getPosition())
                                                match_last_base = true;
                                            read0++;
                                            ref1++;
                                        }
                                        break;
                                    default:
                                        throw new IllegalStateException(op.name());
                                }
                            }
                            // premature end or start
                            if (!match_last_base || (exon.isPlusStrand() && ref1 < exon.getEnd()) || (exon.isMinusStrand() && ref1 < exon.getStart()) || (this.ignore_with_indels && indel_flag) || last_exon_in_intron_flag) {
                                continue;
                            }
                            // if(read0!=bases.length) throw new IllegalStateException("read0:"+read0+" expected "+bases.length+" in "+rec.getReadName());
                            // if(ref1!=1+rec.getUnclippedEnd())throw new IllegalStateException("ref1:"+ref1+" expected 1+"+rec.getUnclippedEnd()+" in "+rec.getReadName());
                            ++count.n_tested_reads;
                            String polyA;
                            if (exon.isMinusStrand()) {
                                polyA = AcidNucleics.reverseComplement(sb);
                            } else {
                                polyA = sb.toString();
                            }
                            if (primerAAA != null) {
                                final int pos = polyA.indexOf(primerAAA);
                                if (pos > 0)
                                    polyA = polyA.substring(pos);
                            }
                            int count_polyA = 0;
                            for (int i = 0; i < polyA.length(); i++) {
                                if (polyA.charAt(i) != 'A')
                                    break;
                                count_polyA++;
                            }
                            if (count_polyA > 0) {
                                count.n_tested_reads_with_A++;
                                count.sum_polyA += count_polyA;
                            }
                            if (count_polyA > count.max_length_polyA) {
                                count.max_length_polyA = count_polyA;
                            }
                        }
                    // end of loop last exon
                    }
                    progress.close();
                }
            }
            ++bam_index;
            if (inputs.isEmpty() || bam_index >= inputs.size())
                break;
        }
        final Set<VCFHeaderLine> metaData = new HashSet<>();
        final VCFInfoHeaderLine infoGeneId = new VCFInfoHeaderLine("GENE", 1, VCFHeaderLineType.String, "Gene ID in " + this.gffPath);
        metaData.add(infoGeneId);
        final VCFInfoHeaderLine infoTranscriptId = new VCFInfoHeaderLine("TRANSCRIPT", 1, VCFHeaderLineType.String, "Transcript ID in " + this.gffPath);
        metaData.add(infoTranscriptId);
        final VCFInfoHeaderLine infoStrand = new VCFInfoHeaderLine("STRAND", 1, VCFHeaderLineType.String, "Strand");
        metaData.add(infoStrand);
        final VCFInfoHeaderLine infoTranscriptMaxPolyA = new VCFInfoHeaderLine("TRANSCRIPT_MAX", 1, VCFHeaderLineType.Integer, "Max poly A in Transcript");
        metaData.add(infoTranscriptMaxPolyA);
        final VCFInfoHeaderLine infoGeneMaxPolyA = new VCFInfoHeaderLine("GENE_MAX", 1, VCFHeaderLineType.Integer, "Max poly A in Gene");
        metaData.add(infoGeneMaxPolyA);
        final VCFInfoHeaderLine infoEndPos = new VCFInfoHeaderLine("POS3", 1, VCFHeaderLineType.Integer, "End 3 prime position");
        metaData.add(infoEndPos);
        final VCFInfoHeaderLine infoGeneName = new VCFInfoHeaderLine("GENE_NAME", 1, VCFHeaderLineType.String, "Gene Name");
        metaData.add(infoGeneName);
        final VCFInfoHeaderLine infoBiotype = new VCFInfoHeaderLine("GENE_BIOTYPE", 1, VCFHeaderLineType.String, "Gene Biotype");
        metaData.add(infoBiotype);
        final int n_last_exon_bases = Math.max(0, Integer.parseInt(dynaParams.getOrDefault("last.n.exons", "10")));
        final VCFInfoHeaderLine infoLastExonBases = new VCFInfoHeaderLine("LAST_BASES", 1, VCFHeaderLineType.String, "Last exon bases N=" + n_last_exon_bases + ". Reverse-complemented for negative strand.");
        metaData.add(infoLastExonBases);
        final int n_after_exon_bases = Math.max(0, Integer.parseInt(dynaParams.getOrDefault("after.n.exons", "10")));
        final VCFInfoHeaderLine infoAfterExonBases = new VCFInfoHeaderLine("AFTER_BASES", 1, VCFHeaderLineType.String, "Bases after exon N=" + n_after_exon_bases + ". Reverse-complemented for negative strand.");
        metaData.add(infoAfterExonBases);
        final VCFInfoHeaderLine infoOtherIdss = new VCFInfoHeaderLine("OTHER_IDS", VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "Other transcripts ending at the same coordinate.");
        metaData.add(infoOtherIdss);
        final VCFFormatHeaderLine fmtMaxPolyA = new VCFFormatHeaderLine("MAX", 1, VCFHeaderLineType.Integer, "Max poly A");
        metaData.add(fmtMaxPolyA);
        final VCFFormatHeaderLine fmtReadPolyA = new VCFFormatHeaderLine("DPA", 1, VCFHeaderLineType.Integer, "Read with at least one A");
        metaData.add(fmtReadPolyA);
        final VCFFormatHeaderLine fmtAveragePolyA = new VCFFormatHeaderLine("AVG", 1, VCFHeaderLineType.Float, "average length of poly-A for reads carrying at least one A.");
        metaData.add(fmtAveragePolyA);
        VCFStandardHeaderLines.addStandardInfoLines(metaData, true, VCFConstants.DEPTH_KEY, VCFConstants.END_KEY);
        VCFStandardHeaderLines.addStandardFormatLines(metaData, true, VCFConstants.DEPTH_KEY);
        final VCFHeader header = new VCFHeader(metaData, samples.stream().sorted().collect(Collectors.toList()));
        header.setSequenceDictionary(dict);
        JVarkitVersion.getInstance().addMetaData(this, header);
        final UnaryOperator<String> afterColon = S -> {
            if (!(S.startsWith("gene:") || S.startsWith("transcript:")))
                return S;
            int colon = S.indexOf(":");
            return S.substring(colon + 1);
        };
        final List<Allele> ALLELES = Collections.singletonList(Allele.create("N", true));
        try (VariantContextWriter w = writingVariantsDelegate.dictionary(dict).open(this.outputFile);
            ReferenceSequenceFile fai = ReferenceSequenceFileFactory.getReferenceSequenceFile(this.faidx)) {
            w.writeHeader(header);
            exonMap.values().stream().sorted(new ContigDictComparator(dict).createLocatableComparator()).forEach(T -> {
                if (T.getDP() == 0)
                    return;
                final String lastBases;
                final String afterBases;
                if (T.isPlusStrand()) {
                    lastBases = fai.getSubsequenceAt(T.getContig(), Math.max(T.getStart(), T.getEnd() - n_last_exon_bases), T.getEnd()).getBaseString();
                    final SAMSequenceRecord ssr = Objects.requireNonNull(dict.getSequence(T.getContig()));
                    afterBases = fai.getSubsequenceAt(T.getContig(), T.getEnd() + 1, Math.min(T.getEnd() + n_after_exon_bases, ssr.getLengthOnReference())).getBaseString();
                } else if (T.isMinusStrand()) {
                    lastBases = AcidNucleics.reverseComplement(fai.getSubsequenceAt(T.getContig(), T.getStart(), Math.min(T.getEnd(), T.getStart() + n_last_exon_bases)).getBaseString());
                    afterBases = AcidNucleics.reverseComplement(fai.getSubsequenceAt(T.getContig(), Math.max(1, T.getStart() - n_after_exon_bases), T.getStart() - 1).getBaseString());
                } else {
                    lastBases = null;
                    afterBases = null;
                }
                final VariantContextBuilder vcb = new VariantContextBuilder();
                vcb.chr(T.getContig());
                vcb.start(T.getStart());
                vcb.stop(T.getEnd());
                vcb.id(afterColon.apply(T.transcriptId));
                vcb.attribute(VCFConstants.END_KEY, T.getEnd());
                vcb.attribute(infoGeneId.getID(), afterColon.apply(T.gene.geneId));
                vcb.attribute(infoTranscriptId.getID(), afterColon.apply(T.transcriptId));
                vcb.attribute(infoStrand.getID(), T.strand.name());
                vcb.attribute(infoEndPos.getID(), T.getPosition());
                if (T.otherIds != null && !T.otherIds.isEmpty()) {
                    vcb.attribute(infoOtherIdss.getID(), T.otherIds.stream().map(afterColon).collect(Collectors.toList()));
                }
                if (!StringUtils.isBlank(lastBases)) {
                    vcb.attribute(infoLastExonBases.getID(), lastBases);
                }
                if (!StringUtils.isBlank(afterBases)) {
                    vcb.attribute(infoAfterExonBases.getID(), afterBases);
                }
                if (!StringUtils.isBlank(T.gene.geneName)) {
                    vcb.attribute(infoGeneName.getID(), T.gene.geneName);
                }
                if (!StringUtils.isBlank(T.gene.biotype)) {
                    vcb.attribute(infoBiotype.getID(), T.gene.biotype);
                }
                final List<Genotype> genotypes = new ArrayList<>(samples.size());
                for (String sn : samples) {
                    final ExonCount count = T.sample2count.get(sn);
                    final GenotypeBuilder gb = new GenotypeBuilder(sn);
                    gb.attribute(fmtMaxPolyA.getID(), count == null ? 0 : count.max_length_polyA);
                    gb.attribute(fmtReadPolyA.getID(), count == null ? 0 : count.n_tested_reads_with_A);
                    gb.attribute(fmtAveragePolyA.getID(), count == null || count.n_tested_reads_with_A == 0 ? 0f : count.sum_polyA / (float) count.n_tested_reads_with_A);
                    gb.DP(count == null ? 0 : count.n_tested_reads);
                    genotypes.add(gb.make());
                }
                vcb.alleles(ALLELES);
                vcb.genotypes(genotypes);
                vcb.attribute(VCFConstants.DEPTH_KEY, T.getDP());
                final int score = T.getMaxPolyA();
                if (score > 0)
                    vcb.log10PError(score / -10.0);
                vcb.attribute(infoTranscriptMaxPolyA.getID(), score);
                vcb.attribute(infoGeneMaxPolyA.getID(), T.gene.getmaxPolyA());
                w.add(vcb.make());
            });
        }
        return 0;
    } catch (final Throwable err) {
        LOG.error(err);
        return -1;
    } finally {
    }
}
Also used : WritingVariantsDelegate(com.github.lindenb.jvarkit.variant.variantcontext.writer.WritingVariantsDelegate) AsciiLineReader(htsjdk.tribble.readers.AsciiLineReader) Allele(htsjdk.variant.variantcontext.Allele) Program(com.github.lindenb.jvarkit.util.jcommander.Program) LineIterator(htsjdk.tribble.readers.LineIterator) VCFStandardHeaderLines(htsjdk.variant.vcf.VCFStandardHeaderLines) VCFHeader(htsjdk.variant.vcf.VCFHeader) BiFunction(java.util.function.BiFunction) CigarElement(htsjdk.samtools.CigarElement) CigarOperator(htsjdk.samtools.CigarOperator) UnaryOperator(java.util.function.UnaryOperator) SAMFileHeader(htsjdk.samtools.SAMFileHeader) ReferenceSequenceFile(htsjdk.samtools.reference.ReferenceSequenceFile) Map(java.util.Map) Path(java.nio.file.Path) SequenceDictionaryUtils(com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap) GenotypeBuilder(htsjdk.variant.variantcontext.GenotypeBuilder) Collection(java.util.Collection) Logger(com.github.lindenb.jvarkit.util.log.Logger) Set(java.util.Set) Collectors(java.util.stream.Collectors) JvarkitException(com.github.lindenb.jvarkit.lang.JvarkitException) SAMRecord(htsjdk.samtools.SAMRecord) LineIteratorImpl(htsjdk.tribble.readers.LineIteratorImpl) Objects(java.util.Objects) ReferenceSequenceFileFactory(htsjdk.samtools.reference.ReferenceSequenceFileFactory) List(java.util.List) StringUtils(com.github.lindenb.jvarkit.lang.StringUtils) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) CoordMath(htsjdk.samtools.util.CoordMath) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) VCFHeaderLineCount(htsjdk.variant.vcf.VCFHeaderLineCount) SamReaderFactory(htsjdk.samtools.SamReaderFactory) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) Genotype(htsjdk.variant.variantcontext.Genotype) VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) Cigar(htsjdk.samtools.Cigar) CloseableIterator(htsjdk.samtools.util.CloseableIterator) SequenceUtil(htsjdk.samtools.util.SequenceUtil) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) Parameter(com.beust.jcommander.Parameter) AcidNucleics(com.github.lindenb.jvarkit.util.bio.AcidNucleics) HashMap(java.util.HashMap) ParametersDelegate(com.beust.jcommander.ParametersDelegate) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) Interval(htsjdk.samtools.util.Interval) Strand(htsjdk.tribble.annotation.Strand) SAMRecordDefaultFilter(com.github.lindenb.jvarkit.samtools.SAMRecordDefaultFilter) IOUtils(com.github.lindenb.jvarkit.io.IOUtils) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) VCFConstants(htsjdk.variant.vcf.VCFConstants) Gff3Feature(htsjdk.tribble.gff.Gff3Feature) Locatable(htsjdk.samtools.util.Locatable) VCFHeaderLineType(htsjdk.variant.vcf.VCFHeaderLineType) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) ToIntFunction(java.util.function.ToIntFunction) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) JVarkitVersion(com.github.lindenb.jvarkit.util.JVarkitVersion) SamReader(htsjdk.samtools.SamReader) SamInputResource(htsjdk.samtools.SamInputResource) Gff3Codec(htsjdk.tribble.gff.Gff3Codec) QueryInterval(htsjdk.samtools.QueryInterval) DynamicParameter(com.beust.jcommander.DynamicParameter) VCFFormatHeaderLine(htsjdk.variant.vcf.VCFFormatHeaderLine) SAMSequenceRecord(htsjdk.samtools.SAMSequenceRecord) Collections(java.util.Collections) InputStream(java.io.InputStream) VCFHeaderLine(htsjdk.variant.vcf.VCFHeaderLine) HashMap(java.util.HashMap) ProgressFactory(com.github.lindenb.jvarkit.util.log.ProgressFactory) ArrayList(java.util.ArrayList) SAMSequenceRecord(htsjdk.samtools.SAMSequenceRecord) ReferenceSequenceFile(htsjdk.samtools.reference.ReferenceSequenceFile) LineIteratorImpl(htsjdk.tribble.readers.LineIteratorImpl) ContigNameConverter(com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter) HashSet(java.util.HashSet) AsciiLineReader(htsjdk.tribble.readers.AsciiLineReader) Genotype(htsjdk.variant.variantcontext.Genotype) CigarOperator(htsjdk.samtools.CigarOperator) GenotypeBuilder(htsjdk.variant.variantcontext.GenotypeBuilder) CigarElement(htsjdk.samtools.CigarElement) SAMRecord(htsjdk.samtools.SAMRecord) SAMFileHeader(htsjdk.samtools.SAMFileHeader) Interval(htsjdk.samtools.util.Interval) QueryInterval(htsjdk.samtools.QueryInterval) QueryInterval(htsjdk.samtools.QueryInterval) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) LineIterator(htsjdk.tribble.readers.LineIterator) ContigDictComparator(com.github.lindenb.jvarkit.util.samtools.ContigDictComparator) SamReader(htsjdk.samtools.SamReader) VariantContextWriter(htsjdk.variant.variantcontext.writer.VariantContextWriter) VCFHeader(htsjdk.variant.vcf.VCFHeader) VCFFormatHeaderLine(htsjdk.variant.vcf.VCFFormatHeaderLine) Path(java.nio.file.Path) SamReaderFactory(htsjdk.samtools.SamReaderFactory) InputStream(java.io.InputStream) VCFInfoHeaderLine(htsjdk.variant.vcf.VCFInfoHeaderLine) Allele(htsjdk.variant.variantcontext.Allele) Gff3Codec(htsjdk.tribble.gff.Gff3Codec) Cigar(htsjdk.samtools.Cigar) VariantContextBuilder(htsjdk.variant.variantcontext.VariantContextBuilder) IntervalTreeMap(htsjdk.samtools.util.IntervalTreeMap)

Aggregations

ContigDictComparator (com.github.lindenb.jvarkit.util.samtools.ContigDictComparator)28 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)26 Parameter (com.beust.jcommander.Parameter)25 Program (com.github.lindenb.jvarkit.util.jcommander.Program)25 Logger (com.github.lindenb.jvarkit.util.log.Logger)25 Path (java.nio.file.Path)25 List (java.util.List)25 Collectors (java.util.stream.Collectors)23 Launcher (com.github.lindenb.jvarkit.util.jcommander.Launcher)22 ArrayList (java.util.ArrayList)22 Set (java.util.Set)20 HashSet (java.util.HashSet)19 IOUtils (com.github.lindenb.jvarkit.io.IOUtils)18 SequenceDictionaryUtils (com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils)18 StringUtils (com.github.lindenb.jvarkit.lang.StringUtils)17 VCFHeader (htsjdk.variant.vcf.VCFHeader)17 ContigNameConverter (com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter)16 CloserUtil (htsjdk.samtools.util.CloserUtil)16 VariantContextBuilder (htsjdk.variant.variantcontext.VariantContextBuilder)16 VariantContextWriter (htsjdk.variant.variantcontext.writer.VariantContextWriter)16