model.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /**
  2. * Copyright (c) 2019-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { StateAction, StateBuilder, StateTransformer, State } from '../../mol-state';
  7. import { PluginContext } from '../../mol-plugin/context';
  8. import { PluginStateObject as PSO } from '../../mol-plugin-state/objects';
  9. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  10. import { Ingredient, CellPacking } from './data';
  11. import { getFromPdb, getFromCellPackDB, IngredientFiles, parseCif, parsePDBfile, getStructureMean, getFromOPM } from './util';
  12. import { Model, Structure, StructureSymmetry, StructureSelection, QueryContext, Unit, Trajectory } from '../../mol-model/structure';
  13. import { trajectoryFromMmCIF, MmcifFormat } from '../../mol-model-formats/structure/mmcif';
  14. import { trajectoryFromPDB } from '../../mol-model-formats/structure/pdb';
  15. import { Mat4, Vec3, Quat } from '../../mol-math/linear-algebra';
  16. import { SymmetryOperator } from '../../mol-math/geometry';
  17. import { Task, RuntimeContext } from '../../mol-task';
  18. import { StateTransforms } from '../../mol-plugin-state/transforms';
  19. import { ParseCellPack, StructureFromCellpack, DefaultCellPackBaseUrl, StructureFromAssemblies, CreateSphere } from './state';
  20. import { MolScriptBuilder as MS } from '../../mol-script/language/builder';
  21. import { getMatFromResamplePoints } from './curve';
  22. import { compile } from '../../mol-script/runtime/query/compiler';
  23. import { CifCategory, CifField } from '../../mol-io/reader/cif';
  24. import { mmCIF_Schema } from '../../mol-io/reader/cif/schema/mmcif';
  25. import { Column } from '../../mol-data/db';
  26. import { createModels } from '../../mol-model-formats/structure/basic/parser';
  27. import { CellpackPackingPreset, CellpackMembranePreset } from './preset';
  28. import { Asset } from '../../mol-util/assets';
  29. import { Color } from '../../mol-util/color';
  30. import { readFromFile } from '../../mol-util/data-source';
  31. import { objectForEach } from '../../mol-util/object';
  32. //import fetch from 'node-fetch';
  33. function getCellPackModelUrl(fileName: string, baseUrl: string) {
  34. return `${baseUrl}/results/${fileName}`;
  35. }
  36. class TrajectoryCache {
  37. private map = new Map<string, Trajectory>();
  38. set(id: string, trajectory: Trajectory) { this.map.set(id, trajectory); }
  39. get(id: string) { return this.map.get(id); }
  40. }
  41. async function getModel(plugin: PluginContext, id: string, ingredient: Ingredient,
  42. baseUrl: string, trajCache: TrajectoryCache, location: string,
  43. file?: Asset.File
  44. ) {
  45. const assetManager = plugin.managers.asset;
  46. const modelIndex = (ingredient.source.model) ? parseInt(ingredient.source.model) : 0;
  47. let surface = (ingredient.ingtype) ? (ingredient.ingtype === 'transmembrane') : false;
  48. if (location == 'surface') surface = true;
  49. let trajectory = trajCache.get(id);
  50. let assets: Asset.Wrapper[] = [];
  51. if (!trajectory) {
  52. if (file) {
  53. if (file.name.endsWith('.cif')) {
  54. const text = await plugin.runTask(assetManager.resolve(file, 'string'));
  55. assets.push(text);
  56. const cif = (await parseCif(plugin, text.data)).blocks[0];
  57. trajectory = await plugin.runTask(trajectoryFromMmCIF(cif));
  58. } else if (file.name.endsWith('.bcif')) {
  59. const binary = await plugin.runTask(assetManager.resolve(file, 'binary'));
  60. assets.push(binary);
  61. const cif = (await parseCif(plugin, binary.data)).blocks[0];
  62. trajectory = await plugin.runTask(trajectoryFromMmCIF(cif));
  63. } else if (file.name.endsWith('.pdb')) {
  64. const text = await plugin.runTask(assetManager.resolve(file, 'string'));
  65. assets.push(text);
  66. const pdb = await parsePDBfile(plugin, text.data, id);
  67. trajectory = await plugin.runTask(trajectoryFromPDB(pdb));
  68. } else {
  69. throw new Error(`unsupported file type '${file.name}'`);
  70. }
  71. } else if (id.match(/^[1-9][a-zA-Z0-9]{3,3}$/i)) {
  72. if (surface){
  73. try {
  74. const data = await getFromOPM(plugin, id, assetManager);
  75. assets.push(data.asset);
  76. data.pdb.id! = id.toUpperCase();
  77. trajectory = await plugin.runTask(trajectoryFromPDB(data.pdb));
  78. } catch (e) {
  79. // fallback to getFromPdb
  80. // console.error(e);
  81. const { mmcif, asset } = await getFromPdb(plugin, id, assetManager);
  82. assets.push(asset);
  83. trajectory = await plugin.runTask(trajectoryFromMmCIF(mmcif));
  84. }
  85. } else {
  86. const { mmcif, asset } = await getFromPdb(plugin, id, assetManager);
  87. assets.push(asset);
  88. trajectory = await plugin.runTask(trajectoryFromMmCIF(mmcif));
  89. }
  90. } else {
  91. const data = await getFromCellPackDB(plugin, id, baseUrl, assetManager);
  92. assets.push(data.asset);
  93. if ('pdb' in data) {
  94. trajectory = await plugin.runTask(trajectoryFromPDB(data.pdb));
  95. } else {
  96. trajectory = await plugin.runTask(trajectoryFromMmCIF(data.mmcif));
  97. }
  98. }
  99. trajCache.set(id, trajectory!);
  100. }
  101. const model = await plugin.resolveTask(trajectory?.getFrameAtIndex(modelIndex)!);
  102. return { model, assets };
  103. }
  104. async function getStructure(plugin: PluginContext, model: Model, source: Ingredient, props: { assembly?: string } = {}) {
  105. let structure = Structure.ofModel(model);
  106. //const label = { label: 'Model', description: Structure.elementDescription(base) };
  107. //let structure = new PSO.Molecule.Structure(base, label);
  108. const { assembly } = props;
  109. if (assembly) {
  110. structure = await plugin.runTask(StructureSymmetry.buildAssembly(structure, assembly));
  111. }
  112. let query;
  113. if (source.source.selection){
  114. var sel: any = source.source.selection;
  115. //selection can have the model ID as well. remove it
  116. const asymIds: string[] = sel.replaceAll(' ', '').replaceAll(':', '').split('or').slice(1);
  117. //console.log("selection is ", source.selection, asymIds);
  118. //query = MS.struct.modifier.union([
  119. // MS.struct.generator.atomGroups({
  120. // 'entity-test': MS.core.rel.eq([MS.ammp('entityType'), 'polymer']),
  121. // 'chain-test': MS.core.set.has([MS.set(...asymIds), MS.ammp('auth_asym_id')])
  122. // })
  123. //]);
  124. query = MS.struct.modifier.union([
  125. MS.struct.generator.atomGroups({
  126. 'chain-test': MS.core.set.has([MS.set(...asymIds), MS.ammp('auth_asym_id')])
  127. })
  128. ]);
  129. } else {
  130. query = MS.struct.modifier.union([
  131. MS.struct.generator.atomGroups({
  132. 'entity-test': MS.core.rel.eq([MS.ammp('entityType'), 'polymer'])
  133. })
  134. ]);
  135. }
  136. const compiled = compile<StructureSelection>(query);
  137. const result = compiled(new QueryContext(structure));
  138. structure = StructureSelection.unionStructure(result);
  139. //change here if possible the label or the?
  140. //structure.label = source.name;
  141. return structure;
  142. }
  143. function getTransformLegacy(trans: Vec3, rot: Quat) {
  144. const q: Quat = Quat.create(-rot[3], rot[0], rot[1], rot[2]);
  145. const m: Mat4 = Mat4.fromQuat(Mat4.zero(), q);
  146. Mat4.transpose(m, m);
  147. Mat4.scale(m, m, Vec3.create(-1.0, 1.0, -1.0));
  148. Mat4.setTranslation(m, trans);
  149. return m;
  150. }
  151. function getTransform(trans: Vec3, rot: Quat) {
  152. const q: Quat = Quat.create(-rot[0], rot[1], rot[2], -rot[3]);
  153. const m: Mat4 = Mat4.fromQuat(Mat4.zero(), q);
  154. const p: Vec3 = Vec3.create(-trans[0], trans[1], trans[2]);
  155. Mat4.setTranslation(m, p);
  156. return m;
  157. }
  158. function getResultTransforms(results: Ingredient['results'], legacy: boolean) {
  159. if (legacy) return results.map((r: Ingredient['results'][0]) => getTransformLegacy(r[0], r[1]));
  160. else return results.map((r: Ingredient['results'][0]) => getTransform(r[0], r[1]));
  161. }
  162. function getCurveTransforms(ingredient: Ingredient) {
  163. const n = ingredient.nbCurve || 0;
  164. const instances: Mat4[] = [];
  165. let segmentLength = 3.4;
  166. if (ingredient.uLength){
  167. segmentLength = ingredient.uLength;
  168. } else if (ingredient.radii){
  169. segmentLength = ingredient.radii[0].radii
  170. ? ingredient.radii[0].radii[0] * 2.0
  171. : 3.4;
  172. }
  173. let resampling: boolean = false;
  174. for (let i = 0; i < n; ++i) {
  175. const cname = `curve${i}`;
  176. if (!(cname in ingredient)) {
  177. console.warn(`Expected '${cname}' in ingredient`)
  178. continue;
  179. }
  180. const _points = ingredient[cname] as Vec3[];
  181. if (_points.length <= 2) {
  182. // TODO handle curve with 2 or less points
  183. continue;
  184. }
  185. // test for resampling
  186. let distance: number = Vec3.distance(_points[0], _points[1]);
  187. if (distance >= segmentLength + 2.0) {
  188. console.info(distance);
  189. resampling = true;
  190. }
  191. const points = new Float32Array(_points.length * 3);
  192. for (let i = 0, il = _points.length; i < il; ++i) Vec3.toArray(_points[i], points, i * 3);
  193. const newInstances = getMatFromResamplePoints(points, segmentLength, resampling);
  194. instances.push(...newInstances);
  195. }
  196. return instances;
  197. }
  198. function getAssembly(name: string, transforms: Mat4[], structure: Structure) {
  199. const builder = Structure.Builder({ label: name });
  200. const { units } = structure;
  201. for (let i = 0, il = transforms.length; i < il; ++i) {
  202. const id = `${i + 1}`;
  203. const op = SymmetryOperator.create(id, transforms[i], { assembly: { id, operId: i, operList: [ id ] } });
  204. for (const unit of units) {
  205. builder.addWithOperator(unit, op);
  206. }
  207. }
  208. return builder.getStructure();
  209. }
  210. function getCifCurve(name: string, transforms: Mat4[], model: Model) {
  211. if (!MmcifFormat.is(model.sourceData)) throw new Error('mmcif source data needed');
  212. const { db } = model.sourceData.data;
  213. const d = db.atom_site;
  214. const n = d._rowCount;
  215. const rowCount = n * transforms.length;
  216. const { offsets, count } = model.atomicHierarchy.chainAtomSegments;
  217. const x = d.Cartn_x.toArray();
  218. const y = d.Cartn_y.toArray();
  219. const z = d.Cartn_z.toArray();
  220. const Cartn_x = new Float32Array(rowCount);
  221. const Cartn_y = new Float32Array(rowCount);
  222. const Cartn_z = new Float32Array(rowCount);
  223. const map = new Uint32Array(rowCount);
  224. const seq = new Int32Array(rowCount);
  225. let offset = 0;
  226. for (let c = 0; c < count; ++c) {
  227. const cStart = offsets[c];
  228. const cEnd = offsets[c + 1];
  229. const cLength = cEnd - cStart;
  230. for (let t = 0, tl = transforms.length; t < tl; ++t) {
  231. const m = transforms[t];
  232. for (let j = cStart; j < cEnd; ++j) {
  233. const i = offset + j - cStart;
  234. const xj = x[j], yj = y[j], zj = z[j];
  235. Cartn_x[i] = m[0] * xj + m[4] * yj + m[8] * zj + m[12];
  236. Cartn_y[i] = m[1] * xj + m[5] * yj + m[9] * zj + m[13];
  237. Cartn_z[i] = m[2] * xj + m[6] * yj + m[10] * zj + m[14];
  238. map[i] = j;
  239. seq[i] = t + 1;
  240. }
  241. offset += cLength;
  242. }
  243. }
  244. function multColumn<T>(column: Column<T>) {
  245. const array = column.toArray();
  246. return Column.ofLambda({
  247. value: row => array[map[row]],
  248. areValuesEqual: (rowA, rowB) => map[rowA] === map[rowB] || array[map[rowA]] === array[map[rowB]],
  249. rowCount, schema: column.schema
  250. });
  251. }
  252. const _atom_site: CifCategory.SomeFields<mmCIF_Schema['atom_site']> = {
  253. auth_asym_id: CifField.ofColumn(multColumn(d.auth_asym_id)),
  254. auth_atom_id: CifField.ofColumn(multColumn(d.auth_atom_id)),
  255. auth_comp_id: CifField.ofColumn(multColumn(d.auth_comp_id)),
  256. auth_seq_id: CifField.ofNumbers(seq),
  257. B_iso_or_equiv: CifField.ofColumn(Column.ofConst(0, rowCount, Column.Schema.float)),
  258. Cartn_x: CifField.ofNumbers(Cartn_x),
  259. Cartn_y: CifField.ofNumbers(Cartn_y),
  260. Cartn_z: CifField.ofNumbers(Cartn_z),
  261. group_PDB: CifField.ofColumn(Column.ofConst('ATOM', rowCount, Column.Schema.str)),
  262. id: CifField.ofColumn(Column.ofLambda({
  263. value: row => row,
  264. areValuesEqual: (rowA, rowB) => rowA === rowB,
  265. rowCount, schema: d.id.schema,
  266. })),
  267. label_alt_id: CifField.ofColumn(multColumn(d.label_alt_id)),
  268. label_asym_id: CifField.ofColumn(multColumn(d.label_asym_id)),
  269. label_atom_id: CifField.ofColumn(multColumn(d.label_atom_id)),
  270. label_comp_id: CifField.ofColumn(multColumn(d.label_comp_id)),
  271. label_seq_id: CifField.ofNumbers(seq),
  272. label_entity_id: CifField.ofColumn(Column.ofConst('1', rowCount, Column.Schema.str)),
  273. occupancy: CifField.ofColumn(Column.ofConst(1, rowCount, Column.Schema.float)),
  274. type_symbol: CifField.ofColumn(multColumn(d.type_symbol)),
  275. pdbx_PDB_ins_code: CifField.ofColumn(Column.ofConst('', rowCount, Column.Schema.str)),
  276. pdbx_PDB_model_num: CifField.ofColumn(Column.ofConst(1, rowCount, Column.Schema.int)),
  277. };
  278. const categories = {
  279. entity: CifCategory.ofTable('entity', db.entity),
  280. chem_comp: CifCategory.ofTable('chem_comp', db.chem_comp),
  281. atom_site: CifCategory.ofFields('atom_site', _atom_site)
  282. };
  283. return {
  284. header: name,
  285. categoryNames: Object.keys(categories),
  286. categories
  287. };
  288. }
  289. async function getCurve(plugin: PluginContext, name: string, ingredient: Ingredient, transforms: Mat4[], model: Model) {
  290. const cif = getCifCurve(name, transforms, model);
  291. const curveModelTask = Task.create('Curve Model', async ctx => {
  292. const format = MmcifFormat.fromFrame(cif);
  293. const models = await createModels(format.data.db, format, ctx);
  294. return models.representative;
  295. });
  296. const curveModel = await plugin.runTask(curveModelTask);
  297. //ingredient.source.selection = undefined;
  298. return getStructure(plugin, curveModel, ingredient);
  299. }
  300. async function getIngredientStructure(plugin: PluginContext, ingredient: Ingredient, baseUrl: string, ingredientFiles: IngredientFiles, trajCache: TrajectoryCache, location: 'surface' | 'interior' | 'cytoplasme') {
  301. const { name, source, results, nbCurve } = ingredient;
  302. if (source.pdb === 'None') return;
  303. const file = ingredientFiles[source.pdb];
  304. if (!file) {
  305. // TODO can these be added to the library?
  306. if (name === 'HIV1_CAhex_0_1_0') return; // 1VU4CtoH_hex.pdb
  307. if (name === 'HIV1_CAhexCyclophilA_0_1_0') return; // 1AK4fitTo1VU4hex.pdb
  308. if (name === 'iLDL') return; // EMD-5239
  309. if (name === 'peptides') return; // peptide.pdb
  310. if (name === 'lypoglycane') return;
  311. }
  312. // model id in case structure is NMR
  313. const { model, assets } = await getModel(plugin, source.pdb || name, ingredient, baseUrl, trajCache, location, file);
  314. if (!model) return;
  315. let structure: Structure;
  316. if (nbCurve) {
  317. //console.log("await getCurve", name, nbCurve, model);
  318. structure = await getCurve(plugin, name, ingredient, getCurveTransforms(ingredient), model);
  319. //console.log("getCurve", structure);
  320. } else {
  321. if ( (!results || results.length===0)) return;
  322. let bu: string|undefined = source.bu ? source.bu : undefined;
  323. if (bu){
  324. if (bu === 'AU') {
  325. bu = undefined;
  326. } else {
  327. bu = bu.slice(2);
  328. }
  329. }
  330. structure = await getStructure(plugin, model, ingredient, { assembly: bu });
  331. // transform with offset and pcp
  332. let legacy: boolean = true;
  333. //if (name === 'MG_213_214_298_6MER_ADP') {
  334. // console.log("getStructure ", ingredient.offset,ingredient.principalVector,ingredient);
  335. //}
  336. var pcp = ingredient.principalVector?ingredient.principalVector:ingredient.principalAxis;
  337. if (pcp){
  338. legacy = false;
  339. const structureMean = getStructureMean(structure);
  340. Vec3.negate(structureMean, structureMean);
  341. const m1: Mat4 = Mat4.identity();
  342. Mat4.setTranslation(m1, structureMean);
  343. structure = Structure.transform(structure, m1);
  344. if (ingredient.offset){
  345. let o: Vec3 = Vec3.create(ingredient.offset[0], ingredient.offset[1], ingredient.offset[2]);
  346. if (!Vec3.exactEquals(o, Vec3.zero())){ // -1, 1, 4e-16 ??
  347. if (location !== 'surface')//(name === 'MG_213_214_298_6MER_ADP')
  348. {
  349. Vec3.negate(o, o);
  350. //console.log("after negate offset ",name, o);
  351. }
  352. const m: Mat4 = Mat4.identity();
  353. Mat4.setTranslation(m, o);
  354. structure = Structure.transform(structure, m);
  355. }
  356. }
  357. if (pcp){
  358. let p: Vec3 = Vec3.create(pcp[0], pcp[1], pcp[2]);
  359. if (!Vec3.exactEquals(p, Vec3.unitZ)){
  360. //if (location !== 'surface')//(name === 'MG_213_214_298_6MER_ADP')
  361. //{
  362. //Vec3.negate(p, p);
  363. //console.log("after negate ", p);
  364. // }
  365. const q: Quat = Quat.identity();
  366. Quat.rotationTo(q, p, Vec3.unitZ);
  367. const m: Mat4 = Mat4.fromQuat(Mat4.zero(), q);
  368. //if (location !== 'surface') Mat4.invert(m, m);
  369. structure = Structure.transform(structure, m);
  370. //if (location === 'surface') console.log('surface',name,ingredient.principalVector, q);
  371. }
  372. }
  373. }
  374. structure = getAssembly(name, getResultTransforms(results, legacy), structure);
  375. //console.log("getStructure ", name, structure.label, structure);
  376. }
  377. return { structure, assets };
  378. }
  379. export function createStructureFromCellPack(plugin: PluginContext, packing: CellPacking, baseUrl: string, ingredientFiles: IngredientFiles) {
  380. return Task.create('Create Packing Structure', async ctx => {
  381. const { ingredients, location, name } = packing;
  382. const assets: Asset.Wrapper[] = [];
  383. const trajCache = new TrajectoryCache();
  384. const structures: Structure[] = [];
  385. const colors: Color[] = [];
  386. //let skipColors: boolean = false;
  387. for (const iName in ingredients) {
  388. if (ctx.shouldUpdate) await ctx.update(iName);
  389. const ingredientStructure = await getIngredientStructure(plugin, ingredients[iName], baseUrl, ingredientFiles, trajCache, location);
  390. if (ingredientStructure) {
  391. structures.push(ingredientStructure.structure);
  392. assets.push(...ingredientStructure.assets);
  393. const c = ingredients[iName].color;
  394. if (c){
  395. colors.push(Color.fromNormalizedRgb(c[0], c[1], c[2]));
  396. } else {
  397. colors.push(Color.fromNormalizedRgb(1,0,0));
  398. //skipColors = true;
  399. }
  400. }
  401. }
  402. if (ctx.shouldUpdate) await ctx.update(`${name} - units`);
  403. const units: Unit[] = [];
  404. let offsetInvariantId = 0;
  405. let offsetChainGroupId = 0;
  406. for (const s of structures) {
  407. if (ctx.shouldUpdate) await ctx.update(`${s.label}`);
  408. let maxInvariantId = 0;
  409. let maxChainGroupId = 0;
  410. for (const u of s.units) {
  411. const invariantId = u.invariantId + offsetInvariantId;
  412. const chainGroupId = u.chainGroupId + offsetChainGroupId;
  413. if (u.invariantId > maxInvariantId) maxInvariantId = u.invariantId;
  414. units.push(Unit.create(units.length, invariantId, chainGroupId, u.traits, u.kind, u.model, u.conformation.operator, u.elements, u.props));
  415. }
  416. offsetInvariantId += maxInvariantId + 1;
  417. offsetChainGroupId += maxChainGroupId + 1;
  418. }
  419. if (ctx.shouldUpdate) await ctx.update(`${name} - structure`);
  420. const structure = Structure.create(units, {label: name+"."+location});
  421. for( let i = 0, il = structure.models.length; i < il; ++i) {
  422. Model.TrajectoryInfo.set(structure.models[i], { size: il, index: i });
  423. }
  424. return { structure, assets, colors: colors };
  425. });
  426. }
  427. async function handleHivRna(plugin: PluginContext, packings: CellPacking[], baseUrl: string) {
  428. for (let i = 0, il = packings.length; i < il; ++i) {
  429. if (packings[i].name === 'HIV1_capsid_3j3q_PackInner_0_1_0'|| packings[i].name === 'HIV_capsid') {
  430. const url = Asset.getUrlAsset(plugin.managers.asset, `${baseUrl}/extras/rna_allpoints.json`);
  431. const json = await plugin.runTask(plugin.managers.asset.resolve(url, 'json', false));
  432. const points = json.data.points as number[];
  433. const curve0: Vec3[] = [];
  434. for (let j = 0, jl = points.length; j < jl; j += 3) {
  435. curve0.push(Vec3.fromArray(Vec3(), points, j));
  436. }
  437. packings[i].ingredients['RNA'] = {
  438. source: { pdb: 'RNA_U_Base.pdb', transform: { center: false } },
  439. results: [],
  440. name: 'RNA',
  441. nbCurve: 1,
  442. curve0
  443. };
  444. }
  445. }
  446. }
  447. async function loadMembrane(plugin: PluginContext, name: string, state: State, params: LoadCellPackModelParams) {
  448. let file: Asset.File | undefined = undefined;
  449. if (params.ingredients !== null) {
  450. const fileName = `${name}.bcif`;
  451. for (const f of params.ingredients) {
  452. if (fileName === f.name) {
  453. file = f;
  454. break;
  455. }
  456. }
  457. if (!file){
  458. // check for cif directly
  459. const cifileName = `${name}.cif`;
  460. for (const f of params.ingredients) {
  461. if (cifileName === f.name) {
  462. file = f;
  463. break;
  464. }
  465. }
  466. }
  467. }
  468. let b = state.build().toRoot();
  469. if (file) {
  470. if (file.name.endsWith('.cif')) {
  471. b = b.apply(StateTransforms.Data.ReadFile, { file, isBinary: false, label: file.name }, { state: { isGhost: true } });
  472. } else if (file.name.endsWith('.bcif')) {
  473. b = b.apply(StateTransforms.Data.ReadFile, { file, isBinary: true, label: file.name }, { state: { isGhost: true } });
  474. }
  475. } else {
  476. const url = Asset.getUrlAsset(plugin.managers.asset, `${params.baseUrl}/membranes/${name}.bcif`);
  477. b = b.apply(StateTransforms.Data.Download, { url, isBinary: true, label: name }, { state: { isGhost: true } });
  478. }
  479. const props = {
  480. type: {
  481. name: 'assembly' as const,
  482. params: { id: '1' }
  483. }
  484. };
  485. if (params.source.name === 'id' && params.source.params !== "MycoplasmaGenitalium.json")
  486. //old membrane
  487. {
  488. const membrane = await b.apply(StateTransforms.Data.ParseCif, undefined, { state: { isGhost: true } })
  489. .apply(StateTransforms.Model.TrajectoryFromMmCif, undefined, { state: { isGhost: true } })
  490. .apply(StateTransforms.Model.ModelFromTrajectory, undefined, { state: { isGhost: true } })
  491. .apply(StructureFromAssemblies, undefined, { state: { isGhost: true } })
  492. .commit({ revertOnError: true });
  493. const membraneParams = {
  494. representation: params.preset.representation,
  495. };
  496. await CellpackMembranePreset.apply(membrane, membraneParams, plugin);
  497. } else {
  498. const membrane = await b.apply(StateTransforms.Data.ParseCif, undefined, { state: { isGhost: true } })
  499. .apply(StateTransforms.Model.TrajectoryFromMmCif, undefined, { state: { isGhost: true } })
  500. .apply(StateTransforms.Model.ModelFromTrajectory, undefined, { state: { isGhost: true } })
  501. .apply(StateTransforms.Model.StructureFromModel, props, { state: { isGhost: true } })
  502. .commit({ revertOnError: true });
  503. const membraneParams = {
  504. representation: params.preset.representation,
  505. };
  506. await CellpackMembranePreset.apply(membrane, membraneParams, plugin);
  507. }
  508. }
  509. async function loadPackings(plugin: PluginContext, runtime: RuntimeContext, state: State, params: LoadCellPackModelParams) {
  510. const ingredientFiles = params.ingredients || [];
  511. let cellPackJson: StateBuilder.To<PSO.Format.Json, StateTransformer<PSO.Data.String, PSO.Format.Json>>;
  512. let modelFile: Asset.File|null= params.results;
  513. if (params.source.name === 'id') {
  514. const url = Asset.getUrlAsset(plugin.managers.asset, getCellPackModelUrl(params.source.params, params.baseUrl));
  515. //console.log("getting "+params.source.params+" "+url.url);
  516. cellPackJson = state.build().toRoot()
  517. .apply(StateTransforms.Data.Download, { url, isBinary: false, label: params.source.params }, { state: { isGhost: true } });
  518. if (params.source.params === "MycoplasmaGenitalium.json"){
  519. const m_url = Asset.getUrlAsset(plugin.managers.asset, `${params.baseUrl}/results/results_149_curated_serialized.bin`);
  520. //console.log("getting results "+m_url.url);
  521. const model_data = await fetch(m_url.url);
  522. modelFile = Asset.File(new File([await model_data.arrayBuffer()], 'model.bin'));
  523. //console.log("MycoplasmaGenitalium.json loading setup ?",modelFile);
  524. }
  525. } else {
  526. const file = params.source.params;
  527. const rfile = params.results;
  528. if (!file?.file) {
  529. plugin.log.error('No file selected');
  530. return;
  531. }
  532. let jsonFile: Asset.File;
  533. if (file.name.toLowerCase().endsWith('.zip')) {
  534. const data = await readFromFile(file.file, 'zip').runInContext(runtime);
  535. jsonFile = Asset.File(new File([data['model.json']], 'model.json'));
  536. modelFile = Asset.File(new File([data['model.bin']], 'model.bin'));
  537. objectForEach(data, (v, k) => {
  538. if (k === 'model.json') return;
  539. else if (k === 'model.bin') return;
  540. ingredientFiles.push(Asset.File(new File([v], k)));
  541. });
  542. } else {
  543. jsonFile = file;
  544. modelFile = rfile;
  545. }
  546. cellPackJson = state.build().toRoot()
  547. .apply(StateTransforms.Data.ReadFile, { file: jsonFile, isBinary: false, label: jsonFile.name }, { state: { isGhost: true } });
  548. }
  549. const cellPackBuilder = cellPackJson
  550. .apply(StateTransforms.Data.ParseJson, undefined, { state: { isGhost: true } })
  551. .apply(ParseCellPack,{modeFile:modelFile});
  552. const cellPackObject = await state.updateTree(cellPackBuilder).runInContext(runtime);
  553. const { packings } = cellPackObject.obj!.data;
  554. await handleHivRna(plugin, packings, params.baseUrl);
  555. for (let i = 0, il = packings.length; i < il; ++i) {
  556. const p = { packing: i, baseUrl: params.baseUrl, ingredientFiles };
  557. const packing = await state.build()
  558. .to(cellPackBuilder.ref)
  559. .apply(StructureFromCellpack, p)
  560. .commit({ revertOnError: true });
  561. const packingParams = {
  562. traceOnly: params.preset.traceOnly,
  563. representation: params.preset.representation,
  564. };
  565. await CellpackPackingPreset.apply(packing, packingParams, plugin);
  566. if ( packings[i].location === 'surface') {
  567. if (params.membrane){
  568. await loadMembrane(plugin, packings[i].name, state, params);
  569. }
  570. if (typeof(packings[i].mb) !== 'undefined'){
  571. var nSpheres = packings[i].mb!.positions.length/3;
  572. for (var j=0;j<nSpheres;j++) {
  573. await state.build()
  574. .toRoot()
  575. .apply(CreateSphere, {center:Vec3.create(packings[i].mb!.positions[j*3+0],
  576. packings[i].mb!.positions[j*3+1],
  577. packings[i].mb!.positions[j*3+2]),
  578. radius:packings[i].mb!.radii[j] })
  579. .commit()
  580. }
  581. }
  582. }
  583. }
  584. }
  585. const LoadCellPackModelParams = {
  586. source: PD.MappedStatic('id', {
  587. 'id': PD.Select('InfluenzaModel2.json', [
  588. ['blood_hiv_immature_inside.json', 'Blood HIV immature'],
  589. ['HIV_immature_model.json', 'HIV immature'],
  590. ['BloodHIV1.0_mixed_fixed_nc1.cpr', 'Blood HIV'],
  591. ['HIV-1_0.1.6-8_mixed_radii_pdb.json', 'HIV'],
  592. ['influenza_model1.json', 'Influenza envelope'],
  593. ['InfluenzaModel2.json', 'Influenza Complete'],
  594. ['ExosomeModel.json', 'Exosome Model'],
  595. //['Mycoplasma1.5_mixed_pdb_fixed.cpr', 'Mycoplasma simple'],
  596. //['MycoplasmaModel.json', 'Mycoplasma WholeCell model'],
  597. ['MycoplasmaGenitalium.json', 'Mycoplasma Genitalium curated model'],
  598. ] as const, { description: 'Download the model definition with `id` from the server at `baseUrl.`' }),
  599. 'file': PD.File({ accept: '.json,.cpr,.zip', description: 'Open model definition from .json/.cpr file or open .zip file containing model definition plus ingredients.' }),
  600. }, { options: [['id', 'Id'], ['file', 'File']] }),
  601. baseUrl: PD.Text(DefaultCellPackBaseUrl),
  602. results : PD.File({ accept: '.bin,.json' }),
  603. membrane: PD.Boolean(true),
  604. ingredients: PD.FileList({ accept: '.cif,.bcif,.pdb', label: 'Ingredients' }),
  605. preset: PD.Group({
  606. traceOnly: PD.Boolean(false),
  607. representation: PD.Select('gaussian-surface', PD.arrayToOptions(['spacefill', 'gaussian-surface', 'point', 'orientation']))
  608. }, { isExpanded: true })
  609. };
  610. type LoadCellPackModelParams = PD.Values<typeof LoadCellPackModelParams>
  611. export const LoadCellPackModel = StateAction.build({
  612. display: { name: 'Load CellPack', description: 'Open or download a model' },
  613. params: LoadCellPackModelParams,
  614. from: PSO.Root
  615. })(({ state, params }, ctx: PluginContext) => Task.create('CellPack Loader', async taskCtx => {
  616. await loadPackings(ctx, taskCtx, state, params);
  617. }));