jbrowse-plugin-protein3d 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/LaunchProteinView/components/HelpDialog.js +1 -1
  2. package/dist/LaunchProteinView/components/PdbResultsTable.js +5 -5
  3. package/dist/LaunchProteinView/components/PdbSearch.js +15 -14
  4. package/dist/LaunchProteinView/hooks/useExperimentalStructures.js +9 -0
  5. package/dist/LaunchProteinView/hooks/usePdbEntry.js +10 -0
  6. package/dist/ProteinView/clinVar.js +146 -0
  7. package/dist/ProteinView/clinVarSource.js +72 -0
  8. package/dist/ProteinView/structureModel.js +82 -110
  9. package/dist/ProteinView/variantEffectColorTheme.js +1 -1
  10. package/dist/ProteinView/variantEffectLoader.js +20 -27
  11. package/dist/ProteinView/variantEffectSource.js +116 -33
  12. package/dist/ProteinView/variantEffectStatus.js +59 -0
  13. package/dist/ProteinView/variantEffects.js +13 -36
  14. package/dist/chunks/AddStructureDialog-Z5HMGUWS.js +2 -0
  15. package/dist/chunks/{AddStructureDialog-KB77YRP4.js.map → AddStructureDialog-Z5HMGUWS.js.map} +1 -1
  16. package/dist/chunks/HelpDialog-GBG7PHDR.js +2 -0
  17. package/dist/chunks/{HelpDialog-LLS4EV2C.js.map → HelpDialog-GBG7PHDR.js.map} +2 -2
  18. package/dist/chunks/{ManualAlignmentDialog-5GJHFANI.js → ManualAlignmentDialog-B35TUUYU.js} +2 -2
  19. package/dist/chunks/{ManualAlignmentDialog-5GJHFANI.js.map → ManualAlignmentDialog-B35TUUYU.js.map} +1 -1
  20. package/dist/chunks/{ProteinView-DZE2VNLT.js → ProteinView-DQOR5RTK.js} +2 -2
  21. package/dist/chunks/{ProteinView-DZE2VNLT.js.map → ProteinView-DQOR5RTK.js.map} +1 -1
  22. package/dist/chunks/chunk-2U2S5MMZ.js +2 -0
  23. package/dist/chunks/chunk-2U2S5MMZ.js.map +7 -0
  24. package/dist/chunks/{chunk-NTSSSR67.js → chunk-C2KRWQQY.js} +2 -2
  25. package/dist/chunks/{chunk-NTSSSR67.js.map → chunk-C2KRWQQY.js.map} +1 -1
  26. package/dist/chunks/chunk-GQU3SL56.js +2 -0
  27. package/dist/chunks/chunk-GQU3SL56.js.map +7 -0
  28. package/dist/chunks/chunk-ODVAAHFT.js +2 -0
  29. package/dist/chunks/chunk-ODVAAHFT.js.map +7 -0
  30. package/dist/chunks/chunk-QPR5H2OZ.js +2 -0
  31. package/dist/chunks/chunk-QPR5H2OZ.js.map +7 -0
  32. package/dist/chunks/chunk-RIAQ5NV7.js +2 -0
  33. package/dist/chunks/chunk-RIAQ5NV7.js.map +7 -0
  34. package/dist/chunks/chunk-SQLUPFUS.js +2 -0
  35. package/dist/chunks/chunk-SQLUPFUS.js.map +7 -0
  36. package/dist/chunks/chunk-TPLXHUOA.js +16 -0
  37. package/dist/chunks/chunk-TPLXHUOA.js.map +7 -0
  38. package/dist/chunks/chunk-UXGREKQA.js +2 -0
  39. package/dist/chunks/chunk-UXGREKQA.js.map +7 -0
  40. package/dist/chunks/clinVarSource-SXH525M3.js +2 -0
  41. package/dist/chunks/clinVarSource-SXH525M3.js.map +7 -0
  42. package/dist/chunks/{molstarExports-PB32MTCP.js → molstarExports-M6FNLMIU.js} +3 -3
  43. package/dist/chunks/{molstarExports-PB32MTCP.js.map → molstarExports-M6FNLMIU.js.map} +2 -2
  44. package/dist/jbrowse-plugin-protein3d.esm.js +26 -7
  45. package/dist/jbrowse-plugin-protein3d.esm.js.map +4 -4
  46. package/dist/version.js +1 -1
  47. package/package.json +3 -2
  48. package/src/LaunchProteinView/components/HelpDialog.tsx +1 -1
  49. package/src/LaunchProteinView/components/PdbResultsTable.tsx +6 -6
  50. package/src/LaunchProteinView/components/PdbSearch.tsx +18 -17
  51. package/src/LaunchProteinView/hooks/useExperimentalStructures.ts +17 -0
  52. package/src/LaunchProteinView/hooks/usePdbEntry.ts +16 -0
  53. package/src/ProteinView/clinVar.test.ts +243 -0
  54. package/src/ProteinView/clinVar.ts +203 -0
  55. package/src/ProteinView/clinVarSource.ts +114 -0
  56. package/src/ProteinView/structureModel.test.ts +31 -16
  57. package/src/ProteinView/structureModel.ts +95 -118
  58. package/src/ProteinView/structureVariantEffects.test.ts +127 -27
  59. package/src/ProteinView/variantEffectColorTheme.ts +1 -1
  60. package/src/ProteinView/variantEffectLoader.test.ts +63 -72
  61. package/src/ProteinView/variantEffectLoader.ts +36 -46
  62. package/src/ProteinView/variantEffectSource.test.ts +20 -0
  63. package/src/ProteinView/variantEffectSource.ts +174 -41
  64. package/src/ProteinView/variantEffectStatus.test.ts +224 -0
  65. package/src/ProteinView/variantEffectStatus.ts +104 -0
  66. package/src/ProteinView/variantEffects.test.ts +7 -88
  67. package/src/ProteinView/variantEffects.ts +29 -69
  68. package/src/version.ts +1 -1
  69. package/dist/LaunchProteinView/hooks/usePdbBestStructures.js +0 -19
  70. package/dist/LaunchProteinView/hooks/usePdbEntryMolecules.js +0 -7
  71. package/dist/chunks/AddStructureDialog-KB77YRP4.js +0 -2
  72. package/dist/chunks/HelpDialog-LLS4EV2C.js +0 -2
  73. package/dist/chunks/chunk-AJ6VTDLS.js +0 -2
  74. package/dist/chunks/chunk-AJ6VTDLS.js.map +0 -7
  75. package/dist/chunks/chunk-O73MUA7S.js +0 -2
  76. package/dist/chunks/chunk-O73MUA7S.js.map +0 -7
  77. package/dist/chunks/chunk-Y4B2HQAN.js +0 -2
  78. package/dist/chunks/chunk-Y4B2HQAN.js.map +0 -7
  79. package/dist/chunks/chunk-YLAEOCSO.js +0 -16
  80. package/dist/chunks/chunk-YLAEOCSO.js.map +0 -7
  81. package/src/LaunchProteinView/hooks/usePdbBestStructures.ts +0 -33
  82. package/src/LaunchProteinView/hooks/usePdbEntryMolecules.ts +0 -17
@@ -14,7 +14,7 @@ export default function HelpDialog({ handleClose, }) {
14
14
  " resolves the feature to a UniProt accession \u2014 from its own identifiers, or one you type \u2014 and opens AlphaFold's predicted model for it."),
15
15
  React.createElement("li", null,
16
16
  React.createElement("b", null, "PDB search"),
17
- " lists the experimental structures PDBe maps to that accession, ranked on coverage and resolution. A crystal is usually one domain, often with binding partners, so the view picks the chain the transcript belongs to once the structure loads."),
17
+ " lists the experimental structures RCSB aligns to that accession, ranked on coverage and resolution. A crystal is usually one domain, often with binding partners, so the view picks the chain the transcript belongs to once the structure loads."),
18
18
  React.createElement("li", null,
19
19
  React.createElement("b", null, "Foldseek search"),
20
20
  " sends the protein sequence to the foldseek.com servers and lists structures similar in shape, including ones with little sequence similarity."),
@@ -30,7 +30,7 @@ export default function PdbResultsTable({ entries, selectedPdbId, onSelect, }) {
30
30
  return (React.createElement(React.Fragment, null,
31
31
  React.createElement(Typography, { variant: "body2", color: "textSecondary" },
32
32
  entries.length,
33
- " PDB entries, ranked by PDBe on coverage and resolution",
33
+ " PDB entries, ranked on coverage, then resolution",
34
34
  entries.length > shown.length
35
35
  ? ` (showing the first ${MAX_ROWS})`
36
36
  : ''),
@@ -43,7 +43,7 @@ export default function PdbResultsTable({ entries, selectedPdbId, onSelect, }) {
43
43
  React.createElement(TableCell, { className: classes.headerCell }, "Method"),
44
44
  React.createElement(TableCell, { className: classes.headerCell }, "Resolution"),
45
45
  React.createElement(TableCell, { className: classes.headerCell },
46
- React.createElement(Tooltip, { title: "The span of the UniProt sequence this entry resolves, by SIFTS. A crystal is usually one domain rather than the whole protein." },
46
+ React.createElement(Tooltip, { title: "The span of the UniProt sequence this entry resolves, by RCSB's UniProt alignment. A crystal is usually one domain rather than the whole protein." },
47
47
  React.createElement("span", null, "UniProt residues"))),
48
48
  React.createElement(TableCell, { className: classes.headerCell }, "Coverage"),
49
49
  React.createElement(TableCell, { className: classes.headerCell }, "Chains"))),
@@ -56,14 +56,14 @@ export default function PdbResultsTable({ entries, selectedPdbId, onSelect, }) {
56
56
  React.createElement(Radio, { checked: selected, size: "small" })),
57
57
  React.createElement(TableCell, null,
58
58
  React.createElement(ExternalLink, { href: rcsbEntryUrl(entry.pdbId) }, entry.pdbId.toUpperCase())),
59
- React.createElement(TableCell, null, entry.experimentalMethod),
59
+ React.createElement(TableCell, null, entry.method),
60
60
  React.createElement(TableCell, null, entry.resolution === undefined
61
61
  ? '-'
62
62
  : `${entry.resolution.toFixed(2)} Å`),
63
63
  React.createElement(TableCell, null,
64
- entry.unpStart,
64
+ entry.start,
65
65
  "-",
66
- entry.unpEnd),
66
+ entry.end),
67
67
  React.createElement(TableCell, null,
68
68
  (entry.coverage * 100).toFixed(0),
69
69
  "%"),
@@ -12,8 +12,8 @@ import UniProtLookupControls from './UniProtLookupControls';
12
12
  import UniProtLookupResults from './UniProtLookupResults';
13
13
  import ExternalLink from '../../components/ExternalLink';
14
14
  import useDebouncedValue from '../hooks/useDebouncedValue';
15
- import usePdbBestStructures from '../hooks/usePdbBestStructures';
16
- import usePdbEntryMolecules from '../hooks/usePdbEntryMolecules';
15
+ import useExperimentalStructures from '../hooks/useExperimentalStructures';
16
+ import usePdbEntry from '../hooks/usePdbEntry';
17
17
  import useTranscriptIsoformSelection from '../hooks/useTranscriptIsoformSelection';
18
18
  const useStyles = makeStyles()({
19
19
  dialogContent: {
@@ -26,18 +26,18 @@ const useStyles = makeStyles()({
26
26
  },
27
27
  },
28
28
  });
29
- // Experimental structures of the gene's protein, found through SIFTS: PDBe
30
- // lists every entry mapped to the UniProt accession, ranked on coverage and
31
- // resolution, so a reader who does not know a PDB id can still reach one.
29
+ // Experimental structures of the gene's protein: RCSB lists every entry it
30
+ // aligns to the UniProt accession, ranked on coverage and resolution, so a
31
+ // reader who does not know a PDB id can still reach one.
32
32
  // A crystal is usually a fragment, often with partners, so the view aligns
33
33
  // the transcript to it after launch rather than expecting a sequence match
34
34
  // here.
35
35
  const PdbSearch = observer(function PdbSearch({ feature, preferredTranscriptId, session, view, handleClose, lookup, sideBySide, onSideBySideChange, }) {
36
36
  const { classes } = useStyles();
37
37
  const { uniprotId, isLookupLoading, lookupError } = lookup;
38
- const { entries, error: pdbError, isLoading: isPdbLoading, } = usePdbBestStructures(uniprotId);
38
+ const { entries, error: pdbError, isLoading: isPdbLoading, } = useExperimentalStructures(uniprotId);
39
39
  const [userPdbId, setUserPdbId] = useState();
40
- // A typed id reaches entries PDBe's SIFTS listing never offers: a structure
40
+ // A typed id reaches entries the accession's listing never offers: a structure
41
41
  // of a complex filed under a partner, anything a paper names. Debounced, so
42
42
  // the three characters on the way to four are not three fetches.
43
43
  const [typedPdbId, setTypedPdbId] = useState('');
@@ -55,7 +55,8 @@ const PdbSearch = observer(function PdbSearch({ feature, preferredTranscriptId,
55
55
  // The chosen entry's residues, which rank the isoforms and label the picker,
56
56
  // the same annotation the AlphaFold tab shows. Their failure costs the
57
57
  // ranking rather than the launch, which reads the structure file itself.
58
- const { sequences: structureSequences, error: moleculesError, isValidating: isMoleculesValidating, } = usePdbEntryMolecules(selectedPdbId);
58
+ const { entry, error: entryError, isValidating: isEntryValidating, } = usePdbEntry(selectedPdbId);
59
+ const structureSequences = entry?.proteinSequences;
59
60
  const { transcripts, structureSequence, ranking, isLoading: isIsoformLoading, isRanking, error: isoformError, partialFailure: isoformPartialFailure, selectedTranscriptId, setSelectedTranscriptId, selectedTranscript, selectedIsoform, } = useTranscriptIsoformSelection({
60
61
  feature,
61
62
  view,
@@ -66,21 +67,21 @@ const PdbSearch = observer(function PdbSearch({ feature, preferredTranscriptId,
66
67
  // Until the entry's chains arrive the ranking has no structure and orders
67
68
  // the isoforms by length, so a launch that takes the ranked default waits.
68
69
  // The right-clicked isoform needs no ranking and launches at once.
69
- // An entry PDBe cannot describe stops holding the launch.
70
- const awaitsChains = isMoleculesValidating &&
71
- !moleculesError &&
70
+ // An entry RCSB cannot describe stops holding the launch.
71
+ const awaitsChains = isEntryValidating &&
72
+ !entryError &&
72
73
  selectedTranscriptId !== preferredTranscriptId;
73
74
  const isoformStatuses = [
74
75
  isIsoformLoading && 'Loading protein sequences from transcript isoforms',
75
76
  isRanking && 'Aligning isoforms to the structure',
76
- awaitsChains && 'Reading the chains of the entry from PDBe',
77
+ awaitsChains && 'Reading the chains of the entry from RCSB',
77
78
  // the selection reads the debounced id, so a launch inside the debounce
78
79
  // opened the entry selected before the typing
79
80
  trimmedTypedPdbId !== debouncedTypedPdbId && 'Reading the typed PDB ID',
80
81
  ];
81
82
  const lookupStatuses = [
82
83
  isLookupLoading && 'Looking up UniProt ID',
83
- isPdbLoading && 'Listing PDB entries from PDBe',
84
+ isPdbLoading && 'Listing PDB entries from RCSB',
84
85
  ];
85
86
  const loadingStatuses = [...lookupStatuses, ...isoformStatuses].filter((s) => !!s);
86
87
  const isLoading = loadingStatuses.length > 0;
@@ -115,7 +116,7 @@ const PdbSearch = observer(function PdbSearch({ feature, preferredTranscriptId,
115
116
  setTypedPdbId(event.target.value);
116
117
  }, slotProps: { inputLabel: { shrink: true } }, sx: { width: 240 } }),
117
118
  uniprotId && entries && !isPdbLoading ? (entries.length > 0 ? (React.createElement(PdbResultsTable, { entries: entries, selectedPdbId: selectedPdbId, onSelect: setUserPdbId })) : (React.createElement(Typography, null,
118
- "PDBe lists no experimental structure for",
119
+ "RCSB lists no experimental structure for",
119
120
  ' ',
120
121
  React.createElement(ExternalLink, { href: uniprotEntryUrl(uniprotId) }, uniprotId),
121
122
  ". The AlphaFoldDB tab has a predicted one."))) : null,
@@ -0,0 +1,9 @@
1
+ import { fetchExperimentalStructures } from 'p2s_mapper';
2
+ import useSWR from 'swr';
3
+ import { STATIC_SWR_OPTIONS } from './swrOptions';
4
+ // An accession with no experimental structure, the ordinary case for most
5
+ // genes, answers an empty list rather than an error.
6
+ export default function useExperimentalStructures(uniprotId) {
7
+ const { data, error, isLoading } = useSWR(uniprotId ? ['experimental-structures', uniprotId] : null, ([, id]) => fetchExperimentalStructures(id), STATIC_SWR_OPTIONS);
8
+ return { entries: data, error, isLoading };
9
+ }
@@ -0,0 +1,10 @@
1
+ import { fetchPdbEntry } from 'p2s_mapper';
2
+ import useSWR from 'swr';
3
+ import { STATIC_SWR_OPTIONS } from './swrOptions';
4
+ // The entry's protein sequences rank the isoforms and label the picker: a few
5
+ // kB of JSON from RCSB, where reading them out of the structure file meant
6
+ // downloading and parsing the whole mmCIF, minutes for a ribosome.
7
+ export default function usePdbEntry(pdbId) {
8
+ const { data, error, isLoading, isValidating } = useSWR(pdbId ? ['pdb-entry', pdbId] : null, ([, id]) => fetchPdbEntry(id), STATIC_SWR_OPTIONS);
9
+ return { entry: data, error, isLoading, isValidating };
10
+ }
@@ -0,0 +1,146 @@
1
+ export const CLINVAR_BUILDS = ['GRCh38', 'GRCh37'];
2
+ const BUILD_NAMES = {
3
+ GRCh38: ['grch38', 'hg38'],
4
+ GRCh37: ['grch37', 'hg19'],
5
+ };
6
+ // Every version of NCBI's human reference series, by its revision history
7
+ // (measured 2026-10-10): GRCh37 through GRCh37.p13, then GRCh38 through
8
+ // GRCh38.p14. The series is GRC's lineage, so a later version may be a new
9
+ // major; it stays unrecognised until it is checked.
10
+ const ACCESSION_VERSIONS = {
11
+ GRCh37: { GCF: [13, 25], GCA: [1, 14] },
12
+ GRCh38: { GCF: [26, 40], GCA: [15, 29] },
13
+ };
14
+ function isBuildAccession(build, name) {
15
+ const match = /^(GCF|GCA)_000001405\.(\d+)$/i.exec(name);
16
+ const prefix = match?.[1]?.toUpperCase();
17
+ if (prefix !== 'GCF' && prefix !== 'GCA') {
18
+ return false;
19
+ }
20
+ const [first, last] = ACCESSION_VERSIONS[build][prefix];
21
+ const version = Number(match?.[2]);
22
+ return version >= first && version <= last;
23
+ }
24
+ /**
25
+ * The ClinVar build an assembly is, by its name or any alias: `hg38`,
26
+ * `GRCh38.p14` and `GCF_000001405.40` are GRCh38. Undefined for any other
27
+ * assembly, which NCBI publishes no ClinVar VCF for.
28
+ */
29
+ export function clinVarBuild(assemblyNames) {
30
+ const names = assemblyNames.map(n => n.toLowerCase());
31
+ return CLINVAR_BUILDS.find(build => BUILD_NAMES[build].some(prefix => names.some(n => n === prefix || n.startsWith(`${prefix}.`))) || assemblyNames.some(n => isBuildAccession(build, n)));
32
+ }
33
+ export function clinVarVcfUrl(build) {
34
+ return `https://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_${build}/clinvar.vcf.gz`;
35
+ }
36
+ /**
37
+ * Whether a refName is a mitochondrion ClinVar's VCF for the build does not
38
+ * number. Both VCFs number the rCRS as `MT`, which is GRCh38's chrM and
39
+ * GRCh37's own `MT`, but hg19's chrM is NC_001807, a different 16571-base
40
+ * sequence.
41
+ */
42
+ export function isUnnumberedMitochondrion(refName, build) {
43
+ return build === 'GRCh37' && /^(chrM|M|NC_001807(\.\d+)?)$/i.test(refName);
44
+ }
45
+ /**
46
+ * The name NCBI's VCF gives a chromosome: `1`..`22`, `X`, `Y` and `MT`.
47
+ * Undefined for a mitochondrion the build's VCF does not number.
48
+ */
49
+ export function clinVarRefName(refName, build) {
50
+ if (isUnnumberedMitochondrion(refName, build)) {
51
+ return undefined;
52
+ }
53
+ const bare = refName.replace(/^chr/i, '');
54
+ return bare === 'M' ? 'MT' : bare;
55
+ }
56
+ const BASE = /^[ACGT]$/;
57
+ function infoField(info, key) {
58
+ return new RegExp(`(?:^|;)${key}=([^;]*)`).exec(info)?.[1];
59
+ }
60
+ /**
61
+ * The substitution a ClinVar VCF line records, when ClinVar's aggregate
62
+ * germline classification calls it pathogenic or likely pathogenic and it is
63
+ * missense on some transcript. `CLNSIG` joins classifications with `/`, `|`
64
+ * and `,` (`Pathogenic/Likely_pathogenic`, `Pathogenic,_low_penetrance`);
65
+ * `Conflicting_classifications_of_pathogenicity` holds no such term, so a
66
+ * conflicted call does not count.
67
+ */
68
+ export function parseClinVarSnv(line) {
69
+ const [, pos, , ref, alt, , , info = ''] = line.split('\t');
70
+ const significance = infoField(info, 'CLNSIG')?.split(/[/|,]/);
71
+ const consequences = infoField(info, 'MC')?.split(',');
72
+ return pos &&
73
+ ref &&
74
+ alt &&
75
+ BASE.test(ref) &&
76
+ BASE.test(alt) &&
77
+ significance?.some(s => s === 'Pathogenic' || s === 'Likely_pathogenic') &&
78
+ consequences?.some(c => c.endsWith('|missense_variant'))
79
+ ? { start: +pos - 1, ref, alt }
80
+ : undefined;
81
+ }
82
+ const COMPLEMENT = { A: 'T', C: 'G', G: 'C', T: 'A' };
83
+ /**
84
+ * How many distinct missense substitutions ClinVar calls pathogenic or likely
85
+ * pathogenic at each 0-based residue of a transcript. Each substitution is
86
+ * translated on this transcript's own codon: `p2gCodon` (g2p_mapper's, 0-based)
87
+ * lists a codon's genome positions in reading order, so a codon split by an
88
+ * intron and a minus-strand codon both read right. A variant the VCF calls
89
+ * missense on another transcript but that is synonymous, nonsense or outside
90
+ * the coding sequence of this one does not count, nor does one whose `REF`
91
+ * disagrees with the genome. Two codon changes to one amino acid count once.
92
+ * Every residue with a whole codon gets a count, zero included, so a residue
93
+ * ClinVar has no call for is told apart from one the structure cannot place.
94
+ * `checked` counts the variants that landed on a codon, and `disagreeing`
95
+ * those whose `REF` the genome does not spell.
96
+ */
97
+ export function pathogenicCountByTranscriptPosition({ variants, p2gCodon, strand, genomeBase, codonTable, }) {
98
+ const oriented = (base) => base && strand === -1 ? COMPLEMENT[base] : base;
99
+ const codons = new Map();
100
+ const residueAt = new Map();
101
+ for (const [residue, positions] of Object.entries(p2gCodon)) {
102
+ const bases = positions.map(p => oriented(genomeBase(p)?.toUpperCase()));
103
+ if (bases.length === 3 && bases.every(b => b !== undefined)) {
104
+ codons.set(+residue, bases);
105
+ positions.forEach((position, index) => {
106
+ residueAt.set(position, { residue: +residue, index });
107
+ });
108
+ }
109
+ }
110
+ const substitutions = new Map();
111
+ let checked = 0;
112
+ let disagreeing = 0;
113
+ for (const { start, ref, alt } of variants) {
114
+ const at = residueAt.get(start);
115
+ const codon = at ? codons.get(at.residue) : undefined;
116
+ if (!at || !codon) {
117
+ continue;
118
+ }
119
+ checked++;
120
+ if (codon[at.index] !== oriented(ref)) {
121
+ disagreeing++;
122
+ continue;
123
+ }
124
+ const mutated = codon.with(at.index, oriented(alt) ?? '');
125
+ const from = codonTable[codon.join('')];
126
+ const to = codonTable[mutated.join('')];
127
+ if (from && to && from !== to && from !== '*' && to !== '*') {
128
+ const seen = substitutions.get(at.residue) ?? new Set();
129
+ seen.add(to);
130
+ substitutions.set(at.residue, seen);
131
+ }
132
+ }
133
+ const byPosition = new Map([...codons.keys()]
134
+ .toSorted((a, b) => a - b)
135
+ .map(residue => [residue, substitutions.get(residue)?.size ?? 0]));
136
+ return { byPosition, checked, disagreeing };
137
+ }
138
+ /**
139
+ * Whether the genome under a transcript is some other build than the VCF's:
140
+ * most of at least ten variants disagree with it on their `REF`. A few
141
+ * disagreements are a reference correction or a stray record; most mean
142
+ * every count would be zero for the wrong reason.
143
+ */
144
+ export function isWrongBuild({ checked, disagreeing, }) {
145
+ return checked >= 10 && disagreeing / checked > 0.5;
146
+ }
@@ -0,0 +1,72 @@
1
+ import { TabixIndexedFile } from '@gmod/tabix';
2
+ import { getGeneticCode } from '@jbrowse/core/util/geneticCodes';
3
+ import { transcriptGeneticCodeId } from '@jbrowse/core/util/translateTranscript';
4
+ import { clinVarRefName, clinVarVcfUrl, isWrongBuild, parseClinVarSnv, pathogenicCountByTranscriptPosition, } from './clinVar';
5
+ import { VariantEffectRefusal } from './variantEffects';
6
+ import { fetchRegionSequence } from '../LaunchProteinView/utils/translateTranscripts';
7
+ import { genomeToTranscriptSeqMapping } from '../mappings';
8
+ const files = new Map();
9
+ function clinVarVcf(build) {
10
+ let file = files.get(build);
11
+ if (!file) {
12
+ const url = clinVarVcfUrl(build);
13
+ file = new TabixIndexedFile({ url, tbiUrl: `${url}.tbi` });
14
+ files.set(build, file);
15
+ }
16
+ return file;
17
+ }
18
+ async function readPathogenicSnvs(build, refNames, start, end, signal) {
19
+ const file = clinVarVcf(build);
20
+ const names = await file.getReferenceSequenceNames({ signal });
21
+ const refName = refNames
22
+ .map(n => clinVarRefName(n, build))
23
+ .find(n => n !== undefined && names.includes(n));
24
+ if (!refName) {
25
+ throw new Error(`ClinVar's ${build} VCF has no sequence ${refNames[0]}`);
26
+ }
27
+ const variants = [];
28
+ await file.getLines(refName, start, end, {
29
+ signal,
30
+ lineCallback: line => {
31
+ const snv = parseClinVarSnv(line);
32
+ if (snv) {
33
+ variants.push(snv);
34
+ }
35
+ },
36
+ });
37
+ return variants;
38
+ }
39
+ /**
40
+ * The pathogenic missense count at each residue of a transcript, read from
41
+ * NCBI's ClinVar VCF by range over the transcript's coding span and translated
42
+ * on the genome under it
43
+ */
44
+ export async function fetchClinVarCounts({ build, feature, assemblyName, session, signal, }) {
45
+ const { p2gCodon, strand, refName } = genomeToTranscriptSeqMapping(feature);
46
+ const positions = Object.values(p2gCodon).flat();
47
+ if (positions.length === 0) {
48
+ throw new Error('the transcript has no coding sequence');
49
+ }
50
+ const start = Math.min(...positions);
51
+ const end = Math.max(...positions) + 1;
52
+ const assembly = await session.assemblyManager.waitForAssembly(assemblyName);
53
+ const [variants, genome] = await Promise.all([
54
+ readPathogenicSnvs(build, [refName, ...(assembly?.getAliasesForRefName(refName) ?? [])], start, end, signal),
55
+ fetchRegionSequence({ session, assemblyName, refName, start, end }),
56
+ ]);
57
+ const { seq, assemblyGeneticCodeId } = genome;
58
+ if (!seq) {
59
+ throw new Error('no genome sequence under the transcript');
60
+ }
61
+ const counts = pathogenicCountByTranscriptPosition({
62
+ variants,
63
+ p2gCodon,
64
+ strand,
65
+ genomeBase: position => seq[position - start],
66
+ codonTable: getGeneticCode(transcriptGeneticCodeId(feature, assemblyGeneticCodeId)).codonTable,
67
+ });
68
+ if (isWrongBuild(counts)) {
69
+ throw new VariantEffectRefusal(`ClinVar's REF disagrees with this assembly's sequence at ${counts.disagreeing} of ${counts.checked} variants; is the assembly ${build}?`);
70
+ }
71
+ return counts.byPosition;
72
+ }
@@ -13,7 +13,8 @@ import { kyteDoolittleScores, mapResidueValuesToColumns } from './residueTracks'
13
13
  import { structureUniProt } from './structureUniProt';
14
14
  import { assemblyNaming, errorMessage } from './util';
15
15
  import { makeVariantEffectLoader } from './variantEffectLoader';
16
- import { VARIANT_EFFECT_SOURCE_NAMES, isVariantEffectScheme, placeValues, } from './variantEffects';
16
+ import { alphaMissenseAsk, clinVarAsk, fetchVariantEffects, } from './variantEffectSource';
17
+ import { variantEffectStatus } from './variantEffectStatus';
17
18
  import { codingSpans, genomeToTranscriptSeqMapping } from '../mappings';
18
19
  // `connectedViewId` comes from a spec, which can name any view of the session
19
20
  function isGenomeView(view) {
@@ -240,8 +241,8 @@ const Structure = types
240
241
  uniProtMappingsError: undefined,
241
242
  /**
242
243
  * #volatile
243
- * What the view's variant-effect colour scheme asked for this structure's
244
- * UniProt entry, and the per-position values once they arrive
244
+ * The key of what the view's variant-effect colour scheme asked for this
245
+ * structure, and the values once they arrive
245
246
  */
246
247
  variantEffects: undefined,
247
248
  /**
@@ -520,99 +521,6 @@ const Structure = types
520
521
  mappedEntity: this.mappedEntity,
521
522
  });
522
523
  },
523
- /**
524
- * #getter
525
- * The view's colour scheme, when it colours by a variant-effect source
526
- */
527
- get variantEffectScheme() {
528
- const scheme = this.parentView.colorScheme;
529
- return isVariantEffectScheme(scheme) ? scheme : undefined;
530
- },
531
- /**
532
- * #getter
533
- * The entry a variant-effect source is asked for: the structure's UniProt
534
- * entry, unless the model folds an isoform the sources do not number
535
- */
536
- get variantEffectAccession() {
537
- const { uniprotId, isoformAccession } = this.uniProtEntry;
538
- return isoformAccession ? undefined : uniprotId;
539
- },
540
- /**
541
- * #getter
542
- * The variant-effect state, while it answers the current scheme and entry
543
- */
544
- get currentVariantEffects() {
545
- const state = self.variantEffects;
546
- return this.variantEffectScheme &&
547
- !this.uniProtEntry.isLoading &&
548
- state?.scheme === this.variantEffectScheme &&
549
- state.accession === this.variantEffectAccession
550
- ? state
551
- : undefined;
552
- },
553
- /**
554
- * #getter
555
- * Whether the source numbers a sequence other than the one this
556
- * structure's chain spells, where the two are mapped one to one: an
557
- * AlphaFold model folded from an older revision of the entry would take
558
- * every value a residue off, and nothing else would say so. A PDB entry
559
- * goes through SIFTS, which maps the construct to the current entry.
560
- */
561
- get variantEffectSequenceDiffers() {
562
- const values = this.currentVariantEffects?.values;
563
- const entity = this.mappedEntity;
564
- return (!!values && !!entity && !this.pdbId && values.sequence !== entity.seq);
565
- },
566
- /**
567
- * #getter
568
- * The scheme's values on the mapped entity's residues, by label_seq_id.
569
- * Only the residues the UniProt entry's map reaches get one (see
570
- * structureUniProt): an AlphaFold model of the entry one to one, a PDB
571
- * entry through SIFTS' segments.
572
- */
573
- get placedVariantEffects() {
574
- const values = this.currentVariantEffects?.values;
575
- const entity = this.mappedEntity;
576
- return values && entity && !this.variantEffectSequenceDiffers
577
- ? placeValues(values, this.uniProtEntry.mapUniProtPosition, entity)
578
- : undefined;
579
- },
580
- /**
581
- * #getter
582
- * Whether the scheme's values are still on their way. Kept out of
583
- * `loading`: colour arriving late only recolours, so selection, framing
584
- * and the ready marker do not wait on a download that can run to 14 MB.
585
- */
586
- get variantEffectsPending() {
587
- const state = this.currentVariantEffects;
588
- return (!!this.variantEffectScheme &&
589
- (!state ||
590
- (state.accession !== undefined &&
591
- !state.values &&
592
- state.error === undefined)));
593
- },
594
- /**
595
- * #getter
596
- * Why the scheme leaves this structure grey, once that is settled
597
- */
598
- get variantEffectMessage() {
599
- const scheme = this.variantEffectScheme;
600
- const state = this.currentVariantEffects;
601
- if (!scheme || !state) {
602
- return undefined;
603
- }
604
- const source = VARIANT_EFFECT_SOURCE_NAMES[scheme];
605
- const { isoformAccession } = this.uniProtEntry;
606
- return state.error !== undefined
607
- ? `Could not fetch ${source} for ${state.accession}: ${errorMessage(state.error)}`
608
- : this.variantEffectSequenceDiffers
609
- ? `${source} for ${state.accession} number a sequence that differs from this model's`
610
- : state.accession !== undefined
611
- ? undefined
612
- : isoformAccession
613
- ? `${source} are numbered for the canonical entry, not isoform ${isoformAccession}`
614
- : `No UniProt entry to place ${source} on`;
615
- },
616
524
  /**
617
525
  * #getter
618
526
  * The alignment every map, highlight and the panel read: the stored one,
@@ -1032,19 +940,6 @@ const Structure = types
1032
940
  }
1033
941
  return `Mapping ${this.label} to UniProt`;
1034
942
  },
1035
- /**
1036
- * #getter
1037
- * What went wrong with this structure, for the line beside its label in
1038
- * the header: a failed load, or a structure with no chain the transcript
1039
- * can be aligned to. One line per structure, rather than a view-wide
1040
- * banner that names neither which structure nor what it was doing.
1041
- */
1042
- get statusMessage() {
1043
- const { error } = self;
1044
- return error === undefined
1045
- ? (self.alignmentSkipped ?? this.variantEffectMessage)
1046
- : errorMessage(error);
1047
- },
1048
943
  /**
1049
944
  * #getter
1050
945
  * Identity and coverage of the pairwise alignment, for the header readout
@@ -1123,6 +1018,83 @@ const Structure = types
1123
1018
  get molstarPluginContext() {
1124
1019
  return this.parentView.molstarPluginContext;
1125
1020
  },
1021
+ }))
1022
+ .views(self => ({
1023
+ /**
1024
+ * #getter
1025
+ * What this structure can ask the view's variant-effect source for,
1026
+ * undefined while the view colours by none. ClinVar reads the genome on
1027
+ * the connected view's assembly.
1028
+ */
1029
+ get variantEffectAsk() {
1030
+ const { colorScheme } = self.parentView;
1031
+ if (colorScheme === 'alphamissense') {
1032
+ return alphaMissenseAsk(self.uniProtEntry);
1033
+ }
1034
+ if (colorScheme === 'clinvar') {
1035
+ const assemblyName = self.connectedView?.assemblyNames[0];
1036
+ const assembly = assemblyName
1037
+ ? getSession(self).assemblyManager.get(assemblyName)
1038
+ : undefined;
1039
+ return clinVarAsk({
1040
+ feature: self.feature,
1041
+ assemblyName,
1042
+ assemblyNames: [
1043
+ ...(assemblyName ? [assemblyName] : []),
1044
+ ...(assembly ? [assembly.name, ...assembly.aliases] : []),
1045
+ ],
1046
+ });
1047
+ }
1048
+ return undefined;
1049
+ },
1050
+ }))
1051
+ .views(self => ({
1052
+ /**
1053
+ * #getter
1054
+ * The variant-effect request's standing and its values placed on the
1055
+ * mapped entity; see variantEffectStatus
1056
+ */
1057
+ get variantEffectStatus() {
1058
+ return variantEffectStatus({
1059
+ ask: self.variantEffectAsk,
1060
+ state: self.variantEffects,
1061
+ entity: self.mappedEntity,
1062
+ pdbId: self.pdbId,
1063
+ mapUniProtPosition: self.uniProtEntry.mapUniProtPosition,
1064
+ transcriptToStructure: self.transcriptSeqToStructureSeqPosition,
1065
+ });
1066
+ },
1067
+ }))
1068
+ .views(self => ({
1069
+ /**
1070
+ * #getter
1071
+ * The scheme's values on the mapped entity's residues, by label_seq_id
1072
+ */
1073
+ get placedVariantEffects() {
1074
+ return self.variantEffectStatus.placed;
1075
+ },
1076
+ /**
1077
+ * #getter
1078
+ * Whether the scheme's values are still on their way, which the ready
1079
+ * marker does not wait for
1080
+ */
1081
+ get variantEffectsPending() {
1082
+ return self.variantEffectStatus.pending;
1083
+ },
1084
+ /**
1085
+ * #getter
1086
+ * What went wrong with this structure, for the line beside its label in
1087
+ * the header: a failed load, a structure with no chain the transcript
1088
+ * can be aligned to, or a colour scheme that leaves it grey. One line per
1089
+ * structure, rather than a view-wide banner that names neither which
1090
+ * structure nor what it was doing.
1091
+ */
1092
+ get statusMessage() {
1093
+ const { error } = self;
1094
+ return error === undefined
1095
+ ? (self.alignmentSkipped ?? self.variantEffectStatus.message)
1096
+ : errorMessage(error);
1097
+ },
1126
1098
  }))
1127
1099
  .views(self => ({
1128
1100
  /**
@@ -1451,7 +1423,7 @@ const Structure = types
1451
1423
  .actions(self => ({
1452
1424
  afterAttach() {
1453
1425
  const { pdbId } = self;
1454
- addDisposer(self, autorun(makeVariantEffectLoader(self, () => isAlive(self))));
1426
+ addDisposer(self, autorun(makeVariantEffectLoader(self, () => isAlive(self), request => fetchVariantEffects(request, getSession(self)))));
1455
1427
  if (pdbId) {
1456
1428
  fetchUniProtStructureMappings(pdbId).then(mappings => {
1457
1429
  if (isAlive(self)) {
@@ -49,7 +49,7 @@ const STYLES = {
49
49
  clinvar: {
50
50
  color: count => rgbColor(clinVarRgb(count)),
51
51
  legend: CLINVAR_LEGEND,
52
- description: 'Colors residues by how many missense substitutions ClinVar calls pathogenic or likely pathogenic. Residues the entry cannot place are grey.',
52
+ description: 'Colors residues by how many missense substitutions ClinVar calls pathogenic or likely pathogenic, read off the genome under the transcript. Residues the alignment to the transcript does not reach are grey.',
53
53
  },
54
54
  };
55
55
  function variantEffectTheme(scheme) {