Skip to content

Commit

Permalink
storage: Add variant-walker tool #TASK-6722
Browse files Browse the repository at this point in the history
  • Loading branch information
j-coll committed Oct 8, 2024
1 parent 285b667 commit 4b8dad2
Show file tree
Hide file tree
Showing 34 changed files with 1,950 additions and 175 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ protected List<String> getSteps() {
protected void run() throws Exception {
List<URI> uris = new ArrayList<>(2);
step(ID, () -> {
// Use scratch directory to store intermediate files. Move files to final directory at the end
// The scratch directory is expected to be faster than the final directory
// This also avoids moving files to final directory if the tool fails
Path outDir = getScratchDir();
String outputFile = StringUtils.isEmpty(toolParams.getOutputFileName())
? outDir.toString()
Expand All @@ -86,6 +89,7 @@ protected void run() throws Exception {
toolParams.getVariantsFile(), query, queryOptions, token));
});
step("move-files", () -> {
// Move files to final directory
IOManager ioManager = catalogManager.getIoManagerFactory().get(uris.get(0));
for (URI uri : uris) {
String fileName = UriUtils.fileName(uri);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.opencb.opencga.analysis.variant;

import org.apache.solr.common.StringUtils;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.opencga.analysis.tools.OpenCgaTool;
import org.opencb.opencga.catalog.io.IOManager;
import org.opencb.opencga.core.common.UriUtils;
import org.opencb.opencga.core.models.common.Enums;
import org.opencb.opencga.core.models.variant.VariantWalkerParams;
import org.opencb.opencga.core.tools.annotations.Tool;
import org.opencb.opencga.core.tools.annotations.ToolParams;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.io.VariantWriterFactory;

import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Tool(id = VariantWalkerTool.ID, description = VariantWalkerTool.DESCRIPTION,
scope = Tool.Scope.PROJECT, resource = Enums.Resource.VARIANT)
public class VariantWalkerTool extends OpenCgaTool {
public static final String ID = "variant-walk";
public static final String DESCRIPTION = "Filter and walk variants from the variant storage to produce a file";

@ToolParams
protected VariantWalkerParams toolParams = new VariantWalkerParams();

private VariantWriterFactory.VariantOutputFormat format;

@Override
protected void check() throws Exception {
super.check();

if (StringUtils.isEmpty(toolParams.getFileFormat())) {
toolParams.setFileFormat(VariantWriterFactory.VariantOutputFormat.VCF.toString());
}

format = VariantWriterFactory.toOutputFormat(toolParams.getOutputFileName(), toolParams.getOutputFileName());
}

@Override
protected List<String> getSteps() {
return Arrays.asList(ID, "move-files");
}

@Override
protected void run() throws Exception {
List<URI> uris = new ArrayList<>(2);
step(ID, () -> {
// Use scratch directory to store intermediate files. Move files to final directory at the end
// The scratch directory is expected to be faster than the final directory
// This also avoids moving files to final directory if the tool fails
Path outDir = getScratchDir();
String outputFile = StringUtils.isEmpty(toolParams.getOutputFileName())
? outDir.toString()
: outDir.resolve(toolParams.getOutputFileName()).toString();
Query query = toolParams.toQuery();
QueryOptions queryOptions = new QueryOptions(params);
for (VariantQueryParam param : VariantQueryParam.values()) {
queryOptions.remove(param.key());
}
uris.addAll(variantStorageManager.walkData(outputFile,
format, query, queryOptions, toolParams.getDockerImage(), toolParams.getCommandLine(), token));
});
step("move-files", () -> {
// Move files to final directory
IOManager ioManager = catalogManager.getIoManagerFactory().get(uris.get(0));
for (URI uri : uris) {
String fileName = UriUtils.fileName(uri);
logger.info("Moving file -- " + fileName);
ioManager.move(uri, getOutDir().resolve(fileName).toUri());
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.opencb.commons.datastore.solr.SolrManager;
import org.opencb.opencga.analysis.StorageManager;
import org.opencb.opencga.analysis.variant.VariantExportTool;
import org.opencb.opencga.analysis.variant.VariantWalkerTool;
import org.opencb.opencga.analysis.variant.manager.operations.*;
import org.opencb.opencga.analysis.variant.metadata.CatalogStorageMetadataSynchronizer;
import org.opencb.opencga.analysis.variant.metadata.CatalogVariantMetadataFactory;
Expand Down Expand Up @@ -187,6 +188,32 @@ public List<URI> exportData(String outputFile, VariantOutputFormat outputFormat,
});
}

/**
* Exports the result of the given query and the associated metadata.
*
* @param outputFile Optional output file. If null or empty, will print into the Standard output. Won't export any metadata.
* @param format Variant Output format.
* @param query Query with the variants to export
* @param queryOptions Query options
* @param dockerImage Docker image to use
* @param commandLine Command line to use
* @param token User's session id
* @throws CatalogException if there is any error with Catalog
* @throws StorageEngineException If there is any error exporting variants
* @return generated files
*/
public List<URI> walkData(String outputFile, VariantOutputFormat format,
Query query, QueryOptions queryOptions, String dockerImage, String commandLine, String token)
throws CatalogException, StorageEngineException {
String anyStudy = catalogUtils.getAnyStudy(query, token);
return secureAnalysis(VariantWalkerTool.ID, anyStudy, queryOptions, token, engine -> {
Query finalQuery = catalogUtils.parseQuery(query, queryOptions, engine.getCellBaseUtils(), token);
checkSamplesPermissions(finalQuery, queryOptions, token);
URI outputUri = new VariantExportOperationManager(this, engine).getOutputUri(outputFile, format, finalQuery, token);
return engine.walkData(outputUri, format, finalQuery, queryOptions, dockerImage, commandLine);
});
}

// --------------------------//
// Data Operation methods //
// --------------------------//
Expand Down Expand Up @@ -506,6 +533,8 @@ public boolean hasVariantSetup(String studyStr, String token) throws CatalogExce

public ObjectMap configureProject(String projectStr, ObjectMap params, String token) throws CatalogException, StorageEngineException {
return secureOperationByProject("configure", projectStr, params, token, engine -> {
validateNewConfiguration(engine, params);

DataStore dataStore = getDataStoreByProjectId(projectStr, token);

dataStore.getOptions().putAll(params);
Expand All @@ -517,6 +546,7 @@ public ObjectMap configureProject(String projectStr, ObjectMap params, String to

public ObjectMap configureStudy(String studyStr, ObjectMap params, String token) throws CatalogException, StorageEngineException {
return secureOperation("configure", studyStr, params, token, engine -> {
validateNewConfiguration(engine, params);
Study study = catalogManager.getStudyManager()
.get(studyStr,
new QueryOptions(INCLUDE, StudyDBAdaptor.QueryParams.INTERNAL_CONFIGURATION_VARIANT_ENGINE_OPTIONS.key()),
Expand All @@ -540,6 +570,14 @@ public ObjectMap configureStudy(String studyStr, ObjectMap params, String token)
});
}

private void validateNewConfiguration(VariantStorageEngine engine, ObjectMap params) throws StorageEngineException {
for (VariantStorageOptions option : VariantStorageOptions.values()) {
if (option.isProtected() && params.get(option.key()) != null) {
throw new StorageEngineException("Unable to update protected option '" + option.key() + "'");
}
}
}

/**
* Modify SampleIndex configuration. Automatically submit a job to rebuild the sample index.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.io.VariantWriterFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
Expand All @@ -48,6 +49,17 @@ public VariantExportOperationManager(VariantStorageManager variantStorageManager

public List<URI> export(String outputFileStr, VariantWriterFactory.VariantOutputFormat outputFormat, String variantsFile,
Query query, QueryOptions queryOptions, String token) throws Exception {
URI outputFile = getOutputUri(outputFileStr, outputFormat, query, token);

VariantMetadataFactory metadataExporter =
new CatalogVariantMetadataFactory(catalogManager, variantStorageEngine.getDBAdaptor(), token);

URI variantsFileUri = StringUtils.isEmpty(variantsFile) ? null : UriUtils.createUri(variantsFile);
return variantStorageEngine.exportData(outputFile, outputFormat, variantsFileUri, query, queryOptions, metadataExporter);
}

public URI getOutputUri(String outputFileStr, VariantWriterFactory.VariantOutputFormat format, Query query, String token)
throws CatalogException, IOException {
URI outputFile;
if (!VariantWriterFactory.isStandardOutput(outputFileStr)) {
URI outdirUri;
Expand All @@ -71,19 +83,14 @@ public List<URI> export(String outputFileStr, VariantWriterFactory.VariantOutput
outputFileName = buildOutputFileName(query, token);
}
outputFile = outdirUri.resolve(outputFileName);
outputFile = VariantWriterFactory.checkOutput(outputFile, outputFormat);
outputFile = VariantWriterFactory.checkOutput(outputFile, format);
} else {
outputFile = outdirUri;
}
} else {
outputFile = null;
}

VariantMetadataFactory metadataExporter =
new CatalogVariantMetadataFactory(catalogManager, variantStorageEngine.getDBAdaptor(), token);

URI variantsFileUri = StringUtils.isEmpty(variantsFile) ? null : UriUtils.createUri(variantsFile);
return variantStorageEngine.exportData(outputFile, outputFormat, variantsFileUri, query, queryOptions, metadataExporter);
return outputFile;
}

private String buildOutputFileName(Query query, String token) throws CatalogException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public abstract class OpenCgaCompleter implements Completer {
.map(Candidate::new)
.collect(toList());

private List<Candidate> variantList = asList( "aggregationstats","annotation-metadata","annotation-query","circos-run","cohort-stats-delete","cohort-stats-info","cohort-stats-run","exomiser-run","export-run","family-genotypes","family-qc-run","file-delete","gatk-run","genome-plot-run","gwas-run","hr-detect-run","index-run","individual-qc-run","inferred-sex-run","knockout-gene-query","knockout-individual-query","knockout-run","mendelian-error-run","metadata","mutational-signature-query","mutational-signature-run","plink-run","query","relatedness-run","rvtests-run","sample-aggregation-stats","sample-eligibility-run","sample-qc-run","sample-query","sample-run","sample-stats-query","sample-stats-run","stats-export-run","stats-run")
private List<Candidate> variantList = asList( "aggregationstats","annotation-metadata","annotation-query","circos-run","cohort-stats-delete","cohort-stats-info","cohort-stats-run","exomiser-run","export-run","family-genotypes","family-qc-run","file-delete","gatk-run","genome-plot-run","gwas-run","hr-detect-run","index-run","individual-qc-run","inferred-sex-run","knockout-gene-query","knockout-individual-query","knockout-run","mendelian-error-run","metadata","mutational-signature-query","mutational-signature-run","plink-run","query","relatedness-run","rvtests-run","sample-aggregation-stats","sample-eligibility-run","sample-qc-run","sample-query","sample-run","sample-stats-query","sample-stats-run","stats-export-run","stats-run","walker-run")
.stream()
.map(Candidate::new)
.collect(toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public OpencgaCliOptionsParser() {
analysisVariantSubCommands.addCommand("sample-stats-run", analysisVariantCommandOptions.runSampleStatsCommandOptions);
analysisVariantSubCommands.addCommand("stats-export-run", analysisVariantCommandOptions.runStatsExportCommandOptions);
analysisVariantSubCommands.addCommand("stats-run", analysisVariantCommandOptions.runStatsCommandOptions);
analysisVariantSubCommands.addCommand("walker-run", analysisVariantCommandOptions.runWalkerCommandOptions);

projectsCommandOptions = new ProjectsCommandOptions(commonCommandOptions, jCommander);
jCommander.addCommand("projects", projectsCommandOptions);
Expand Down
Loading

0 comments on commit 4b8dad2

Please sign in to comment.