Search in sources :

Example 21 with VcfIterator

use of com.github.lindenb.jvarkit.util.vcf.VcfIterator in project jvarkit by lindenb.

the class NgsFilesSummary method readVCF.

@Override
protected void readVCF(final File f) {
    if (!f.canRead())
        return;
    LOG.debug("readVCF  " + f);
    VcfIterator r = null;
    InputStream in = null;
    try {
        in = IOUtils.openFileForReading(f);
        r = new VcfIteratorImpl(in);
        VCFHeader header = r.getHeader();
        for (final String sample : header.getSampleNamesInOrder()) {
            print(sample, InfoType.VCF, f);
        }
    } catch (final Exception err) {
        LOG.error(err);
    } finally {
        CloserUtil.close(r);
        CloserUtil.close(in);
    }
}
Also used : VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) VcfIteratorImpl(com.github.lindenb.jvarkit.util.vcf.VcfIteratorImpl) InputStream(java.io.InputStream) VCFHeader(htsjdk.variant.vcf.VCFHeader) IOException(java.io.IOException)

Example 22 with VcfIterator

use of com.github.lindenb.jvarkit.util.vcf.VcfIterator in project jvarkit by lindenb.

the class VcfPhyloTree method doWork.

@Override
public int doWork(final List<String> args) {
    VcfIterator iter = null;
    try {
        iter = super.openVcfIterator(oneFileOrNull(args));
        final List<SampleNode> samplesNodes = new ArrayList<>(iter.getHeader().getSampleNamesInOrder().stream().map(S -> new OneSampleNode(S)).collect(Collectors.toList()));
        if (samplesNodes.size() < 3) {
            LOG.error("expected at least 3 samples in input");
            return -1;
        }
        final List<List<Call>> variants = new ArrayList<>();
        while (iter.hasNext()) {
            final VariantContext ctx = iter.next();
            final int n_nocall = (int) ctx.getGenotypes().stream().filter(G -> G.isNoCall()).count();
            final int n_homref = (int) ctx.getGenotypes().stream().filter(G -> G.isHomRef()).count();
            if (n_nocall + n_homref == ctx.getNSamples())
                continue;
            final List<Call> row = new ArrayList<>(ctx.getNSamples());
            for (int i = 0; i < samplesNodes.size(); i++) {
                row.add(new Call(ctx.getGenotype(i)));
            }
            variants.add(row);
        }
        iter.close();
        iter = null;
        while (samplesNodes.size() > 1) {
            LOG.info("Iteration N=" + samplesNodes.size() + " / variants:" + variants.size());
            int best_x1 = -1;
            int best_x2 = -1;
            double best_distance = -1;
            for (int x1 = 0; x1 + 1 < samplesNodes.size(); ++x1) {
                for (int x2 = x1 + 1; x2 < samplesNodes.size(); ++x2) {
                    double distance = 0;
                    for (final List<Call> row : variants) {
                        final Call c1 = row.get(x1);
                        final Call c2 = row.get(x2);
                        distance += c1.distance(c2);
                    }
                    if (best_distance == -1 || best_distance > distance) {
                        best_distance = distance;
                        best_x1 = x1;
                        best_x2 = x2;
                    }
                }
            }
            final List<SampleNode> newSampleNodes = new ArrayList<>(samplesNodes.size() - 1);
            for (int x1 = 0; x1 < samplesNodes.size(); ++x1) {
                if (x1 == best_x1 || x1 == best_x2)
                    continue;
                newSampleNodes.add(samplesNodes.get(x1));
            }
            LOG.info("Merging\n\t" + samplesNodes.get(best_x1) + "\nand\n\t" + samplesNodes.get(best_x2) + "\ndistance\n\t" + best_distance);
            newSampleNodes.add(new MergeSampleNode(samplesNodes.get(best_x1), samplesNodes.get(best_x2), best_distance));
            for (int y = 0; y < variants.size(); ++y) {
                final List<Call> row = variants.get(y);
                final List<Call> newrow = new ArrayList<>(samplesNodes.size() - 1);
                for (int x1 = 0; x1 < samplesNodes.size(); ++x1) {
                    if (x1 == best_x1 || x1 == best_x2)
                        continue;
                    newrow.add(row.get(x1));
                }
                newrow.add(new Call(row.get(best_x1), row.get(best_x2)));
                variants.set(y, newrow);
            }
            samplesNodes.clear();
            samplesNodes.addAll(newSampleNodes);
        }
        System.out.println("digraph G {");
        samplesNodes.get(0).printDot(System.out);
        System.out.println("}");
        LOG.info("Done");
        return 0;
    } catch (final Throwable err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(iter);
    }
}
Also used : ArrayList(java.util.ArrayList) VariantContext(htsjdk.variant.variantcontext.VariantContext) VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 23 with VcfIterator

use of com.github.lindenb.jvarkit.util.vcf.VcfIterator in project jvarkit by lindenb.

the class SplitVcf method doWork.

private int doWork(final String inputName) {
    if (this.outputFile == null || !this.outputFile.getName().contains(REPLACE_GROUPID)) {
        throw new JvarkitException.UserError("Output file pattern undefined or doesn't contain " + REPLACE_GROUPID + " : " + this.outputFile);
    }
    if (!(this.outputFile.getName().endsWith(".vcf") || this.outputFile.getName().endsWith(".vcf.gz"))) {
        throw new JvarkitException.UserError("output file must end with '.vcf' or '.vcf.gz'");
    }
    BufferedReader r = null;
    VcfIterator in = null;
    try {
        in = openVcfIterator(inputName);
        final SAMSequenceDictionary samSequenceDictionary = in.getHeader().getSequenceDictionary();
        if (samSequenceDictionary == null) {
            throw new JvarkitException.VcfDictionaryMissing(inputName == null ? "<input>" : inputName);
        }
        this.underminedGroup = new SplitGroup(UNDERTERMINED_NAME);
        this.name2group.put(UNDERTERMINED_NAME, this.underminedGroup);
        if (this.chromGroupFile != null) {
            r = IOUtils.openFileForBufferedReading(this.chromGroupFile);
            String line;
            while ((line = r.readLine()) != null) {
                if (line.isEmpty() || line.startsWith("#"))
                    continue;
                final String[] tokens = line.split("[ \t,]+");
                final String groupName = tokens[0].trim();
                if (groupName.isEmpty())
                    throw new JvarkitException.UserError("Empty group name in " + line);
                if (this.UNDERTERMINED_NAME.equals(groupName))
                    throw new JvarkitException.UserError("Group cannot be named " + UNDERTERMINED_NAME);
                if (this.name2group.containsKey(groupName))
                    throw new JvarkitException.UserError("Group defined twice " + groupName);
                for (int i = 1; i < tokens.length; i++) {
                    String sequence;
                    int start;
                    int end;
                    final String segment = tokens[i].trim();
                    if (segment.isEmpty())
                        continue;
                    int colon = segment.indexOf(':');
                    if (colon == -1) {
                        final SAMSequenceRecord ssr = samSequenceDictionary.getSequence(segment);
                        if (ssr == null) {
                            throw new JvarkitException.ContigNotFoundInDictionary(segment, samSequenceDictionary);
                        }
                        sequence = segment;
                        start = 1;
                        end = ssr.getSequenceLength();
                    } else {
                        int hyphen = segment.indexOf('-', colon);
                        if (hyphen == -1)
                            throw new JvarkitException.UserError("Bad segment:" + segment);
                        sequence = segment.substring(0, colon);
                        if (samSequenceDictionary.getSequence(sequence) == null)
                            throw new JvarkitException.UserError("Unknown chromosome , not in dict " + segment);
                        start = Integer.parseInt(segment.substring(colon + 1, hyphen));
                        end = Integer.parseInt(segment.substring(hyphen + 1));
                    }
                    final Interval interval = new Interval(sequence, start, end);
                    this.putInterval(groupName, interval);
                }
            }
            r.close();
            r = null;
        } else {
            LOG.info("creating default split interval");
            for (final SAMSequenceRecord seq : samSequenceDictionary.getSequences()) {
                final String groupName = seq.getSequenceName();
                final Interval interval = new Interval(groupName, 1, seq.getSequenceLength());
                this.putInterval(groupName, interval);
            }
        }
        /* open all output vcf */
        for (final SplitGroup g : this.name2group.values()) {
            g.open(in.getHeader());
        }
        /* loop over vcf variations */
        final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(samSequenceDictionary);
        while (in.hasNext()) {
            final VariantContext record = progress.watch(in.next());
            final Interval interval = new Interval(record.getContig(), record.getStart(), record.getEnd());
            Set<SplitGroup> splitGroups = this.getGroupsFromInterval(interval);
            if (splitGroups.isEmpty()) {
                splitGroups = Collections.singleton(this.underminedGroup);
            }
            for (final SplitGroup splitGroup : splitGroups) {
                splitGroup._writer.add(record);
            }
        }
        progress.finish();
        in.close();
        for (final SplitGroup g : this.name2group.values()) {
            g.close();
        }
        return 0;
    } catch (final Exception err) {
        for (final SplitGroup g : this.name2group.values()) {
            CloserUtil.close(g);
            if (in != null)
                g.getFile().delete();
        }
        return -1;
    } finally {
        for (final SplitGroup g : this.name2group.values()) {
            CloserUtil.close(g);
        }
        CloserUtil.close(r);
        CloserUtil.close(in);
        this.name2group.clear();
        this.interval2group.clear();
    }
}
Also used : SAMSequenceDictionaryProgress(com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress) VariantContext(htsjdk.variant.variantcontext.VariantContext) SAMSequenceRecord(htsjdk.samtools.SAMSequenceRecord) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOException(java.io.IOException) JvarkitException(com.github.lindenb.jvarkit.lang.JvarkitException) JvarkitException(com.github.lindenb.jvarkit.lang.JvarkitException) VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) BufferedReader(java.io.BufferedReader) Interval(htsjdk.samtools.util.Interval)

Example 24 with VcfIterator

use of com.github.lindenb.jvarkit.util.vcf.VcfIterator in project jvarkit by lindenb.

the class VcfToBam method doWork.

@Override
public int doWork(final List<String> args) {
    if (this.faidx == null) {
        LOG.error("No REF defined");
        return -1;
    }
    if (readSize <= 0) {
        LOG.error("bad read size");
        return -1;
    }
    if (fragmentSize <= readSize * 2) {
        LOG.error("bad fragment size");
        return -1;
    }
    VcfIterator iter = null;
    try {
        this.indexedFastaSequenceFile = new IndexedFastaSequenceFile(this.faidx);
        iter = super.openVcfIterator(super.oneFileOrNull(args));
        run(iter);
        return 0;
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(iter);
    }
}
Also used : VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) IndexedFastaSequenceFile(htsjdk.samtools.reference.IndexedFastaSequenceFile) IOException(java.io.IOException)

Example 25 with VcfIterator

use of com.github.lindenb.jvarkit.util.vcf.VcfIterator in project jvarkit by lindenb.

the class VcfToSvg method doWork.

@Override
public int doWork(final List<String> args) {
    if (this.outputFile != null && !outputFile.getName().contains(SEGMENT)) {
        LOG.error("output file must contain the word " + SEGMENT + " :" + this.outputFile);
        return -1;
    }
    TabixKnownGeneFileReader tabix = null;
    VcfIterator r = null;
    OutputStream outputStream = null;
    XMLStreamWriter w = null;
    PrintWriter manifestW = null;
    try {
        LOG.info("opening knownGene ");
        tabix = new TabixKnownGeneFileReader(knownGeneUri);
        if (manifestFile != null && this.outputFile != null) {
            manifestW = new PrintWriter(manifestFile);
        } else {
            manifestW = new PrintWriter(new NullOuputStream());
        }
        final Set<String> chromosomes = tabix.getChromosomes();
        final XMLOutputFactory xof = XMLOutputFactory.newInstance();
        r = super.openVcfIterator(super.oneFileOrNull(args));
        final VCFHeader header = r.getHeader();
        while (r.hasNext()) {
            final VariantContext ctx = r.next();
            String tabixContig = ctx.getContig();
            if (!chromosomes.contains(tabixContig)) {
                if (tabixContig.startsWith("chr")) {
                    tabixContig = tabixContig.substring(3);
                } else if (!tabixContig.startsWith("chr")) {
                    tabixContig = "chr" + tabixContig;
                }
                if (!chromosomes.contains(tabixContig)) {
                    while (r.hasNext()) {
                        final VariantContext ctx2 = r.peek();
                        if (!ctx2.getContig().equals(ctx.getContig()))
                            break;
                        r.next();
                    }
                    LOG.error("No chromosome " + ctx.getContig() + " in " + knownGeneUri + ". Check the chromosome nomenclature.");
                    continue;
                }
            }
            final List<VariantContext> variants = new ArrayList<>();
            final List<KnownGene> genes = new ArrayList<>();
            variants.add(ctx);
            int chromStart = ctx.getStart() - 1;
            int chromEnd = ctx.getEnd();
            /* walk over know gene, loop until there is no overapping transcript 
			 * over that region */
            for (; ; ) {
                genes.clear();
                /* the max chromEnd, let's see if we can get a bigger */
                int newStart = chromStart;
                int newEnd = chromEnd;
                final Iterator<KnownGene> kgr = tabix.iterator(tabixContig, chromStart, chromEnd);
                while (kgr.hasNext()) {
                    final KnownGene g = kgr.next();
                    if (this.removeNonCoding && g.isNonCoding())
                        continue;
                    genes.add(g);
                    newStart = Math.min(g.getTxStart(), newStart);
                    newEnd = Math.max(g.getTxEnd(), newEnd);
                }
                if (newStart >= chromStart && newEnd <= chromEnd) {
                    break;
                }
                chromStart = newStart;
                chromEnd = newEnd;
            }
            // intergenic, no gene over that variant
            if (genes.isEmpty())
                continue;
            // fill the variant for that region
            while (r.hasNext()) {
                final VariantContext ctx2 = r.peek();
                if (!ctx2.getContig().equals(ctx.getContig()))
                    break;
                if (ctx2.getStart() > chromEnd)
                    break;
                variants.add(r.next());
            }
            if (this.variantsInExonOnly) {
                variants.removeIf(V -> {
                    for (final KnownGene gene : genes) {
                        for (final KnownGene.Exon exon : gene.getExons()) {
                            if (V.getEnd() < exon.getStart() || V.getStart() >= exon.getEnd()) {
                            // rien
                            } else {
                                return false;
                            }
                        }
                    }
                    return true;
                });
            }
            if (this.variantFILTEREDOpacity <= 0) {
                variants.removeIf(V -> V.isFiltered());
            }
            if (this.variantIndelOpacity <= 0) {
                variants.removeIf(V -> V.isIndel());
            }
            if (variants.isEmpty())
                continue;
            LOG.info("Variants (" + variants.size() + ") Transcripts (" + genes.size() + ") " + tabixContig + ":" + chromStart + "-" + chromEnd);
            if (outputFile != null) {
                File fname = new File(outputFile.getParentFile(), outputFile.getName().replaceAll("__SEGMENT__", ctx.getContig() + "_" + chromStart + "_" + chromEnd));
                LOG.info("saving as " + fname);
                outputStream = IOUtils.openFileForWriting(fname);
                w = xof.createXMLStreamWriter(outputStream);
                manifestW.println(ctx.getContig() + "\t" + chromStart + "\t" + chromEnd + "\t" + genes.stream().map(G -> G.getName()).collect(Collectors.joining(",")) + "\t" + genes.size() + "\t" + variants.size() + "\t" + fname);
            } else {
                w = xof.createXMLStreamWriter(stdout());
            }
            double featureHeight = 10;
            double TRANSCRIPT_HEIGHT = featureHeight;
            final int all_genotypes_width = variants.size() * this.genotype_width;
            if (trimToVariants) {
                chromStart = variants.stream().map(V -> V.getStart() - 1).min((A, B) -> A.compareTo(B)).get();
                chromEnd = variants.stream().map(V -> V.getEnd() + 1).max((A, B) -> A.compareTo(B)).get();
            }
            final int drawinAreaWidth = Math.max(all_genotypes_width, 1000);
            final Interval interval = new Interval(ctx.getContig(), chromStart, chromEnd);
            final int interline_weight = 6;
            final int margin_top = 10;
            final int margin_bottom = 10;
            final int margin_right = 100;
            final int margin_left = 100;
            w.writeStartDocument("UTF-8", "1.0");
            w.writeStartElement("svg");
            w.writeDefaultNamespace(SVG.NS);
            w.writeNamespace("xlink", XLINK.NS);
            w.writeAttribute("version", "1.1");
            w.writeAttribute("width", String.valueOf(margin_right + margin_right + drawinAreaWidth));
            w.writeAttribute("height", String.valueOf(margin_top + margin_bottom + genes.size() * TRANSCRIPT_HEIGHT + interline_weight * featureHeight + header.getSampleNamesInOrder().size() * this.genotype_width));
            title(w, ctx.getContig() + ":" + chromStart + "-" + chromEnd);
            w.writeStartElement("desc");
            w.writeCharacters("generated with " + getProgramName() + "\n" + "Author: Pierre Lindenbaum PhD. @yokofakun .");
            w.writeEndElement();
            // defs
            w.writeStartElement("defs");
            // genotypes
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.HOM_REF);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:lime;stroke;none;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(this.genotype_width));
            w.writeAttribute("height", String.valueOf(this.genotype_width));
            w.writeEndElement();
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.NO_CALL);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:silver;stroke;gray;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(this.genotype_width));
            w.writeAttribute("height", String.valueOf(this.genotype_width));
            w.writeEndElement();
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.HOM_VAR);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:crimson;stroke;none;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(this.genotype_width));
            w.writeAttribute("height", String.valueOf(this.genotype_width));
            w.writeEndElement();
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.MIXED);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:pink;stroke;none;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(this.genotype_width));
            w.writeAttribute("height", String.valueOf(this.genotype_width));
            w.writeEndElement();
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.UNAVAILABLE);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:gray;stroke;none;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(this.genotype_width));
            w.writeAttribute("height", String.valueOf(this.genotype_width));
            w.writeEndElement();
            w.writeStartElement("g");
            // 
            w.writeAttribute("id", "g_" + GenotypeType.HET);
            w.writeEmptyElement("rect");
            w.writeAttribute("style", "fill:lime;stroke;black;");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", "0");
            w.writeAttribute("width", String.valueOf(genotype_width));
            w.writeAttribute("height", String.valueOf(genotype_width));
            w.writeEmptyElement("polygon");
            w.writeAttribute("style", "fill:crimson;stroke;black;");
            w.writeAttribute("points", "0,0 " + genotype_width + ",0 0," + genotype_width + " 0,0");
            w.writeEndElement();
            // strand
            w.writeEmptyElement("polyline");
            w.writeAttribute("id", "strandF");
            w.writeAttribute("points", "-5,-5 0,0 -5,5");
            w.writeEmptyElement("polyline");
            w.writeAttribute("id", "strandR");
            w.writeAttribute("points", "5,-5 0,0 5,5");
            // gradients
            w.writeStartElement("linearGradient");
            w.writeAttribute("id", "grad01");
            w.writeAttribute("x1", "50%");
            w.writeAttribute("x2", "50%");
            w.writeAttribute("y1", "0%");
            w.writeAttribute("y2", "100%");
            w.writeEmptyElement("stop");
            w.writeAttribute("offset", "0%");
            w.writeAttribute("style", "stop-color:black;stop-opacity:1;");
            w.writeEmptyElement("stop");
            w.writeAttribute("offset", "50%");
            w.writeAttribute("style", "stop-color:white;stop-opacity:1;");
            w.writeEmptyElement("stop");
            w.writeAttribute("offset", "100%");
            w.writeAttribute("style", "stop-color:black;stop-opacity:1;");
            w.writeEndElement();
            // defs
            w.writeEndElement();
            w.writeStartElement("style");
            w.writeCharacters("svg {fill:none; stroke:black;}\n" + "text {fill:black;stroke:none;font-size:" + (featureHeight / 1.5) + "px;}\n" + ".ruler-label { stroke:red;}\n" + ".frame { stroke:black;fill:none;}\n" + ".kgexon {fill:url(#grad01);stroke:black;}\n" + ".gcpercent {fill:url(#grad02);stroke:black;}" + ".coverage {fill:url(#grad03);stroke:black;}" + ".kgcds {fill:yellow;stroke:black;opacity:0.7;}\n" + ".variant{stroke:none;fill:red;opacity:0.2;}\n" + ".xaxis{stroke:gray;fill:none;opacity:0.2;}\n" + ".postick{font-size:9px;stroke:black;stroke-width:1;}");
            // style
            w.writeEndElement();
            final Function<Integer, Integer> trim = new Function<Integer, Integer>() {

                @Override
                public Integer apply(final Integer t) {
                    return Math.max(interval.getStart(), Math.min(interval.getEnd(), t));
                }
            };
            final Function<Integer, Double> baseToPixel = new Function<Integer, Double>() {

                @Override
                public Double apply(final Integer t) {
                    return margin_left + drawinAreaWidth * (t - (double) interval.getStart()) / ((double) interval.length());
                }
            };
            final Function<Integer, Double> variantIndexToPixel = new Function<Integer, Double>() {

                @Override
                public Double apply(final Integer idx) {
                    final double variant_width = drawinAreaWidth / (double) variants.size();
                    final double midx = variant_width * idx + variant_width / 2.0;
                    return margin_left + midx - genotype_width / 2.0;
                }
            };
            final Function<VariantContext, String> variantTitle = V -> (V.getContig().startsWith("chr") ? V.getContig().substring(3) : V.getContig()) + ":" + V.getStart() + " " + V.getReference().getDisplayString();
            /**
             * title
             */
            double y = 0;
            w.writeStartElement("text");
            w.writeAttribute("x", "0");
            w.writeAttribute("y", String.valueOf(featureHeight));
            w.writeCharacters(interval.toString());
            w.writeEndElement();
            y += featureHeight;
            for (final KnownGene g : genes) {
                int cdsHeigh = 5;
                double exonHeight = TRANSCRIPT_HEIGHT - 5;
                double midY = TRANSCRIPT_HEIGHT / 2;
                w.writeStartElement("g");
                w.writeAttribute("transform", "translate(0," + y + ")");
                title(w, g.getName());
                w.writeStartElement("text");
                w.writeAttribute("x", String.valueOf(margin_left - 10));
                w.writeAttribute("y", String.valueOf(featureHeight));
                w.writeAttribute("style", "text-anchor:end;");
                w.writeCharacters(g.getName());
                w.writeEndElement();
                /* transcript line */
                w.writeEmptyElement("line");
                w.writeAttribute("class", "kgtr");
                w.writeAttribute("x1", String.valueOf(baseToPixel.apply(trim.apply(g.getTxStart()))));
                w.writeAttribute("y1", String.valueOf(midY));
                w.writeAttribute("x2", String.valueOf(baseToPixel.apply(trim.apply(g.getTxEnd()))));
                w.writeAttribute("y2", String.valueOf(midY));
                /* strand symbols */
                for (double pixX = 0; pixX < drawinAreaWidth; pixX += 30) {
                    double pos0 = interval.getStart() + (pixX / (double) drawinAreaWidth) * interval.length();
                    if (pos0 + 1 < g.getTxStart())
                        continue;
                    if (pos0 > g.getTxEnd())
                        break;
                    w.writeEmptyElement("use");
                    w.writeAttribute("class", "kgstrand");
                    w.writeAttribute("xlink", XLINK.NS, "href", "#strand" + (g.isPositiveStrand() ? "F" : "R"));
                    w.writeAttribute("x", String.valueOf(margin_left + pixX));
                    w.writeAttribute("y", String.valueOf(midY));
                }
                /* exons */
                for (KnownGene.Exon exon : g.getExons()) {
                    if (exon.getStart() + 1 >= interval.getEnd())
                        continue;
                    if (exon.getEnd() <= interval.getStart())
                        continue;
                    w.writeStartElement("rect");
                    w.writeAttribute("class", "kgexon");
                    w.writeAttribute("x", String.valueOf(baseToPixel.apply(trim.apply(exon.getStart()))));
                    w.writeAttribute("y", String.valueOf(midY - exonHeight / 2));
                    w.writeAttribute("width", String.valueOf(baseToPixel.apply(trim.apply(exon.getEnd())) - baseToPixel.apply((trim.apply(exon.getStart())))));
                    w.writeAttribute("height", String.valueOf(exonHeight));
                    title(w, exon.getName());
                    w.writeEndElement();
                }
                /* coding line */
                if (!g.isNonCoding()) {
                    w.writeEmptyElement("rect");
                    w.writeAttribute("class", "kgcds");
                    w.writeAttribute("x", String.valueOf(baseToPixel.apply(trim.apply(g.getCdsStart()))));
                    w.writeAttribute("y", String.valueOf(midY - cdsHeigh / 4.0));
                    w.writeAttribute("width", String.valueOf(baseToPixel.apply(trim.apply(g.getCdsEnd())) - baseToPixel.apply((trim.apply((g.getCdsStart()))))));
                    w.writeAttribute("height", String.valueOf(cdsHeigh / 2.0));
                }
                // String label=String.format("%15s", g.getName());
                // w.writeEmptyElement("path");
                // double fontHeight=Math.min(10,0.8*TRANSCRIPT_HEIGHT);
                // w.writeAttribute("d",this.hershey.svgPath(label,-insets.left,midY-fontHeight/2,insets.left*0.9,fontHeight));
                w.writeEndElement();
                w.writeCharacters("\n");
                y += featureHeight;
            }
            /* draw lines to variants */
            for (int vidx = 0; vidx < variants.size(); ++vidx) {
                final VariantContext vc = variants.get(vidx);
                double x1 = baseToPixel.apply(vc.getStart());
                double x2 = baseToPixel.apply(vc.getEnd());
                final double y2 = y + featureHeight * interline_weight;
                w.writeStartElement("polygon");
                w.writeAttribute("style", "fill:" + (vidx % 2 == 0 ? "ghostwhite" : "lavender") + ";stroke:black;opacity:0.6;stroke-width:0.5;");
                w.writeAttribute("points", "" + x1 + "," + (y - featureHeight / 2.0) + " " + x2 + "," + (y - featureHeight / 2.0) + " " + variantIndexToPixel.apply(vidx) + "," + y2 + " " + (variantIndexToPixel.apply(vidx) + this.genotype_width) + "," + y2);
                title(w, variantTitle.apply(vc));
                w.writeEndElement();
            }
            for (int vidx = 0; vidx < variants.size(); ++vidx) {
                final VariantContext vc = variants.get(vidx);
                final double y2 = y + featureHeight * interline_weight;
                w.writeStartElement("text");
                w.writeAttribute("transform", "translate(" + (String.valueOf(variantIndexToPixel.apply(vidx) + genotype_width / 2.0)) + "," + String.valueOf(y2 - 5) + ") " + "rotate(-45)");
                w.writeAttribute("x", "0");
                w.writeAttribute("y", "0");
                w.writeAttribute("class", "postick");
                w.writeCharacters(variantTitle.apply(vc));
                w.writeEndElement();
                w.writeCharacters("\n");
            }
            y += featureHeight * interline_weight;
            w.writeStartElement("g");
            for (final String sample : header.getSampleNamesInOrder()) {
                for (int vidx = 0; vidx < variants.size(); ++vidx) {
                    final VariantContext vc = variants.get(vidx);
                    final Genotype g = vc.getGenotype(sample);
                    double opacity = 1.0;
                    if (vc.isIndel())
                        opacity *= this.variantIndelOpacity;
                    if (vc.isFiltered())
                        opacity *= this.variantFILTEREDOpacity;
                    if (opacity > 1)
                        opacity = 1;
                    if (opacity <= 0)
                        continue;
                    if (opacity < 1) {
                        w.writeStartElement("g");
                        w.writeAttribute("style", "opacity:" + opacity + ";");
                    }
                    w.writeEmptyElement("use");
                    w.writeAttribute("x", "" + variantIndexToPixel.apply(vidx));
                    w.writeAttribute("y", String.valueOf(y));
                    w.writeAttribute("xlink", XLINK.NS, "href", "#g_" + g.getType());
                    if (opacity < 1) {
                        w.writeEndElement();
                    }
                }
                w.writeCharacters("\n");
                w.writeStartElement("text");
                w.writeAttribute("x", String.valueOf(margin_left - 10));
                w.writeAttribute("y", String.valueOf(y + this.genotype_width / 2.0));
                w.writeAttribute("style", "text-anchor:end;");
                w.writeCharacters(sample);
                w.writeEndElement();
                y += this.genotype_width;
            }
            w.writeCharacters("\n");
            w.writeEndDocument();
            w.writeCharacters("\n");
            w.flush();
            w.close();
            if (outputFile != null) {
                outputStream.flush();
                outputStream.close();
                outputStream = null;
            }
            if (stop_at_first) {
                LOG.info("Stop after first SVG document");
                break;
            }
        }
        r.close();
        manifestW.flush();
        manifestW.close();
        manifestW = null;
        return 0;
    } catch (Throwable err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(r);
        CloserUtil.close(tabix);
        CloserUtil.close(outputStream);
        CloserUtil.close(manifestW);
    }
}
Also used : Genotype(htsjdk.variant.variantcontext.Genotype) XLINK(com.github.lindenb.jvarkit.util.ns.XLINK) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Parameter(com.beust.jcommander.Parameter) NullOuputStream(com.github.lindenb.jvarkit.io.NullOuputStream) VCFHeader(htsjdk.variant.vcf.VCFHeader) Function(java.util.function.Function) SVG(com.github.lindenb.jvarkit.util.svg.SVG) ArrayList(java.util.ArrayList) Interval(htsjdk.samtools.util.Interval) XMLStreamException(javax.xml.stream.XMLStreamException) IOUtils(com.github.lindenb.jvarkit.io.IOUtils) Launcher(com.github.lindenb.jvarkit.util.jcommander.Launcher) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) CloserUtil(htsjdk.samtools.util.CloserUtil) OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) Iterator(java.util.Iterator) Logger(com.github.lindenb.jvarkit.util.log.Logger) VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) GenotypeType(htsjdk.variant.variantcontext.GenotypeType) Set(java.util.Set) Collectors(java.util.stream.Collectors) KnownGene(com.github.lindenb.jvarkit.util.ucsc.KnownGene) TabixKnownGeneFileReader(com.github.lindenb.jvarkit.util.ucsc.TabixKnownGeneFileReader) File(java.io.File) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) List(java.util.List) VariantContext(htsjdk.variant.variantcontext.VariantContext) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) VariantContext(htsjdk.variant.variantcontext.VariantContext) Function(java.util.function.Function) VcfIterator(com.github.lindenb.jvarkit.util.vcf.VcfIterator) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) NullOuputStream(com.github.lindenb.jvarkit.io.NullOuputStream) VCFHeader(htsjdk.variant.vcf.VCFHeader) PrintWriter(java.io.PrintWriter) Genotype(htsjdk.variant.variantcontext.Genotype) TabixKnownGeneFileReader(com.github.lindenb.jvarkit.util.ucsc.TabixKnownGeneFileReader) KnownGene(com.github.lindenb.jvarkit.util.ucsc.KnownGene) File(java.io.File) Interval(htsjdk.samtools.util.Interval)

Aggregations

VcfIterator (com.github.lindenb.jvarkit.util.vcf.VcfIterator)55 VariantContext (htsjdk.variant.variantcontext.VariantContext)39 VCFHeader (htsjdk.variant.vcf.VCFHeader)35 SAMSequenceDictionaryProgress (com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress)30 ArrayList (java.util.ArrayList)28 VariantContextWriter (htsjdk.variant.variantcontext.writer.VariantContextWriter)26 IOException (java.io.IOException)24 File (java.io.File)22 HashSet (java.util.HashSet)19 List (java.util.List)19 Genotype (htsjdk.variant.variantcontext.Genotype)18 Parameter (com.beust.jcommander.Parameter)17 Launcher (com.github.lindenb.jvarkit.util.jcommander.Launcher)17 Program (com.github.lindenb.jvarkit.util.jcommander.Program)17 Logger (com.github.lindenb.jvarkit.util.log.Logger)17 Set (java.util.Set)17 Allele (htsjdk.variant.variantcontext.Allele)16 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)15 VariantContextBuilder (htsjdk.variant.variantcontext.VariantContextBuilder)15 JvarkitException (com.github.lindenb.jvarkit.lang.JvarkitException)14