label.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { Unit, StructureElement, StructureProperties as Props, Bond } from '../mol-model/structure';
  8. import { Loci } from '../mol-model/loci';
  9. import { OrderedSet } from '../mol-data/int';
  10. import { capitalize, stripTags } from '../mol-util/string';
  11. import { Column } from '../mol-data/db';
  12. import { Vec3 } from '../mol-math/linear-algebra';
  13. import { radToDeg } from '../mol-math/misc';
  14. import { Volume } from '../mol-model/volume';
  15. export type LabelGranularity = 'element' | 'conformation' | 'residue' | 'chain' | 'structure'
  16. export const DefaultLabelOptions = {
  17. granularity: 'element' as LabelGranularity,
  18. condensed: false,
  19. reverse: false,
  20. countsOnly: false,
  21. hidePrefix: false,
  22. htmlStyling: true,
  23. };
  24. export type LabelOptions = typeof DefaultLabelOptions
  25. export function lociLabel(loci: Loci, options: Partial<LabelOptions> = {}): string {
  26. switch (loci.kind) {
  27. case 'structure-loci':
  28. return loci.structure.models.map(m => m.entry).filter(l => !!l).join(', ');
  29. case 'element-loci':
  30. return structureElementStatsLabel(StructureElement.Stats.ofLoci(loci), options);
  31. case 'bond-loci':
  32. const bond = loci.bonds[0];
  33. return bond ? bondLabel(bond) : '';
  34. case 'shape-loci':
  35. return loci.shape.name;
  36. case 'group-loci':
  37. const g = loci.groups[0];
  38. return g ? loci.shape.getLabel(OrderedSet.start(g.ids), g.instance) : '';
  39. case 'every-loci':
  40. return 'Everything';
  41. case 'empty-loci':
  42. return 'Nothing';
  43. case 'data-loci':
  44. return loci.getLabel();
  45. case 'volume-loci':
  46. return loci.volume.label || 'Volume';
  47. case 'isosurface-loci':
  48. return [
  49. `${loci.volume.label || 'Volume'}`,
  50. `Isosurface at ${Volume.IsoValue.toString(loci.isoValue)}`
  51. ].join(' | ');
  52. case 'cell-loci':
  53. const size = OrderedSet.size(loci.indices);
  54. const start = OrderedSet.start(loci.indices);
  55. const absVal = Volume.IsoValue.absolute(loci.volume.grid.cells.data[start]);
  56. const relVal = Volume.IsoValue.toRelative(absVal, loci.volume.grid.stats);
  57. const label = [
  58. `${loci.volume.label || 'Volume'}`,
  59. `${size === 1 ? `Cell #${start}` : `${size} Cells`}`
  60. ];
  61. if (size === 1) {
  62. label.push(`${Volume.IsoValue.toString(absVal)} (${Volume.IsoValue.toString(relVal)})`);
  63. }
  64. return label.join(' | ');
  65. }
  66. }
  67. function countLabel(count: number, label: string) {
  68. return count === 1 ? `1 ${label}` : `${count} ${label}s`;
  69. }
  70. function otherLabel(count: number, location: StructureElement.Location, granularity: LabelGranularity, hidePrefix: boolean, reverse: boolean, condensed: boolean) {
  71. return `${elementLabel(location, { granularity, hidePrefix, reverse, condensed })} <small>[+ ${countLabel(count - 1, `other ${capitalize(granularity)}`)}]</small>`;
  72. }
  73. /** Gets residue count of the model chain segments the unit is a subset of */
  74. function getResidueCount(unit: Unit.Atomic) {
  75. const { elements, model } = unit;
  76. const { chainAtomSegments, residueAtomSegments } = model.atomicHierarchy;
  77. const elementStart = chainAtomSegments.offsets[chainAtomSegments.index[elements[0]]];
  78. const elementEnd = chainAtomSegments.offsets[chainAtomSegments.index[elements[elements.length - 1]] + 1] - 1;
  79. return residueAtomSegments.index[elementEnd] - residueAtomSegments.index[elementStart] + 1;
  80. }
  81. export function structureElementStatsLabel(stats: StructureElement.Stats, options: Partial<LabelOptions> = {}): string {
  82. const o = { ...DefaultLabelOptions, ...options };
  83. const label = _structureElementStatsLabel(stats, o.countsOnly, o.hidePrefix, o.condensed, o.reverse);
  84. return o.htmlStyling ? label : stripTags(label);
  85. }
  86. function _structureElementStatsLabel(stats: StructureElement.Stats, countsOnly = false, hidePrefix = false, condensed = false, reverse = false): string {
  87. const { structureCount, chainCount, residueCount, conformationCount, elementCount } = stats;
  88. if (!countsOnly && elementCount === 1 && residueCount === 0 && chainCount === 0) {
  89. return elementLabel(stats.firstElementLoc, { hidePrefix, condensed, granularity: 'element', reverse });
  90. } else if (!countsOnly && elementCount === 0 && residueCount === 1 && chainCount === 0) {
  91. return elementLabel(stats.firstResidueLoc, { hidePrefix, condensed, granularity: 'residue', reverse });
  92. } else if (!countsOnly && elementCount === 0 && residueCount === 0 && chainCount === 1) {
  93. const { unit } = stats.firstChainLoc;
  94. const granularity = (Unit.isAtomic(unit) && getResidueCount(unit) === 1)
  95. ? 'residue' : Unit.Traits.is(unit.traits, Unit.Trait.MultiChain)
  96. ? 'residue' : 'chain';
  97. return elementLabel(stats.firstChainLoc, { hidePrefix, condensed, granularity, reverse });
  98. } else if (!countsOnly) {
  99. const label: string[] = [];
  100. if (structureCount > 0) {
  101. label.push(structureCount === 1 ? elementLabel(stats.firstStructureLoc, { hidePrefix, condensed, granularity: 'structure', reverse }) : otherLabel(structureCount, stats.firstStructureLoc, 'structure', hidePrefix, reverse, condensed));
  102. }
  103. if (chainCount > 0) {
  104. label.push(chainCount === 1 ? elementLabel(stats.firstChainLoc, { condensed, granularity: 'chain', hidePrefix, reverse }) : otherLabel(chainCount, stats.firstChainLoc, 'chain', hidePrefix, reverse, condensed));
  105. hidePrefix = true;
  106. }
  107. if (residueCount > 0) {
  108. label.push(residueCount === 1 ? elementLabel(stats.firstResidueLoc, { condensed, granularity: 'residue', hidePrefix, reverse }) : otherLabel(residueCount, stats.firstResidueLoc, 'residue', hidePrefix, reverse, condensed));
  109. hidePrefix = true;
  110. }
  111. if (conformationCount > 0) {
  112. label.push(conformationCount === 1 ? elementLabel(stats.firstConformationLoc, { condensed, granularity: 'conformation', hidePrefix, reverse }) : otherLabel(conformationCount, stats.firstConformationLoc, 'conformation', hidePrefix, reverse, condensed));
  113. hidePrefix = true;
  114. }
  115. if (elementCount > 0) {
  116. label.push(elementCount === 1 ? elementLabel(stats.firstElementLoc, { condensed, granularity: 'element', hidePrefix, reverse }) : otherLabel(elementCount, stats.firstElementLoc, 'element', hidePrefix, reverse, condensed));
  117. }
  118. return label.join('<small> + </small>');
  119. } else {
  120. const label: string[] = [];
  121. if (structureCount > 0) label.push(countLabel(structureCount, 'Structure'));
  122. if (chainCount > 0) label.push(countLabel(chainCount, 'Chain'));
  123. if (residueCount > 0) label.push(countLabel(residueCount, 'Residue'));
  124. if (conformationCount > 0) label.push(countLabel(conformationCount, 'Conformation'));
  125. if (elementCount > 0) label.push(countLabel(elementCount, 'Element'));
  126. return label.join('<small> + </small>');
  127. }
  128. }
  129. export function bondLabel(bond: Bond.Location, options: Partial<LabelOptions> = {}): string {
  130. return bundleLabel({ loci: [
  131. StructureElement.Loci(bond.aStructure, [{ unit: bond.aUnit, indices: OrderedSet.ofSingleton(bond.aIndex) }]),
  132. StructureElement.Loci(bond.bStructure, [{ unit: bond.bUnit, indices: OrderedSet.ofSingleton(bond.bIndex) }])
  133. ]}, options);
  134. }
  135. export function bundleLabel(bundle: Loci.Bundle<any>, options: Partial<LabelOptions> = {}): string {
  136. const o = { ...DefaultLabelOptions, ...options };
  137. const label = _bundleLabel(bundle, o);
  138. return o.htmlStyling ? label : stripTags(label);
  139. }
  140. export function _bundleLabel(bundle: Loci.Bundle<any>, options: LabelOptions) {
  141. const { granularity, hidePrefix, reverse, condensed } = options;
  142. let isSingleElements = true;
  143. for (const l of bundle.loci) {
  144. if (!StructureElement.Loci.is(l) || StructureElement.Loci.size(l) !== 1) {
  145. isSingleElements = false;
  146. break;
  147. }
  148. }
  149. if (isSingleElements) {
  150. const locations = (bundle.loci as StructureElement.Loci[]).map(l => {
  151. const { unit, indices } = l.elements[0];
  152. return StructureElement.Location.create(l.structure, unit, unit.elements[OrderedSet.start(indices)]);
  153. });
  154. const labels = locations.map(l => _elementLabel(l, granularity, hidePrefix, reverse || condensed));
  155. if (condensed) {
  156. return labels.map(l => l[0].replace(/\[.*\]/g, '').trim()).filter(l => !!l).join(' \u2014 ');
  157. }
  158. let offset = 0;
  159. for (let i = 0, il = Math.min(...labels.map(l => l.length)) - 1; i < il; ++i) {
  160. let areIdentical = true;
  161. for (let j = 1, jl = labels.length; j < jl; ++j) {
  162. if (labels[0][i] !== labels[j][i]) {
  163. areIdentical = false;
  164. break;
  165. }
  166. }
  167. if (areIdentical) offset += 1;
  168. else break;
  169. }
  170. if (offset > 0) {
  171. const offsetLabels = [labels[0].join(' | ')];
  172. for (let j = 1, jl = labels.length; j < jl; ++j) {
  173. offsetLabels.push(labels[j].slice(offset).filter(l => !!l).join(' | '));
  174. }
  175. return offsetLabels.join(' \u2014 ');
  176. } else {
  177. return labels.map(l => l.filter(l => !!l).join(' | ')).filter(l => !!l).join('</br>');
  178. }
  179. } else {
  180. const labels = bundle.loci.map(l => lociLabel(l, options));
  181. return labels.filter(l => !!l).join(condensed ? ' \u2014 ' : '</br>');
  182. }
  183. }
  184. export function elementLabel(location: StructureElement.Location, options: Partial<LabelOptions> = {}): string {
  185. const o = { ...DefaultLabelOptions, ...options };
  186. const _label = _elementLabel(location, o.granularity, o.hidePrefix, o.reverse || o.condensed);
  187. const label = o.condensed ? _label[0].replace(/\[.*\]/g, '').trim() : _label.filter(l => !!l).join(' | ');
  188. return o.htmlStyling ? label : stripTags(label);
  189. }
  190. function _elementLabel(location: StructureElement.Location, granularity: LabelGranularity = 'element', hidePrefix = false, reverse = false): string[] {
  191. const label: string[] = [];
  192. if (!hidePrefix) {
  193. let entry = location.unit.model.entry;
  194. if (entry.length > 30) entry = entry.substr(0, 27) + '\u2026'; // ellipsis
  195. label.push(`<small>${entry}</small>`); // entry
  196. if (granularity !== 'structure') {
  197. label.push(`<small>Model ${location.unit.model.modelNum}</small>`); // model
  198. label.push(`<small>Instance ${location.unit.conformation.operator.name}</small>`); // instance
  199. }
  200. }
  201. if (Unit.isAtomic(location.unit)) {
  202. label.push(..._atomicElementLabel(location as StructureElement.Location<Unit.Atomic>, granularity, reverse));
  203. } else if (Unit.isCoarse(location.unit)) {
  204. label.push(..._coarseElementLabel(location as StructureElement.Location<Unit.Spheres | Unit.Gaussians>, granularity));
  205. } else {
  206. label.push('Unknown');
  207. }
  208. return reverse ? label.reverse() : label;
  209. }
  210. function _atomicElementLabel(location: StructureElement.Location<Unit.Atomic>, granularity: LabelGranularity, hideOccupancy = false): string[] {
  211. const rI = StructureElement.Location.residueIndex(location);
  212. const label_asym_id = Props.chain.label_asym_id(location);
  213. const auth_asym_id = Props.chain.auth_asym_id(location);
  214. const has_label_seq_id = location.unit.model.atomicHierarchy.residues.label_seq_id.valueKind(rI) === Column.ValueKind.Present;
  215. const label_seq_id = Props.residue.label_seq_id(location);
  216. const auth_seq_id = Props.residue.auth_seq_id(location);
  217. const ins_code = Props.residue.pdbx_PDB_ins_code(location);
  218. const comp_id = Props.atom.label_comp_id(location);
  219. const atom_id = Props.atom.label_atom_id(location);
  220. const alt_id = Props.atom.label_alt_id(location);
  221. const occupancy = Props.atom.occupancy(location);
  222. const microHetCompIds = Props.residue.microheterogeneityCompIds(location);
  223. const compId = granularity === 'residue' && microHetCompIds.length > 1 ?
  224. `(${microHetCompIds.join('|')})` : comp_id;
  225. const label: string[] = [];
  226. switch (granularity) {
  227. case 'element':
  228. label.push(`<b>${atom_id}</b>${alt_id ? `%${alt_id}` : ''}`);
  229. case 'conformation':
  230. if (granularity === 'conformation' && alt_id) {
  231. label.push(`<small>Conformation</small> <b>${alt_id}</b>`);
  232. }
  233. case 'residue':
  234. const seq_id = label_seq_id === auth_seq_id || !has_label_seq_id ? auth_seq_id : label_seq_id;
  235. label.push(`<b>${compId} ${seq_id}</b>${seq_id !== auth_seq_id ? ` <small>[auth</small> <b>${auth_seq_id}</b><small>]</small>` : ''}<b>${ins_code ? ins_code : ''}</b>`);
  236. case 'chain':
  237. if (label_asym_id === auth_asym_id) {
  238. label.push(`<b>${label_asym_id}</b>`);
  239. } else {
  240. if (granularity === 'chain' && Unit.Traits.is(location.unit.traits, Unit.Trait.MultiChain)) {
  241. label.push(`<small>[auth</small> <b>${auth_asym_id}</b><small>]</small>`);
  242. } else {
  243. label.push(`<b>${label_asym_id}</b> <small>[auth</small> <b>${auth_asym_id}</b><small>]</small>`);
  244. }
  245. }
  246. }
  247. if (label.length > 0 && occupancy !== 1 && !hideOccupancy) {
  248. label[0] = `${label[0]} <small>[occupancy</small> <b>${Math.round(100 * occupancy) / 100}</b><small>]</small>`;
  249. }
  250. return label.reverse();
  251. }
  252. function _coarseElementLabel(location: StructureElement.Location<Unit.Spheres | Unit.Gaussians>, granularity: LabelGranularity): string[] {
  253. const asym_id = Props.coarse.asym_id(location);
  254. const seq_id_begin = Props.coarse.seq_id_begin(location);
  255. const seq_id_end = Props.coarse.seq_id_end(location);
  256. const label: string[] = [];
  257. switch (granularity) {
  258. case 'element':
  259. case 'conformation':
  260. case 'residue':
  261. if (seq_id_begin === seq_id_end) {
  262. const entityIndex = Props.coarse.entityKey(location);
  263. const seq = location.unit.model.sequence.byEntityKey[entityIndex];
  264. const comp_id = seq.sequence.compId.value(seq_id_begin - 1); // 1-indexed
  265. label.push(`<b>${comp_id} ${seq_id_begin}</b>`);
  266. } else {
  267. label.push(`<b>${seq_id_begin}-${seq_id_end}</b>`);
  268. }
  269. case 'chain':
  270. label.push(`<b>${asym_id}</b>`);
  271. }
  272. return label.reverse();
  273. }
  274. //
  275. export function distanceLabel(pair: Loci.Bundle<2>, options: Partial<LabelOptions & { measureOnly: boolean, unitLabel: string }> = {}) {
  276. const o = { ...DefaultLabelOptions, measureOnly: false, unitLabel: '\u212B', ...options };
  277. const [cA, cB] = pair.loci.map(l => Loci.getCenter(l)!);
  278. const distance = `${Vec3.distance(cA, cB).toFixed(2)} ${o.unitLabel}`;
  279. if (o.measureOnly) return distance;
  280. const label = bundleLabel(pair, o);
  281. return o.condensed ? `${distance} | ${label}` : `Distance ${distance}</br>${label}`;
  282. }
  283. export function angleLabel(triple: Loci.Bundle<3>, options: Partial<LabelOptions & { measureOnly: boolean }> = {}) {
  284. const o = { ...DefaultLabelOptions, measureOnly: false, ...options };
  285. const [cA, cB, cC] = triple.loci.map(l => Loci.getCenter(l)!);
  286. const vAB = Vec3.sub(Vec3(), cA, cB);
  287. const vCB = Vec3.sub(Vec3(), cC, cB);
  288. const angle = `${radToDeg(Vec3.angle(vAB, vCB)).toFixed(2)}\u00B0`;
  289. if (o.measureOnly) return angle;
  290. const label = bundleLabel(triple, o);
  291. return o.condensed ? `${angle} | ${label}` : `Angle ${angle}</br>${label}`;
  292. }
  293. export function dihedralLabel(quad: Loci.Bundle<4>, options: Partial<LabelOptions & { measureOnly: boolean }> = {}) {
  294. const o = { ...DefaultLabelOptions, measureOnly: false, ...options };
  295. const [cA, cB, cC, cD] = quad.loci.map(l => Loci.getCenter(l)!);
  296. const dihedral = `${radToDeg(Vec3.dihedralAngle(cA, cB, cC, cD)).toFixed(2)}\u00B0`;
  297. if (o.measureOnly) return dihedral;
  298. const label = bundleLabel(quad, o);
  299. return o.condensed ? `${dihedral} | ${label}` : `Dihedral ${dihedral}</br>${label}`;
  300. }