Package: cpg-workflows
Hail Batch WorkflowsThis repository provides implementations of genomics workflows using Hail Batch, specifically:WES/WGS Seqr Loader: FASTQ -> CRAM -> GVCF -> pVCF -> Matrix Table -> Elasticsearch index, with an ability to use parts of this pipeline as e.g. a single-sample germline variant calling workflow (FASTQ -> GVCF), joint-calling pipeline (GVCF -> pVCF), AS-VQSR pipeline, etc.WES/WGS Large Cohort Workflow: FASTQ -> CRAM -> GVCF -> VDS with Hail Table annotations.GATK-SV: CRAM -> VCF and more, orchestratesGATK-SV WDL workflowsin Hail Batch. SeeThis READMEfor more information.InstallationRequirements:Analysis runnerClone the repository recursively and change into the repository folder:gitclone--recurse-submodulesgit@github.com:populationgenomics/production-pipelines.gitcdproduction-pipelinesSeqr LoaderSeqr Loader is a combination of the followingWARP-inspired workflows:Single-sample whole genome and WES germline calling, FASTQ -> GVCF (BWA/DRAGMAP, GATK4 HaplotypeCaller)Single-sample calling with re-alignment, CRAM -> GVCF (we useBAZAMto extract FASTQ from CRAM/BAM)Whole genome and WES joint-calling, GVCFs -> pVCFWES AS-VQSR and WGS VQSR workflowsAs well as:The Broad's seqr loading pipelinesSomalierpedigree checksMultiQCQC reporting.The workflow uses Metamist as a source of FASTQ, CRAMs, and sample/participant metadata, and TOML configs for extended configuration (dataset and sequencing groups, Hail Batch parameters, Elasticsearch credentials, QC thresholds).Example usageTo run the Seqr Loader workflow on the dataset calledvalidation, create a config file~/myconfig.tomlas follows:[workflow]input_datasets=['validation']sequencing_type='genome'create_es_index_for_datasets=['validation']skip_sgs=['CPGXXXX',# eg: low coverage (8x)]Submitmain.py seqr_loaderto the analysis runner, and pass along the config above, as well as thecpg_workflowsDocker image:analysis-runner\--datasetseqr--description"Seqr Loader"--output-dir"seqr-loader"\--access-levelfull\--config~/myconfig.toml\--imageaustralia-southeast1-docker.pkg.dev/cpg-common/images/cpg_workflows:latest\main.py\seqr_loaderNote that you can pass multiple configs to the analysis runner, by repeating the--configoption multiple times. All config will be merged by the  analysis runner. For more info about configs, seeteam-docs.For more options available for seqr-loader configuration, check the seqr-loader defaults inconfigs/defaults/seqr_loader.tomlas well as cpg-workflows defaults incpg_workflows/defaults.toml.Seqr production load invocationconfigs/seqr-main.tomlprovides relevant configuration defaults for a CPG production seqr-loader run. Specifically, in contains the list of datasets to query from Metamist and joint-call together, and a list of blacklisted sequencing groups in those datasets. Another handy configs,configs/genome.tomlorconfigs/exome.toml, can be passed to subset sequencing groups to WGS or WES specifically. To use along withconfigs/seqr-main.toml, of these two must be provided, as the seqr-loader can work on only one type of data at a time.For example, to load the genome data:analysis-runner\--datasetseqr--description"Seqr Loader"--output-dir"seqr-loader"\--access-levelfull\--configconfigs/seqr-main.toml\--configconfigs/genome.toml\--imageaustralia-southeast1-docker.pkg.dev/cpg-common/images/cpg_workflows:latest\main.py\seqr_loaderStage selection example: only align Seqr sequencing groupsSeqr Loader can be used partially, controlled byworkflows/first_stages,workflows/last_stages, andworkflows/only_stagesparameters.In order to align data, you only need to trigger theAlignstage from the workflow (orCramMultiQC, if you also want a dataset-level MultiQC report), which can be done withworkflows/last_stages. So you can create a configuration file like the following:[workflow]last_stages=['CramMultiQC']And assuming it's named~/myconfig.toml, run:analysis-runner\--datasetseqr--description"CRAM MultiQC"--output-dir"seqr"\--access-levelfull\--configconfigs/seqr-main.toml\--configconfigs/genome.toml\--config~/myconfig.toml\--imageaustralia-southeast1-docker.pkg.dev/cpg-common/images/cpg_workflows:latest\main.py\seqr_loaderFor exomes, replaceconfigs/genome.tomlwithconfigs/exome.toml, or setsequencing_type = 'exome'in theworkflowsection.The sectionworkflows/input_datasetsinconfigs/seqr-main.tomlspecified the list of all projects to be processed, excluding sequencing groups specified in theworkflows/skip_sgssection.QC reports for each dataset would be exposed on a web server, e.g. forvalidationgenomes, the URL would behttps://main-web.populationgenomics.org.au/validation/qc/cram/multiqc.html, and for exomes, it will  behttps://main-web.populationgenomics.org.au/validation/exome/qc/cram/multiqc.html.If samples had pedigree data, a Somalier report will be run to infer and validate participant relationships, with report produced ashttps://main-web.populationgenomics.org.au/validation/qc/cram/somalier.htmlStage selection example: create GVCFs and QC variant callsRun the same command as in the above section, but with the following section in~/myconfig.toml:[workflow]last_stages=['GvcfMultiQC']The genome GVCF QC report will be exposed ashttps://main-web.populationgenomics.org.au/validation/qc/gvcf/multiqc.html, forvalidationsamples it would include ahap.pysection with validation stats.Stage selection example: upload Elasticsearch indicesIf you want the workflow to create Elasticsearch indices in the end, make sure you include the stageMtToEsinto the workflow (if every prerequisite stage is already finished, you can specify it underfirst_stages), and set theworkflow/create_es_index_for_datasetssection with the list of datasets for which you want the indices to be created:[workflow]first_stages=['MtToEs']create_es_index_for_datasets=['validation']The resulting index will be named using the current datestamp, or usingworfklow/output_versionoption if it's specified. The Elasticsearch server is configured using theelasticsearchsection inconfigs/defailts/seqr_loader.toml. The reason for not automatically creating indices for every project is that the Elasticsearch instance can easily run out of disk space, so additional safeguard is handy.Large Cohort WorkflowAnother workflow in this repository isHail Queryworkflow for large germline genomic variant calling cohorts.Large-cohort workflow diverges from seqr-loader after the single-sampleGenotypestage (which outputs GVCF files). Instead of using GATK for joint genotyping, it uses Hail VCF combiner:Combine GVCFs (generated by GATK4) into aVDSformat.Perform sample-level QC, including, pedigree, sex and ancestry inference.Perform variant-level QC, includingallele-specific VQSR.UsageGiven the config~/myconfig.tomlis:[workflow]input_datasets=['validation']sequencing_type='genome'scatter_count=20output_version='0.1'Run the analysis runner:analysis-runner\--datasetfewgenomes--description"Larcoh validation"--output-dir"larcoh"\--access-levelmain\--config~/myconfig.toml\--imageaustralia-southeast1-docker.pkg.dev/cpg-common/images/cpg_workflows:latest\main.py\large_cohortThe workflow will find inputs using Metamist along with available sample metadata (e.g. known population labels, pedigree), align and call GVCFs, and follow with the VCF combiner and downstream annotation, writing the results into thegs://cpg-validation-mainbucket.Note that you can pass multiple configs to the analysis runner, by repeating the--configoption multiple times. All config will be merged by the analysis runner. For more info about configs, seeteam-docs.For more options available for the large-cohort workflow configuration, check the defaults inconfigs/defaults/large_cohort.toml, as well as cpg-workflows defaults incpg_workflows/defaults.toml.OutputsVDSGVCFs are combined into aVDS folder formatwhich is writen togs://cpg-fewgenomes-test/vds/v0-1.vds.Sample QCSample-level metadata and QC is written togs://cpg-fewgenomes-test/large-cohort/v0-1/sample_qc.ht, with the following row fields.Metamist metadata:'s': str
'external_id': str
'dataset': str
'gvcf': str
'sex': str
'continental_pop': str
'subcontinental_pop': strhl.sample_qcannotations:'sample_qc': struct {
    n_het: int64,
    n_hom_var: int64,
    n_non_ref: int64,
    n_singleton: int64,
    n_singleton_ti: int64,
    n_singleton_tv: int64,
    n_snp: int64,
    n_insertion: int64,
    n_deletion: int64,
    n_transition: int64,
    n_transversion: int64,
    n_star: int64,
    r_ti_tv: float64,
    r_ti_tv_singleton: float64,
    r_het_hom_var: float64,
    r_insertion_deletion: float64,
    bases_over_gq_threshold: tuple (
        int64,
        int64,
        int64
    ),
    bases_over_dp_threshold: tuple (
        int64,
        int64,
        int64,
        int64,
        int64
    )
}Sex imputation:'is_female': bool
'var_data_chr20_mean_dp': float64
'chrX_mean_dp': float64
'chrX_ploidy': float64
'chrY_mean_dp': float64
'chrY_ploidy': float64
'X_karyotype': str
'Y_karyotype': str
'sex_karyotype': str
'impute_sex_stats': struct {
    f_stat: float64,
    n_called: int64,
    expected_homs: float64,
    observed_homs: int64
}Soft filters are assigned based on the sample QC (low_coverageandbad_sample_qc_metrics) and sex imputation results (sex_aneuploidyandambiguous_sex):'filters': set<str>Thresholds for sample QC filters are pulled from the config TOML (you can see the default values inconfigs/defaults/large_cohort.toml.RelatednessPC-Relate methodis used to identify pairs of the 1st and the 2nd degree relatives (kin coefficient threshold - below which samples are considered unrelated - is specified aslarge_cohort.max_kininTOML). Pairwise sample relatedness matrix is written as a Hail table index by a tuple of sample IDs:gs://cpg-fewgenomes-test/large-cohort/v0-1/relatedness.htRow fields:
    'i': str
    'j': str
    'kin': float64
    'ibd0': float64
    'ibd1': float64
    'ibd2': float64
----------------------------------------
Key: ['i', 'j']gs://cpg-fewgenomes-test/large-cohort/v0-1/relateds_to_drop.htis a sample-level table which contains related samples to drop, with top ranking sample selected from each family. Sets of unrelated individuals are determined using Hail'smaximal_independent_set.Row fields:
    's': str
    'rank': int64
----------------------------------------
Key: ['s']AncestryPCA results are written intogs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry:gs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry/eigenvalues.htgs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry/loadings.htgs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry/scores.htWhen there are samples with known continental population available (the metamist participant metadata field with that data can be specified in theTOMLaslarge_cohort.training_pop), a random forest method is used to infer population labels from the PCA results. The method is trained using 16 principal components as features on samples with known ancestry (the number of components can be adjusted in the TOML as well aslarge_cohort.n_pcs). Ancestry was assigned to all samples for which the probability of that ancestry was high enough (the threshold is configured aslarge_cohort.min_pop_probin the TOML). Results are written as sample-level tablegs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry/inferred_pop.ht.Row fields:
    's': str
    'scores': array<float64>
    'pop': str
    'is_training': bool
    'pca_scores': array<float64>
----------------------------------------
Key: ['s']Plots for PCA and loadings are written togs://cpg-fewgenomes-test-web/large-cohort/v0-1/ancestry/*, a bucket that is exposed ashttps://test-web.populationgenomics.org.au/fewgenomes/large-cohort/ancestry/*Dense subsetFor PCA and PC-relate, a dense subset of the original dataset is used. The markers for the subset are read from thereferences.gnomad.predetermined_qc_variantsHail table specified in the TOML config. The table is suitable for both exomes and genomes, so that a mixture of different sequencing types can be processed together. The resulting subset is written togs://cpg-fewgenomes-test/large-cohort/v0-1/dense-subset.mt.Allele-specific variant quality score recalibration (AS-VQSR)Variants from good quality samples are filtered using theAS-VQSR method:Variants are exported into a sites-only VCF,Batch jobs are submitted to create SNP and indel recalibration models using the allele-specific version of GATK Variant Quality Score RecalibrationVQSR, with the standard GATK training resources (HapMap, Omni, 1000 Genomes, Mills indels), and the following features:SNVs:AS_FS,AS_SOR,AS_ReadPosRankSum,AS_MQRankSum,AS_QD,AS_MQ,Indels:AS_FS,AS_SOR,AS_ReadPosRankSum,AS_MQRankSum,AS_QD.The models are applied to the VCFs and combine them back into one VCF.VCF is converted back into a sites-only locus-level Hail tablegs://cpg-fewgenomes-test/large-cohort/v0-1/vqsr.ht, with split multiallelics.Row fields:
    'locus': locus<GRCh38>
    'alleles': array<str>
    'filters': set<str>
    'info': struct {
        NEGATIVE_TRAIN_SITE: bool,
        POSITIVE_TRAIN_SITE: bool,
        culprit: str
    }
    'a_index': int32
    'was_split': boolNote that theinfo.AS-*annotations used for AS-VQSR are dropped, and only the resulting filter label is appended into thefiltersfield, e.g.VQSRTrancheINDEL99.50to99.90,VQSRTrancheSNP99.00to99.90+, etc. The AS_VQSLOD thresholds for assigning filters are configurable in theTOMLasvqsr.snp_filter_levelandvqsr.indel_filter_level.This pipeline is largely compiled from the following two WDL workflows:hail-ukbb-200k-callset/GenotypeAndFilter.AS.wdlTheBroad VQSR workflowdocumentedhere, translated from WDL with a help ofJanis.FrequenciesFrequencies are calculated using the Hail'shl.variant_qcmethod from good quality samples, and written togs://cpg-fewgenomes-test/large-cohort/v0-1/frequencies.htlocus-level table with split multiallelics:Row fields:
    'locus': locus<GRCh38>
    'alleles': array<str>
    'a_index': int32
    'was_split': bool
    'InbreedingCoeff': float64
    'dp_stats': struct {
        mean: float64,
        stdev: float64,
        min: float64,
        max: float64
    }
    'gq_stats': struct {
        mean: float64,
        stdev: float64,
        min: float64,
        max: float64
    }
    'AC': array<int32>
    'AF': array<float64>
    'AN': int32
    'homozygote_count': array<int32>
    'call_rate': float64
    'n_called': int64
    'n_not_called': int64
    'n_filtered': int64
    'n_het': int64
    'n_non_ref': int64
    'het_freq_hwe': float64
    'p_value_hwe': float64
    'p_value_excess_het': float64
----------------------------------------
Key: ['locus', 'alleles']Applied outputsTables generated by the workflow can be applied to a VDS or a split+dense matrix table in the following way:importhailashlvds=hl.vds.read_vds('gs://cpg-fewgenomes-test/vds/v0-1.vds')sample_qc_ht=hl.read_table('gs://cpg-fewgenomes-test/large-cohort/v0-1/sample_qc.ht')relateds_to_drop_ht=hl.read_table('gs://cpg-fewgenomes-test/large-cohort/v0-1/relateds_to_drop.ht')pop_ht=hl.read_table('gs://cpg-fewgenomes-test/large-cohort/v0-1/ancestry/inferred_pop.ht')vqsr_ht=hl.read_table('gs://cpg-fewgenomes-test/large-cohort/v0-1/vqsr.ht')freq_ht=hl.read_table('gs://cpg-fewgenomes-test/large-cohort/v0-1/frequencies.ht')# Row-level tables require a split+dense matrix table:vds=hl.vds.split_multi(vds,filter_changed_loci=True)mt=hl.vds.to_dense_mt(vds)# Hard-filtering samples and variants:mt=mt.filter_cols(hl.len(sample_qc_ht[mt.col_key].filters)>0,keep=False)mt=mt.filter_cols(hl.is_defined(relateds_to_drop_ht[mt.col_key]),keep=False)mt=mt.filter_rows(hl.len(vqsr_ht[mt.row_key].filters)>0,keep=False)# Annotating samples and variants:mt=mt.annotate_cols(**sample_qc_ht[mt.col_key])mt=mt.annotate_cols(**pop_ht[mt.col_key])mt=mt.annotate_rows(**vqsr_ht[mt.row_key])mt=mt.annotate_rows(**freq_ht[mt.row_key])ReferencesThe workflow is largely inspired bythe Hail pipeline used for the QC of gnomAD releases. Good summaries of gnomAD QC can be found in gnomAD update blog posts:https://macarthurlab.org/2017/02/27/the-genome-aggregation-database-gnomadhttps://macarthurlab.org/2018/10/17/gnomad-v2-1https://macarthurlab.org/2019/10/16/gnomad-v3-0https://gnomad.broadinstitute.org/blog/2020-10-gnomad-v3-1-new-content-methods-annotations-and-data-availability/#sample-and-variant-quality-controlhttps://blog.hail.is/whole-exome-and-whole-genome-sequencing-recommendations/GATK-SVBroad'sGATK-SV workflowis WIP, but it can be already used to call SV evidence from individual samples.Under the hood, the workflow invokes the GATK-SV WDL workflow using a managed Cromwell instance via the analysis runner helper functions. The WDL workflow repository isforked, and the latest commit to use is specified ingatk_sv/gatk_sv.pyas aGATK_SV_COMMITconstant.Building reference and dockersRunning the workflow requires the Broad reference data copied to aworkflow/reference_prefixbucket, and images copied toworkflow/image_registry_prefix. In order to do that, use the following scripts:bashsync_references.sh
pythonsync_images.pyThe latter script will print a section for thegatk-sv.toml[images]section, that you'd need to insert there to make sure the workflow points to the latest tags. Also, when updating the GATK-SV fork, double check that the[references.broad.sv.*]sections in the config are up-to-date as well, and add new missing reference files if there are any.DevelopmentDev installationAssumingpython3points topython3.10, set up a virtual environment:python3-mpipinstallvirtualenv
virtualenvvenvsourcevenv/bin/activateInstall the package, and the development environment:pipinstall-e.
pipinstall-rrequirements-dev.txtCodebaseThe entry point of the codebase ismain.pyscript. It containsWORKFLOWSdictionary, which is listing all available workflows. A workflow is defined by the final stages it needs to trigger, with each stage pulling other required stages recursively followingrequired_stageslinks. Those final stages are passed to therun_workflow()function, which would orchestrate stages and required inputs.In this documentation section, we describe in more detail how exactly it's implemented.cpg_workflowslibraryHail Batchis a powerful system for workflow programming and execution using cloud compute and storage. In CPG, we manage our own Hail Batch deployment, along with theanalysis-runnertool that provides an approachable and secure way to submit analysis scripts to Hail Batch.In Hail, the workflows can be described using Python, and be built to be parts of more complex applications. E.g. the analysis-runner uses Hail Batch to drive itself, and the genomic variation analysis tool called Hail Query can use Hail Batch as a backend. All that makes Hail Batch a natural choice to design genomics workflows.Classical genomics best-practices workflow implementations likeWARPandGATK-SVuse WDL to be run withCromwellor Terra. In order to integrate WDL workflows into a Hail Batch infrastructure, there are a few possible approaches.Start a Cromwell instance as part of Hail Batch job script, and submit a sub-workflow inside that job,Maintain a managed Cromwell instance, and wrap only workflow submissions in a Hail Batch job,Fully re-engineer WDL workflows in Python and Hail Batch.For the GATK-SV workflow, we went with the approach #2. The workflow is quite complex, it uses many layers of branching nested sub-workflows, and it implements even minor file processing commands as separate WDL tasks. We also do not intend to adjust this workflow much as of now. In order to run GATK-SV, we support a managed Cromwell instance along with aPython helperthat wraps interaction with Cromwell using Hail Batch jobs, and we utilize Cromwell API along withSwaggerto explore Cromwell logs.As for the WGS/WES germline variant workflows, we re-engineered them fully in Hail Batch, largely inspired by WARP, but with significant divergence from WARP: we added dataset-specific pedigree checks and dataset-specific MultiQC reports, allele-specific VQSR for WGS, cohort annotation using Hail Query and exporting to the Elasticsearch using scripts fromseqr-loading-pipelines. There are also several CPG-specific layers, like reading inputs and metadata fromMetamist; reporting analysis results back to Metamist; setting global configuration with TOML; and a necessity for a more fine-grained tuning of tool's parameters and compute resources.To facilitate re-engineering WARP workflows and creating workflows scratch, we implemented some abstractions in this module, namely a workflow "stage" with expected inputs, outputs, and dependencies, and "stage" target ("sample", "dataset", "cohort"). Unlike WDL's concept of nested sub-workflows, Hail Batch is intrinsically lower-level, naturally providing one layer of jobs, with each job corresponding to on bash script that is run on one cloud VM. That doesn't always match a higher-level task in the application domain. For example, a workflow stage called "genotype" can include multiple jobs to generate calling intervals, partition inputs, run the genotyping tool in parallel instances, gather results, perform post-processing and filtering. That "stage" would sit between an "alignment" stage and a "joint calling" stage, and a user might need to start a workflow from a specific stage, reusing pre-existing outputs; or run the pipeline only up to a specific stage. So it's helpful to abstract a set of jobs related in a domain-specific way as a stage, with an ability to restart/skip/select stages. It also turns out that GATK-SV facilitates from these abstractions too, as it consists of multiple disconnected sub-workflows of different levels.StagesThis library provides an abstraction interface on top of Hail Batch jobs, namely aStageabstract class, parametrised by theTargetabstract class, representing what target this stage works with.For example, a stage that performs read alignment to produce a CRAM file, would be derived fromSequencingGroupStage, and be parametrised bySequencingGroup, and a stage that performs joint-calling would be derived fromCohortStage, parametrised byCohort.EachStagefinal implementation must declare paths to the outputs it would write in theexpected_outputs()method. It must also define how jobs are added into Hail Batch using thequeue_jobs()method.For example, out "Align" stage that runs BWA might look like as following:fromcpg_utilsimportPathfromcpg_workflows.workflowimportstage,SequencingGroupStage,SequencingGroup,StageInput,StageOutputfromcpg_utils.hail_batchimportget_batch@stageclassAlign(SequencingGroupStage):defexpected_outputs(self,sequencing_group:SequencingGroup)->Path:returnsequencing_group.make_cram_path().pathdefqueue_jobs(self,sequencing_group:SequencingGroup,inputs:StageInput)->StageOutput|None:j=get_batch().new_job('BWA',self.get_job_attrs(sequencing_group))j.command(f'bwa ... >{j.output}')get_batch().write_output(j.output,str(self.expected_outputs(sequencing_group)))# Construct StageOutput object, where we pass a path to the results,returnself.make_outputs(sequencing_group,self.expected_outputs(sequencing_group),[j])Thequeue_jobs()method is expected to return an output of typeStageOutput: you can callself.make_outputs()to construct that object.Stages can depend on each other (i.e. they form a directed acyclic graph), which is specified using a parameterrequired_stagesto the@stageclass decorator, and theinputsparameter inqueue_jobs()to get the output of a previous stage. E.g. our sequencing group genotyping stage might look like this:fromcpg_utilsimportPathfromcpg_workflows.workflowimportstage,SequencingGroupStage,SequencingGroup,StageInput,StageOutputAlign=...@stage(required_stages=Align)classGenotype(SequencingGroupStage):defexpected_outputs(self,sequencing_group:SequencingGroup)->Path:returnsequencing_group.make_gvcf_path().pathdefqueue_jobs(self,sequencing_group:SequencingGroup,inputs:StageInput)->StageOutput|None:jobs=...returnself.make_outputs(sequencing_group,self.expected_outputs(sequencing_group),jobs)Stage of different levels can depend on each other, and the library will resolve that correctly. E.g. joint calling stage that takes GVCF outputs to produce a cohort-level VCF would look like this:fromcpg_utilsimportPathfromcpg_workflows.workflowimportstage,CohortStage,Cohort,StageInput,StageOutputGenotype=...@stage(required_stages=Genotype)classJointCalling(CohortStage):defexpected_outputs(self,cohort:Cohort)->Path:returncohort.analysis_dataset.prefix()/'joint-called.vcf.gz'defqueue_jobs(self,cohort:Cohort,inputs:StageInput)->StageOutput|None:# Get outputs from previous stage. Because the Genotype stage# acts on a sequencing_group, we use a method `as_path_by_target` that returns# a dictionary index by sequencing group ID:gvcf_path_by_sg=inputs.as_path_by_target(Genotype)assertlen(gvcf_path_by_sg)==len(cohort.get_sequencing_groups())jobs=...returnself.make_outputs(cohort,self.expected_outputs(cohort),jobs)To submit a set of defined stages to Hail Batch, just call therun_workflow(stages)method:fromcpg_workflows.workflowimportrun_workflowJointCalling=...run_workflow().run(stages=[JointCalling])It takes a list of stage classes as a single parameter, and it would resolve all implicit dependencies automatically.ConfigurationThe library implicitly reads configuration using thecpg_utils.config.get_config()from a TOML file specified in theCPG_CONFIG_PATHenvironment variables, which are passed via the analysis runner's--configflag. For example, you can prepare a TOML config fileconfig.tomlas follows:[workflow]sequencing_type='genome'only_datasets=['hgdp','thousand-genomes']skip_sgs=['CPGXXXX','CPGXXXX']skip_stages=['Align']check_inputs=true# checks e.g. if fastq for align stage existcheck_intermediates=false# explitic calls to can_reuse(path) will return Falsecheck_expected_outputs=true# if expected_outputs() exist, skip stageAnd execute the workflow scriptmain.pywith the analysis-runner as follows:analysis-runner--datasetseqr--access-leveltest-otest-workflow\--configconfigs/config.tomlmain.pyThe script would be able to access config parameters withfromcpg_utils.configimportget_configassertget_config()['workflow']['sequencing_type']=='genome'Note that the workflow implicitly reads inputs from Metamist, and requiresworkflow/only_datasetsandworkflow/sequencing_typeto be defined to pull proper inputs.TOML files inconfigs/defaultsandcpg_workflows/defaults.tomllist possible configuration parameters for workflows, please refer to those configs for documentation.Also keep in mind that analysis-runner would implicitly set a set of config parameters suitable specifically for the CPG infrastructure, e.g. the generated config after analysis-runner post-processing would look like this:[workflow]access_level="test"dataset_gcp_project="validation"dataset="validation"[hail]billing_project="validation"pool_label="large-cohort"[images]cpg_workflows="australia-southeast1-docker.pkg.dev/cpg-common/images/cpg_workflows:1.4.1"bcftools="australia-southeast1-docker.pkg.dev/cpg-common/images/bcftools:1.16"...[references]genome_build="GRCh38"vep_mount="gs://cpg-common-main/references/vep/105.0/mount"...[references.broad]dragmap_prefix="gs://cpg-common-main/references/hg38/v0/dragen_reference"...[storage.default]default="gs://cpg-validation-main"web="gs://cpg-validation-main-web"analysis="gs://cpg-validation-main-analysis"tmp="gs://cpg-validation-main-tmp"web_url="https://main-web.populationgenomics.org.au/validation"...If you are not using the analysis runner, you'd have to set those generated values explicitly.Batch helpersThecpg_utils.hail_batchmodule provides a helper functionget_batchto set up Hail Batch in the CPG context, assuminghail/billing_projectandhail/backendare set in config.fromcpg_utils.hail_batchimportget_batchb=get_batch(name='My batch')j=b.new_job('My job',...)...The Batch instance derives from a class extended from standard HailBatchclass, and it records stats of added jobs and prints statistics before submission, highlighting labelled jobs, e.g.:Willsubmit186jobs:
BWA:3for3samples
Somalierextract(CRAMs):3for3samples
HaplotypeCaller:3for3samples
ReblockGVCF:3for3samples
Somalierextract(GVCFs):3for3samples
Otherjobs:171The Batch instance also constructs the job name if the names of a sample and a dataset are provided as attributes, e.g.:>>>j=b.new_job('My job',dict(sequencing_group='CPGXXXX',dataset='fewgenomes'))>>>print(j.name)fewgenomes/CPGXXXX:Myjobcpg_utils.hail_batchprovides a helpercommandto set up a command that can be used to add monitoring of disk space, or authenticate with GCP:fromcpg_utils.hail_batchimportcommandj=...j.command(command('sleep 600',monitor_space=True,setup_gcp=True))This will wrap the command as follows:set-opipefailset-exexportGOOGLE_APPLICATION_CREDENTIALS=/gsa-key/key.json
gcloud-qauthactivate-service-account--key-file=$GOOGLE_APPLICATION_CREDENTIALS(whiletrue;dodf-h;du-sh$BATCH_TMPDIR;sleep600;done)&sleep600df-h;du-sh$BATCH_TMPDIRReusing existing resultsworkflow/check_expected_outputs = truecontrols whether the paths returned byexpected_outputs()of each job correspond to existing objects, and would skip stages with already existing outputs.You can also call the methodcpg_workflows.utils.can_reuse(path)explicitly within the code called fromqueue_jobs().workflow/check_intermediates = truecontrols whethercan_reuse()checks the object(s), or always returnsFalse.workflow/check_inputs = truecontrols whether inputs to the first stage in the pipeline should be checked for existence, e.g. alignment inputs for anAlignstage.skip_sgs_with_missing_inputcontrols the behaviour if those inputs are missing: where skip such sequencing groups, or stop the workflow.You can also start the pipeline from a specific stage withworkflow/first_stages(it would skip all previous stages, but still check immediately required inputs for the first stage).workflow/last_stageswould stop the workflow after the stages specified.workflow/only_stageswould execute only stages specified, ignoring dependencies.You can also force the pipeline to skip certain sequencing groups withworkflow/skip_sgs, pick only certain sequencing groups withworkflow/only_sgs, force re-processing of certain sequencing groups withworkflow/force_sgs.workflow/skip_datasetsandworkflow/only_datasetsare available, and more fine-grained combination ofskip_sgsandskip_stages:[workflow.skip_stages_for_sgs]CramQC=['CPGXXXX']Available stagesTo see available workflow stages, explore thecpg_workflows/stagesfolder. A stage wrappers for Hail Batch jobs that allow to glue them together into genomics workflows.cpg_workflowsalso provides helper functions that create Hail Batch jobs for different domain-specific applications, e.g. alignment, deduplication, QC, variant calling, creating calling intervals, running VQSR, creating ES index, etc. Those jobs can be called from thequeue_jobsmethod of a stage, or in isolation, as they don't need to know about the stage they are called from, but only need aBatchobject.Slack QC notificationsConfig's[slack]section activates QC reports to a Slack channel. For example:[slack]channel='workflows-qc'token_secret_id='slack-seqr-loader-token'token_project_id='seqr-308602'Would send messages on QC completion to theworkflows-qcchannel, flagging failed samples.Two scripts send Slack messages:check_multiqc.pyandcheck_pedigree.py. Note that the MultiQC checks only work when theqc_thresholdssection is also specified, for example:[qc_thresholds.genome.min]"MEDIAN_COVERAGE"=10"PCT_PF_READS_ALIGNED"=0.80[qc_thresholds.genome.max]"FREEMIX"=0.04"PERCENT_DUPLICATION"=25Thresholds can be adjusted as needed, per workflow or dataset. Note that the metrics names here should match the ones in the MultiQC JSON.