use of htsjdk.variant.variantcontext.Genotype in project hmftools by hartwigmedical.
the class StrelkaPostProcess method readAD.
@NotNull
private static int[] readAD(@NotNull final VariantContext variant, @NotNull Function<Allele, String> alleleKey) {
final Genotype tumorGenotype = variant.getGenotype(TUMOR_GENOTYPE);
final List<Integer> alleleAds = variant.getAlleles().stream().map(allele -> {
final String[] alleleADs = tumorGenotype.getExtendedAttribute(alleleKey.apply(allele), "0").toString().split(SEPARATOR);
if (alleleADs.length > 0) {
try {
return Integer.parseInt(alleleADs[0]);
} catch (final NumberFormatException e) {
return 0;
}
}
return 0;
}).collect(Collectors.toList());
final Integer[] ads = new Integer[alleleAds.size()];
return ArrayUtils.toPrimitive(alleleAds.toArray(ads));
}
use of htsjdk.variant.variantcontext.Genotype in project hmftools by hartwigmedical.
the class MNVMerger method mergeVariants.
// MIVO: assumes variant list is sorted by start position and variants have only one sample (tumor)
// MIVO: gaps will *ALWAYS* be added to the output variant (no checking is done here to make sure they are needed)
@NotNull
@VisibleForTesting
static VariantContext mergeVariants(@NotNull final List<VariantContext> variants, @NotNull final Map<Integer, Character> gapReads) {
final List<Allele> alleles = createMnvAlleles(variants, gapReads);
final VariantContext firstVariant = variants.get(0);
final VariantContext lastVariant = variants.get(variants.size() - 1);
final Map<String, Object> attributes = createMnvAttributes(variants);
final String sampleName = firstVariant.getSampleNamesOrderedByName().get(0);
final Genotype genotype = new GenotypeBuilder(sampleName, alleles).DP(mergeDP(variants)).AD(mergeAD(variants)).make();
return new VariantContextBuilder(firstVariant.getSource(), firstVariant.getContig(), firstVariant.getStart(), lastVariant.getEnd(), alleles).genotypes(genotype).filters(firstVariant.getFilters()).attributes(attributes).make();
}
use of htsjdk.variant.variantcontext.Genotype in project ASCIIGenome by dariober.
the class GenotypeMatrix method genotypeAsAlleleIndexes.
/**
* Get the sample genotype in the same format as it appears on the VCF file.
* I.e. allele indexes separated by '/' or '|' (if phased). E.g. 0/0, 0/1 etc
*/
private String genotypeAsAlleleIndexes(VariantContext ctx, String sample) {
Genotype gt = ctx.getGenotype(sample);
char sep = gt.isPhased() ? '|' : '/';
List<String> all = new ArrayList<String>();
for (Allele a : gt.getAlleles()) {
if (a.isNoCall()) {
all.add(".");
} else {
int i = ctx.getAlleleIndex(a);
all.add(Integer.toString(i));
}
}
return '"' + Joiner.on(sep).join(all) + '"';
}
use of htsjdk.variant.variantcontext.Genotype in project jvarkit by lindenb.
the class BamToSVG method printSample.
private void printSample(XMLStreamWriter w, double top_y, final Sample sample) throws XMLStreamException {
w.writeComment("START SAMPLE: " + sample.name);
w.writeStartElement(SVG.NS, "g");
w.writeAttribute("transform", "translate(0," + top_y + ")");
double y = 0;
/* write title */
w.writeEmptyElement("path");
w.writeAttribute("class", "samplename");
w.writeAttribute("title", sample.name);
w.writeAttribute("d", this.hershey.svgPath(sample.name, scaleRect(new Rectangle2D.Double(0, y, this.drawinAreaWidth, HEIGHT_SAMPLE_NAME))));
y += HEIGHT_SAMPLE_NAME;
/* write REFERENCE */
w.writeComment("REFERENCE");
for (int pos = this.interval.start; // ignore if too small
this.featureWidth > 5 && pos <= this.interval.end; ++pos) {
char c = (this.genomicSequence == null ? 'N' : this.genomicSequence.charAt(pos - 1));
double x0 = baseToPixel(pos);
w.writeEmptyElement("use");
w.writeAttribute("x", format(x0));
w.writeAttribute("y", format(y));
w.writeAttribute("xlink", XLINK.NS, "href", "#b" + c);
}
y += featureHeight;
/* skip line for later consensus */
double consensus_y = y;
y += featureHeight;
Map<Integer, Counter<Character>> pos2consensus = new HashMap<Integer, Counter<Character>>();
/* print variants */
if (!pos2variant.isEmpty()) {
for (VariantContext ctx : this.pos2variant) {
Genotype g = ctx.getGenotype(sample.name);
if (g == null || !g.isCalled() || g.isHomRef())
continue;
if (ctx.getEnd() < this.interval.start)
continue;
if (ctx.getStart() > this.interval.end)
continue;
double x0 = baseToPixel(ctx.getStart());
w.writeEmptyElement("use");
w.writeAttribute("x", format(x0));
w.writeAttribute("y", format(y));
w.writeAttribute("title", ctx.getAltAlleleWithHighestAlleleCount().getDisplayString());
if (g.isHomVar()) {
w.writeAttribute("xlink", XLINK.NS, "href", "#homvar");
} else if (g.isHet()) {
w.writeAttribute("xlink", XLINK.NS, "href", "#het");
}
}
y += featureHeight;
}
/* print all lines */
w.writeComment("Alignments");
for (int nLine = 0; nLine < sample.lines.size(); ++nLine) {
w.writeStartElement("g");
w.writeAttribute("transform", "translate(0," + format(y + nLine * featureHeight) + ")");
List<SAMRecord> line = sample.lines.get(nLine);
// loop over records on that line
for (SAMRecord record : line) {
printSamRecord(w, record, pos2consensus);
}
// g
w.writeEndElement();
}
/* write consensus */
w.writeComment("Consensus");
for (int pos = this.interval.start; // ignore if too small
this.featureWidth > 5 && pos <= this.interval.end; ++pos) {
Counter<Character> cons = pos2consensus.get(pos);
if (cons == null)
continue;
char c = cons.getMostFrequent();
double x0 = baseToPixel(pos);
w.writeEmptyElement("use");
w.writeAttribute("x", format(x0));
w.writeAttribute("y", format(consensus_y));
w.writeAttribute("xlink", XLINK.NS, "href", "#b" + c);
}
/* surrounding frame for that sample */
w.writeEmptyElement("rect");
w.writeAttribute("class", "frame");
w.writeAttribute("x", format(0));
w.writeAttribute("y", format(0));
w.writeAttribute("width", format(drawinAreaWidth));
w.writeAttribute("height", format(sample.getHeight()));
// g for sample
w.writeEndElement();
w.writeComment("END SAMPLE: " + sample.name);
}
use of htsjdk.variant.variantcontext.Genotype in project jvarkit by lindenb.
the class IgvReview method start.
@Override
public void start(final Stage stage) throws Exception {
stage.setTitle(getClass().getSimpleName());
Predicate<VariantContext> ctxFilter;
Map<String, String> params = super.getParameters().getNamed();
if (params.containsKey("--filter")) {
ctxFilter = JexlVariantPredicate.create(params.get("--filter"));
} else {
ctxFilter = V -> true;
}
final List<String> args = super.getParameters().getUnnamed();
final File configFile;
if (args.isEmpty()) {
final FileChooser fc = new FileChooser();
final String lastDirStr = preferences.get(LAST_USED_DIR_KEY, null);
if (lastDirStr != null && !lastDirStr.isEmpty()) {
fc.setInitialDirectory(new File(lastDirStr));
}
fc.getExtensionFilters().addAll(Collections.singletonList(new FileChooser.ExtensionFilter("Config file", "*.config", "*.cfg", "*.list")));
configFile = fc.showOpenDialog(stage);
} else if (args.size() == 1) {
configFile = new File(args.get(0));
} else {
configFile = null;
}
if (configFile == null || !configFile.exists()) {
JfxUtils.dialog().cause("Illegal number of arguments or file doesn't exists.").show(stage);
Platform.exit();
return;
}
if (configFile.isFile() && configFile.getParentFile() != null) {
this.preferences.put(LAST_USED_DIR_KEY, configFile.getParentFile().getPath());
}
final List<String> configLines = Files.readAllLines(configFile.toPath());
final Predicate<String> ignoreComment = (S) -> !S.startsWith("#");
final Predicate<String> predVcf = S -> S.endsWith(".vcf") || S.endsWith(".vcf.gz");
if (configLines.stream().filter(ignoreComment).filter(predVcf).count() != 1) {
JfxUtils.dialog().cause("Found more than one vcf file in " + configFile).show(stage);
Platform.exit();
return;
}
final File vcfFile = configLines.stream().filter(ignoreComment).filter(predVcf).map(S -> new File(S)).findFirst().get();
LOG.info("Opening vcf file and loading in memory");
VCFFileReader vfr = null;
CloseableIterator<VariantContext> iter = null;
final Set<String> sampleNames;
try {
this.variants.clear();
vfr = new VCFFileReader(vcfFile, false);
this.vcfHeader = vfr.getFileHeader();
sampleNames = new HashSet<>(this.vcfHeader.getSampleNamesInOrder());
if (sampleNames.isEmpty()) {
JfxUtils.dialog().cause("No Genotypes in " + vcfFile).show(stage);
Platform.exit();
return;
}
iter = vfr.iterator();
this.variants.addAll(iter.stream().filter(ctxFilter).filter(CTX -> CTX.isVariant()).collect(Collectors.toList()));
} catch (final Exception err) {
JfxUtils.dialog().cause(err).show(stage);
Platform.exit();
return;
} finally {
CloserUtil.close(iter);
CloserUtil.close(vfr);
}
if (this.variants.isEmpty()) {
JfxUtils.dialog().cause("No Variants").show(stage);
Platform.exit();
return;
}
final SAMSequenceDictionary dict = this.vcfHeader.getSequenceDictionary();
if (dict == null || dict.isEmpty()) {
JfxUtils.dialog().cause(JvarkitException.VcfDictionaryMissing.getMessage(vcfFile.getPath())).show(stage);
Platform.exit();
return;
}
final SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.LENIENT);
configLines.stream().filter(ignoreComment).filter(S -> S.endsWith(".bam")).map(S -> new File(S)).forEach(F -> {
final SamReader samIn = srf.open(F);
final SAMFileHeader header = samIn.getFileHeader();
CloserUtil.close(samIn);
String sample = null;
for (final SAMReadGroupRecord rg : header.getReadGroups()) {
String s = rg.getSample();
if (s == null)
continue;
if (sample == null) {
sample = s;
} else if (!sample.equals(s)) {
JfxUtils.dialog().cause("Two samples in " + F).show(stage);
Platform.exit();
return;
}
}
if (sample == null) {
JfxUtils.dialog().cause("No sample in " + F + ". Ignoring").show(stage);
return;
}
if (!sampleNames.contains(sample)) {
JfxUtils.dialog().cause("Not in VCF header " + sample + " / " + F + ". Ignoring").show(stage);
return;
}
this.sample2bamFile.put(sample, F);
});
if (this.sample2bamFile.isEmpty()) {
JfxUtils.dialog().cause("No valid bam file in " + configFile).show(stage);
return;
}
sampleNames.retainAll(this.sample2bamFile.keySet());
if (sampleNames.isEmpty()) {
JfxUtils.dialog().cause("No Sample associated to bam").show(stage);
return;
}
ObservableList<VariantAndGenotype> genotypes = FXCollections.observableArrayList(this.variants.stream().flatMap(CTX -> CTX.getGenotypes().stream().filter(G -> sampleNames.contains(G.getSampleName())).map(G -> new VariantAndGenotype(CTX, G))).collect(Collectors.toList()));
if (genotypes.isEmpty()) {
JfxUtils.dialog().cause("No Genotype to show").show(stage);
return;
}
Menu menu = new Menu("File");
MenuItem menuItem = new MenuItem("Save as...");
menuItem.setOnAction(AE -> {
saveVariantsAs(stage);
});
menu.getItems().add(menuItem);
menuItem = new MenuItem("Save");
menuItem.setOnAction(AE -> {
if (this.saveAsFile != null) {
saveVariants(stage, this.saveAsFile);
} else {
saveVariantsAs(stage);
}
});
menu.getItems().add(menuItem);
menu.getItems().add(new SeparatorMenuItem());
menuItem = new MenuItem("Quit");
menuItem.setOnAction(AE -> {
Platform.exit();
});
menu.getItems().add(menuItem);
MenuBar bar = new MenuBar(menu);
this.genotypeTable = new TableView<>(genotypes);
this.genotypeTable.getColumns().add(makeColumn("CHROM", G -> G.ctx.getContig()));
this.genotypeTable.getColumns().add(makeColumn("POS", G -> G.ctx.getStart()));
this.genotypeTable.getColumns().add(makeColumn("ID", G -> G.ctx.getID()));
this.genotypeTable.getColumns().add(makeColumn("REF", G -> G.ctx.getReference().getDisplayString()));
this.genotypeTable.getColumns().add(makeColumn("ALT", G -> G.ctx.getAlternateAlleles().stream().map(A -> A.getDisplayString()).collect(Collectors.joining(","))));
this.genotypeTable.getColumns().add(makeColumn("Sample", G -> G.g.getSampleName()));
this.genotypeTable.getColumns().add(makeColumn("Type", G -> G.g.getType().name()));
this.genotypeTable.getColumns().add(makeColumn("Alleles", G -> G.g.getAlleles().stream().map(A -> A.getDisplayString()).collect(Collectors.joining(","))));
TableColumn<VariantAndGenotype, String> reviewCol = new TableColumn<>("Review");
reviewCol.setCellValueFactory(C -> C.getValue().getReviewProperty());
reviewCol.setCellFactory(TextFieldTableCell.forTableColumn());
reviewCol.setOnEditCommit((E) -> {
int y = E.getTablePosition().getRow();
this.genotypeTable.getItems().get(y).setReview(E.getNewValue());
});
reviewCol.setEditable(true);
this.genotypeTable.getColumns().add(reviewCol);
this.genotypeTable.getSelectionModel().cellSelectionEnabledProperty().set(true);
this.genotypeTable.setEditable(true);
final ContextMenu cm = new ContextMenu();
MenuItem mi1 = new MenuItem("Menu 1");
cm.getItems().add(mi1);
MenuItem mi2 = new MenuItem("Menu 2");
cm.getItems().add(mi2);
this.genotypeTable.setOnMousePressed(event -> {
if (event.isPrimaryButtonDown() && (event.getClickCount() == 3 || event.isShiftDown())) {
moveIgvTo(stage, genotypeTable.getSelectionModel().getSelectedItem());
} else if (event.isSecondaryButtonDown()) {
cm.show(genotypeTable, event.getScreenX(), event.getScreenY());
}
});
final BorderPane pane2 = new BorderPane(this.genotypeTable);
pane2.setPadding(new Insets(10, 10, 10, 10));
VBox vbox1 = new VBox(bar, pane2);
final Scene scene = new Scene(vbox1, 500, 300);
stage.setScene(scene);
stage.show();
}
Aggregations