diff --git a/SequenceAnalysis/resources/web/SequenceAnalysis/field/ChainFileSelectorField.js b/SequenceAnalysis/resources/web/SequenceAnalysis/field/ChainFileSelectorField.js new file mode 100644 index 000000000..ed3bb3cf0 --- /dev/null +++ b/SequenceAnalysis/resources/web/SequenceAnalysis/field/ChainFileSelectorField.js @@ -0,0 +1,88 @@ +Ext4.define('SequenceAnalysis.field.ChainFileSelectorField', { + extend: 'LABKEY.ext4.ComboBox', + alias: 'widget.sequenceanalysis-chainfileselectorfield', + + genomeId: -1, + valueField: 'dataid', + + initComponent: function(){ + Ext4.apply(this, { + xtype: 'labkey-combo', + itemId: 'chainFileId', + fieldLabel: 'Target Genome', + forceSelection: true, + width: 450, + store: { + type: 'labkey-store', + schemaName: 'sequenceanalysis', + queryName: 'chain_files', + columns: 'rowid,chainFile,genomeId2,genomeId2/name', + filterArray: this.getFilterArray(), + autoLoad: true + }, + displayField: 'genomeId2/name', + valueField: 'chainFile', + allowBlank: false + }); + + this.callParent(arguments); + + this.on('afterrender', function() { + var parent = this.up('sequenceanalysis-basesequencepanel'); //Alignment panels + var window = this.up('window'); //OutputHandlerWindow + + if (parent) { + var field = parent.down('field[name=referenceLibraryCreation.SavedLibrary.libraryId]'); + if (field) { + this.mon(field, 'change', this.onGenomeChange, this); + if (field.getValue()){ + this.updateStoreFilters(field.getValue()); + } + } + else if (parent.libraryIds){ + if (parent.libraryIds.length === 1){ + this.updateStoreFilters(parent.libraryIds[0]); + } + else if (!parent.libraryIds.length){ + Ext4.Msg.alert('Genome Error', 'There are no reference genomes associated with these samples'); + } + else if (parent.libraryIds.length > 1){ + Ext4.Msg.alert('Genome Error', 'More than one reference genome associated with these samples. They must all use the same genome.'); + } + } + else { + LDK.Utils.logError('unable to find library field in ChainFileSelectorField'); + } + } + else if (window && window.libraryId){ + this.updateStoreFilters(window.libraryId); + } + else { + LDK.Utils.logError('unable to find basesequencepanel in ChainFileSelectorField'); + Ext4.Msg.alert('Error', 'There is no genome ID provided to this field. This indicates an error in how the module was developed - please contact your administrator.'); + } + }, this); + }, + + onGenomeChange: function(field, genomeId){ + genomeId = genomeId ? genomeId : -1; + if (genomeId === this.genomeId){ + return; + } + + this.updateStoreFilters(genomeId); + }, + + updateStoreFilters: function(genomeId){ + this.genomeId = genomeId; + this.store.filterArray = this.getFilterArray(); + this.store.load(); + }, + + getFilterArray: function(){ + return [ + LABKEY.Filter.create('dateDisabled', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('genomeId1', this.genomeId, LABKEY.Filter.Types.EQUAL) + ] + } +}); \ No newline at end of file diff --git a/SequenceAnalysis/src/org/labkey/sequenceanalysis/SequenceAnalysisModule.java b/SequenceAnalysis/src/org/labkey/sequenceanalysis/SequenceAnalysisModule.java index c5d12f175..8338f7c35 100644 --- a/SequenceAnalysis/src/org/labkey/sequenceanalysis/SequenceAnalysisModule.java +++ b/SequenceAnalysis/src/org/labkey/sequenceanalysis/SequenceAnalysisModule.java @@ -163,6 +163,7 @@ import org.labkey.sequenceanalysis.run.util.CombineGVCFsHandler; import org.labkey.sequenceanalysis.run.util.FastqcRunner; import org.labkey.sequenceanalysis.run.util.SVAnnotateStep; +import org.labkey.sequenceanalysis.run.variant.AnnotateByLiftoverStep; import org.labkey.sequenceanalysis.run.variant.DepthOfCoverageHandler; import org.labkey.sequenceanalysis.run.variant.GenotypeConcordanceStep; import org.labkey.sequenceanalysis.run.variant.GenotypeFiltrationStep; @@ -377,6 +378,7 @@ public static void registerPipelineSteps() SequencePipelineService.get().registerPipelineStep(new BcftoolsFillFromFastaStep.Provider()); SequencePipelineService.get().registerPipelineStep(new SVAnnotateStep.Provider()); SequencePipelineService.get().registerPipelineStep(new WhatsHapStep.Provider()); + SequencePipelineService.get().registerPipelineStep(new AnnotateByLiftoverStep.Provider()); //handlers SequenceAnalysisService.get().registerFileHandler(new LiftoverHandler()); diff --git a/SequenceAnalysis/src/org/labkey/sequenceanalysis/analysis/LiftoverHandler.java b/SequenceAnalysis/src/org/labkey/sequenceanalysis/analysis/LiftoverHandler.java index 6da4d9c87..7c9b03df1 100644 --- a/SequenceAnalysis/src/org/labkey/sequenceanalysis/analysis/LiftoverHandler.java +++ b/SequenceAnalysis/src/org/labkey/sequenceanalysis/analysis/LiftoverHandler.java @@ -33,6 +33,7 @@ import org.labkey.api.sequenceanalysis.run.LiftoverBcfToolsWrapper; import org.labkey.api.sequenceanalysis.run.SelectVariantsWrapper; import org.labkey.api.util.FileType; +import org.labkey.api.util.FileUtil; import org.labkey.api.view.ActionURL; import org.labkey.api.writer.PrintWriters; import org.labkey.sequenceanalysis.SequenceAnalysisModule; @@ -133,7 +134,7 @@ public boolean canProcess(SequenceOutputFile f) private static File getUnmappedOutputFile(File liftedVcfFile) { - return new File(liftedVcfFile.getParentFile(), liftedVcfFile.getName().replaceAll(".lifted-", ".unmapped-")); + return FileUtil.appendName(liftedVcfFile.getParentFile(), liftedVcfFile.getName().replaceAll(".lifted-", ".unmapped-")); } private static String getOutputExtension(File inputFile) @@ -214,7 +215,7 @@ public void processFilesRemote(List inputFiles, JobContext c throw new PipelineJobException("Expected single input file"); } - SequenceOutputFile f = inputFiles.get(0); + SequenceOutputFile f = inputFiles.getFirst(); job.getLogger().info("processing output: " + f.getFile().getName()); RecordedAction action = new RecordedAction(getName()); @@ -228,7 +229,7 @@ public void processFilesRemote(List inputFiles, JobContext c File outDir = ((FileAnalysisJobSupport) job).getAnalysisDirectory().toNioPathForRead().toFile(); String baseName = SequenceAnalysisService.get().getUnzippedBaseName(f.getFile().getName()); - File lifted = new File(outDir, baseName + ".lifted-" + targetGenomeId + getOutputExtension(f.getFile())); + File lifted = FileUtil.appendName(outDir, baseName + ".lifted-" + targetGenomeId + getOutputExtension(f.getFile())); File unmappedOutput = retainUnmapped ? getUnmappedOutputFile(lifted) : null; try @@ -316,7 +317,7 @@ public void liftOverVcf(JobContext ctx, ReferenceGenome targetGenome, ReferenceG if (dropGenotypes || intervals != null) { ctx.getLogger().info("subsetting VCF"); - File outputFile = new File(output.getParentFile(), SequenceAnalysisService.get().getUnzippedBaseName(currentVCF.getName()) + ".noGenotypes.vcf.gz"); + File outputFile = FileUtil.appendName(output.getParentFile(), SequenceAnalysisService.get().getUnzippedBaseName(currentVCF.getName()) + ".noGenotypes.vcf.gz"); if (new File(outputFile.getPath() + ".tbi").exists()) { ctx.getLogger().info("resuming from file: " + outputFile.getPath()); @@ -364,7 +365,7 @@ public void liftOverVcf(JobContext ctx, ReferenceGenome targetGenome, ReferenceG File unmappedOutputFile = unmappedOutput; if (unmappedOutputFile == null) { - unmappedOutputFile = new File(currentVCF.getParentFile(), "liftoverRejects.vcf.gz"); + unmappedOutputFile = FileUtil.appendName(currentVCF.getParentFile(), "liftoverRejects.vcf.gz"); } LiftoverVcfWrapper wrapper = new LiftoverVcfWrapper(job.getLogger()); @@ -410,7 +411,7 @@ public File getScatterJobOutput(JobContext ctx) throws PipelineJobException { if (ctx.getJob() instanceof SequenceOutputHandlerJob sj) { - SequenceOutputFile so = sj.getFiles().get(0); + SequenceOutputFile so = sj.getFiles().getFirst(); return ProcessVariantsHandler.getScatterOutputByCategory(ctx, so.getCategory()); } @@ -423,7 +424,7 @@ public File getScatterJobOutput(JobContext ctx) throws PipelineJobException @Override public SequenceOutputFile createFinalSequenceOutput(PipelineJob job, File processed, List inputFiles) throws PipelineJobException { - return ProcessVariantsHandler.createSequenceOutput(job, processed, inputFiles, inputFiles.get(0).getCategory()); + return ProcessVariantsHandler.createSequenceOutput(job, processed, inputFiles, inputFiles.getFirst().getCategory()); } public void liftOverBed(File chain, File input, File output, @Nullable File unmappedOutput, PipelineJob job, double pct) throws IOException, PipelineJobException @@ -498,7 +499,7 @@ public void performAdditionalMergeTasks(JobContext ctx, PipelineJob job, Referen throw new PipelineJobException("No unmapped VCF found"); } - File combined = getUnmappedOutputFile(orderedScatterOutputs.get(0)); + File combined = getUnmappedOutputFile(orderedScatterOutputs.getFirst()); File combinedIdx = new File(combined.getPath() + ".tbi"); if (combinedIdx.exists()) { @@ -510,7 +511,7 @@ public void performAdditionalMergeTasks(JobContext ctx, PipelineJob job, Referen } SequenceOutputFile so = new SequenceOutputFile(); - so.setName(orderedScatterOutputs.get(0).getName() + ": Lifted/Unmapped"); + so.setName(orderedScatterOutputs.getFirst().getName() + ": Lifted/Unmapped"); so.setFile(combined); so.setCategory("VCF File"); so.setLibrary_id(genome.getGenomeId()); diff --git a/SequenceAnalysis/src/org/labkey/sequenceanalysis/run/variant/AnnotateByLiftoverStep.java b/SequenceAnalysis/src/org/labkey/sequenceanalysis/run/variant/AnnotateByLiftoverStep.java new file mode 100644 index 000000000..880ac0ea5 --- /dev/null +++ b/SequenceAnalysis/src/org/labkey/sequenceanalysis/run/variant/AnnotateByLiftoverStep.java @@ -0,0 +1,283 @@ +package org.labkey.sequenceanalysis.run.variant; + +import htsjdk.samtools.util.Interval; +import org.jetbrains.annotations.Nullable; +import org.json.JSONObject; +import org.labkey.api.data.ContainerType; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.data.TableInfo; +import org.labkey.api.data.TableSelector; +import org.labkey.api.exp.api.ExpData; +import org.labkey.api.exp.api.ExperimentService; +import org.labkey.api.pipeline.PipelineJob; +import org.labkey.api.pipeline.PipelineJobException; +import org.labkey.api.query.FieldKey; +import org.labkey.api.query.QueryService; +import org.labkey.api.sequenceanalysis.SequenceAnalysisService; +import org.labkey.api.sequenceanalysis.SequenceOutputFile; +import org.labkey.api.sequenceanalysis.pipeline.AbstractVariantProcessingStepProvider; +import org.labkey.api.sequenceanalysis.pipeline.BcftoolsRunner; +import org.labkey.api.sequenceanalysis.pipeline.PipelineContext; +import org.labkey.api.sequenceanalysis.pipeline.PipelineStepProvider; +import org.labkey.api.sequenceanalysis.pipeline.ReferenceGenome; +import org.labkey.api.sequenceanalysis.pipeline.SequenceAnalysisJobSupport; +import org.labkey.api.sequenceanalysis.pipeline.ToolParameterDescriptor; +import org.labkey.api.sequenceanalysis.pipeline.VariantProcessingStep; +import org.labkey.api.sequenceanalysis.pipeline.VariantProcessingStepOutputImpl; +import org.labkey.api.sequenceanalysis.run.AbstractCommandPipelineStep; +import org.labkey.api.sequenceanalysis.run.DISCVRSeqRunner; +import org.labkey.api.sequenceanalysis.run.LiftoverBcfToolsWrapper; +import org.labkey.api.util.FileUtil; +import org.labkey.api.util.PageFlowUtil; +import org.labkey.sequenceanalysis.SequenceAnalysisSchema; +import org.labkey.sequenceanalysis.run.util.VariantAnnotatorWrapper; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Created by bimber on 5/2/2017. + */ +public class AnnotateByLiftoverStep extends AbstractCommandPipelineStep implements VariantProcessingStep +{ + public static final String CHAIN_FILE = "chainFileId"; + public static final String TARGET_GENOME = "targetGenomeId"; + + final List liftFields = Arrays.asList("LiftedContig", "LiftedStart", "LiftedStop", "ReverseComplementedAlleles"); + + public AnnotateByLiftoverStep(PipelineStepProvider provider, PipelineContext ctx) + { + super(provider, ctx, new BcftoolsRunner(ctx.getLogger())); + } + + public static class Provider extends AbstractVariantProcessingStepProvider implements SupportsScatterGather + { + public Provider() + { + super("AnnotateByLiftoverStep", "Annotate Using LiftOver", "LiftOver/BackportLiftedVcf", "This will lift a VCF to the target genome, and then use this result to annotate annotate an input NHP VCF using human annotations including funcotator. This jobs will automatically look for chain files based on the source VCF genome and GRCh37/38 targets and will fail if these are not found.", Arrays.asList( + ToolParameterDescriptor.createExpDataParam(CHAIN_FILE, "Target Genome", "The target genome for liftover", "sequenceanalysis-chainfileselectorfield", new JSONObject() + {{ + put("allowBlank", false); + }}, null) + ), new LinkedHashSet(List.of("sequenceanalysis/field/ChainFileSelectorField.js")), null); + } + + @Override + public AnnotateByLiftoverStep create(PipelineContext context) + { + return new AnnotateByLiftoverStep(this, context); + } + } + + @Override + public void init(PipelineJob job, SequenceAnalysisJobSupport support, List inputFiles) throws UnsupportedOperationException, PipelineJobException + { + Set genomeIds = new HashSet<>(); + for (SequenceOutputFile so : inputFiles) + { + genomeIds.add(so.getLibrary_id()); + } + + if (genomeIds.size() != 1) + { + throw new PipelineJobException("All inputs must be from the same genome"); + } + + Integer chainFileId = getProvider().getParameterByName(CHAIN_FILE).extractValue(getPipelineCtx().getJob(), getProvider(), getStepIdx(), Integer.class); + if (chainFileId == null) + { + throw new PipelineJobException("Chain file not provided"); + } + + //find chain files: + job.getLogger().debug("Caching chain file"); + ExpData data = ExperimentService.get().getExpData(chainFileId); + if (data == null) + { + throw new PipelineJobException("Unable to find ExpData chain file: " + chainFileId); + } + + support.cacheExpData(data); + + // Target Genome: + TableInfo ti = QueryService.get().getUserSchema(getPipelineCtx().getJob().getUser(), getPipelineCtx().getJob().getContainer().getContainerFor(ContainerType.DataType.tabParent), SequenceAnalysisSchema.SCHEMA_NAME).getTable(SequenceAnalysisSchema.TABLE_CHAIN_FILES); + Integer targetGenomeId = new TableSelector(ti, PageFlowUtil.set("genomeId2"), new SimpleFilter(FieldKey.fromString("chainFile"), chainFileId), null).getObject(Integer.class); + support.cacheObject(TARGET_GENOME, targetGenomeId); + + ReferenceGenome rg = SequenceAnalysisService.get().getReferenceGenome(targetGenomeId, getPipelineCtx().getJob().getUser()); + support.cacheGenome(rg); + } + + private boolean indexExists(File vcf) + { + return new File(vcf.getPath() + ".tbi").exists(); + } + + @Override + public Output processVariants(File inputVCF, File outputDirectory, ReferenceGenome genome, @Nullable List intervals) throws PipelineJobException + { + VariantProcessingStepOutputImpl output = new VariantProcessingStepOutputImpl(); + + Integer chainFileId = getProvider().getParameterByName(CHAIN_FILE).extractValue(getPipelineCtx().getJob(), getProvider(), getStepIdx(), Integer.class); + File chainFile = getPipelineCtx().getSequenceSupport().getCachedData(chainFileId); + if (!chainFile.exists()) + { + throw new PipelineJobException("Unable to find chain file: " + chainFileId); + } + + int targetGenomeId = getPipelineCtx().getSequenceSupport().getCachedObject(TARGET_GENOME, Integer.class); + ReferenceGenome targetGenome = getPipelineCtx().getSequenceSupport().getCachedGenome(targetGenomeId); + + // Subset, drop annotations and genotypes: + File subsetVcf = FileUtil.appendName(outputDirectory, SequenceAnalysisService.get().getUnzippedBaseName(inputVCF.getName()) + ".subset.vcf.gz"); + if (!indexExists(subsetVcf)) + { + BcftoolsRunner br = new BcftoolsRunner(getPipelineCtx().getLogger()); + + List selectArgs = new ArrayList<>(); + selectArgs.add(BcftoolsRunner.getBcfToolsPath().getPath()); + selectArgs.add("annotate"); + selectArgs.add("-x"); + selectArgs.add("INFO,FORMAT"); + + selectArgs.add("-o"); + selectArgs.add(subsetVcf.getPath()); + + if (intervals != null) + { + selectArgs.add("-r"); + selectArgs.add(intervals.stream().map(interval -> interval.getContig() + ":" + interval.getStart() + "-" + interval.getEnd()).collect(Collectors.joining(","))); + } + + selectArgs.add(inputVCF.getPath()); + + br.execute(selectArgs); + + try + { + SequenceAnalysisService.get().ensureVcfIndex(subsetVcf, getPipelineCtx().getLogger()); + } + catch (IOException e) + { + throw new PipelineJobException(e); + } + } + else + { + getPipelineCtx().getLogger().debug("VCF index exists, skipping subset: " + subsetVcf.getPath()); + } + output.addIntermediateFile(subsetVcf); + output.addIntermediateFile(new File(subsetVcf.getPath() + ".tbi")); + + // Lift + File liftedVcf = FileUtil.appendName(outputDirectory, SequenceAnalysisService.get().getUnzippedBaseName(inputVCF.getName()) + ".lifted.vcf.gz"); + if (!indexExists(liftedVcf)) + { + LiftoverBcfToolsWrapper lbw = new LiftoverBcfToolsWrapper(getPipelineCtx().getLogger()); + lbw.doLiftover(subsetVcf, chainFile, genome.getWorkingFastaFile(), targetGenome.getWorkingFastaFile(), null, liftedVcf); + + try + { + SequenceAnalysisService.get().ensureVcfIndex(liftedVcf, getPipelineCtx().getLogger()); + } + catch (IOException e) + { + throw new PipelineJobException(e); + } + } + else + { + getPipelineCtx().getLogger().debug("VCF index exists, skipping liftOver: " + liftedVcf.getPath()); + } + output.addIntermediateFile(liftedVcf); + output.addIntermediateFile(new File(liftedVcf.getPath() + ".tbi")); + + // Backport + File liftedVcfBackport = FileUtil.appendName(outputDirectory, SequenceAnalysisService.get().getUnzippedBaseName(inputVCF.getName()) + ".lifted.bp.vcf.gz"); + if (!indexExists(liftedVcfBackport)) + { + DISCVRSeqRunner bpRunner = new DISCVRSeqRunner(getPipelineCtx().getLogger()); + List args = bpRunner.getBaseArgs("BackportLiftedVcf"); + + args.add("-V"); + args.add(liftedVcf.getPath()); + + args.add("-R"); + args.add(targetGenome.getWorkingFastaFile().getPath()); + + args.add("--targetFasta"); + args.add(genome.getWorkingFastaFile().getPath()); + + args.add("-O"); + args.add(liftedVcfBackport.getPath()); + + bpRunner.execute(args); + if (!liftedVcfBackport.exists()) + { + throw new PipelineJobException("Unable to find file: " + liftedVcfBackport.getPath()); + } + } + else + { + getPipelineCtx().getLogger().debug("VCF index exists, skipping liftOver/backport: " + liftedVcfBackport.getPath()); + } + output.addIntermediateFile(liftedVcfBackport); + output.addIntermediateFile(new File(liftedVcfBackport.getPath() + ".tbi")); + + // Annotate original: + File vcfAnnotated = FileUtil.appendName(outputDirectory, SequenceAnalysisService.get().getUnzippedBaseName(inputVCF.getName()) + ".lifted.bp.annot.vcf.gz"); + if (!indexExists(vcfAnnotated)) + { + VariantAnnotatorWrapper bpRunner = new VariantAnnotatorWrapper(getPipelineCtx().getLogger()); + List args = bpRunner.getBaseArgs("VariantAnnotator"); + + args.add("-V"); + args.add(liftedVcfBackport.getPath()); + + args.add("-R"); + args.add(genome.getWorkingFastaFile().getPath()); + + args.add("-O"); + args.add(vcfAnnotated.getPath()); + + args.add("-O"); + args.add(vcfAnnotated.getPath()); + + args.add("-resource:lifted"); + args.add(liftedVcfBackport.getPath()); + + args.add("--resource-allele-concordance"); + + args.add("-E"); + args.add("lifted.LiftedContig"); + + args.add("-E"); + args.add("lifted.LiftedStart"); + + args.add("-E"); + args.add("lifted.LiftedStop"); + + bpRunner.execute(args); + if (!liftedVcfBackport.exists()) + { + throw new PipelineJobException("Unable to find file: " + vcfAnnotated.getPath()); + } + } + else + { + getPipelineCtx().getLogger().debug("VCF index exists, skipping liftOver/backport: " + vcfAnnotated.getPath()); + } + + output.setVcf(vcfAnnotated); + + return output; + } + +}