use of htsjdk.variant.variantcontext.GenotypeBuilder in project jvarkit by lindenb.
the class Biostar78285 method doWork.
@Override
public int doWork(final List<String> args) {
if (this.gc_percent_window < 1) {
LOG.error("Bad GC% window size:" + this.gc_percent_window);
return -1;
}
final List<File> bamFiles = IOUtil.unrollFiles(args.stream().map(F -> new File(F)).collect(Collectors.toCollection(HashSet::new)), ".bam");
SAMSequenceDictionary dict = null;
final List<SamReader> samReaders = new ArrayList<>();
final List<CloseableIterator<SAMRecord>> samIterators = new ArrayList<>();
final TreeSet<String> samples = new TreeSet<>();
final String DEFAULT_PARTITION = "UNDEFINED_PARTITION";
IndexedFastaSequenceFile indexedFastaSequenceFile = null;
VariantContextWriter out = null;
try {
final SamReaderFactory samReaderFactory = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.LENIENT);
for (final File bamFile : bamFiles) {
LOG.info("Opening " + bamFile);
final SamReader samReader = samReaderFactory.open(bamFile);
samReaders.add(samReader);
final SAMFileHeader header = samReader.getFileHeader();
if (header == null) {
LOG.error("No header in " + bamFile);
return -1;
}
if (header.getSortOrder() != SortOrder.coordinate) {
LOG.error("Sam file " + bamFile + " is not sorted on coordinate :" + header.getSortOrder());
return -1;
}
samples.addAll(header.getReadGroups().stream().map(RG -> this.partition.apply(RG, DEFAULT_PARTITION)).collect(Collectors.toSet()));
final SAMSequenceDictionary currDict = header.getSequenceDictionary();
if (currDict == null) {
LOG.error("SamFile doesn't contain a SAMSequenceDictionary : " + bamFile);
return -1;
}
if (dict == null) {
dict = currDict;
} else if (!SequenceUtil.areSequenceDictionariesEqual(dict, currDict)) {
LOG.error(JvarkitException.DictionariesAreNotTheSame.getMessage(dict, currDict));
return -1;
}
}
if (samReaders.isEmpty()) {
LOG.error("no bam");
return -1;
}
if (dict == null) {
LOG.error("no dictionary");
return -1;
}
final QueryInterval[] intervals;
if (this.captureBed != null) {
LOG.info("Opening " + this.captureBed);
ContigNameConverter.setDefaultAliases(dict);
final List<QueryInterval> L = new ArrayList<>();
final BedLineCodec codec = new BedLineCodec();
final LineIterator li = IOUtils.openFileForLineIterator(this.captureBed);
while (li.hasNext()) {
final BedLine bed = codec.decode(li.next());
if (bed == null)
continue;
final QueryInterval q = bed.toQueryInterval(dict);
L.add(q);
}
CloserUtil.close(li);
intervals = QueryInterval.optimizeIntervals(L.toArray(new QueryInterval[L.size()]));
} else {
intervals = null;
}
for (final SamReader samReader : samReaders) {
LOG.info("querying " + samReader.getResourceDescription());
final CloseableIterator<SAMRecord> iter;
if (intervals == null) {
iter = samReader.iterator();
} else {
iter = samReader.queryOverlapping(intervals);
}
samIterators.add(new FilterIterator<SAMRecord>(iter, R -> !R.getReadUnmappedFlag() && !filter.filterOut(R)));
}
if (this.refFile != null) {
LOG.info("opening " + refFile);
indexedFastaSequenceFile = new IndexedFastaSequenceFile(this.refFile);
final SAMSequenceDictionary refdict = indexedFastaSequenceFile.getSequenceDictionary();
ContigNameConverter.setDefaultAliases(refdict);
if (refdict == null) {
throw new JvarkitException.FastaDictionaryMissing(this.refFile);
}
if (!SequenceUtil.areSequenceDictionariesEqual(dict, refdict)) {
LOG.error(JvarkitException.DictionariesAreNotTheSame.getMessage(dict, refdict));
return -1;
}
}
out = openVariantContextWriter(this.outputFile);
final Set<VCFHeaderLine> metaData = new HashSet<>();
VCFStandardHeaderLines.addStandardFormatLines(metaData, true, VCFConstants.DEPTH_KEY, VCFConstants.GENOTYPE_KEY);
VCFStandardHeaderLines.addStandardInfoLines(metaData, true, VCFConstants.DEPTH_KEY);
metaData.add(new VCFFormatHeaderLine("DF", 1, VCFHeaderLineType.Integer, "Number of Reads on plus strand"));
metaData.add(new VCFFormatHeaderLine("DR", 1, VCFHeaderLineType.Integer, "Number of Reads on minus strand"));
metaData.add(new VCFInfoHeaderLine("AVG_DP", 1, VCFHeaderLineType.Float, "Mean depth"));
metaData.add(new VCFInfoHeaderLine("MEDIAN_DP", 1, VCFHeaderLineType.Float, "Median depth"));
metaData.add(new VCFInfoHeaderLine("MIN_DP", 1, VCFHeaderLineType.Integer, "Min depth"));
metaData.add(new VCFInfoHeaderLine("MAX_DP", 1, VCFHeaderLineType.Integer, "Max depth"));
metaData.add(new VCFHeaderLine(Biostar78285.class.getSimpleName() + ".SamFilter", this.filter.toString()));
for (final Integer treshold : this.minDepthTresholds) {
metaData.add(new VCFFilterHeaderLine("DP_LT_" + treshold, "All genotypes have DP< " + treshold));
metaData.add(new VCFInfoHeaderLine("NUM_DP_LT_" + treshold, 1, VCFHeaderLineType.Integer, "Number of genotypes having DP< " + treshold));
metaData.add(new VCFInfoHeaderLine("FRACT_DP_LT_" + treshold, 1, VCFHeaderLineType.Float, "Fraction of genotypes having DP< " + treshold));
}
if (indexedFastaSequenceFile != null) {
metaData.add(new VCFInfoHeaderLine("GC_PERCENT", 1, VCFHeaderLineType.Integer, "GC% window_size:" + this.gc_percent_window));
}
final List<Allele> refAlleles = Collections.singletonList(Allele.create("N", true));
final List<Allele> NO_CALLS = Arrays.asList(Allele.NO_CALL, Allele.NO_CALL);
final VCFHeader vcfHeader = new VCFHeader(metaData, samples);
vcfHeader.setSequenceDictionary(dict);
out.writeHeader(vcfHeader);
final SAMRecordCoordinateComparator samRecordCoordinateComparator = new SAMRecordCoordinateComparator();
final PeekableIterator<SAMRecord> peekIter = new PeekableIterator<>(new MergingIterator<>((R1, R2) -> samRecordCoordinateComparator.fileOrderCompare(R1, R2), samIterators));
final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict);
for (final SAMSequenceRecord ssr : dict.getSequences()) {
final IntervalTree<Boolean> capturePos;
if (intervals != null) {
if (!Arrays.stream(intervals).anyMatch(I -> I.referenceIndex == ssr.getSequenceIndex())) {
continue;
}
capturePos = new IntervalTree<>();
Arrays.stream(intervals).filter(I -> I.referenceIndex == ssr.getSequenceIndex()).forEach(I -> capturePos.put(I.start, I.end, true));
;
} else {
capturePos = null;
}
final GenomicSequence genomicSequence;
if (indexedFastaSequenceFile != null && indexedFastaSequenceFile.getSequenceDictionary().getSequence(ssr.getSequenceName()) != null) {
genomicSequence = new GenomicSequence(indexedFastaSequenceFile, ssr.getSequenceName());
} else {
genomicSequence = null;
}
final List<SAMRecord> buffer = new ArrayList<>();
for (int ssr_pos = 1; ssr_pos <= ssr.getSequenceLength(); ++ssr_pos) {
if (capturePos != null && !capturePos.overlappers(ssr_pos, ssr_pos).hasNext())
continue;
progress.watch(ssr.getSequenceName(), ssr_pos);
while (peekIter.hasNext()) {
final SAMRecord rec = peekIter.peek();
if (rec.getReadUnmappedFlag()) {
// consumme
peekIter.next();
continue;
}
if (this.filter.filterOut(rec)) {
// consumme
peekIter.next();
continue;
}
if (rec.getReferenceIndex() < ssr.getSequenceIndex()) {
throw new IllegalStateException("should not happen");
}
if (rec.getReferenceIndex() > ssr.getSequenceIndex()) {
break;
}
if (rec.getAlignmentEnd() < ssr_pos) {
throw new IllegalStateException("should not happen");
}
if (rec.getAlignmentStart() > ssr_pos) {
break;
}
buffer.add(peekIter.next());
}
int x = 0;
while (x < buffer.size()) {
final SAMRecord R = buffer.get(x);
if (R.getReferenceIndex() != ssr.getSequenceIndex() || R.getAlignmentEnd() < ssr_pos) {
buffer.remove(x);
} else {
x++;
}
}
final Map<String, PosInfo> count = samples.stream().map(S -> new PosInfo(S)).collect(Collectors.toMap(P -> P.sample, Function.identity()));
for (final SAMRecord rec : buffer) {
if (rec.getReferenceIndex() != ssr.getSequenceIndex())
throw new IllegalStateException("should not happen");
if (rec.getAlignmentEnd() < ssr_pos)
continue;
if (rec.getAlignmentStart() > ssr_pos)
continue;
final Cigar cigar = rec.getCigar();
if (cigar == null)
continue;
int refpos = rec.getAlignmentStart();
final String sample = this.partition.getPartion(rec, DEFAULT_PARTITION);
for (final CigarElement ce : cigar.getCigarElements()) {
if (refpos > ssr_pos)
break;
final CigarOperator op = ce.getOperator();
if (op.consumesReferenceBases()) {
if (op.consumesReadBases()) {
if (refpos <= ssr_pos && ssr_pos <= refpos + ce.getLength()) {
final PosInfo posInfo = count.get(sample);
if (posInfo != null) {
posInfo.dp++;
if (rec.getReadNegativeStrandFlag()) {
posInfo.negative_strand++;
}
}
break;
}
}
refpos += ce.getLength();
}
}
}
final VariantContextBuilder vcb = new VariantContextBuilder();
final Set<String> filters = new HashSet<>();
vcb.chr(ssr.getSequenceName());
vcb.start(ssr_pos);
vcb.stop(ssr_pos);
if (genomicSequence == null) {
vcb.alleles(refAlleles);
} else {
vcb.alleles(Collections.singletonList(Allele.create((byte) genomicSequence.charAt(ssr_pos - 1), true)));
final GenomicSequence.GCPercent gcp = genomicSequence.getGCPercent(Math.max((ssr_pos - 1) - this.gc_percent_window, 0), Math.min(ssr_pos + this.gc_percent_window, ssr.getSequenceLength()));
if (!gcp.isEmpty()) {
vcb.attribute("GC_PERCENT", gcp.getGCPercentAsInteger());
}
}
vcb.attribute(VCFConstants.DEPTH_KEY, (int) count.values().stream().mapToInt(S -> S.dp).sum());
vcb.genotypes(count.values().stream().map(C -> new GenotypeBuilder(C.sample, NO_CALLS).DP((int) C.dp).attribute("DR", C.negative_strand).attribute("DF", C.dp - C.negative_strand).make()).collect(Collectors.toList()));
for (final Integer treshold : this.minDepthTresholds) {
final int count_lt = (int) count.values().stream().filter(S -> S.dp < treshold).count();
if (count_lt == samples.size()) {
filters.add("DP_LT_" + treshold);
}
vcb.attribute("NUM_DP_LT_" + treshold, count_lt);
if (!samples.isEmpty()) {
vcb.attribute("FRACT_DP_LT_" + treshold, count_lt / (float) samples.size());
}
}
if (!samples.isEmpty()) {
final int[] array = count.values().stream().mapToInt(S -> S.dp).toArray();
vcb.attribute("AVG_DP", Percentile.average().evaluate(array));
vcb.attribute("MEDIAN_DP", Percentile.median().evaluate(array));
vcb.attribute("MIN_DP", (int) Percentile.min().evaluate(array));
vcb.attribute("MAX_DP", (int) Percentile.max().evaluate(array));
}
if (filters.isEmpty()) {
vcb.passFilters();
} else {
vcb.filters(filters);
}
out.add(vcb.make());
}
}
progress.finish();
peekIter.close();
out.close();
out = null;
return 0;
} catch (final Exception err) {
LOG.error(err);
return -1;
} finally {
CloserUtil.close(out);
CloserUtil.close(samIterators);
CloserUtil.close(samReaders);
CloserUtil.close(indexedFastaSequenceFile);
}
}
use of htsjdk.variant.variantcontext.GenotypeBuilder in project jvarkit by lindenb.
the class Biostar86363 method doVcfToVcf.
@Override
protected int doVcfToVcf(String inputName, VcfIterator in, VariantContextWriter out) {
final List<Allele> empty_g = new ArrayList<Allele>(2);
empty_g.add(Allele.NO_CALL);
empty_g.add(Allele.NO_CALL);
VCFHeader h = in.getHeader();
final List<String> vcf_samples = h.getSampleNamesInOrder();
h.addMetaDataLine(new VCFFormatHeaderLine("GR", 1, VCFHeaderLineType.Integer, "(1) = Genotype was reset by " + getProgramName()));
this.recalculator.setHeader(h);
out.writeHeader(h);
while (in.hasNext()) {
VariantContext ctx = in.next();
ContigPosRef cap = new ContigPosRef(ctx);
Set<String> samplesToReset = this.pos2sample.get(cap);
if (samplesToReset != null) {
VariantContextBuilder vcb = new VariantContextBuilder(ctx);
List<Genotype> genotypes = new ArrayList<Genotype>();
for (String sample : vcf_samples) {
Genotype g = ctx.getGenotype(sample);
if (g == null)
continue;
GenotypeBuilder gb = new GenotypeBuilder(g);
if (samplesToReset.contains(sample)) {
gb.alleles(empty_g);
gb.attribute("GR", 1);
} else {
gb.attribute("GR", 0);
}
g = gb.make();
genotypes.add(g);
}
vcb.genotypes(genotypes);
ctx = this.recalculator.apply(vcb.make());
}
out.add(ctx);
}
return 0;
}
use of htsjdk.variant.variantcontext.GenotypeBuilder in project jvarkit by lindenb.
the class VcfTools method isMendelianIncompatibility.
public boolean isMendelianIncompatibility(final Genotype child, final Genotype father, final Genotype mother) {
if (child == null || !child.isCalled() || (father == null && mother == null))
return false;
if (father == null || !father.isCalled()) {
return this.isMendelianIncompatibility(child, mother);
}
if (mother == null || !mother.isCalled()) {
return this.isMendelianIncompatibility(child, father);
}
final Allele[] alleles = new Allele[2];
for (final Allele af : father.getAlleles()) {
alleles[0] = af;
for (final Allele am : mother.getAlleles()) {
alleles[1] = am;
final Genotype sim = new GenotypeBuilder(child.getSampleName()).alleles(Arrays.asList(alleles)).make();
if (child.sameGenotype(sim, true))
return false;
}
}
return true;
}
use of htsjdk.variant.variantcontext.GenotypeBuilder in project jvarkit by lindenb.
the class VcfMultiToOneAlleleTest method testNoMultiple.
@Test
public void testNoMultiple() throws IOException {
List<Genotype> genotypes = new ArrayList<>();
genotypes.add(new GenotypeBuilder("S1", Arrays.asList(REF, A1)).make());
genotypes.add(new GenotypeBuilder("S2", Arrays.asList(A1, A1)).make());
genotypes.add(new GenotypeBuilder("S3", Arrays.asList(REF, REF)).make());
List<VariantContext> variants = createVcf("--samples", genotypes);
Assert.assertEquals(variants.size(), 1);
VariantContext ctx = variants.get(0);
Assert.assertEquals(ctx.getGenotypes().size(), genotypes.size());
Assert.assertTrue(ctx.getGenotype("S1").sameGenotype(genotypes.get(0)));
Assert.assertTrue(ctx.getGenotype("S2").sameGenotype(genotypes.get(1)));
Assert.assertTrue(ctx.getGenotype("S3").sameGenotype(genotypes.get(2)));
}
use of htsjdk.variant.variantcontext.GenotypeBuilder in project jvarkit by lindenb.
the class Biostar130456 method doWork.
@Override
public int doWork(final List<String> args) {
if (this.filepattern == null || !filepattern.contains(SAMPLE_TAG)) {
LOG.error("File pattern is missing " + SAMPLE_TAG);
return -1;
}
PrintStream out = null;
VcfIterator in = null;
final String inputName = oneFileOrNull(args);
try {
out = openFileOrStdoutAsPrintStream(outputFile);
in = super.openVcfIterator(inputName);
final VCFHeader header = in.getHeader();
this.recalculator.setHeader(header);
final Set<String> samples = new HashSet<String>(header.getSampleNamesInOrder());
final Map<String, VariantContextWriter> sample2writer = new HashMap<String, VariantContextWriter>(samples.size());
if (samples.isEmpty()) {
LOG.error("VCF doesn't contain any sample");
return -1;
}
LOG.info("N sample:" + samples.size());
for (final String sample : samples) {
final VCFHeader h2 = new VCFHeader(header.getMetaDataInInputOrder(), Collections.singleton(sample));
super.addMetaData(h2);
final String sampleFile = filepattern.replaceAll(SAMPLE_TAG, sample);
out.println(sampleFile);
final File fout = new File(sampleFile);
if (fout.getParentFile() != null)
fout.getParentFile().mkdirs();
final VariantContextWriter w = VCFUtils.createVariantContextWriter(fout);
w.writeHeader(h2);
sample2writer.put(sample, w);
}
final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header).logger(LOG);
while (in.hasNext()) {
final VariantContext ctx = progress.watch(in.next());
for (final String sample : samples) {
final Genotype g = ctx.getGenotype(sample);
if (g == null)
continue;
if (remove_uncalled && (!g.isAvailable() || !g.isCalled() || g.isNoCall())) {
continue;
}
if (remove_homref && g.isHomRef())
continue;
final VariantContextWriter w = sample2writer.get(sample);
final VariantContextBuilder vcb = new VariantContextBuilder(ctx);
final GenotypeBuilder gb = new GenotypeBuilder(g);
vcb.genotypes(Collections.singletonList(gb.make()));
final VariantContext ctx2 = this.recalculator.apply(vcb.make());
w.add(ctx2);
}
}
for (final String sample : samples) {
LOG.info("Closing for sample " + sample);
final VariantContextWriter w = sample2writer.get(sample);
w.close();
}
progress.finish();
out.flush();
return RETURN_OK;
} catch (final Exception e) {
LOG.error(e);
return -1;
} finally {
CloserUtil.close(out);
CloserUtil.close(in);
}
}
Aggregations