common.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. */
  6. import { Unit, Structure, ElementIndex, StructureElement, ResidueIndex } from '../../../../mol-model/structure';
  7. import { Mat4, Vec3 } from '../../../../mol-math/linear-algebra';
  8. import { TransformData, createTransform } from '../../../../mol-geo/geometry/transform-data';
  9. import { OrderedSet, SortedArray } from '../../../../mol-data/int';
  10. import { EmptyLoci, Loci } from '../../../../mol-model/loci';
  11. import { PhysicalSizeTheme } from '../../../../mol-theme/size/physical';
  12. import { AtomicNumbers } from '../../../../mol-model/structure/model/properties/atomic';
  13. import { fillSerial } from '../../../../mol-util/array';
  14. import { ParamDefinition as PD } from '../../../../mol-util/param-definition';
  15. import { AssignableArrayLike } from '../../../../mol-util/type-helpers';
  16. import { getBoundary } from '../../../../mol-math/geometry/boundary';
  17. import { Box3D } from '../../../../mol-math/geometry';
  18. /** Return a Loci for the elements of a whole residue the elementIndex belongs to. */
  19. export function getResidueLoci(structure: Structure, unit: Unit.Atomic, elementIndex: ElementIndex): Loci {
  20. const { elements, model } = unit;
  21. if (OrderedSet.indexOf(elements, elementIndex) !== -1) {
  22. const { index, offsets } = model.atomicHierarchy.residueAtomSegments;
  23. const rI = index[elementIndex];
  24. const _indices: number[] = [];
  25. for (let i = offsets[rI], il = offsets[rI + 1]; i < il; ++i) {
  26. const unitIndex = OrderedSet.indexOf(elements, i);
  27. if (unitIndex !== -1) _indices.push(unitIndex);
  28. }
  29. const indices = OrderedSet.ofSortedArray<StructureElement.UnitIndex>(SortedArray.ofSortedArray(_indices));
  30. return StructureElement.Loci(structure, [{ unit, indices }]);
  31. }
  32. return EmptyLoci;
  33. }
  34. /**
  35. * Return a Loci for the elements of a whole residue the elementIndex belongs to but
  36. * restrict to elements that have the same label_alt_id or none
  37. */
  38. export function getAltResidueLoci(structure: Structure, unit: Unit.Atomic, elementIndex: ElementIndex) {
  39. const { elements, model } = unit;
  40. const { label_alt_id } = model.atomicHierarchy.atoms;
  41. const elementAltId = label_alt_id.value(elementIndex);
  42. if (OrderedSet.indexOf(elements, elementIndex) !== -1) {
  43. const { index } = model.atomicHierarchy.residueAtomSegments;
  44. const rI = index[elementIndex];
  45. return getAltResidueLociFromId(structure, unit, rI, elementAltId);
  46. }
  47. return StructureElement.Loci(structure, []);
  48. }
  49. export function getAltResidueLociFromId(structure: Structure, unit: Unit.Atomic, residueIndex: ResidueIndex, elementAltId: string) {
  50. const { elements, model } = unit;
  51. const { label_alt_id } = model.atomicHierarchy.atoms;
  52. const { offsets } = model.atomicHierarchy.residueAtomSegments;
  53. const _indices: number[] = [];
  54. for (let i = offsets[residueIndex], il = offsets[residueIndex + 1]; i < il; ++i) {
  55. const unitIndex = OrderedSet.indexOf(elements, i);
  56. if (unitIndex !== -1) {
  57. const altId = label_alt_id.value(i);
  58. if (elementAltId === altId || altId === '') {
  59. _indices.push(unitIndex);
  60. }
  61. }
  62. }
  63. const indices = OrderedSet.ofSortedArray<StructureElement.UnitIndex>(SortedArray.ofSortedArray(_indices));
  64. return StructureElement.Loci(structure, [{ unit, indices }]);
  65. }
  66. //
  67. export function createUnitsTransform({ units }: Unit.SymmetryGroup, transformData?: TransformData) {
  68. const unitCount = units.length;
  69. const n = unitCount * 16;
  70. const array = transformData && transformData.aTransform.ref.value.length >= n ? transformData.aTransform.ref.value : new Float32Array(n);
  71. for (let i = 0; i < unitCount; i++) {
  72. Mat4.toArray(units[i].conformation.operator.matrix, array, i * 16);
  73. }
  74. return createTransform(array, unitCount, transformData);
  75. }
  76. export const UnitKindInfo = {
  77. 'atomic': {},
  78. 'spheres': {},
  79. 'gaussians': {},
  80. };
  81. export type UnitKind = keyof typeof UnitKindInfo
  82. export const UnitKindOptions = PD.objectToOptions(UnitKindInfo);
  83. export function includesUnitKind(unitKinds: UnitKind[], unit: Unit) {
  84. for (let i = 0, il = unitKinds.length; i < il; ++i) {
  85. if (Unit.isAtomic(unit) && unitKinds[i] === 'atomic') return true;
  86. if (Unit.isSpheres(unit) && unitKinds[i] === 'spheres') return true;
  87. if (Unit.isGaussians(unit) && unitKinds[i] === 'gaussians') return true;
  88. }
  89. return false;
  90. }
  91. //
  92. const MaxCells = 500_000_000;
  93. /** guard against overly high resolution for the given box size */
  94. export function ensureReasonableResolution<T>(box: Box3D, props: { resolution: number } & T) {
  95. const volume = Box3D.volume(box);
  96. const approxCells = volume / props.resolution;
  97. const resolution = approxCells > MaxCells ? volume / MaxCells : props.resolution;
  98. return { ...props, resolution };
  99. }
  100. export function getConformation(unit: Unit) {
  101. switch (unit.kind) {
  102. case Unit.Kind.Atomic: return unit.model.atomicConformation;
  103. case Unit.Kind.Spheres: return unit.model.coarseConformation.spheres;
  104. case Unit.Kind.Gaussians: return unit.model.coarseConformation.gaussians;
  105. }
  106. }
  107. export const CommonSurfaceParams = {
  108. ignoreHydrogens: PD.Boolean(false, { description: 'Whether or not to include hydrogen atoms in the surface calculation.' }),
  109. traceOnly: PD.Boolean(false, { description: 'Whether or not to only use trace atoms in the surface calculation.' }),
  110. includeParent: PD.Boolean(false, { description: 'Include elements of the parent structure in surface calculation to get a surface patch of the current structure.' }),
  111. };
  112. export const DefaultCommonSurfaceProps = PD.getDefaultValues(CommonSurfaceParams);
  113. export type CommonSurfaceProps = typeof DefaultCommonSurfaceProps
  114. const v = Vec3();
  115. function squaredDistance(x: number, y: number, z: number, center: Vec3) {
  116. return Vec3.squaredDistance(Vec3.set(v, x, y, z), center);
  117. }
  118. /** marks `indices` for filtering/ignoring in `id` when not in `elements` */
  119. function filterId(id: AssignableArrayLike<number>, elements: SortedArray, indices: SortedArray) {
  120. let start = 0;
  121. const end = elements.length;
  122. for (let i = 0, il = indices.length; i < il; ++i) {
  123. const idx = SortedArray.indexOfInRange(elements, indices[i], start, end);
  124. if (idx === -1) {
  125. id[i] = -2;
  126. } else {
  127. id[i] = idx;
  128. start = idx;
  129. }
  130. }
  131. }
  132. export function getUnitConformationAndRadius(structure: Structure, unit: Unit, props: CommonSurfaceProps) {
  133. const { ignoreHydrogens, traceOnly, includeParent } = props;
  134. const rootUnit = includeParent ? structure.root.unitMap.get(unit.id) : unit;
  135. const { x, y, z } = getConformation(rootUnit);
  136. const { elements } = rootUnit;
  137. const { center, radius: sphereRadius } = unit.boundary.sphere;
  138. const extraRadius = (2 + 1.5) * 2; // TODO should be twice (the max vdW/sphere radius plus the probe radius)
  139. const radiusSq = (sphereRadius + extraRadius) * (sphereRadius + extraRadius);
  140. let indices: SortedArray<ElementIndex>;
  141. let id: AssignableArrayLike<number>;
  142. if (ignoreHydrogens || traceOnly || (includeParent && rootUnit !== unit)) {
  143. const _indices = [];
  144. const _id = [];
  145. for (let i = 0, il = elements.length; i < il; ++i) {
  146. const eI = elements[i];
  147. if (ignoreHydrogens && isHydrogen(rootUnit, eI)) continue;
  148. if (traceOnly && !isTrace(rootUnit, eI)) continue;
  149. if (includeParent && squaredDistance(x[eI], y[eI], z[eI], center) > radiusSq) continue;
  150. _indices.push(eI);
  151. _id.push(i);
  152. }
  153. indices = SortedArray.ofSortedArray(_indices);
  154. id = _id;
  155. } else {
  156. indices = elements;
  157. id = fillSerial(new Int32Array(indices.length));
  158. }
  159. if (includeParent && rootUnit !== unit) {
  160. filterId(id, unit.elements, indices);
  161. }
  162. const position = { indices, x, y, z, id };
  163. const boundary = unit === rootUnit ? unit.boundary : getBoundary(position);
  164. const l = StructureElement.Location.create(structure, rootUnit);
  165. const sizeTheme = PhysicalSizeTheme({}, { scale: 1 });
  166. const radius = (index: number) => {
  167. l.element = index as ElementIndex;
  168. return sizeTheme.size(l);
  169. };
  170. return { position, boundary, radius };
  171. }
  172. export function getStructureConformationAndRadius(structure: Structure, ignoreHydrogens: boolean, traceOnly: boolean) {
  173. const l = StructureElement.Location.create(structure);
  174. const sizeTheme = PhysicalSizeTheme({}, { scale: 1 });
  175. let xs: ArrayLike<number>;
  176. let ys: ArrayLike<number>;
  177. let zs: ArrayLike<number>;
  178. let rs: ArrayLike<number>;
  179. let id: ArrayLike<number>;
  180. if (ignoreHydrogens || traceOnly) {
  181. const _xs: number[] = [];
  182. const _ys: number[] = [];
  183. const _zs: number[] = [];
  184. const _rs: number[] = [];
  185. const _id: number[] = [];
  186. for (let i = 0, m = 0, il = structure.units.length; i < il; ++i) {
  187. const unit = structure.units[i];
  188. const { elements } = unit;
  189. const { x, y, z } = unit.conformation;
  190. l.unit = unit;
  191. for (let j = 0, jl = elements.length; j < jl; ++j) {
  192. const eI = elements[j];
  193. if (ignoreHydrogens && isHydrogen(unit, eI)) continue;
  194. if (traceOnly && !isTrace(unit, eI)) continue;
  195. _xs.push(x(eI));
  196. _ys.push(y(eI));
  197. _zs.push(z(eI));
  198. l.element = eI;
  199. _rs.push(sizeTheme.size(l));
  200. _id.push(m + j);
  201. }
  202. m += elements.length;
  203. }
  204. xs = _xs, ys = _ys, zs = _zs, rs = _rs;
  205. id = _id;
  206. } else {
  207. const { elementCount } = structure;
  208. const _xs = new Float32Array(elementCount);
  209. const _ys = new Float32Array(elementCount);
  210. const _zs = new Float32Array(elementCount);
  211. const _rs = new Float32Array(elementCount);
  212. for (let i = 0, m = 0, il = structure.units.length; i < il; ++i) {
  213. const unit = structure.units[i];
  214. const { elements } = unit;
  215. const { x, y, z } = unit.conformation;
  216. l.unit = unit;
  217. for (let j = 0, jl = elements.length; j < jl; ++j) {
  218. const eI = elements[j];
  219. const mj = m + j;
  220. _xs[mj] = x(eI);
  221. _ys[mj] = y(eI);
  222. _zs[mj] = z(eI);
  223. l.element = eI;
  224. _rs[mj] = sizeTheme.size(l);
  225. }
  226. m += elements.length;
  227. }
  228. xs = _xs, ys = _ys, zs = _zs, rs = _rs;
  229. id = fillSerial(new Uint32Array(elementCount));
  230. }
  231. const position = { indices: OrderedSet.ofRange(0, id.length), x: xs, y: ys, z: zs, id };
  232. const radius = (index: number) => rs[index];
  233. return { position, radius };
  234. }
  235. const _H = AtomicNumbers['H'];
  236. export function isHydrogen(unit: Unit, element: ElementIndex) {
  237. if (Unit.isCoarse(unit)) return false;
  238. return unit.model.atomicHierarchy.derived.atom.atomicNumber[element] === _H;
  239. }
  240. export function isH(atomicNumber: ArrayLike<number>, element: ElementIndex) {
  241. return atomicNumber[element] === _H;
  242. }
  243. export function isTrace(unit: Unit, element: ElementIndex) {
  244. if (Unit.isCoarse(unit)) return true;
  245. const atomId = unit.model.atomicHierarchy.atoms.label_atom_id.value(element);
  246. if (atomId === 'CA' || atomId === 'P') return true;
  247. return false;
  248. }
  249. export function getUnitExtraRadius(unit: Unit) {
  250. if (Unit.isAtomic(unit)) return 4;
  251. let max = 0;
  252. const { elements } = unit;
  253. const { r } = unit.conformation;
  254. for (let i = 0, _i = elements.length; i < _i; i++) {
  255. const _r = r(elements[i]);
  256. if (_r > max) max = _r;
  257. }
  258. return max + 1;
  259. }
  260. export function getStructureExtraRadius(structure: Structure) {
  261. let max = 0;
  262. for (const ug of structure.unitSymmetryGroups) {
  263. const r = getUnitExtraRadius(ug.units[0]);
  264. if (r > max) max = r;
  265. }
  266. return max;
  267. }