# Grouping and lane order

A gene track's biotype sections, an alignments track's haplotype bands, a
multi-sample variant track's karyotype rows, a multiway synteny track's lanes
and a multi-row display's partitions are all set by a field (or, for multiway
synteny, the assembly itself) that splits the data into sections and a `sort`
list that orders them. Each example below links to the guide or tutorial that
works it through in full.

## `field` and `sort`

Most of these displays take a `facet` object: `{ field, sort }`. `field` is a
feature attribute, a dotted path into a structured one (`INFO.SVTYPE`), or a
`jexl:` expression — each distinct value it returns makes one section. `sort` is
a list of values: the ones it names stack first, in that order, and every other
value found in the data follows, sorted. A value in `sort` that the data never
produces is never drawn, because `sort` orders sections and does not create
them. Naming one ahead of time therefore adds no refetch when it later appears.

A `rows.sort` orders a display's rows by the same rule, with one difference:
rows a source lists, such as a VCF's samples or a multi-BigWig's subtracks, keep
the source's order past the `sort` list rather than sorting.

A short form exists for the common case of no ordering: `"facet": "tags.HP"` is
`"facet": { "field": "tags.HP", "sort": [] }`.

## Feature tracks

NCBI RefSeq genes on hg38, grouped and colored by `gene_biotype`, with the
protein-coding section pinned to the top and each biotype given a distinct color
from the same list:

```json
{
  "facet": {
    "field": "gene_biotype",
    "sort": ["protein_coding", "snoRNA", "lncRNA", "pseudogene"]
  },
  "encoding": {
    "color": {
      "field": "gene_biotype",
      "scale": {
        "domain": ["protein_coding", "snoRNA", "lncRNA", "pseudogene"]
      }
    }
  }
}
```

<Video src="/media/ui/gene_track_channel_spec.mp4" caption="Edit plot from the Group by dialog, the spec above pasted in, and the sections in the facet's sort order." />

Open the session this video starts in: <https://jbrowse.org/code/jb2/main/?config=test_data%2Fconfig_demo.json&session=spec-%7B%22views%22%3A%5B%7B%22type%22%3A%22LinearGenomeView%22%2C%22assembly%22%3A%22hg38%22%2C%22loc%22%3A%22chr17%3A7%2C540%2C000-7%2C640%2C000%22%2C%22trackLabels%22%3A%22offset%22%2C%22tracks%22%3A%5B%7B%22trackId%22%3A%22ncbi_refseq_109_hg38_latest%22%2C%22geneGlyphMode%22%3A%22representative%22%2C%22labels%22%3A%7B%22description%22%3A%7B%22show%22%3Afalse%7D%7D%2C%22height%22%3A640%7D%5D%7D%5D%7D&sessionName=Screenshot>

[The gene track guide's Grouping features into sections section](https://jbrowse.org/jb2/docs/user_guides/gene_track#grouping-features-into-sections)
has the full mechanism — the Group by/Color by menus, the draggable chips, and
what **Edit plot...** accepts.

## Alignments tracks

The alignments displays take `facet` the same way, plus seven built-in read
dimensions: `strand`, `firstOfPairStrand`, `pairOrientation`, `pairing`,
`split`, `spliced`, `mapq`. The same idea over a `LinearMarkDisplay` faceting a
BAM by its `HP` haplotype tag:

<Figure src="/img/mark_display/facet.png" caption="HG002 ONT reads faceted by their HP tag: each haplotype's reads packed into a separate band under the chip that names it, and the untagged reads in a third."/>

Session spec, on config <https://jbrowse.org/code/jb2/main/test_data/config_demo.json>:

```json
{
  "sessionTracks": [
    {
      "type": "AlignmentsTrack",
      "trackId": "snrpn_facet",
      "name": "HG002 ONT reads faceted by HP",
      "assemblyNames": [
        "hg38"
      ],
      "adapter": {
        "type": "BamAdapter",
        "uri": "https://jbrowse.org/demos/methylation/HG002_SNRPN_5mC_haplotagged.bam"
      },
      "displays": [
        {
          "type": "LinearMarkDisplay",
          "displayId": "snrpn_facet-LinearMarkDisplay",
          "transform": [
            {
              "type": "formula",
              "expr": "jexl:getTag(feature,'HP')",
              "as": "HP"
            }
          ],
          "facet": "HP",
          "marks": [
            {
              "mark": "rect",
              "transform": [
                {
                  "type": "pileup"
                }
              ],
              "encoding": {
                "row": "row",
                "color": {
                  "field": "HP",
                  "scale": {
                    "type": "ordinal"
                  },
                  "legend": {
                    "title": "Haplotype"
                  }
                }
              }
            }
          ]
        }
      ]
    }
  ],
  "views": [
    {
      "type": "LinearGenomeView",
      "assembly": "hg38",
      "loc": "chr15:24,900,000-25,000,000",
      "tracks": [
        {
          "trackId": "snrpn_facet",
          "height": 400,
          "forceLoad": true
        }
      ]
    }
  ]
}
```

[The cookbook's alignments recipe](https://jbrowse.org/jb2/docs/cookbook#alignments-tracks) has a
worked `LinearAlignmentsDisplay` config; the reordering rule is the same `sort`.

## Variant tracks

`LinearVariantDisplay` takes the same `facet` object to band rows by a metadata
column instead of VCF file order. In the two examples below, the bands group
samples that the VCF lists in whatever order it has them:

```json
"facet": { "field": "karyotype", "sort": ["Standard", "In(2L)t"] }
```

<Figure src="/img/popgen/in2lt_inversion.png" caption="Top: the six dm6 arms with the In(2L)t extent over Fst. Below: chr2L with one row per DGRP line, grouped by karyotype." links="Six arms=popgen/fst_in2lt_2L"/>

Session spec (Six arms), on config <https://jbrowse.org/ucsc/dm6/config.json>:

```json
{
  "sessionTracks": [
    {
      "type": "FeatureTrack",
      "trackId": "in2lt_inversion",
      "name": "In(2L)t inversion",
      "assemblyNames": [
        "dm6"
      ],
      "adapter": {
        "type": "FromConfigAdapter",
        "adapterId": "in2lt",
        "features": [
          {
            "uniqueId": "in2lt",
            "refName": "chr2L",
            "start": 2225744,
            "end": 13154180,
            "name": "In(2L)t",
            "type": "inversion"
          }
        ]
      }
    },
    {
      "type": "QuantitativeTrack",
      "trackId": "fst_in2lt",
      "name": "Fst (In(2L)t vs standard, 2kb windows)",
      "assemblyNames": [
        "dm6"
      ],
      "adapter": {
        "type": "BigWigAdapter",
        "uri": "https://jbrowse.org/demos/popgen/fst_In2Lt.bw"
      }
    }
  ],
  "views": [
    {
      "type": "LinearGenomeView",
      "assembly": "dm6",
      "displayedRegionNames": [
        "chr2L",
        "chr2R",
        "chr3L",
        "chr3R",
        "chr4",
        "chrX"
      ],
      "tracks": [
        {
          "trackId": "in2lt_inversion",
          "height": 40
        },
        {
          "trackId": "fst_in2lt",
          "height": 240
        }
      ]
    }
  ]
}
```

```json
"facet": { "field": "karyotype", "sort": ["2L+a/2L+a", "2La/2L+a", "2La/2La"] }
```

<Figure src="/img/ld/anopheles_2la.png" caption="Ag1000G arm 2L with the published extents of 2La and Vgsc above r² blocks for Cameroon and Gabon."/>

Each order follows the genetics: dosage order in the mosquito figure,
standard-before-inverted in the fly figure, both read off the `sort` lists
above.
[LD in mosquitoes](https://jbrowse.org/jb2/docs/tutorials/ld_mosquitoes#reading-the-2la-ld-block-against-the-karyotype-rows)
works through the mosquito one, and
[population genomics](https://jbrowse.org/jb2/docs/tutorials/population_genomics#the-inversion-genome-wide-and-within-each-arrangement)
reads the fly inversion as diversity in each arrangement.

## The mark display

`LinearMarkDisplay` takes the same `facet` object, and separately, a `row`
channel that packs features within a section (a BAM's pileup, or any mark whose
`transform` runs a `pileup` step). Faceting and row-packing are independent — a
facet splits into sections first, and each mark packs rows inside each section:

<Figure src="/img/mark_display/facet.png" caption="HG002 ONT reads faceted by their HP tag: each haplotype's reads packed into a separate band under the chip that names it, and the untagged reads in a third."/>

Session spec, on config <https://jbrowse.org/code/jb2/main/test_data/config_demo.json>:

```json
{
  "sessionTracks": [
    {
      "type": "AlignmentsTrack",
      "trackId": "snrpn_facet",
      "name": "HG002 ONT reads faceted by HP",
      "assemblyNames": [
        "hg38"
      ],
      "adapter": {
        "type": "BamAdapter",
        "uri": "https://jbrowse.org/demos/methylation/HG002_SNRPN_5mC_haplotagged.bam"
      },
      "displays": [
        {
          "type": "LinearMarkDisplay",
          "displayId": "snrpn_facet-LinearMarkDisplay",
          "transform": [
            {
              "type": "formula",
              "expr": "jexl:getTag(feature,'HP')",
              "as": "HP"
            }
          ],
          "facet": "HP",
          "marks": [
            {
              "mark": "rect",
              "transform": [
                {
                  "type": "pileup"
                }
              ],
              "encoding": {
                "row": "row",
                "color": {
                  "field": "HP",
                  "scale": {
                    "type": "ordinal"
                  },
                  "legend": {
                    "title": "Haplotype"
                  }
                }
              }
            }
          ]
        }
      ]
    }
  ],
  "views": [
    {
      "type": "LinearGenomeView",
      "assembly": "hg38",
      "loc": "chr15:24,900,000-25,000,000",
      "tracks": [
        {
          "trackId": "snrpn_facet",
          "height": 400,
          "forceLoad": true
        }
      ]
    }
  ]
}
```

[The mark display guide's Facets section](https://jbrowse.org/jb2/docs/config_guides/mark_display#facets)
has the full mechanism, including how the track menu's **Sections** list writes
a drag back into `sort`.

## Multiway synteny

`MultiWaySyntenyDisplay` draws one lane per assembly rather than one section per
field value, so there is no `facet` — its `rows` is the lane arrangement, and
`rows.sort` lists assembly names. It composes with `ribbons.encoding.color`,
which paints each ribbon by a field — here, the relative strand between the two
lanes a ribbon joins:

```json
{
  "type": "SyntenyTrack",
  "trackId": "grape_peach_cacao_blocks",
  "name": "Grape vs peach, cacao, arabidopsis, poplar, tomato, citrus (MCScan blocks)",
  "assemblyNames": [
    "grape",
    "peach",
    "cacao",
    "poplar",
    "citrus",
    "arabidopsis",
    "tomato"
  ],
  "adapter": {
    "type": "MCScanBlocksAdapter",
    "uri": "grape_peach_cacao.blocks",
    "blockAssemblies": [
      "grape",
      "peach",
      "cacao",
      "poplar",
      "citrus",
      "arabidopsis",
      "tomato"
    ],
    "bedLocations": [
      "grape.bed",
      "peach.bed",
      "cacao.bed",
      "poplar.bed",
      "citrus.bed",
      "arabidopsis.bed",
      "tomato.bed"
    ]
  },
  "displays": [
    {
      "type": "MultiWaySyntenyDisplay",
      "displayId": "grape_peach_cacao_blocks-MultiWaySyntenyDisplay",
      "rows": {
        "sort": ["peach", "cacao", "poplar", "citrus", "arabidopsis", "tomato"]
      },
      "ribbons": { "encoding": { "color": "strand" } }
    }
  ]
}
```

CLI:

```bash
jbrowse add-track-json '{
  "type": "SyntenyTrack",
  "trackId": "grape_peach_cacao_blocks",
  "name": "Grape vs peach, cacao, arabidopsis, poplar, tomato, citrus (MCScan blocks)",
  "assemblyNames": [
    "grape",
    "peach",
    "cacao",
    "poplar",
    "citrus",
    "arabidopsis",
    "tomato"
  ],
  "adapter": {
    "type": "MCScanBlocksAdapter",
    "uri": "grape_peach_cacao.blocks",
    "blockAssemblies": [
      "grape",
      "peach",
      "cacao",
      "poplar",
      "citrus",
      "arabidopsis",
      "tomato"
    ],
    "bedLocations": [
      "grape.bed",
      "peach.bed",
      "cacao.bed",
      "poplar.bed",
      "citrus.bed",
      "arabidopsis.bed",
      "tomato.bed"
    ]
  },
  "displays": [
    {
      "type": "MultiWaySyntenyDisplay",
      "displayId": "grape_peach_cacao_blocks-MultiWaySyntenyDisplay",
      "rows": {
        "sort": ["peach", "cacao", "poplar", "citrus", "arabidopsis", "tomato"]
      },
      "ribbons": { "encoding": { "color": "strand" } }
    }
  ]
}'
```

<Figure src="/img/multiway_synteny/lgv_track_lanes_colored.png" caption="A grape locus over seven genomes, lanes pinned by retention, ribbons red where a lane runs the same way as the one above and blue where it is inverted." />

Session spec, on config <https://jbrowse.org/demos/grape_peach_cacao/config.json>:

```json
{
  "views": [
    {
      "type": "LinearGenomeView",
      "assembly": "GCF_030704535.1",
      "loc": "chr11:778,000-866,000",
      "tracks": [
        {
          "trackId": "GCF_030704535.1-ncbiRefSeq",
          "filter": [
            "geneLike"
          ],
          "displayMode": "compact"
        },
        {
          "trackId": "grape_peach_cacao_blocks",
          "type": "MultiWaySyntenyDisplay",
          "rows": {
            "sort": [
              "GCF_000346465.2",
              "GCF_000208745.1",
              "poplar",
              "citrus",
              "arabidopsis",
              "tomato"
            ]
          },
          "ribbons": {
            "encoding": {
              "color": "strand"
            }
          },
          "height": 340
        }
      ]
    }
  ]
}
```

Unlisted assemblies still get a lane — they stack below the named ones,
densest-first, so a ribbon chain through them is cut as late as possible.
[The synteny track guide](https://jbrowse.org/jb2/docs/config_guides/synteny_track#three-or-more-genomes)
covers the adapter side, and
[the multi-way synteny display guide](https://jbrowse.org/jb2/docs/user_guides/multiway_synteny_display#choosing-and-ordering-lanes)
the lane controls in the app.

## Row-partitioned tracks

`LinearMultiRowFeatureDisplay` draws one fixed row per value, set through `rows`
instead of `facet`, with the same `sort` and without a facet section's chip,
hiding or overflow merge. Nine ENCODE cell types, pinned to ENCODE's own tiers
rather than alphabetical order:

```json
{
  "type": "FeatureTrack",
  "trackId": "broad_chromhmm_multirow_hg19",
  "name": "ChromHMM chromatin state (Broad ENCODE, 9 cell types)",
  "uri": "wgEncodeBroadHmm.multirow.bed.gz",
  "csi": true,
  "assemblyNames": ["hg19"],
  "category": ["ENCODE", "Chromatin state"],
  "displays": [
    {
      "type": "LinearMultiRowFeatureDisplay",
      "rows": {
        "field": "cellType",
        "sort": [
          "GM12878",
          "H1-hESC",
          "K562",
          "HepG2",
          "HUVEC",
          "HMEC",
          "HSMM",
          "NHEK",
          "NHLF"
        ]
      },
      "height": 200
    }
  ]
}
```

CLI:

```bash
jbrowse add-track-json '{
  "type": "FeatureTrack",
  "trackId": "broad_chromhmm_multirow_hg19",
  "name": "ChromHMM chromatin state (Broad ENCODE, 9 cell types)",
  "uri": "wgEncodeBroadHmm.multirow.bed.gz",
  "csi": true,
  "assemblyNames": ["hg19"],
  "category": ["ENCODE", "Chromatin state"],
  "displays": [
    {
      "type": "LinearMultiRowFeatureDisplay",
      "rows": {
        "field": "cellType",
        "sort": [
          "GM12878",
          "H1-hESC",
          "K562",
          "HepG2",
          "HUVEC",
          "HMEC",
          "HSMM",
          "NHEK",
          "NHLF"
        ]
      },
      "height": 200
    }
  ]
}'
```

At a larger scale, a `rows.sort` of six names with `rows.kept` narrows a
127-epigenome track to the three tissues a figure is about, in the order the
comparison reads:

<Figure src="/img/chromhmm_hoxa_fibroblasts.png" caption="Lung fibroblasts, foreskin fibroblasts and ES cells over HOXA, with HOXA1-A7 and HOXA9-A13 boxed."/>

Session spec, on config <https://jbrowse.org/code/jb2/main/test_data/config_demo.json>:

```json
{
  "views": [
    {
      "type": "LinearGenomeView",
      "assembly": "hg19",
      "loc": "chr7:27,110,000-27,265,000",
      "tracks": [
        {
          "trackId": "ncbi_gff_hg19",
          "labels": {
            "description": {
              "show": false
            }
          },
          "filter": [
            "geneLike",
            "jexl:feature.type!='pseudogene'"
          ],
          "height": 110
        },
        {
          "trackId": "roadmap_chromhmm_multirow_hg19",
          "rows": {
            "field": "cellType",
            "sort": [
              "NHLF Lung Fibroblast Primary Cells",
              "IMR90 fetal lung fibroblasts Cell Line",
              "Foreskin Fibroblast Primary Cells skin01",
              "Foreskin Fibroblast Primary Cells skin02",
              "H1 Cells",
              "H9 Cells"
            ],
            "kept": [
              "NHLF Lung Fibroblast Primary Cells",
              "IMR90 fetal lung fibroblasts Cell Line",
              "Foreskin Fibroblast Primary Cells skin01",
              "Foreskin Fibroblast Primary Cells skin02",
              "H1 Cells",
              "H9 Cells"
            ]
          },
          "height": 240
        }
      ]
    }
  ]
}
```

[The ChromHMM tutorial](https://jbrowse.org/jb2/docs/tutorials/chromhmm#the-legend-filtering-and-row-order)
has both tracks in full, plus what an unset `rows.sort` does instead: **Cluster
rows by similarity...** derives a row order from the data itself.

## Reordering at runtime

Every one of these displays writes a drag-to-reorder back into the same `sort`
slot it read the curated order from — the gene track and mark display's
**Sections** list, the alignments track menu's group-by sections, multiway
synteny's **Lanes** menu and lane-header drag, and the multi-row display's row
drag, which writes `rows.sort`. A session saved after reordering records the new
order in `config.json` terms.

## See also

- **Tutorial:** [Synteny from an ortholog table (grape, peach, cacao)](https://jbrowse.org/jb2/docs/tutorials/multiway_synteny_grape_peach_cacao)
- **Tutorial:** [Pangenome (HPRC) part 2: haplotypes against each other](https://jbrowse.org/jb2/docs/tutorials/pangenome_hprc_haplotypes)
- **Tutorial:** [ChromHMM chromatin states](https://jbrowse.org/jb2/docs/tutorials/chromhmm)
- **Tutorial:** [Selection scans (Drosophila DGRP)](https://jbrowse.org/jb2/docs/tutorials/population_genomics)
- **Tutorial:** [LD across an inversion (mosquitoes)](https://jbrowse.org/jb2/docs/tutorials/ld_mosquitoes)
- **User guide:** [Gene track](https://jbrowse.org/jb2/docs/user_guides/gene_track)
- **Config guide:** [Mark display](https://jbrowse.org/jb2/docs/config_guides/mark_display)
- **Config guide:** [Alignments track](https://jbrowse.org/jb2/docs/config_guides/alignments_track)
- **Config guide:** [Synteny track](https://jbrowse.org/jb2/docs/config_guides/synteny_track)
- **Reference:** [LinearVariantDisplay](https://jbrowse.org/jb2/docs/config/linearvariantdisplay)
- **Reference:** [LinearMultiRowFeatureDisplay](https://jbrowse.org/jb2/docs/config/linearmultirowfeaturedisplay)
- **Reference:** [MultiWaySyntenyDisplay](https://jbrowse.org/jb2/docs/config/multiwaysyntenydisplay)
