structure.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { PluginContext } from '../../mol-plugin/context';
  7. import { StateObjectRef, StateObjectSelector, StateTransformer, StateTransform, StateObjectCell } from '../../mol-state';
  8. import { PluginStateObject as SO } from '../objects';
  9. import { StateTransforms } from '../transforms';
  10. import { RootStructureDefinition } from '../helpers/root-structure';
  11. import { StructureComponentParams, StaticStructureComponentType } from '../helpers/structure-component';
  12. import { BuiltInTrajectoryFormat, TrajectoryFormatProvider } from '../formats/trajectory';
  13. import { StructureRepresentationBuilder } from './structure/representation';
  14. import { StructureSelectionQuery } from '../helpers/structure-selection-query';
  15. import { Task } from '../../mol-task';
  16. import { StructureElement } from '../../mol-model/structure';
  17. import { ModelSymmetry } from '../../mol-model-formats/structure/property/symmetry';
  18. import { SpacegroupCell } from '../../mol-math/geometry';
  19. import Expression from '../../mol-script/language/expression';
  20. import { TrajectoryHierarchyBuilder } from './structure/hierarchy';
  21. export class StructureBuilder {
  22. private get dataState() {
  23. return this.plugin.state.data;
  24. }
  25. private async parseTrajectoryData(data: StateObjectRef<SO.Data.Binary | SO.Data.String>, format: BuiltInTrajectoryFormat | TrajectoryFormatProvider) {
  26. const provider = typeof format === 'string' ? this.plugin.dataFormats.get(format) as TrajectoryFormatProvider : format;
  27. if (!provider) throw new Error(`'${format}' is not a supported data format.`);
  28. const { trajectory } = await provider.parse(this.plugin, data);
  29. return trajectory;
  30. }
  31. private parseTrajectoryBlob(data: StateObjectRef<SO.Data.Blob>, params: StateTransformer.Params<StateTransforms['Data']['ParseBlob']>) {
  32. const state = this.dataState;
  33. const trajectory = state.build().to(data)
  34. .apply(StateTransforms.Data.ParseBlob, params, { state: { isGhost: true } })
  35. .apply(StateTransforms.Model.TrajectoryFromBlob, void 0);
  36. return trajectory.commit({ revertOnError: true });
  37. }
  38. readonly hierarchy = new TrajectoryHierarchyBuilder(this.plugin);
  39. readonly representation = new StructureRepresentationBuilder(this.plugin);
  40. parseTrajectory(data: StateObjectRef<SO.Data.Binary | SO.Data.String>, format: BuiltInTrajectoryFormat | TrajectoryFormatProvider): Promise<StateObjectSelector<SO.Molecule.Trajectory>>
  41. parseTrajectory(blob: StateObjectRef<SO.Data.Blob>, params: StateTransformer.Params<StateTransforms['Data']['ParseBlob']>): Promise<StateObjectSelector<SO.Molecule.Trajectory>>
  42. parseTrajectory(data: StateObjectRef, params: any) {
  43. const cell = StateObjectRef.resolveAndCheck(this.dataState, data as StateObjectRef);
  44. if (!cell) throw new Error('Invalid data cell.');
  45. if (SO.Data.Blob.is(cell.obj)) {
  46. return this.parseTrajectoryBlob(data, params);
  47. } else {
  48. return this.parseTrajectoryData(data, params);
  49. }
  50. }
  51. createModel(trajectory: StateObjectRef<SO.Molecule.Trajectory>, params?: StateTransformer.Params<StateTransforms['Model']['ModelFromTrajectory']>, initialState?: Partial<StateTransform.State>) {
  52. const state = this.dataState;
  53. const model = state.build().to(trajectory)
  54. .apply(StateTransforms.Model.ModelFromTrajectory, params || { modelIndex: 0 }, { state: initialState });
  55. return model.commit({ revertOnError: true });
  56. }
  57. insertModelProperties(model: StateObjectRef<SO.Molecule.Model>, params?: StateTransformer.Params<StateTransforms['Model']['CustomModelProperties']>, initialState?: Partial<StateTransform.State>) {
  58. const state = this.dataState;
  59. const props = state.build().to(model)
  60. .apply(StateTransforms.Model.CustomModelProperties, params, { state: initialState });
  61. return props.commit({ revertOnError: true });
  62. }
  63. tryCreateUnitcell(model: StateObjectRef<SO.Molecule.Model>, params?: StateTransformer.Params<StateTransforms['Representation']['ModelUnitcell3D']>, initialState?: Partial<StateTransform.State>) {
  64. const state = this.dataState;
  65. const m = StateObjectRef.resolveAndCheck(state, model)?.obj?.data;
  66. if (!m) return;
  67. const cell = ModelSymmetry.Provider.get(m)?.spacegroup.cell;
  68. if (SpacegroupCell.isZero(cell)) return;
  69. const unitcell = state.build().to(model)
  70. .apply(StateTransforms.Representation.ModelUnitcell3D, params, { state: initialState });
  71. return unitcell.commit({ revertOnError: true });
  72. }
  73. createStructure(modelRef: StateObjectRef<SO.Molecule.Model>, params?: RootStructureDefinition.Params, initialState?: Partial<StateTransform.State>) {
  74. const state = this.dataState;
  75. if (!params) {
  76. const model = StateObjectRef.resolveAndCheck(state, modelRef);
  77. if (model) {
  78. const symm = ModelSymmetry.Provider.get(model.obj?.data!);
  79. if (!symm || symm?.assemblies.length === 0) params = { name: 'deposited', params: { } };
  80. }
  81. }
  82. const structure = state.build().to(modelRef)
  83. .apply(StateTransforms.Model.StructureFromModel, { type: params || { name: 'assembly', params: { } } }, { state: initialState });
  84. return structure.commit({ revertOnError: true });
  85. }
  86. insertStructureProperties(structure: StateObjectRef<SO.Molecule.Structure>, params?: StateTransformer.Params<StateTransforms['Model']['CustomStructureProperties']>) {
  87. const state = this.dataState;
  88. const props = state.build().to(structure)
  89. .apply(StateTransforms.Model.CustomStructureProperties, params);
  90. return props.commit({ revertOnError: true });
  91. }
  92. isComponentTransform(cell: StateObjectCell) {
  93. return cell.transform.transformer === StateTransforms.Model.StructureComponent;
  94. }
  95. /** returns undefined if the component is empty/null */
  96. async tryCreateComponent(structure: StateObjectRef<SO.Molecule.Structure>, params: StructureComponentParams, key: string, tags?: string[]): Promise<StateObjectSelector<SO.Molecule.Structure> | undefined> {
  97. const state = this.dataState;
  98. const root = state.build().to(structure);
  99. const keyTag = `structure-component-${key}`;
  100. const component = root.applyOrUpdateTagged(keyTag, StateTransforms.Model.StructureComponent, params, {
  101. tags: tags ? [...tags, keyTag] : [keyTag]
  102. });
  103. await component.commit();
  104. const selector = component.selector;
  105. if (!selector.isOk || selector.cell?.obj?.data.elementCount === 0) {
  106. await state.build().delete(selector.ref).commit();
  107. return;
  108. }
  109. return selector;
  110. }
  111. tryCreateComponentFromExpression(structure: StateObjectRef<SO.Molecule.Structure>, expression: Expression, key: string, params?: { label?: string, tags?: string[] }) {
  112. return this.tryCreateComponent(structure, {
  113. type: { name: 'expression', params: expression },
  114. nullIfEmpty: true,
  115. label: (params?.label || '').trim()
  116. }, key, params?.tags);
  117. }
  118. tryCreateComponentStatic(structure: StateObjectRef<SO.Molecule.Structure>, type: StaticStructureComponentType, params?: { label?: string, tags?: string[] }) {
  119. return this.tryCreateComponent(structure, {
  120. type: { name: 'static', params: type },
  121. nullIfEmpty: true,
  122. label: (params?.label || '').trim()
  123. }, `static-${type}`, params?.tags);
  124. }
  125. tryCreateComponentFromSelection(structure: StateObjectRef<SO.Molecule.Structure>, selection: StructureSelectionQuery, key: string, params?: { label?: string, tags?: string[] }): Promise<StateObjectSelector<SO.Molecule.Structure> | undefined> {
  126. return this.plugin.runTask(Task.create('Query Component', async taskCtx => {
  127. let { label, tags } = params || { };
  128. label = (label || '').trim();
  129. const structureData = StateObjectRef.resolveAndCheck(this.dataState, structure)?.obj?.data;
  130. if (!structureData) return;
  131. const transformParams: StructureComponentParams = selection.referencesCurrent
  132. ? {
  133. type: {
  134. name: 'bundle',
  135. params: StructureElement.Bundle.fromSelection(await selection.getSelection(this.plugin, taskCtx, structureData)) },
  136. nullIfEmpty: true,
  137. label: label || selection.label
  138. } : {
  139. type: { name: 'expression', params: selection.expression },
  140. nullIfEmpty: true,
  141. label: label || selection.label
  142. };
  143. if (selection.ensureCustomProperties) {
  144. await selection.ensureCustomProperties({ fetch: this.plugin.fetch, runtime: taskCtx }, structureData);
  145. }
  146. return this.tryCreateComponent(structure, transformParams, key, tags);
  147. }))
  148. }
  149. constructor(public plugin: PluginContext) {
  150. }
  151. }