AlignmentRepresentationPresetProvider.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. * Copyright (c) 2021 RCSB PDB and contributors, licensed under MIT, See LICENSE file for more info.
  3. * @author Joan Segura Mora <joan.segura@rcsb.org>
  4. */
  5. import {
  6. StructureRepresentationPresetProvider
  7. } from "molstar/lib/mol-plugin-state/builder/structure/representation-preset";
  8. import {PluginContext} from "molstar/lib/mol-plugin/context";
  9. import {PluginStateObject} from "molstar/lib/mol-plugin-state/objects";
  10. import {StateObjectRef} from "molstar/lib/mol-state";
  11. import {Structure, StructureElement, StructureProperties as SP, Unit} from "molstar/lib/mol-model/structure";
  12. import {MolScriptBuilder as MS} from "molstar/lib/mol-script/language/builder";
  13. import reprBuilder = StructureRepresentationPresetProvider.reprBuilder;
  14. import uniqid from "uniqid";
  15. import {PLDDTConfidenceColorThemeProvider} from "molstar/lib/extensions/model-archive/quality-assessment/color/plddt";
  16. import {ColorTheme} from "molstar/lib/mol-theme/color";
  17. import {createSelectionExpressions} from "@rcsb/rcsb-molstar/build/src/viewer/helpers/selection";
  18. import {ParamDefinition as PD} from "molstar/lib/mol-util/param-definition";
  19. import {Loci} from "molstar/lib/mol-model/loci";
  20. import {alignAndSuperpose} from "molstar/lib/mol-model/structure/structure/util/superposition";
  21. import {Mat4} from "molstar/lib/mol-math/linear-algebra";
  22. import {SymmetryOperator} from "molstar/lib/mol-math/geometry/symmetry-operator";
  23. import {StateTransforms} from "molstar/lib/mol-plugin-state/transforms";
  24. import {TagDelimiter} from "@rcsb/rcsb-saguaro-app";
  25. let refData: Structure|undefined = undefined;
  26. let refId: {entryId:string;entityId:string;}|undefined = undefined;
  27. export const AlignmentRepresentationPresetProvider = StructureRepresentationPresetProvider<{pdb?:{entryId:string;entityId:string;};},any>({
  28. id: 'alignment-to-reference',
  29. display: {
  30. name: 'Alignemnt to Reference'
  31. },
  32. isApplicable: (structureRef: PluginStateObject.Molecule.Structure, plugin: PluginContext): boolean => true,
  33. params: (structureRef: PluginStateObject.Molecule.Structure | undefined, plugin: PluginContext) => ({
  34. pdb: PD.Value<{entryId:string;entityId:string;}|undefined>(undefined)
  35. }),
  36. apply: async (structureRef: StateObjectRef<PluginStateObject.Molecule.Structure>, params: {pdb?:{entryId:string;entityId:string;};}, plugin: PluginContext) => {
  37. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, structureRef);
  38. if(!structureCell) return;
  39. const structure = structureCell.obj!.data;
  40. if(plugin.managers.structure.hierarchy.current.structures.length == 1){
  41. refId = params.pdb
  42. }
  43. if(refId && params.pdb){
  44. await structuralAlignment(plugin, refId, params.pdb, structure);
  45. }
  46. const entryId = params.pdb?.entryId!;
  47. const entityId = params.pdb?.entityId!;
  48. const l = StructureElement.Location.create(structure);
  49. const asymObserved: {[key:string]:boolean} = {};
  50. for(const unit of structure.units) {
  51. StructureElement.Location.set(l, structure, unit, unit.elements[0]);
  52. const asymId = SP.chain.label_asym_id(l);
  53. if(asymObserved[asymId])
  54. continue;
  55. asymObserved[asymId] = true;
  56. const operators = SP.unit.pdbx_struct_oper_list_ids(l);
  57. const type = SP.entity.type(l);
  58. if (type == "polymer") {
  59. const comp = await plugin.builders.structure.tryCreateComponentFromExpression(
  60. structureCell,
  61. MS.struct.generator.atomGroups({
  62. 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), asymId])
  63. }),
  64. uniqid(`${entryId}${TagDelimiter.entity}${entityId}${TagDelimiter.instance}${asymId}_${operators.join(",")}`),
  65. {
  66. label: `${entryId}${TagDelimiter.entity}${entityId}${TagDelimiter.instance}${asymId}-${operators.join(",")}`
  67. }
  68. );
  69. //TODO This needs to be called after tryCreateComponentFromExpression
  70. const { update, builder } = reprBuilder(plugin, {
  71. ignoreHydrogens: true,
  72. ignoreLight: false,
  73. quality: "auto"
  74. });
  75. builder.buildRepresentation(update, comp, {
  76. color: PLDDTConfidenceColorThemeProvider.isApplicable({ structure }) ? PLDDTConfidenceColorThemeProvider.name as ColorTheme.BuiltIn : "chain-id",
  77. type: "cartoon"
  78. })
  79. await update.commit({ revertOnError: false });
  80. }
  81. }
  82. for(const expression of createSelectionExpressions(entryId)){
  83. if(expression.tag == "polymer")
  84. continue;
  85. const comp = await plugin.builders.structure.tryCreateComponentFromExpression(
  86. structureCell,
  87. expression.expression,
  88. uniqid(`${entryId}${TagDelimiter.entity}${entityId}_${expression.tag}`),
  89. {
  90. label: `${entryId}${TagDelimiter.entity}${entityId}-${expression.tag}`
  91. });
  92. //TODO This needs to be called after tryCreateComponentFromExpression
  93. const { update, builder } = reprBuilder(plugin, {
  94. ignoreHydrogens: true,
  95. ignoreLight: false,
  96. quality: "auto"
  97. });
  98. builder.buildRepresentation(update, comp, {
  99. type: expression.type
  100. });
  101. await update.commit({ revertOnError: false });
  102. }
  103. }
  104. });
  105. async function structuralAlignment(plugin: PluginContext, ref:{entryId:string;entityId:string;}, pdb:{entryId:string;entityId:string;}, structure: Structure): Promise<void> {
  106. if(ref.entryId == pdb.entryId){
  107. refData = structure;
  108. }else{
  109. const pdbData: Structure = structure;
  110. const pdbUnit:Unit|undefined = pdbData?.units.find((u,n)=>u.model.atomicHierarchy.chains.label_entity_id.value(n) === pdb.entityId);
  111. const refUnit:Unit|undefined = refData?.units.find((u,n)=>u.model.atomicHierarchy.chains.label_entity_id.value(n) === ref.entityId);
  112. if(pdbData && pdbUnit && refData && refUnit){
  113. const refLoci: Loci = Structure.toStructureElementLoci(Structure.create([refUnit]));
  114. const pdbLoci: Loci = Structure.toStructureElementLoci(Structure.create([pdbUnit]));
  115. if(StructureElement.Loci.is(refLoci) && StructureElement.Loci.is(pdbLoci)) {
  116. const pivot = plugin.managers.structure.hierarchy.findStructure(refLoci.structure);
  117. const coordinateSystem = pivot?.transform?.cell.obj?.data.coordinateSystem;
  118. const transforms = alignAndSuperpose([refLoci, pdbLoci]);
  119. const { bTransform } = transforms[0];
  120. await transform(plugin, plugin.helpers.substructureParent.get(pdbData)!, bTransform, coordinateSystem);
  121. }
  122. }
  123. }
  124. }
  125. const SuperpositionTag = 'SuperpositionTransform';
  126. async function transform(plugin:PluginContext, s: StateObjectRef<PluginStateObject.Molecule.Structure>, matrix: Mat4, coordinateSystem?: SymmetryOperator): Promise<void>{
  127. const r = StateObjectRef.resolveAndCheck(plugin.state.data, s);
  128. if (!r) return;
  129. const o = plugin.state.data.selectQ(q => q.byRef(r.transform.ref).subtree().withTransformer(StateTransforms.Model.TransformStructureConformation))[0];
  130. const transform = coordinateSystem && !Mat4.isIdentity(coordinateSystem.matrix)
  131. ? Mat4.mul(Mat4(), coordinateSystem.matrix, matrix)
  132. : matrix;
  133. const params = {
  134. transform: {
  135. name: 'matrix' as const,
  136. params: { data: transform, transpose: false }
  137. }
  138. };
  139. const b = o
  140. ? plugin.state.data.build().to(o).update(params)
  141. : plugin.state.data.build().to(s)
  142. .insert(StateTransforms.Model.TransformStructureConformation, params, { tags: SuperpositionTag });
  143. await plugin.runTask(plugin.state.data.updateTree(b));
  144. }