name: ?f"Variant calls {wildcards.event}"

default-view: ?"overview" if input.variant_oncoprints else f"{params.groups[0]}-coding"
max-in-memory-rows: 1500

__definitions__:
  - import os
  - |
    def read_file(path):
        return open(path, 'r').read()
  - |
    hgvsp_content = f"""
      function(value, row) {{
        let hgvsp_regex = /^(.+?):(.+)$/;
        // discard protein id
        let hgvsp = value.match(hgvsp_regex)[2].replace('%3D', '=');
        return hgvsp
      }}
    """
  - |
    varsome_link = f"""
    function(row) {{
      let hgvsp_regex = /^(.+?):(.+)$/;
      // discard protein id

      let hgvsp = row.hgvsp.match(hgvsp_regex)[2].replace('%3D', '=');

      let chr = row.chromosome;
      let pos = row.position;
      let ref = row["reference allele"];
      let alt = row["alternative allele"];
      var build = ""
      if  ( "{params.build}" === "GRCh38" ) {{
        build = "hg38/"
      }} else {{
        build = "hg19/"
      }}
      const url = "https://varsome.com/variant/";
      let aa_regex = /^[ACGTacgt]+$/;
      if ( ref.match(aa_regex) && alt.match(aa_regex)) {{
        let descriptor = `${{chr}}:${{pos}}:${{ref}}:${{alt}}`
        return `${{url}}${{build}}${{descriptor}}`;
      }}
      else {{
        return `${{hgvsp}}`;
      }}
    }}
    """
  - |
    genomenexus_link = f"""
      function(row) {{
        let hgvsg = row.hgvsg
        var build = ""
        if  ( "{params.build}" === "GRCh38" ) {{
          build = "grch38."
        }}
        const url_suffix = "genomenexus.org/variant/"
        return `https://${{build}}${{url_suffix}}${{hgvsg}}`
      }}
    """

datasets:
  ?if input.variant_oncoprints:
    gene-oncoprint:
      path: ?params.gene_oncoprint
      separator: "\t"
      headers: ?len(params.group_annotations.columns) + 1
      links:
        gene details:
          column: symbol
          view: "overview-{value}"
    ?for label in params.labels.index.values:
      ?label:
        path: ?os.path.join(params.oncoprint_sorted_datasets, f"{label}.tsv")
        separator: "\t"
        headers: 2
    ?for gene, path in params.variant_oncoprints:
      ?f"variant-oncoprint-{gene}":
        path: ?path
        separator: "\t"
        headers: ?len(params.group_annotations.columns) + 1
        links:
          ?for group in params.groups:
            ?group:
              column: hgvsp
              table-row: ?f"{group}-coding/hgvsp"
              optional: true

  ?for group, path in zip(params.groups, params.coding_calls):
    ?f"{group}-coding":
      path: ?path
      separator: "\t"
  ?for group, path in zip(params.groups, params.noncoding_calls):
    ?f"{group}-noncoding":
      path: ?path
      separator: "\t"

views:
  ?if params.gene_oncoprint:
    ?for view in ["gene-oncoprint"] + list(params.labels.index.values):
      __variables__:
        labels: ?params.group_annotations.columns.values if view == "gene-oncoprint" else [view]
      ?"overview" if view == "gene-oncoprint" else f"by {view}":
        ?if view == "gene-oncoprint":
          desc: |
            Overview table showing all discovered variants in all samples. Use link
            button to jump to detail views for the respective genes.
        ?else:
          desc: |
            ?f"""
            Rows are sorted by their statistical dependency on {view}, which is determined by a 
            [Chi² test](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.chi2.html).
            The corresponding p-value and Benjamini-Hochberg corrected FDR is shown in the last two columns.
            They represent the probability to observe an at least as strong dependency by chance.
            Rows with highest dependency are shown first.
            """
        dataset: ?view
        render-table:
          ?if labels:
            headers:
              ?for i, annotation in enumerate(labels):
                ?i + 1:
                  label: ?annotation
                  plot:
                    heatmap:
                      scale: ordinal
                      color-scheme: category20
          columns:
            symbol:
              link-to-url:
                ensembl:
                  url: https://www.ensembl.org/Homo_sapiens/Gene/Summary?g={value}
            consequence:
              plot:
                heatmap:
                  scale: ordinal
                  color-scheme: category20
            ?for group in params.groups:
              ?group:
                plot:
                  heatmap:
                    scale: ordinal
                    color-scheme: paired
                    aux-domain-columns: ?list(params.groups)
            p-value dependency:
              plot:
                ticks:
                  scale: linear
              optional: true
            FDR dependency:
              plot:
                ticks:
                  scale: linear
              optional: true
    
    ?for gene, path in params.variant_oncoprints:
      ?f"overview-{gene}":
        desc: ?f"Variants found in gene {gene}."
        dataset: ?f"variant-oncoprint-{gene}"
        hidden: true
        render-table:
          ?if params.group_annotations.columns.values:
            headers:
              ?for i, annotation in enumerate(params.group_annotations.columns.values):
                ?i + 1:
                  label: ?annotation
                  plot:
                    heatmap:
                      scale: ordinal
                      color-scheme: category20
          columns:
            consequence:
              plot:
                heatmap:
                  scale: ordinal
                  color-scheme: category20
            ?for group in params.groups:
              ?group:
                plot:
                  heatmap:
                    scale: ordinal
                    color-scheme: paired
                    aux-domain-columns: ?list(params.groups)
            hgvsg:
              display-mode: hidden

  ?for group in params.groups:
    ?f"{group}-coding":
      desc: ?f"Variants in coding regions.\n{config['calling']['fdr-control']['events'][wildcards.event]['desc']}"
      dataset: ?f"{group}-coding"
      render-table:
        columns:
          symbol:
            link-to-url:
              ensembl:
                url: https://www.ensembl.org/Homo_sapiens/Transcript/Summary?t={feature}
          hgvsp:
            link-to-url:
              custom-content: ?hgvsp_content
              varsome:
                url: "{query_varsome}"
              genome nexus:
                url: "{query_genomenexus}"
          vartype:
            display-mode: hidden
          impact:
            plot:
              heatmap:
                scale: ordinal
                domain:
                  - HIGH
                  - MODERATE
                  - LOW
                  - MODIFIER
                range:
                  - "#ec0000"
                  - "#ec5300"
                  - "#ec9b00"
                  - "#ecca00"
          consequence:
            plot:
              heatmap:
                color-scheme: category20
                scale: ordinal
          revel:
            optional: true
            plot:
              heatmap:
                scale: "linear"
                domain: [0.0, 1.0]
                range:
                  - white
                  - "#ff5555"
          "regex('.+: allele frequency')":
            plot:
              ticks:
                scale: "linear"
                domain: [0.0, 1.0]
                aux-domain-columns:
                  - "regex('.+: allele frequency')"
                color:
                  scale: "linear"
                  domain: [0.0, 0.05, 0.0500000001, 1.0]
                  range:
                  - "#ffd6b3"
                  - "#ff7f0e"
                  - "#a8d2f0"
                  - "#1f77b4"
          "regex('.+: read depth')":
            plot:
              ticks:
                scale: "linear"
                aux-domain-columns:
                  - "regex('.+: read depth')"
          "regex('prob: .+')":
            plot:
              heatmap:
                scale: linear
                domain: [0.0, 1.0]
                range:
                  - white
                  - "#1f77b4"
          "gnomad genome af":
            optional: true
            plot:
              heatmap:
                scale: "linear"
                domain: [0.0, 0.01, 1.0]
                range:
                  - white
                  - "#adebad"
                  - "#29a329"
          gene:
            display-mode: hidden
          feature:
            display-mode: hidden
          binned max vaf:
            display-mode: hidden
          hgvsg:
            display-mode: detail
          chromosome:
            display-mode: detail
          position:
             display-mode: detail
          reference allele:
            display-mode: detail
          alternative allele:
            display-mode: detail
          protein position:
            display-mode: detail
          protein alteration (short):
            display-mode: detail
          ?for alias in params.samples.loc[params.samples["group"] == group, "alias"]:
            '?f"{alias}: short observations"':
              optional: true
              custom-plot:
                data: ?read_file(params.data_short_observations)
                spec: ?read_file(params.spec_short_observations)
              display-mode: detail
            '?f"{alias}: observations"':
              optional: true
              custom-plot:
                data: ?read_file(params.data_observations)
                spec: ?read_file(params.spec_observations)
              display-mode: detail
        add-columns:
          query_varsome:
            value: ?varsome_link
            display-mode: hidden
          query_genomenexus:
            value: ?genomenexus_link
            display-mode: hidden




    ?f"{group}-noncoding":
      desc: ?f"Variants in non-coding regions.\n{config['calling']['fdr-control']['events'][wildcards.event]['desc']}"
      dataset: ?f"{group}-noncoding"
      render-table:
        columns:
          symbol:
            optional: true
            link-to-url:
              ensembl:
                url: https://www.ensembl.org/Homo_sapiens/Transcript/Summary?t={feature}
          consequence:
            plot:
              heatmap:
                color-scheme: category20
                scale: ordinal
          vartype:
            display-mode: hidden
          impact:
            plot:
              heatmap:
                scale: ordinal
                domain:
                  - HIGH
                  - MODERATE
                  - LOW
                  - MODIFIER
                range:
                  - "#ec0000"
                  - "#ec5300"
                  - "#ec9b00"
                  - "#ecca00"
          "regex('.+: allele frequency')":
            plot:
              ticks:
                scale: "linear"
                domain: [0.0, 1.0]
                aux-domain-columns:
                  - "regex('.+: allele frequency')"
                color:
                  scale: "linear"
                  domain: [0.0, 0.05, 0.0500000001, 1.0]
                  range:
                  - "#ffd6b3"
                  - "#ff7f0e"
                  - "#a8d2f0"
                  - "#1f77b4"
          "regex('.+: read depth')":
            plot:
              ticks:
                scale: "linear"
                aux-domain-columns:
                  - "regex('.+: read depth')"
          "regex('prob: .+')":
            plot:
              heatmap:
                scale: linear
                domain: [0.0, 1.0]
                range:
                  - white
                  - "#1f77b4"
          "gnomad genome af":
            optional: true
            plot:
              heatmap:
                scale: "linear"
                domain: [0.0, 0.01, 1.0]
                range:
                  - white
                  - "#adebad"
                  - "#29a329"
          id:
            optional: true
            display-mode: hidden
          gene:
            display-mode: hidden
          feature:
            display-mode: hidden
          binned max vaf:
            display-mode: hidden
          hgvsg:
            optional: true
            display-mode: detail
          chromosome:
            display-mode: detail
          position:
             display-mode: detail
          reference allele:
            display-mode: detail
          alternative allele:
            display-mode: detail
          ?for alias in params.samples.loc[params.samples["group"] == group, "alias"]:
            '?f"{alias}: short observations"':
              optional: true
              custom-plot:
                data: ?read_file(params.data_short_observations)
                spec: ?read_file(params.spec_short_observations)
              display-mode: detail
            '?f"{alias}: observations"':
              optional: true
              custom-plot:
                data: ?read_file(params.data_observations)
                spec: ?read_file(params.spec_observations)
              display-mode: detail
