structure.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import * as B from 'benchmark'
  7. import * as util from 'util'
  8. import * as fs from 'fs'
  9. import fetch from 'node-fetch'
  10. import CIF from 'mol-io/reader/cif'
  11. import { Structure, Model, Queries as Q, Element, Selection, StructureSymmetry, Query, Format, StructureProperties as SP } from 'mol-model/structure'
  12. //import { Segmentation, OrderedSet } from 'mol-data/int'
  13. import to_mmCIF from 'mol-model/structure/export/mmcif'
  14. import { Vec3 } from 'mol-math/linear-algebra';
  15. //import { printUnits } from 'apps/structure-info/model';
  16. //import { EquivalenceClasses } from 'mol-data/util';
  17. require('util.promisify').shim();
  18. const readFileAsync = util.promisify(fs.readFile);
  19. const writeFileAsync = util.promisify(fs.writeFile);
  20. async function readData(path: string) {
  21. if (path.match(/\.bcif$/)) {
  22. const input = await readFileAsync(path)
  23. const data = new Uint8Array(input.byteLength);
  24. for (let i = 0; i < input.byteLength; i++) data[i] = input[i];
  25. return data;
  26. } else {
  27. return readFileAsync(path, 'utf8');
  28. }
  29. }
  30. (Symbol as any).asyncIterator = (Symbol as any).asyncIterator || Symbol.for('Symbol.asyncIterator');
  31. interface ProgressGenerator<T> extends AsyncIterableIterator<number | T> {
  32. next(cont?: boolean): Promise<IteratorResult<number | T>>
  33. }
  34. async function *test(): ProgressGenerator<boolean> {
  35. const r = yield await new Promise<number>(res => res(10));
  36. return r;
  37. }
  38. async function runIt(itP: () => ProgressGenerator<boolean>) {
  39. const it = itP();
  40. while (true) {
  41. const { value, done } = await it.next(true);
  42. if (done) return value;
  43. }
  44. }
  45. runIt(test).then(r => console.log('rerdasdasda', r))
  46. export async function readCIF(path: string) {
  47. console.time('readData');
  48. const input = await readData(path)
  49. console.timeEnd('readData');
  50. console.time('parse');
  51. const comp = typeof input === 'string' ? CIF.parseText(input) : CIF.parseBinary(input);
  52. const parsed = await comp.run();
  53. console.timeEnd('parse');
  54. if (parsed.isError) {
  55. throw parsed;
  56. }
  57. const data = parsed.result.blocks[0];
  58. console.time('schema')
  59. const mmcif = Format.mmCIF(data);
  60. console.timeEnd('schema')
  61. console.time('buildModels')
  62. const models = await Model.create(mmcif).run();
  63. console.timeEnd('buildModels')
  64. const structures = models.map(Structure.ofModel);
  65. return { mmcif, models, structures };
  66. }
  67. const DATA_DIR = './build/data';
  68. if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR);
  69. function getBcifUrl(pdbId: string) {
  70. return `http://www.ebi.ac.uk/pdbe/coordinates/${pdbId.toLowerCase()}/full?encoding=bcif`
  71. }
  72. function getBcifPath(pdbId: string) {
  73. return `${DATA_DIR}/${pdbId.toLowerCase()}_full.bcif`
  74. }
  75. async function ensureBcifAvailable(pdbId: string) {
  76. const bcifPath = getBcifPath(pdbId);
  77. if (!fs.existsSync(bcifPath)) {
  78. console.log(`downloading ${pdbId} bcif...`)
  79. const data = await fetch(getBcifUrl(pdbId))
  80. await writeFileAsync(bcifPath, await data.buffer())
  81. console.log(`done downloading ${pdbId} bcif`)
  82. }
  83. }
  84. export async function getBcif(pdbId: string) {
  85. await ensureBcifAvailable(pdbId);
  86. return await readCIF(getBcifPath(pdbId));
  87. }
  88. export namespace PropertyAccess {
  89. function baseline(model: Model) {
  90. if (model.sourceData.kind !== 'mmCIF') throw new Error('Model must be mmCIF');
  91. const atom_site = model.sourceData.data.atom_site;
  92. const id = atom_site.id.value;
  93. let s = 0;
  94. for (let i = 0, _i = atom_site._rowCount; i < _i; i++) {
  95. s += id(i);
  96. }
  97. return s;
  98. }
  99. function sumProperty(structure: Structure, p: Element.Property<number>) {
  100. const l = Element.Location();
  101. let s = 0;
  102. for (const unit of structure.units) {
  103. l.unit = unit;
  104. const elements = unit.elements;
  105. for (let j = 0, _j = elements.length; j < _j; j++) {
  106. l.element = elements[j];
  107. s += p(l);
  108. }
  109. }
  110. return s;
  111. }
  112. // function sumPropertySegmented(structure: Structure, p: Element.Property<number>) {
  113. // const { elements, units } = structure;
  114. // const unitIds = ElementSet.unitIndices(elements);
  115. // const l = Element.Location();
  116. // let s = 0;
  117. // let vA = 0, cC = 0, rC = 0;
  118. // for (let i = 0, _i = unitIds.length; i < _i; i++) {
  119. // const unit = units[unitIds[i]] as Unit.Atomic;
  120. // l.unit = unit;
  121. // const set = ElementSet.groupAt(elements, i);
  122. // const chainsIt = Segmentation.transientSegments(unit.hierarchy.chainSegments, set.elements);
  123. // const residues = unit.hierarchy.residueSegments;
  124. // while (chainsIt.hasNext) {
  125. // cC++;
  126. // const chainSegment = chainsIt.move();
  127. // const residuesIt = Segmentation.transientSegments(residues, set.elements, chainSegment);
  128. // while (residuesIt.hasNext) {
  129. // rC++;
  130. // const residueSegment = residuesIt.move();
  131. // // l.element= OrdSet.getAt(set, residueSegment.start);
  132. // // console.log(unit.hierarchy.residues.auth_comp_id.value(unit.residueIndex[l.atom]), l.atom, OrdSet.getAt(set, residueSegment.end))
  133. // for (let j = residueSegment.start, _j = residueSegment.end; j < _j; j++) {
  134. // l.element= ElementGroup.getAt(set, j);
  135. // vA++;
  136. // s += p(l);
  137. // }
  138. // }
  139. // }
  140. // }
  141. // console.log('seg atom count', vA, cC, rC);
  142. // return s;
  143. // }
  144. // function sumPropertyResidue(structure: Structure, p: Element.Property<number>) {
  145. // const { atoms, units } = structure;
  146. // const unitIds = ElementSet.unitIds(atoms);
  147. // const l = Element.Location();
  148. // let s = 0;
  149. // for (let i = 0, _i = unitIds.length; i < _i; i++) {
  150. // const unit = units[unitIds[i]];
  151. // l.unit = unit;
  152. // const set = ElementSet.unitGetByIndex(atoms, i);
  153. // const residuesIt = Segmentation.transientSegments(unit.hierarchy.residueSegments, set.atoms);
  154. // while (residuesIt.hasNext) {
  155. // l.element= ElementGroup.getAt(set, residuesIt.move().start);
  156. // s += p(l);
  157. // }
  158. // }
  159. // return s;
  160. // }
  161. // function sumPropertyAtomSetIt(structure: Structure, p: Element.Property<number>) {
  162. // const { elements, units } = structure;
  163. // let s = 0;
  164. // const atomsIt = ElementSet.elements(elements);
  165. // const l = Element.Location();
  166. // while (atomsIt.hasNext) {
  167. // const a = atomsIt.move();
  168. // l.unit = units[Element.unit(a)];
  169. // l.element= Element.index(a);
  170. // s += p(l);
  171. // }
  172. // return s;
  173. // }
  174. // function sumPropertySegmentedMutable(structure: Structure, p: Property<number>) {
  175. // const { atoms, units } = structure;
  176. // const unitIds = ElementSet.unitIds(atoms);
  177. // const l = Property.createLocation();
  178. // let s = 0;
  179. // for (let i = 0, _i = unitIds.length; i < _i; i++) {
  180. // const unit = units[unitIds[i]];
  181. // l.unit = unit;
  182. // const set = ElementSet.unitGetByIndex(atoms, i);
  183. // const chainsIt = Segmentation.transientSegments(unit.hierarchy.chainSegments, set);
  184. // const residuesIt = Segmentation.transientSegments(unit.hierarchy.residueSegments, set);
  185. // while (chainsIt.hasNext) {
  186. // const chainSegment = chainsIt.move();
  187. // residuesIt.updateRange(chainSegment);
  188. // while (residuesIt.hasNext) {
  189. // const residueSegment = residuesIt.move();
  190. // for (let j = residueSegment.start, _j = residueSegment.end; j < _j; j++) {
  191. // l.element= OrdSet.getAt(set, j);
  192. // s += p(l);
  193. // }
  194. // }
  195. // }
  196. // }
  197. // return s;
  198. // }
  199. // function sumDirect(structure: Structure) {
  200. // const { atoms, units } = structure;
  201. // const unitIds = ElementSet.unitIds(atoms);
  202. // let s = 0;
  203. // for (let i = 0, _i = unitIds.length; i < _i; i++) {
  204. // const unitId = unitIds[i];
  205. // const unit = units[unitId];
  206. // const set = ElementSet.unitGetByIndex(atoms, i);
  207. // //const { residueIndex, chainIndex } = unit;
  208. // const p = unit.conformation.atomId.value;
  209. // for (let j = 0, _j = ElementGroup.size(set); j < _j; j++) {
  210. // const aI = ElementGroup.getAt(set, j);
  211. // s += p(aI);
  212. // }
  213. // }
  214. // return s;
  215. // }
  216. // function concatProperty(structure: Structure, p: Property<string>) {
  217. // const { atoms, units } = structure;
  218. // const unitIds = ElementSet.unitIds(atoms);
  219. // const l = Property.createLocation(structure);
  220. // let s = [];
  221. // for (let i = 0, _i = unitIds.length; i < _i; i++) {
  222. // const unitId = unitIds[i];
  223. // l.unit = units[unitId];
  224. // const set = ElementSet.unitGetByIndex(atoms, i);
  225. // const { residueIndex, chainIndex } = l.unit;
  226. // for (let j = 0, _j = OrdSet.size(set); j < _j; j++) {
  227. // const aI = OrdSet.getAt(set, j);
  228. // l.element= aI;
  229. // l.residueIndex = residueIndex[aI];
  230. // l.chainIndex = chainIndex[aI];
  231. // s[s.length] = p(l);
  232. // }
  233. // }
  234. // return s;
  235. // }
  236. export function write(s: Structure) {
  237. console.log(to_mmCIF('test', s));
  238. }
  239. export async function testAssembly(id: string, s: Structure) {
  240. console.time('assembly')
  241. const a = await StructureSymmetry.buildAssembly(s, '1').run();
  242. //const auth_comp_id = SP.residue.auth_comp_id;
  243. //const q1 = Query(Q.generators.atoms({ residueTest: l => auth_comp_id(l) === 'ALA' }));
  244. //const alas = await query(q1, a);
  245. console.timeEnd('assembly')
  246. fs.writeFileSync(`${DATA_DIR}/${id}_assembly.bcif`, to_mmCIF(id, a, true));
  247. //fs.writeFileSync(`${DATA_DIR}/${id}_assembly.bcif`, to_mmCIF(id, Selection.unionStructure(alas), true));
  248. console.log('exported');
  249. }
  250. export async function testSymmetry(id: string, s: Structure) {
  251. console.time('symmetry')
  252. const a = await StructureSymmetry.buildSymmetryRange(s, Vec3.create(-1, -1, -1), Vec3.create(1, 1, 1)).run();
  253. //const auth_comp_id = SP.residue.auth_comp_id;
  254. //const q1 = Query(Q.generators.atoms({ residueTest: l => auth_comp_id(l) === 'ALA' }));
  255. //const alas = await query(q1, a);
  256. console.timeEnd('symmetry')
  257. fs.writeFileSync(`${DATA_DIR}/${id}_symm.bcif`, to_mmCIF(id, a, true));
  258. //fs.writeFileSync(`${DATA_DIR}/${id}_assembly.bcif`, to_mmCIF(id, Selection.unionStructure(alas), true));
  259. console.log('exported');
  260. }
  261. export async function testIncludeSurroundings(id: string, s: Structure) {
  262. //const a = s;
  263. console.time('symmetry')
  264. const a = await StructureSymmetry.buildSymmetryRange(s, Vec3.create(-2, -2, -2), Vec3.create(2, 2, 2)).run();
  265. //console.log(printUnits(a));
  266. const auth_comp_id = SP.residue.auth_comp_id, op = SP.unit.operator_name;
  267. //const q1 = Q.generators.atoms({ residueTest: l => auth_comp_id(l) === 'REA' });
  268. const q1 = Q.modifiers.includeSurroundings(Q.generators.atoms({
  269. chainTest: l => op(l) === '1_555',
  270. residueTest: l => auth_comp_id(l) === 'REA'
  271. }), {
  272. radius: 5,
  273. wholeResidues: true
  274. });
  275. const surr = Selection.unionStructure(await query(Query(q1), a));
  276. console.timeEnd('symmetry')
  277. // for (const u of surr.units) {
  278. // const { atomId } = u.model.atomicConformation;
  279. // console.log(`${u.id}, ${u.conformation.operator.name}`);
  280. // for (let i = 0; i < u.elements.length; i++) {
  281. // console.log(` ${atomId.value(u.elements[i])}`);
  282. // }
  283. // }
  284. // const it = surr.elementLocations();
  285. // while (it.hasNext) {
  286. // const e = it.move();
  287. // console.log(`${SP.unit.operator_name(e)} ${SP.atom.id(e)}`);
  288. // }
  289. //fs.writeFileSync(`${DATA_DIR}/${id}_surr.bcif`, to_mmCIF(id, a, true));
  290. fs.writeFileSync(`${DATA_DIR}/${id}_surr.cif`, to_mmCIF(id, surr, false));
  291. console.log('exported');
  292. }
  293. // export async function testGrouping(structure: Structure) {
  294. // const { elements, units } = await Run(Symmetry.buildAssembly(structure, '1'));
  295. // console.log('grouping', units.length);
  296. // console.log('built asm');
  297. // const uniqueGroups = EquivalenceClasses<number, { unit: Unit, group: ElementGroup }>(
  298. // ({ unit, group }) => ElementGroup.hashCode(group),
  299. // (a, b) => a.unit.model.id === b.unit.model.id && (a.group.key === b.group.key && OrderedSet.areEqual(a.group.elements, b.group.elements))
  300. // );
  301. // for (let i = 0, _i = ElementSet.groupCount(elements); i < _i; i++) {
  302. // const group = ElementSet.groupAt(elements, i);
  303. // const unitId = ElementSet.groupUnitIndex(elements, i);
  304. // uniqueGroups.add(unitId, { unit: units[unitId], group });
  305. // }
  306. // console.log('group count', uniqueGroups.groups.length);
  307. // }
  308. function query(q: Query, s: Structure) {
  309. return q(s).run();
  310. }
  311. export async function run() {
  312. //const { structures, models/*, mmcif*/ } = await getBcif('1cbs');
  313. // const { structures, models } = await getBcif('3j3q');
  314. const { structures, models /*, mmcif*/ } = await readCIF('e:/test/quick/1cbs_updated.cif');
  315. //const { structures: s1, /*, mmcif*/ } = await readCIF('e:/test/quick/1tqn_updated.cif');
  316. // testGrouping(structures[0]);
  317. // console.log('------');
  318. // testGrouping(s1[0]);
  319. //const { structures, models/*, mmcif*/ } = await readCIF('e:/test/quick/5j7v_updated.cif');
  320. //console.log(mmcif.pdbx_struct_oper_list.matrix.toArray());
  321. // console.log(mmcif.pdbx_struct_oper_list.vector.toArray());
  322. //await testAssembly('1hrv', structures[0]);
  323. //await testSymmetry('1cbs', structures[0]);
  324. await testIncludeSurroundings('1cbs', structures[0]);
  325. // throw '';
  326. // console.log(models[0].symmetry.assemblies);
  327. //const { structures, models } = await readCIF('e:/test/molstar/3j3q.bcif');
  328. // fs.writeFileSync('e:/test/molstar/3j3q.bcif', to_mmCIF('test', structures[0], true));
  329. // return;
  330. // console.log(toMmCIFString('test', structures[0]));
  331. // return;
  332. console.log('bs', baseline(models[0]));
  333. console.log('sp', sumProperty(structures[0], l => l.unit.model.atomicConformation.atomId.value(l.element)));
  334. //console.log(sumPropertySegmented(structures[0], l => l.unit.model.atomSiteConformation.atomId.value(l.element)));
  335. //console.log(sumPropertySegmentedMutable(structures[0], l => l.unit.model.conformation.atomId.value(l.element));
  336. //console.log(sumPropertyAtomSetIt(structures[0], l => l.unit.model.atomSiteConformation.atomId.value(l.element)));
  337. //console.log(sumProperty(structures[0], Property.cachedAtomColumn(m => m.conformation.atomId)));
  338. //console.log(sumDirect(structures[0]));
  339. //console.log('r', sumPropertyResidue(structures[0], l => l.unit.hierarchy.residues.auth_seq_id.value(l.unit.residueIndex[l.atom])));
  340. console.time('atom.x');
  341. console.log('atom.x', sumProperty(structures[0], SP.atom.x));
  342. console.timeEnd('atom.x');
  343. console.time('__x')
  344. //console.log('__x', sumProperty(structures[0], l => l.unit.conformation.x[l.atom]));
  345. console.timeEnd('__x')
  346. //const authSeqId = Element.property(l => l.unit.hierarchy.residues.auth_seq_id.value(l.unit.residueIndex[l.atom]));
  347. //const auth_seq_id = SP.residue.auth_seq_id;
  348. const auth_comp_id = SP.residue.auth_comp_id;
  349. //const auth_asym_id = SP.chain.auth_asym_id;
  350. //const set = new Set(['A', 'B', 'C', 'D']);
  351. //const q = Q.generators.atomGroups({ atomTest: l => auth_seq_id(l) < 3 });
  352. const q = Query(Q.generators.atoms({ atomTest: Q.pred.eq(SP.residue.auth_comp_id, 'ALA') }));
  353. const P = SP
  354. //const q0 = Q.generators.atoms({ atomTest: l => auth_comp_id(l) === 'ALA' });
  355. const q1 = Query(Q.generators.atoms({ residueTest: l => auth_comp_id(l) === 'ALA' }));
  356. const q2 = Query(Q.generators.atoms({ residueTest: l => auth_comp_id(l) === 'ALA', groupBy: SP.residue.key }));
  357. const q3 = Query(Q.generators.atoms({
  358. chainTest: Q.pred.inSet(P.chain.auth_asym_id, ['A', 'B', 'C', 'D']),
  359. residueTest: Q.pred.eq(P.residue.auth_comp_id, 'ALA')
  360. }));
  361. await query(q, structures[0]);
  362. //console.log(to_mmCIF('test', Selection.union(q0r)));
  363. console.time('q1')
  364. await query(q1, structures[0]);
  365. console.timeEnd('q1')
  366. console.time('q1')
  367. await query(q1, structures[0]);
  368. console.timeEnd('q1')
  369. console.time('q2')
  370. const q2r = await query(q2, structures[0]);
  371. console.timeEnd('q2')
  372. console.log(Selection.structureCount(q2r));
  373. //console.log(q1(structures[0]));
  374. const col = models[0].atomicConformation.atomId.value;
  375. const suite = new B.Suite();
  376. suite
  377. //.add('test q', () => q1(structures[0]))
  378. //.add('test q', () => q(structures[0]))
  379. .add('test int', () => sumProperty(structures[0], l => col(l.element)))
  380. .add('test q1', async () => await query(q1, structures[0]))
  381. .add('test q3', async () => await query(q3, structures[0]))
  382. // .add('sum residue', () => sumPropertyResidue(structures[0], l => l.unit.hierarchy.residues.auth_seq_id.value(l.unit.residueIndex[l.atom])))
  383. // .add('baseline', () => baseline(models[0]))
  384. // .add('direct', () => sumDirect(structures[0]))
  385. //.add('normal int', () => sumProperty(structures[0], l => l.unit.model.conformation.atomId.value(l.element))
  386. //.add('atom set it int', () => sumPropertyAtomSetIt(structures[0], l => l.unit.conformation.atomId.value(l.element))
  387. // .add('segmented faster int', () => sumPropertySegmented(structures[0], l => l.unit.conformation.atomId.value(l.element))
  388. // .add('faster int', () => sumProperty(structures[0], l => l.unit.conformation.atomId.value(l.element))
  389. //.add('segmented faster _x', () => sumPropertySegmented(structures[0], l => l.unit.conformation.__x[l.atom]))
  390. //.add('faster _x', () => sumProperty(structures[0], l => l.unit.conformation.__x[l.atom] + l.unit.conformation.__y[l.atom] + l.unit.conformation.__z[l.atom]))
  391. //.add('segmented mut faster int', () => sumPropertySegmentedMutable(structures[0], l => l.unit.conformation.atomId.value(l.element))
  392. //.add('normal shortcut int', () => sumProperty(structures[0], l => l.conformation.atomId.value(l.element))
  393. //.add('cached int', () => sumProperty(structures[0], Property.cachedAtomColumn(m => m.conformation.atomId)))
  394. //.add('concat str', () => concatProperty(structures[0], l => l.unit.model.hierarchy.atoms.auth_atom_id.value(l.element))
  395. //.add('cached concat str', () => concatProperty(structures[0], Property.cachedAtomColumn(m => m.hierarchy.atoms.auth_atom_id)))
  396. .on('cycle', (e: any) => console.log(String(e.target)))
  397. .run();
  398. }
  399. }
  400. PropertyAccess.run();