From a79b421515e227c34239f025fb5c454d56a1eda4 Mon Sep 17 00:00:00 2001 From: Clint Valentine Date: Sun, 13 Feb 2022 19:39:56 -0500 Subject: [PATCH] Use allele info in VariantContext comparisons for stable sorts --- .gitignore | 1 + .../variantcontext/VariantContextComparator.java | 16 +++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index f10fff99c0..694f85de06 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ htsjdk.iws .command_tmp +.DS_Store atlassian-ide-plugin.xml /htsjdk.version.properties /test-output/ diff --git a/src/main/java/htsjdk/variant/variantcontext/VariantContextComparator.java b/src/main/java/htsjdk/variant/variantcontext/VariantContextComparator.java index d4e288f978..be407db31a 100644 --- a/src/main/java/htsjdk/variant/variantcontext/VariantContextComparator.java +++ b/src/main/java/htsjdk/variant/variantcontext/VariantContextComparator.java @@ -83,11 +83,17 @@ public int compare(final VariantContext firstVariantContext, final VariantContex // Will throw NullPointerException -- happily -- if either of the chromosomes/contigs aren't // present. This error checking should already have been done in the constructor but it's left // in as defence anyway. - final int contigCompare = - this.contigIndexLookup.get(firstVariantContext.getContig()) - this.contigIndexLookup.get(secondVariantContext.getContig()); - return contigCompare != 0 - ? contigCompare - : firstVariantContext.getStart() - secondVariantContext.getStart(); + int contigCompare = this.contigIndexLookup.get(firstVariantContext.getContig()).compareTo(this.contigIndexLookup.get(secondVariantContext.getContig())); + contigCompare = contigCompare == 0 ? firstVariantContext.getStart() - secondVariantContext.getStart() : contigCompare; + if (contigCompare == 0) { + // Compare variants that have the same genomic span (chr:start-end) lexicographically by all alleles (ref and alts). + for (int i = 0; i < firstVariantContext.getAlleles().size(); i++) { + if (i > secondVariantContext.getAlleles().size()) { return 1; } + contigCompare = firstVariantContext.getAlleles().get(i).compareTo(secondVariantContext.getAlleles().get(i)); + if (contigCompare != 0) return contigCompare; + } + } + return contigCompare; } /**