model.ts 29 KB

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