* Adding KIN loading to mesoscale app
* Initial pull-in of NGL Kinemage parser code. It is called by parser.ts and counts of objects are printed.
* Moving interface definitions to scheme.ts for Kin file reader.
* Organizing and commenting list structures. Specifying types where known.
* Removing copied PLY parsing and geometry generation code from KIN file reader. Passing the Kinemage data structure from the parser to the geometry generator. Stubs now in place for KIN with no geometry currently being generated. Also updated the kin.spec.ts file to check a Kinemage file.
* Initial construction of lines from vector lists. Still need to do multiple vector lists, colors, labels, and more.
* Initial implementation of converting vectors into lines. Still needs groups, colors, labels, etc.
* Duplicating ANVIL structure in a kinemage extension directory as a basis for a new Kinemage loading extension
Trying to stick with the master code, which has changed a lot.
* Modifying the kinemage parser to be able to read more than one kinemage entry from the same file. Hooking in a drag and drop handler on .kin files that for now just stores things into a global variable. Adjusting the parsing of kinemage through the original plugin path to handle the new parsing.
* Renaming for clarity
* Fixing name on KinemageDataProvider
* Changing name to kinemage
* First working Kinemage extension code that can draw lines from all drag-and-drop kinemages
* Renaming the Kinemage shape provider pipeline to include the name lines so we can make separate ones for meshes and balls
* Kinemage drag-and-drop handler now shows both lines and ribbons
* Also draws points for dotLists in Kinemage
* Cleaning up nesting and variables
* More cleanup
* Cleaning up
* Continued cleanup
* More work but less fragile
* Only reporting an opened file if we get a kinemage
* Reducing the number of objects and commits
* Fixing over-counting of points
* Adding sphere generation for BallList in Kinemage files. Added reading of radius from list line to enable list-wide specification
* Adding control over line width. Allowing short forms of list names. Working on passing color through
* Fixing width code on vectors. Cleaning up color code
* Setting Kinemage line radius as half the width, clamped to a minimum of 1.0
* Handling @colorset lines in Kinemage. Reporting when we have an unrecognized list element.
* Adding line coloring.
* Enabling support for coloring of ribbons, including rendering both sides with the same color.
* Fixing per-group coloring on meshes and cleaning up
* Adding per-dot coloring
* Adding per-sphere coloring
* Adding labels to elements loaded from Kinemage
* Making Kinemage ribbons have the same normal for every pair of triangles
* Adding README.md for Kinemage extension
* Updating README
* Updating README
* Factoring out file loading from drag and drop handler
* Starting to implement standard file loading for .kin files
* Wraps the text in a file when loading, but this causes it to be parsed twice.
* Hack of commenting out the visuals to make it only parse once
* Removing de-duplication code
* Simplifying function
* Updating comments
* Cleaning up unused objects
* Removing usused Preset
* Removing unused objects left over from original code copied from
* Removing unused objects
* Simplifying function
* Enabling specifying the name of a geometry type loaded by a Kinemage. Not adding entries for object types that are empty lists
* Naming the GUI elements after the PDB file if it is specified in the Kinemage file
* Updating README
* Adding parsing of view parameters from Kinemage
* Constructing Camera.Snapshot objects for each Kinemage View.
* Adding GUI elements to select Views when they are present in the Kinemage file.
* Transposing the orientation matrix to match Mol* orientation
* Changing the name of the view selection GUI elements to match the view that they provide.
* Tweak
* Updating README
* Removing obsolete comment
* Separating the parsing and geometry generation for kinemages
* Updating default visibility when parsing kinemage files. Adding master controls whose visibility icons toggle the state. This does not yet change the visibility of objects in the scene
* Control the geometry generation in kinemages based on the visibility of masters for each list. This is not yet tied into changes caused by the visibility buttons, but it now respects the initial states of the masters in the kinemage file.
* Adding off entry for groups and subgroups that defaults to false
* Adding group and subgroup visibility calculations to kinemage files
* Keeping track of the shapes that are created for a kinemage
* Factoring out shape creation function so we can call it again later. Keeping track of kinData
* Master visibility now working, though it causes view recentering. Removed spurious calls from view adjustment but still happening
* Removing obsolete view code
* Keep the viewpoint from changing when we make masters visible and invisible
* Don't repeat kinemage construction when a later file is loaded
* Ghosting the visibility controls for shapes in kinemages because they will be controlled by the masters and groups
* Split each vector in half, label and color each half by the nearest endpoint. This makes the pop-up labels match what is expected
* Updating Kinemage README with new capabilities
* Adding group visibility controls.
* Cleaning up the visibility calculations for both masters and groups
* Adding subgroup visibility controls
* Orders GUI elements so that subgroups after their group
* Handling 'nobutton' keyword when parsing and also fixing the display of GUI elements
* Updating README
* Turning all but the first group that is in animate off
* Removing unused parameter
* Removing spurious declaration
* Fixing parsing of nobutton tag on list
* Destroy old objects when we change visibility rather than just hiding them
* Make the Transforms associated with the geometry into ghosts so they don't show up in the GUI
* Adding animate and 2animate buttons that do not yet adjust the GUI state to track the changes
* Strating down the path of handling GUI updates with animation
* Animation toggles visibility checkboxes on the groups as it runs.
* Removing obsolete @todo comments
* Removing initial plugin-based Kinemage reader stubs, leaving the extension that handles both File/Open and drag-and-drop
* Overwriting package-lock.json based on new build
* Fixing assignments to handle strings or string arrays to allow the code to compile
* Adding KinemageExtension to viewer app
* This version requires us not to flip the winding numbers of every other triangle so that the colors match.
* Updating contributer documentation
* Removing obsolete entry
* Fixing author tags in documents
* Removing extra line added to file.
* Removing grammar fix and carriage return at end of file.
* Revering whitespace edits.
* Moving reader code for kinemage into its extensions directory
* Moving kin.ts into extensions/kinemage
* Starting down the path of moving the Kinemage GUI controls to the right-side panel. Puts the placeholder there but now shows only part of the geometry and does not see any Kinemage data.
* Continuing to implement controls on the right.
* Visibility of Kinemage controls now working and they are showing up in the right-hand control panel.
* Putting back animation controls and maintaining views across visibility changes
* Allow loading of multiple kinemages, seeing the controls for all of them.
* Comment and README changes
* Comment change
* Initial Kinemage commit that copies the PLY files and references to make it possible to load a PLY-formate file from a file with a KIN extension.
Overwriting package-lock.json
* Adding KIN loading to mesoscale app
* Initial pull-in of NGL Kinemage parser code. It is called by parser.ts and counts of objects are printed.
* Moving interface definitions to scheme.ts for Kin file reader.
* Organizing and commenting list structures. Specifying types where known.
* Removing copied PLY parsing and geometry generation code from KIN file reader. Passing the Kinemage data structure from the parser to the geometry generator. Stubs now in place for KIN with no geometry currently being generated. Also updated the kin.spec.ts file to check a Kinemage file.
* Initial construction of lines from vector lists. Still need to do multiple vector lists, colors, labels, and more.
* Initial implementation of converting vectors into lines. Still needs groups, colors, labels, etc.
* Duplicating ANVIL structure in a kinemage extension directory as a basis for a new Kinemage loading extension
Trying to stick with the master code, which has changed a lot.
* Modifying the kinemage parser to be able to read more than one kinemage entry from the same file. Hooking in a drag and drop handler on .kin files that for now just stores things into a global variable. Adjusting the parsing of kinemage through the original plugin path to handle the new parsing.
* Renaming for clarity
* Fixing name on KinemageDataProvider
* Changing name to kinemage
* First working Kinemage extension code that can draw lines from all drag-and-drop kinemages
* Renaming the Kinemage shape provider pipeline to include the name lines so we can make separate ones for meshes and balls
* Kinemage drag-and-drop handler now shows both lines and ribbons
* Also draws points for dotLists in Kinemage
* Cleaning up nesting and variables
* More cleanup
* Cleaning up
* Continued cleanup
* More work but less fragile
* Only reporting an opened file if we get a kinemage
* Reducing the number of objects and commits
* Fixing over-counting of points
* Adding sphere generation for BallList in Kinemage files. Added reading of radius from list line to enable list-wide specification
* Adding control over line width. Allowing short forms of list names. Working on passing color through
* Fixing width code on vectors. Cleaning up color code
* Setting Kinemage line radius as half the width, clamped to a minimum of 1.0
* Handling @colorset lines in Kinemage. Reporting when we have an unrecognized list element.
* Adding line coloring.
* Enabling support for coloring of ribbons, including rendering both sides with the same color.
* Fixing per-group coloring on meshes and cleaning up
* Adding per-dot coloring
* Adding per-sphere coloring
* Adding labels to elements loaded from Kinemage
* Making Kinemage ribbons have the same normal for every pair of triangles
* Adding README.md for Kinemage extension
* Updating README
* Updating README
* Factoring out file loading from drag and drop handler
* Starting to implement standard file loading for .kin files
* Wraps the text in a file when loading, but this causes it to be parsed twice.
* Hack of commenting out the visuals to make it only parse once
* Removing de-duplication code
* Simplifying function
* Updating comments
* Cleaning up unused objects
* Removing usused Preset
* Removing unused objects left over from original code copied from
* Removing unused objects
* Simplifying function
* Enabling specifying the name of a geometry type loaded by a Kinemage. Not adding entries for object types that are empty lists
* Naming the GUI elements after the PDB file if it is specified in the Kinemage file
* Updating README
* Adding parsing of view parameters from Kinemage
* Constructing Camera.Snapshot objects for each Kinemage View.
* Adding GUI elements to select Views when they are present in the Kinemage file.
* Transposing the orientation matrix to match Mol* orientation
* Changing the name of the view selection GUI elements to match the view that they provide.
* Tweak
* Updating README
* Removing obsolete comment
* Separating the parsing and geometry generation for kinemages
* Updating default visibility when parsing kinemage files. Adding master controls whose visibility icons toggle the state. This does not yet change the visibility of objects in the scene
* Control the geometry generation in kinemages based on the visibility of masters for each list. This is not yet tied into changes caused by the visibility buttons, but it now respects the initial states of the masters in the kinemage file.
* Adding off entry for groups and subgroups that defaults to false
* Adding group and subgroup visibility calculations to kinemage files
* Keeping track of the shapes that are created for a kinemage
* Factoring out shape creation function so we can call it again later. Keeping track of kinData
* Master visibility now working, though it causes view recentering. Removed spurious calls from view adjustment but still happening
* Removing obsolete view code
* Keep the viewpoint from changing when we make masters visible and invisible
* Don't repeat kinemage construction when a later file is loaded
* Ghosting the visibility controls for shapes in kinemages because they will be controlled by the masters and groups
* Split each vector in half, label and color each half by the nearest endpoint. This makes the pop-up labels match what is expected
* Updating Kinemage README with new capabilities
* Adding group visibility controls.
* Cleaning up the visibility calculations for both masters and groups
* Adding subgroup visibility controls
* Orders GUI elements so that subgroups after their group
* Handling 'nobutton' keyword when parsing and also fixing the display of GUI elements
* Updating README
* Turning all but the first group that is in animate off
* Removing unused parameter
* Removing spurious declaration
* Fixing parsing of nobutton tag on list
* Destroy old objects when we change visibility rather than just hiding them
* Make the Transforms associated with the geometry into ghosts so they don't show up in the GUI
* Adding animate and 2animate buttons that do not yet adjust the GUI state to track the changes
* Strating down the path of handling GUI updates with animation
* Animation toggles visibility checkboxes on the groups as it runs.
* Removing obsolete @todo comments
* Removing initial plugin-based Kinemage reader stubs, leaving the extension that handles both File/Open and drag-and-drop
* Fixing assignments to handle strings or string arrays to allow the code to compile
* Adding KinemageExtension to viewer app
* This version requires us not to flip the winding numbers of every other triangle so that the colors match.
* Updating contributer documentation
* Removing obsolete entry
* Fixing author tags in documents
* Removing extra line added to file.
* Removing grammar fix and carriage return at end of file.
* Revering whitespace edits.
* Moving reader code for kinemage into its extensions directory
* Moving kin.ts into extensions/kinemage
* Starting down the path of moving the Kinemage GUI controls to the right-side panel. Puts the placeholder there but now shows only part of the geometry and does not see any Kinemage data.
* Continuing to implement controls on the right.
* Visibility of Kinemage controls now working and they are showing up in the right-hand control panel.
* Putting back animation controls and maintaining views across visibility changes
* Allow loading of multiple kinemages, seeing the controls for all of them.
* Comment and README changes
* Comment change
* Reverting changes to central files that I thought I had to make to get the code to compile on a previous master checkout. The repository compiles without them now.
* Reverting changes made to get things to compile on an earlier master branch
* Reverting another change no longer needed.
* Converting Kinemage parser to using Color rather than number[] and moving HSV conversion into standard location
* Renaming file and removing commented-out code.
* Removing global state and using Transforms instead. Unregistering right-hand-side GUI objects when their associated State Tree objects are deleted.
* Removing unused activeKinemage index
* Adding subgroup visibility controls under groups when appropriate
* Adding * in front of animation groups
* Set background color to black when selecting a Kinemage view
* Updating README
* Implementing @pointmaster behavior properly.
* Re-styling the Kinemage extension right-hand UI to better match MolStar style
* changelog
* move spec
* lint/format
* Refactoring to make the data in the tree nodes immutable and use transforms with parameters to control visibility. This version works but when the animate button is pushed it switches any toggled visibility on other checkboxes back to the initial state
* Keep the animate and animate2 buttons from toggling other state
* Removing commented-out code
* Enable loading multiple kinemages in the same file
* Picking out lint
* Cleaning up test code
* Adding complex test that looks at the various keywords to make sure they are all working.
---------
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
* Update param label and help for Download Structure From AlphaFoldDB
* Download Structure From AlphaFoldDB - allow IDs with version suffix (version to be ignored)
* Update CHANGELOG
`Transformer.Definition.dispose` is documented as "automatically called
on deleting an object," but `State.dispose()` only disposed its own event
subjects and action manager — it never iterated still-live cells to call
their per-transformer dispose. Cells holding GL buffers, mesh data, etc.
only had their dispose fired on explicit deletion (e.g. `clear()`), so
any consumer that called `plugin.dispose()` without first awaiting
`plugin.clear()` retained the callback chain, the GL buffers it points
at, and any closures captured by it.
In a long-running single-page app where the user navigates between
routes that mount/unmount a Mol* viewer, this leaked roughly 25–50 MB
of process RSS per cycle even with `plugin.dispose()` correctly called.
A 20-cycle E2E mount/unmount harness on a 1AKE structure measured a
+541 MB RSS / +266 MB JS-heap delta in the unconditional-`dispose()`
case; calling `await plugin.clear()` before `plugin.dispose()` halved
the residual leak, confirming the per-cell dispose path was missing on
the unconditional `dispose()` route.
This change walks the cell tree once (post-order via the existing
`StateTree.doPostOrder` helper) and invokes the per-transformer dispose
for every still-live cell, swallowing+warning on errors so a single
faulty transformer can't prevent siblings from cleaning up. The
existing per-cell `dispose` helper is reused for consistency with
`updateNode`/`findDeletes` semantics.
Tests cover: chained transformers, sibling subtrees, throwing-dispose
isolation, and transformers without a dispose definition.
Also adds `useDefineForClassFields: false` to the jest esbuild
transform so tests can construct `State` (the `TransientTree` parameter
property + class field pattern relies on legacy class-field semantics,
which `tsc` honors via `target: es2018` but esbuild's default `esnext`
target does not).
Fixes#1825
Co-authored-by: Armando Pellegrini <tech.tools@boltz.bio>
This dependency pulls a 23MB dependency graph to support nodejs v<8.0
Native alternatives exist: fs.promises, and native utils/promisify
Consistency: renaming readFile --> readFileAsync where changes were made.
* Fix circular dependency crash in bundlers (esbuild, Rolldown)
StateTransforms uses `import * as X` namespace imports that are
assigned as object properties at module construction time. When a
bundler concatenates modules into a single scope and reorders their
initialization (as esbuild and Rolldown do), the namespace variable
can still be undefined when the object literal is evaluated, causing
a runtime crash:
Cannot read properties of undefined (reading 'ModelUnitcell3D')
Replace direct property assignments with lazy getters so that
namespace imports are resolved at access time rather than at
construction time. This preserves the existing public API — callers
still use `StateTransforms.Representation.CreateStructureRepresentation3D`
— while making the code safe regardless of module evaluation order.
Fixes#1791
* Add changelog entry and contributor for circular dependency fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
- Fix label attachment inversion (top/bottom and left/right)
- Improve label background vertical centering
- Add label near-clip fade out
- Handle label depth variant for correct transparent background and near fade
- Draw border under text using fragment depth to prevent overlap on adjacent characters
- Clamp border width to avoid exceeding SDF range
- Increase font atlas quality (2x font size multiplier)
- Use clip-space billboard rendering to avoid perspective distortion
* add computeCenter util fn
This is more efficient than using the CentroidHelper patterns.
Time improvement: 135ms --> 113ms on 4JV6/3T5I benchmark
* kabsch received array of indices
instead of array of coordinates which requires to build intermediary arrays in each caller.
* Reuse of Vec3 objects
- Avoid Vec3.create in loops
- use Vec3.squaredDistance instead of repeated double index access
- For simplifying TS manipulations, type xa, ya as Vec3 arrays.
* Reuse Positions
MinimeRmsdPositions.empty was called twice in kabsch fn. A unique call is now done with the full length and the same object is reused.
The length property is passed to ensure that only the portion that contains the required coordinates is used.
* simpler hypothenuse implementation
* missing break statements
- when score has not improved, we don't need to run again with the same parameters
- when the number of residues passing the cutoff is lower than 3, we don't need to run again with stricter cutoffs
* hint at float array
* update headers
* cache transformed coordinates, align indices
* replace ndpwScore with ndpwStructure
ndpwScore was creating an intermediate 2D array which is already cached in ndpwStructure
* trimmedKabschWithTransformedCoordinates
avoid recomputing transformed coordinates (as in trimmedKabsch) when they are already available
* cache rmsdResult and rmsdState
bestTransform must not keep a reference to result.bTransform because its value would change each time kabsch function is run.
* swap shortest structure to B
All transforms are made against the coordinates for structureB when yt is computed.
* reafactor: generalize usage of incremental sequence
Previous implementation was relying on tmpAlignA to hold the indices. It was conflictin in `tryGaplessThreading` with the call to `extendFromSeed`.
A distinct buffer has been created.
* refactor: preallocate dp arrays in constructor, uniform usage of typed arrays
* wrap tm-align in a task + useOverlay
* Skip fragment based strategy if similarity is good
Fragment based alignment takes up most of the computation time due to the O(n3) complexity of aligning fragments of different length. When the alignment is already good, this procedure does not yield improved results (observed also by the original authors).
The threshold for "similar structure" is set to a TM-score of 0.5 according to litterature.
Because it's possible to align 2 structures of very different length, and because the TM-score is normalized using the sequence length, it's important to change the reference for computation from a random choice (sequence A), to the minimal sequence length. This is consistent with the equations from the original TM-align publication (Lmin is used in scoring).
Note that the code already ensures that the shortest sequence is B (less iterations), but this commit makes the min sequence length explicit.
* MVS: Fix primitives in root not being transformed with reference structure
* MultilayerColorTheme only preferSmoothing when a nested theme prefers
* MVSAnnotationColorTheme do not prefer smoothing
* Update file header
* MVS: tweak param type definitions to make type bundle smaller
* MVS: add docstring to all parameter definitions
* MVS: tweak param type definitions to make type bundle smaller 2 (palettes)
* add types
* initial work on MOM number 1 with audio comments
* add some TODO comments
* separate audio as mp3. Do coloring with DG scheme
* move audio in root example folder. test some query in mol-script
* salt bridge.
* better coloring
* support for entry-id test in MolScriptBuilder.
* lint
* update audio, sync animation
* cleanup
* clean up and sync audio/anim
* add reference to MOM1
* mvs-stories updates, better snapshot playback if transition is present
* Add createMVSX
* mvs: support trackball animation
* tweak
* more fine grained speed of camera spin animation
* update TrackballControlsParams.animate.spin.speed
* story-session-url arg support
- add pointer-helper
- add xr-manager to handle xr input and session
- support xr render loop in canvas3d
- add camera.state.minTargetDistance (don't want things too close to your eyes)
- add camera.state.forceFull to show frustum from camera to end of scene
- basic input handling (single controller)
* MVS: CategoricalPalette draft
* MVS: tweak param validation for union, nullable
* MVSAnnotationColorTheme: support categorical palette
* MVS: color theme categorical with list or mapping
* MVS: color theme categorical with named palette
* Add missing color lists
* Sort color lists
* MVS: color theme categorical tidyup
* MVS: color theme continuous params
* MVS: color theme continuous impl
* refactor
* MVS: color theme continuous - reverse, auto overflow_color
* MVS: color theme discrete
* file reorg
* MVS: param union does not need []
* MVS: refactor typing object params
* MVS: color theme - palette defaults in one place
* MVS: declare fields_remapping param
* MVS: implement fields_remapping param
* MVS: docs
* Update CHANGELOG
* MVS: rename fields_remapping -> field_remapping
* PR feedback
* MVS: Generic color themes - case_insensitive param
* MVS: SecondaryStructure named color dict
* Remove accidentaly added file
* Update color map descriptions
* Revert color scheme renaming, keep for v5
* Revert "Revert color scheme renaming, keep for v5"
This reverts commit 12e25c20fe.
* Added color list type "cyclical"
* Color palettes - show description in UI tooltips
* Fixed docstrings
* MVS: Load single state as if multistate
* MVS: join keepCamera and keepSnapshotCamera options
* MVS: remove replaceExisting, addappendSnapshots option
* added toggle for hiding screenshot button
* whoops did the todolist but forgot to commit
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* feat: support host option for build-dev script
* feat: ust update the code related to the host
---------
Co-authored-by: tongfu.e <tongfu.e@xtalpi.com>
* generalize ma_qa_metric support
* do not assume PAE is symmetric
* changelog
* Update src/extensions/model-archive/quality-assessment/prop.ts
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
* Update src/extensions/model-archive/quality-assessment/prop.ts
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
* lint
---------
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
* color, and granularity for selectrion.
* Load json colors per ingredient {"name":{"x":0,"y":0,"z":0}}
* change icon
* use functional components and simple function.
* improve struct_conn handling
* fix
* fix
* check same model
* Update src/mol-model-formats/structure/property/bonds/struct_conn.ts
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
---------
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
* move schema based element addressing from MVS to the core library
* proof of concept
* tweak
* initial visual
* tweak
* tweak structureElementLocationToSchemaItem
* show receptor residues as ball and stick
* wip data model
* custom interactions support
* add example
* wip visuals
* covalent links
* tweak
* fix bug
* cache unit features
* Add structureRef to Molecule.Structure.Selections
* optimize compute
* support multi-structure selections
* analyzeTrajectory support
* readme
* tweak
* headers
* docs
* Optimize StructureElementSchema & remove fromLoci conversion (not production ready for now, will be separate PR)
* move schema code to `StructureElement.Schema` and add fromExpression/Query/Schame functions to Loci and Bundle
* improve selection docs
* adjust covalent bond data model
* tweak fromExpression
* fix type
* remove hydrogen reference
* Fix MVS.rowsToExpression
This is causing an issue when there are multiple units having different inter-unit bonds: the `interBondCount` value is based on the `interBondIndices` length which is correct. But the iteration always starts from the `edges` index === 0. This is only correct for the first pairs of units. The iteration must be done over the `interBondIndices` to get the proper edges.
By returning indices for edges that do not correspond to the given element, the `otherIndex` property can be of bounds.
- keep build process simple, write SW in JS
- support molstar version SW
- add `Viewer.loadFiles` to open supported files
- cleanup pwa icons
- add more file_handlers to pwa manifest
- Can be colored with any structure theme
- Can be colored with the `external-volume` theme
- Can show atoms as a cutout
- Supports principal axes and bounding box as a reference frame
- Add default color support for palette based themes
- Add support for trimming `image` geometry to a box
- Improve/fix iso-level support of `slice` representation
* adding flags for viewport selection controls
* adding logic to remove/keep selection controls
* adding viewport selection control feature
* package updates
* moving selectionTool options out of viewport
* updating selection controls with new properties
* updating property name to match nomenclature
* adding option for custom selection controls
* adding custom selection controls
* minor property name update
* adding property for granularity options
* reassigning StructureSelectionParams.granularity.options if custom granularity options
* adding entry for custom granularity options
* reusing Loci.Granularity to specify valid strings for granularityOptions
* Update src/mol-plugin-ui/spec.ts
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* merging molstar/molstar:main into ventura-rivera/molstar:main
* moving granularityOption logic into componentDidMount
* moving granularityOption logic to componentDidMount and creating structureSelectionParams state
* adding modeOptions and defaultMode properties to sequenceViewer
* adding logic to customize mode controls
* CHANGELOG
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* adding flags for viewport selection controls
* adding logic to remove/keep selection controls
* adding viewport selection control feature
* package updates
* moving selectionTool options out of viewport
* updating selection controls with new properties
* updating property name to match nomenclature
* adding option for custom selection controls
* adding custom selection controls
* minor property name update
* adding property for granularity options
* reassigning StructureSelectionParams.granularity.options if custom granularity options
* adding entry for custom granularity options
* reusing Loci.Granularity to specify valid strings for granularityOptions
* Update src/mol-plugin-ui/spec.ts
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* merging molstar/molstar:main into ventura-rivera/molstar:main
* moving granularityOption logic into componentDidMount
* moving granularityOption logic to componentDidMount and creating structureSelectionParams state
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* adding flags for viewport selection controls
* adding logic to remove/keep selection controls
* adding viewport selection control feature
* package updates
* moving selectionTool options out of viewport
* updating selection controls with new properties
* updating property name to match nomenclature
* adding option for custom selection controls
* adding custom selection controls
* minor property name update
- Add `volume-data` theme that colors positions by volume data
- Add support for color themes to `slice` representation
- Improve/fix palette support in volume color themes
Instead of detecting the protonation at the level of the atom only, the protonation of the unit is detected first. If protonation is known, then the assignment of implicit hydrogens is not needed.
This avoids cases where a nitrogen on a protonated ligand gets assigned a positive charge when it has no hydrogens, because the code was assuming that protonation was unknown in that case.
- Better handle mmCIF files with no entities defined by using `label_asym_id`
- Show bonds in water chains when `ignoreHydorgensVariant` is `non-polar`
Loci.isSubest could return true for a Loci that is a superset of the reference Loci. This was happening when the second Loci contains units that are not matched in the reference Loci. See #1292
In building, saw
```
Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.
More info: https://sass-lang.com/d/legacy-js-api
```
Instead of using `color.channel(..., "red")`, we really were deconstructing rgb by channel just to invert.
So use the underlying SASS api directly.
- Fix trajectory-index color-theme not always updated (#896)
- Fix bond cylinders not updated on size-theme change with `adjustCylinderLength` enabled (#1215)
Previous code was filtering on `polar` hydrogens when looking for an anchorage.
This was not necessary as an acceptor for a regular HBond has only polar hydrogens.
It was removed to make the same code compliant with weak C-H bonds.
This is different from the "Hydrogens: Show All/Hide All/Only Polar" as it is used for filtering out which contacts are represented, while the latter is used to control the display (point to the heavy atoms when H are hidden).
In other words, by considering the H atoms in the geometric constraints, some candidate H bonds are discarded (e.g. because the donor does not have H atoms in the right orientation), while the visibility of hydrogens parameters will still show the same number of hydrogen bonds, just not pointing to the same atoms.
Donor: at least one hydrogen on the donor must be within the donor angle deviation towards the acceptor (angle H-X-A < 45º)
Acceptor: use the closest H on the donor to compute the angles. Ensure that every H atom on the acceptor complies with the ideal angle (no bonded atom from acceptor should be in the way).
* await the the snapshot setting to avoid rendering while applying snapshot. Request : export animation should take in account the trackball controller of 'rock' or 'spin' as well.
* add the updateController option when renderiing snapshot, camera rock and spin are thus taking into account
* forgot a file
* update the canvas3d using the current snapshot to allow camera rock and spin animation rendering
* changelog
* return selectors for each StateTransform in each measurement
* update changelog, modify file header, add name to contributors
* consistently name return selections and labels
---------
Co-authored-by: Ryan DiRisio <rdirisio@treeline.bio>
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* Fixed drag and drop overlay on webkit/safari. Closes#1010
* Use dataTransfer.types when dataTransfer.items is not available/empty
* Updated package.json and header for contribution
* add handlers to MeshBuilder
* Add ring fill visual
* Add nucleotide ring bond visual
* Add nucleotide ring element visual
* Update cartoon representation
* Fix imports
* Smooth normals
* Lint fix
* Update headers and Changelog
* Fix sugar ring mid point
* rename ring -> atomic
* refactor shared nucleotide helpers
* thicknessFactor for nucleic ring/block/fill visuals
* changelog
---------
Co-authored-by: Alexander Rose <alexander.rose@weirdbyte.de>
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* Expose explicit bond orders from struct_conn in mmcif
StructConn was referencing the wrong column name, it was using auth_seq_id instead of label_seq_id
The latter is mandatory by https://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Categories/struct_conn.html
This was causing no matches found during `getEntriesFromStructConn`
for building the bond lookup.
* update CHANGELOG and file headers
* Prefer auth_seq_id, fallback to label_seq_id
* case on presence instead of
* clarify changes in CHANGELOG
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
- Add culling support
- Cull per-object and per-instance
- Cull based on frustum and camera distance
- Add LOD support
- Visibility based on camera distance
- Special mode for spheres with automatic LOD levels
- Add occlusion culling (only WebGL2)
- Hi-Z pass
- Cull based on previous frame's Hi-Z buffer
* Moved MVS extension from mol-view-spec repo
* Viewer supports URL params mvs-url, mvs-data, mvs-format
* Tests
* MVS sanity checks
* MVS extension: drag-and-drop support
* mvs-render try1
* Example CLI utility mvs-render
* Example CLI utility mvs-validate
* MVS extension: renaming
* MVS extension: fixed FOV in mvs-render
* Moved stuff to mol-util/array.ts
* Moved stuff to mol-util/object.ts
* MVS extension: renamed `additions` to `components`
* MVS extension: trying plugin.managers.camera.focusSphere
* MVS extension: refactor focus
* MVS extension: fixed label color once again
* MVS extension: camera position adjustment (compensate FOV differences)
* Fixed formula for camera focus in orthographic mode
* Moved Choice to mol-util/param-choice.ts
* Moved stuff to mol-util/json.ts
* Object.hasOwn polyfill
* MVS extension: small refactor
* Fixed bug in hashString
* Show assembly symmetry from PDBe API (quick and dirty)
* Treat 404 from PDBe API as success
* RCSBAssemblySymmetry extension: make defaults configurable via plugin config items
* RCSBAssemblySymmetry: revert configs to default values
* RCSBAssemblySymmetry: correctly handle non-assembly structure with PDBe API
- add MesoSelectLoci behavior
- add MesoscaleState transform
- show groupBy only if there is more than one option
- make groupBy and filter state-savable
* Removed LazyImports (gl, pngjs, jpeg-js required as param of HeadlessPluginConstructor)
* Added a few methods to HeadlessPluginContext for rendering image without saving to file
* Updated CHANGELOG
* Lint
* Rolled back removing @types/jpeg-js from deps
* Handle resizing viewer element when window remains the same size
* Fix bad rebase
* Fall back to window resize event listener when ResizeObserver not defined
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
* Updated measurements so that the toggle selection button is not shown if selection mode is turned off
* Updated selection controls so that they cannot be turned off if selection mode is not shown
* Extended camera focus bindings to allow override of behaviour to reset camera focus on click
* Exported default bindings for selection and focus so that they can be more easily selectively overridden
* Added description to changelog and headers to modified files
* Fixed spacing in text for toggling selection mode
* Updated camera bindings to not be a breaking change by setting the new bindings to be optional and using default values when undefined
* resolved linting issues with camera bindings
* updated superposition UI to hide selection toggle button when selection mode is disabled
* updated the default value for click to reset camera bindings
* Added HeadlessPluginContext, Canvas3DRenderer, image-renderer example
* Fixed dependencies in package.json
* Removed gl from deps
* Removed gl, pngjs, jpeg-js from dependencies, importing via LazyImports
* Updated docs in src/examples/image-renderer/index.ts
* Added gl, pngjs, jpeg-js to optionalDependencies
* Canvas3DRenderer: default cameraResetDurationMs: 0 (necessary when changing camera between renderings)
---------
Co-authored-by: David Sehnal <dsehnal@users.noreply.github.com>
@@ -84,7 +84,16 @@ Wipes the `build` and `lib` directories and `.tsbuildinfo` files.
Runs the cleanup script prior to building the project, forcing a full rebuild of the project.
Use these commands to resolve occassional build failures which may arise after some dependency updates. Once done, `npm run build` should work again. Note that full rebuilds take more time to complete.
Use these commands to resolve occasional build failures which may arise after some dependency updates. Once done, `npm run build` should work again. Note that full rebuilds take more time to complete.
### Develop with `esbuild`
Experimental support for faster builds with `esbuild`
- `npm run dev:all` - watch mode for all apps and examples
- `npm run dev:viewer` - watch mode for viewer
- `npm run dev:apps` - watch mode for all apps
- `npm run dev:examples` - watch mode for all examples
- `npm run dev -- -a <app name 1> <app name 2> -e <example name 1> ...` - watch mode for specified apps/examples. `-a`/`-e` with without any names will build everything.
### Build for production:
NODE_ENV=production npm run build
@@ -103,7 +112,6 @@ From the root of the project:
and navigate to `build/viewer`
### Code generation
**CIF schemas**
@@ -118,20 +126,16 @@ and navigate to `build/viewer`
@@ -167,13 +171,12 @@ If node complains about a missing acorn peer dependency, run the following comma
### Editor
To get syntax highlighting for shader and graphql files add the following to Visual Code's settings files and make sure relevant extensions are installed in the editor.
To get syntax highlighting for shader files add the following to Visual Code's settings files and make sure relevant extensions are installed in the editor.
"files.associations": {
"*.glsl.ts": "glsl",
"*.frag.ts": "glsl",
"*.vert.ts": "glsl",
"*.gql.ts": "graphql"
"*.vert.ts": "glsl"
},
## Publish
@@ -187,9 +190,14 @@ To get syntax highlighting for shader and graphql files add the following to Vis
npm publish
## Deploy
To prepare apps and demos for https://molstar.org deploy, run:
npm run test
npm run build
node ./scripts/deploy.js # currently updates the viewer on molstar.org/viewer
npm run deploy:local
To commit these changes remotely to the `molstar/molstar.github.io` repo:
npm run deploy:remote
## Contributing
Just open an issue or make a pull request. All contributions are welcome.
The files in this directory are used for deploying the Mol* Viewer as a PWA (Progressive Web App) at https://molstar.org/viewer/. They may serve as an example for creating your own PWA but wont work as-is. See `/script/deploy.js` for where these files are copied and how they are transformed during deployment.
## PWA features
- The Service Worker will cache static resources so the Viewer can be used without internet access. This works without installing, i.e., also in Firefox.
- Once installed, file types listed in the Manifest can be opened from, e.g., the Windows File Explorer.
## Notes for development
In Chrome you can see a list of installed PWAs at chrome://apps/. A right-click opens a menu with an option uninstall.
The Chrome Dev Tools have a section 'Application' to inspect and manage PWA aspects like the Manifest and Service Workers.
BinaryCIF is an efficient, binary flavor of the CIF format. See [specification](https://github.com/molstar/BinaryCIF) and [publication](https://doi.org/10.1371/journal.pcbi.1008247) for further details.
This script reads data in CIF format and converts it lossless to a BinaryCIF file that can be read by Mol* or other
| `--version`, `-v` | Show program's version number and exit. |
| `--cfg` | JSON config file path. If a property is not specified, cmd line param/OS variable/default value are used. |
| `--printCfg` | Print current config for validation and exit. |
| `--cfgTemplate` | Prints default JSON config template to be modified and exit. |
| `--apiPrefix` | Specify the prefix of the API, i.e. <host>/<apiPrefix>/<API queries> |
| `--defaultPort` | Specify the port the server is running on |
| `--cacheMaxSizeInBytes` | Read structures are cached, this specifies the cache size, 0 for off. |
| `--cacheEntryTimeoutMs` | Specify in ms how long to keep entries in cache. |
| `--requestTimeoutMs` | The maximum number of ms the server spends on a request. |
| `--queryTimeoutMs` | The maximum time the server dedicates to executing a query in ms. Does not include the time it takes to read and export the data. |
| `--shutdownTimeoutMinutes` | Server will shut down after this amount of minutes, 0 for off. |
| `--shutdownTimeoutVarianceMinutes` | Modifies the shutdown timer by +/- `timeoutVarianceMinutes` (to avoid multiple instances shutting at the same time) |
| `--maxQueryManyQueries` | Maximum number of queries allowed by the query-many at a time |
| `--defaultSource` | modifies which 'sourceMap' source to use by default |
| `--sourceMap` | Map `id`s for a `source` to a file path. Example: `pdb-bcif '../../data/bcif/${id}.bcif'` - JS expressions can be used inside `${}`, e.g. `${id.substr(1, 2)}/${id}.mdb` Can be specified multiple times. The `SOURCE` variable (e.g. `pdb-bcif`) is arbitrary and depends on how you plan to use the server. Supported formats: cif, bcif, cif.gz, bcif.gz |
| `--sourceMapUrl` | Same as `--sourceMap` but for URL. `--sourceMapUrl src url format` Example: `pdb-cif 'https://www.ebi.ac.uk/pdbe/entry-files/download/${id}_updated.cif' cif` Supported formats: cif, bcif, cif.gz, bcif.gz. Supported protocols: http://, https://, gs:// |
```sh
node lib/commonjs/servers/model/server [-h][-v]
[--cfg CFG]
[--printCfg]
[--cfgTemplate]
[--apiPrefix PREFIX]
[--defaultPort PORT]
[--cacheMaxSizeInBytes CACHE_SIZE]
[--cacheEntryTimeoutMs CACHE_TIMEOUT]
[--requestTimeoutMs REQUEST_TIMEOUT]
[--queryTimeoutMs QUERY_TIMEOUT]
[--shutdownTimeoutMinutes TIME]
[--shutdownTimeoutVarianceMinutes VARIANCE]
[--maxQueryManyQueries QUERY_MANY_LIMIT]
[--defaultSource DEFAULT_SOURCE]
[--sourceMap SOURCE PATH]
[--sourceMapUrl SOURCE PATH SOURCE_MAP_FORMAT]
```
### Production Use
In production, it is required to use a service that will keep the server running, such as [forever.js](https://github.com/foreverjs/forever).
### Memory Issues
Sometimes nodejs might run into problems with memory. This is usually resolved by adding the ``--max-old-space-size=8192`` parameter.
### Preprocessor Example
The preprocessor application allows addiing custom data to CIF files and/or
Provides near-instantaneous access to volumetric data including density maps (for instance, from X-ray crystallography
or cryo-electron microscopy experiments), spatial distribution data, output from electrostatic calculations. It works by
utilizing adaptive downsampling (similar to how Google Earth works).
It uses the text based CIF and BinaryCIF formats to deliver the data to the client.
For quick info about the benefits of using the server, check out the [examples](examples.md).
## Installing and Running
Requires nodejs 8+.
### From GitHub
```
git clone https://github.com/molstar/molstar
npm install
```
Afterwards, build the project source:
```
npm run build:lib
```
and run the server by
```
node lib/commonjs/servers/volume/server
```
### From NPM
```
npm install --production molstar
./volume-server
```
(or ``node node_modules\.bin\volume-server`` in Windows).
The NPM package contains all the tools mentioned here as "binaries":
- ``volume-server``
- ``volume-server-pack``
- ``volume-server-query``
#### Production use
In production it is required to use a service that will keep the server running, such as [forever.js](https://github.com/foreverjs/forever).
#### Memory issues
Sometimes nodejs might run into problems with memory. This is usually resolved by adding the ``--max-old-space-size=8192`` parameter.
### Preparing the Data
For the server to work, CCP4/MAP (models 0, 1, 2 are supported) input data need to be converted into a custom block format.
To achieve this, use the ``pack`` application (``node lib/commonjs/servers/volume/pack`` or ``volume-server-pack`` binary from the NPM package).
### Local Mode
The program ``lib/commonjs/servers/volume/query`` (``volume-server-query`` in NPM package) can be used to query the data without running a http server.
### Navigating the Source Code
The source code is split into 2 mains parts: ``pack`` and ``server``:
- The ``pack`` part provides the means of converting CCP4 files into the internal block format.
- The ``server`` includes
- ``query``: the main part of the server that handles a query. ``execute.ts`` is the "entry point".
- ``algebra``: linear, "coordinate", and "box" algebra provides the means for calculations necessary to concent a user query into a menaningful response.
- API wrapper that handles the requests.
## Consuming the Data
The data can be consumed in any (modern) browser using the [ciftools library](https://github.com/molstar/ciftools) (or any other piece of code that can read text or binary CIF).
The [Data Format](./response-data-format.md) document gives a detailed description of the server response format.
As a reference/example of the server usage is available in Mol* ``mol-plugin`` module.
| `--cfg` | JSON config file path. If a property is not specified, cmd line param/OS variable/default value are used. |
| `--printCfg` | Print current config for validation and exit. |
| `--cfgTemplate` | Prints default JSON config template to be modified and exit. |
| `--apiPrefix` | Specify the prefix of the API, i.e. <host>/<apiPrefix>/<API queries> |
| `--defaultPort` | Specify the port the server is running on |
| `--shutdownTimeoutMinutes` | Server will shut down after this amount of minutes, 0 for off. |
| `--shutdownTimeoutVarianceMinutes` | Modifies the shutdown timer by +/- `timeoutVarianceMinutes` (to avoid multiple instances shutting at the same time) |
| `--idMap` | Map `id`s for a `type` to a file path. Example: `x-ray '../../data/mdb/xray/${id}-ccp4.mdb'` - JS expressions can be used inside `${}`, e.g. `${id.substr(1, 2)}/${id}.mdb` - Can be specified multiple times. - The `TYPE` variable (e.g. `x-ray`) is arbitrary and depends on how you plan to use the server. By default, Mol* Viewer uses `x-ray` and `em`, but any particular use case may vary. - If using URL, it can be http://, https://, gs:// or file:// protocol.|
| `--maxRequestBlockCount` | Maximum number of blocks that could be read in 1 query. This is somewhat tied to the ``maxOutputSizeInVoxelCountByPrecisionLevel`` in that the `<maximum number of voxel> = maxRequestBlockCount * <block size>^3`. The default block size is 96 which corresponds to 28,311,552 voxels with 32 max blocks. |
| `--maxFractionalBoxVolume` | The maximum fractional volume of the query box (to prevent queries that are too big). |
| `--maxOutputSizeInVoxelCountByPrecisionLevel` | What is the (approximate) maximum desired size in voxel count by precision level - Rule of thumb: `<response gzipped size>` in `[<voxel count> / 8, <voxel count> / 4]`. The maximum number of voxels is tied to maxRequestBlockCount. |
The STRUCT_CONN category in the mmCIF file format contains details about the connections between portions of the structure. These can be hydrogen bonds, salt bridges, disulfide bridges and so on (see more at <https://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v40.dic/Categories/struct_conn.html>).
**wwPDB StructConn extension** in Mol* provides functionality to retrieve and visualize these connections.
The extension exposes three functions, located in `src/extensions/wwpdb/struct-conn/index.ts`.
-`getStructConns` - to retrieve struct_conn records from a loaded structure
-`inspectStructConn` - to visualize a struct_conn
-`clearStructConnInspections` - to remove visulizations created by `inspectStructConn`
## Example 1
The following example is a minimal HTML using this functionality:
The PDB ID (`'5elb'`) can be replaced be `undefined`, in which case the functions will apply to the first loaded structure.
## Example 2
This is a more elaborated example, which automatically loads `5elb` (or any PDB entry given in the URL after `?pdb=`), retrieves the list of struct_conns, and creates a button for each struct_conn.
Be aware that some of the struct_conns may be present in the deposited model but not in the preferred assembly (default view). The presented example will raise a dialog window with error message in such cases, e.g. `disulf6` in entry `5elb`.
This documentation outlines the usage of the Mol* extension for visualizing tunnels in molecular structures. The extension integrates with Mol* to render 3D representations of tunnels using specified data sources and properties.
The extension is a key component in ChannelsDB (https://channelsdb2.biodata.ceitec.cz/), enabling users to visualize tunnels within molecules directly from the database. While it is used with ChannelsDB, users can also input their own data or connect to different databases, ensuring versatility across various research environments.
## Data Types
The primary data types involved in tunnel visualization are:
### Tunnel
A Tunnel object contains the actual tunnel data necessary for visualization. It consists of:
-`data`: An array of `Profile` objects that describe the tunnel at various points.
-`props`: Properties such as the tunnel's type, ID, and optional labels or descriptions.
### Profile
A `Profile` object in a `Tunnel` holds detailed geometric and physical properties of a tunnel at specific points along its length. These properties include:
-`Charge`: The electric charge at a specific point in the tunnel.
-`Radius`: The overall radius of the tunnel at this point.
-`FreeRadius`: The radius of the tunnel not obstructed by any molecular elements.
-`T`: Temperature factor or a similar property related to the point.
-`Distance`: Distance along the tunnel's path from the start.
-`X`, `Y`, `Z`: Coordinates of the point in 3D space.
These profiles are crucial for understanding the physical and chemical environment inside the tunnel, allowing for detailed analysis and visualization.
Example:
```json
"Profile":[
{
"Radius":1.49,
"FreeRadius":1.49,
"T":0,
"Distance":0,
"X":-19.152,
"Y":-22.654,
"Z":-13.034,
"Charge":0
},
{
"Radius":1.524,
"FreeRadius":1.524,
"T":0.00625,
"Distance":0.087,
"X":-19.162,
"Y":-22.596,
"Z":-12.969,
"Charge":0
},
{
"Radius":1.56,
"FreeRadius":1.56,
"T":0.0125,
"Distance":0.174,
"X":-19.171,
"Y":-22.539,
"Z":-12.905,
"Charge":0
}
]
```
## Transformers Usage
The extension uses several transformations to process and visualize tunnel data:
### Tunnels Data Transformer
-`Purpose`: Converts a collection of Tunnel data into a state object.
Export components data can be useful to reproduce the same view in a different visualization software.
To do that, one would need to loop over all components, extract its selection (for example by using atom indices) and its representations (type, coloring and sizing).
and run the command `npm run build` (or `watch` for interactive development experience). This will create `build/js/index.js` file which can be imported with a `<script>` tag and the exported functions called view the `molstarLib` prefix (you can customize this parameter).
After opening `index.html` in a browser, you should see

## Using Mol* React UI
The above example does not make use of the default Mol\* React UI and any UI components are therefore the author's responsibility. The below examples show how to (re)use the Mol\* React UI.
- Install `sass`: `npm install sass -save-dev` (or use [`esbuild` plugin](https://www.npmjs.com/package/esbuild-sass-plugin) and `import` the scss file in `ui.tsx`)
When defining the state object, all components are optional, i.e., it is possible to define just the ``data`` component.
Example state is available [here](example-state.json). In the plugin, it is possible to create and load these objects using ``Download JSON``
Example state is available [here](./example-state.json). In the plugin, it is possible to create and load these objects using ``Download JSON``
and ``Open JSON`` buttons in the ``State Snapshots`` section.
# State Tree
@@ -69,7 +69,7 @@ interface Transform.Props {
}
```
"Built-in" data state transforms and description of their parameters are defined in ``mol-plugin/state/transforms``. Behavior transforms are defined in ``mol-plugin/behavior``. Auto-generated documentation for the transforms is also [available](transforms.md).
"Built-in" data state transforms and description of their parameters are defined in ``mol-plugin/state/transforms``. Behavior transforms are defined in ``mol-plugin/behavior``.
Refer to Mol* [Apps](https://github.com/molstar/molstar/tree/master/src/apps) and [Examples](https://github.com/molstar/molstar/tree/master/src/examples).
What is a plugin? A plugin is a collection of modules that provide functionality to the `Mol*` UI. The plugin is responsible for managing the state of the viewer, internal and user interactions. It has been a previous point of confusion for new users of `Mol*` to associate the __viewer__ part of the library with what is further referred to as the __plugin__. These two are closely connected in the `molstar-plugin-ui` module, which is the user-facing part of the library and ultimately provides the viewer, but they are ultimately distinct.
It is recommended that you inspect the general class structure of [`PluginInitWrapper`](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-ui/plugin.tsx#L41), [`PluginUIContext`](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-ui/context.ts#L12) and [`PluginUIComponent`](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-ui/base.tsx#L16) to better understand the flow of data and events in the plugin.
A passing analogy is that a [ `PluginContext` ](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin/context.ts#L71) is the engine that powers computation, rendering, events and subscriptions inside the molstar UI. All UI components depend on `PluginContext`.
There are 4 basic ways of instantiating the Mol* plugin.
## ``Viewer`` wrapper
- The most basic usage is to use the ``Viewer`` wrapper. This is best suited for use cases that do not require custom behavior and are mostly about just displaying a structure.
- See ``Viewer`` class is defined in [src/apps/viewer/app.ts](https://github.com/molstar/molstar/blob/master/src/apps/viewer/app.ts) for available methods
- See [options.ts](https://github.com/molstar/molstar/blob/master/src/apps/viewer/options.ts) for available plugin options
- See [embedded.html](https://github.com/molstar/molstar/blob/master/src/apps/viewer/embedded.html) and [mvs.html](https://github.com/molstar/molstar/blob/master/src/apps/viewer/mvs.html) for example usage
- Importing `molstar.js` will expose `molstar.lib` namespace that allow accessing various functionality without a bundler such as WebPack or esbuild. See the `mvs` example above for basic usage.
- Alternative color themes can be used by importing `theme/dark.css` (or `light/blue`) instead of `molstar.css`
### molstar.js and molstar.css sources
- Download `molstar` NPM package and use the files from `build/viewer` diractory
-`@latest` can be replaced by a specific Mol* version, e.g., `@5.4.2`
- Clone & build the GitHub repository
- This option allows for quite straightforward extension customization, e.g., not including movie export, which reduces the bundle size by ~0.5MB
### Bundle size
By default, the `Viewer` includes all the available extensions. This increases the bundle size significantly, especially by including the `mp4-export`, which is responsible for almost `0.5MB` of compressed bundle size.
It is quite easy to reduce this bundle size by cloning the Mol\* repository, editing [extensions.ts](https://github.com/molstar/molstar/blob/master/src/apps/viewer/options.ts) and rebuilding it with `npm run build:apps`. The new build will be available
in the `build/viewer` directory (the JS file you will find there is uncompressed, but your hosting setup should include automatic gzip compression, significantly reducing the size).
Alternatively, you can explore building your own "viewer" using the base Mol\* library. For this, see the options below.
### Example
```HTML
<style>
#app{
position:absolute;
left:100px;
top:100px;
width:800px;
height:600px;
}
</style>
<!--
molstar.js and .css are obtained from
- the folder build/viewer after cloning and building the molstar package
- from the build/viewer folder in the Mol* NPM package
When using WebPack (or other bundler) with the Mol* NPM package installed, the viewer class can be imported using
```ts
import{Viewer}from'molstar/lib/apps/viewer/app'
functioninitViewer(target: string|HTMLElement){
returnViewer.create(target,{/* options */})// returns a Promise
}
```
## ``PluginContext`` with built-in React UI
- For more customization options it is possible to use the [``PluginContext``](https://github.com/molstar/molstar/blob/master/src/mol-plugin/context.ts) directly.
- When creating the plugin instance it is possible to customize the [``PluginSpec``](https://github.com/molstar/molstar/blob/master/src/mol-plugin/spec.ts).
- The default [``PluginSpec``](https://github.com/molstar/molstar/blob/master/src/mol-plugin/spec.ts) is available [here](https://github.com/molstar/molstar/blob/master/src/mol-plugin/spec.ts).
Furthermore, if it is desirable in your project to use the `molstar`'s React UI components, but you wish to alter or rearrange the layout, you should take a look at the signatures of [ `PluginUIComponent` ](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-ui/base.tsx#L16) which every "control" subclasses.
[ `SequenceView` ](https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-ui/sequence.tsx#L221C4-L221C4), for example, can be used separately from the `PluginUI`. Yet you would need to pass the `PluginUIContext` to it in order for it to observe the changes in the state of the plugin. This can be done via a `PluginContextContainer`:
- The [``PluginContext``](https://github.com/molstar/molstar/blob/master/src/mol-plugin/context.ts) can be instantiated without using the default React UI.
The `markdownExtensions` manager in `PluginContext.manager` allows customizing
the `Markdown` React component to enable executing commands and rendering custom content.
The main use case of this is enriching [MolViewSpec](`https://molstar.org/mol-view-spec`) support.
## API
-`PluginContext.manager.markdownExtensions.register*` functions can be used to register extensions and state/data resolvers to make the the manager work with plugin extension
-`PluginContext.manager.markdownExtensions.remove*` can be used to dynamically remove the above
## Commands
Extends Markdown Hyperlink syntax to support expressions of the form `[title](!c1=v1&c2=v2&...)` into an executable command. The command can be executed either on click, mouse enter, or mouse leave.
Generally, the command should be URL encoded, e.g., `a b` => `a%20b` (in JS, `encodeURIComponent`, in Python `urllib.parse.quote_plus/urlencode`).
### Built-in Commands
-`center-camera` - Centers the camera
-`apply-snapshot=key` - Loads snapshots with the provided key
-`next-snapshot[=-1|1]` - Loads next/previous snapshot, the direction is optional and default to `1`
-`play-snapshots` - Starts playback of state snapshots
-`play-transition` - Plays an animation associated with the given snapshot
-`stop-animation` - Stops currently playing animation
-`focus-refs=ref1,ref2,...` - On click, focuses nodes with the provided refs
-`highlight-refs=ref1,ref2,...` - On mouse over, highlights the provided refs
-`query` is an expression (e.g., `resn HEM` when using PyMol syntax)
- (optional) `lang` is one of `mol-script` (default), `pymol`, `vmd`, `jmol`
- (optional) `action` is an array of `highlight` (default), `focus` (multiple actions can be specified)
- (optional) `focus-radius` is extra distance applied when focusing the selection (default is `3`)
- Example: `[HEM](!query=resn%20HEM%26lang=pymol&action=highlight,focus)` highlights or focuses the HEM residue (the query must be URL encoded because it contains spaces and possibly other special characters)
-`play-audio=src`, `toggle-audio[=src]`, `stop-audio`, `pause-audio`, `dispose-audio` - Audio playback support
## Custom Content
Extends Markdown Image syntax to support expressions of the form `` to render custom elements instead.
### Built-in Custom Content
-`color-swatch=color` - Renders a box with the provided color
- Color palettes:
-`color-palette-name=name` - Renders a gradient with the provided named color palette (see `mol-util/color/lists.ts` for supported color schemes)
-`color-palette-colors=color1,color2` - Renders a gradient with the provided colors
-`color-palette-width=CCS-value` - Specifies the width of the element, defaults to `150px`
-`color-palette-height=CCS-value` - Specified the height of the element, defaults to `0.5em`
-`color-palette-discrete` - Renders discrete color list instead of interpolating
The selection model in Mol\* is based on a generic concept called *location*. A location is a pointer to a selectable element within a scene. For example:
- A structure element location (an atom or a coarse element) is an object composed of `{ structure: Structure, unit: Unit, element: UnitIndex }` (you can think of a `Unit` as a generalized chain)
- A bond location is very similar to structure element, requiring pointers to two units and elements
- A "shape" (generally a mesh) location consists of pointer to the parent shape and a group of triangles
### Loci
Structures and other renderable elements generally consist of many locations and simply using a list of locations would be
prohibitively expensive (e.g., large selections in structures with hundreds of thousands of atoms).
This is why Mol\* introduces
the concept of `Loci` — a compressed representation of multiple locations. Instead of having a list of structure element locations (`{ structure: Structure, unit: Unit, element: UnitIndex }[]`), the representation becomes (simplified) `{ structure: Structure, unit: Unit, elements: OrderedSet<UnitIndex> }`. The ordered set can be further compressed for continuous ranges, keeping only the index of the 1st and last element.
### Bundle
Locations and loci point to the raw JavaScript data structures representing the underlying molecules, making them not serializable in JSON. A *bundle* is a serializable version of the loci.
### Structure Queries
Defining selections directly using the loci would be very cumbersome. For this reason, Mol\* includes the [MolQl query language](https://molql.org) to help define selections.
## Selection Methods
Assuming you have a model already loaded into the plugin (see [Creating Plugin Instance](./instance.md)), these are some of the methods you can use to create selections.
### MolQL (`mol-script`) language
[MolQL](https://molql.org) (`mol-script`) is a language for addressing crystallographic structures and is a part of the Mol* library found at `https://github.com/molstar/molstar/tree/master/src/mol-script`. It can be used against the Molstar plugin as a query language and transpiled against multiple external molecular visualization libraries(see [here](https://github.com/molstar/molstar/tree/master/src/mol-script/transpilers)).
**Example:** Querying a structure for a specific chain and residue range
Select residues with `12<res_id<200 of chain with auth_asym_id=A`
Another way to create a selection is via a `SelectionQuery` object. This is a more programmatic way to create a selection. The following example shows how to select a chain and a residue range using a `SelectionQuery` object.
This relies on the concept of `Expression` which is basically a intermediate representation between a Molscript statement and a selection query.
**Example:** Select residues 10-15 of chains A and F in a structure using a `SelectionQuery` object
Complex queries can be constructed by combining primitive queries at the level of [`chain-test`, `residue-test`, `entity-test`, etc] (https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-script/language/symbol-table/structure-query.ts#L88C4-L94C112) by combining them via logical connectives provided in the `MolscriptBuilder.core.rel` as above.
Inspect these examples to get a better feeling for this syntax: `https://github.com/molstar/molstar/blob/6edbae80db340134341631f669eec86543a0f1a8/src/mol-plugin-state/helpers/structure-selection-query.ts#L88-L580`
Furthermore, a query made this way can be converted to a `Loci` object which is important in many parts of the libary:
```typescript
// Select residue 124 of chain A and convert to Loci
For simple selections, the `StructureElement.Schema` can be used to reference elements within a protein structure using mmCIF `atom_site` field names, e.g.:
If you want to subscribe to selection events (e.g. to change external state in your application based on a user selection), you can use: `plugin.behaviors.interaction.click.subscribe`
Here's an example of passing in a React "set" function to update selected residue positions.
```typescript
import {
Structure,
StructureProperties,
} from "molstar/lib/mol-model/structure"
// setSelected is assumed to be a "set" function returned by useState
// This bit can be customized to record any piece information you want
const localSelected: any[] = [];
for (const { structure } of selections) {
if (!structure) continue;
Structure.eachAtomicHierarchyElement(structure, {
residue: (loc) => {
const position = StructureProperties.residue.label_seq_id(loc);
localSelected.push({ position });
},
});
}
setSelected(localSelected);
}
)
```
## Helper Functions
Given an `Expression`, `QueryFn`, or `StructureElement.Schema` it is possible to use `fromExpression/Query/Schema` functions on `StructureElement.Loci` and `StructureElement.Bundle`.
### `Viewer` app
The `Viewer` app provides the `structureInteractivity` function which allows easy selection/highlighting of the loaded structure. For example:
// transforms[0].bTransform contains the Mat4 to superpose structure2 onto structure1
```
## TM-align Superposition
TM-align is a structure-based alignment algorithm that produces the TM-score, a length-independent metric for comparing protein structures. Unlike RMSD, TM-score is normalized to [0, 1] and is more robust for comparing proteins of different sizes.
- Zhang Y, Skolnick J. "TM-align: a protein structure alignment algorithm based on the TM-score." *Nucleic Acids Research* 33, 2302-2309 (2005). DOI: [10.1093/nar/gki524](https://doi.org/10.1093/nar/gki524)
- Kabsch W. "A solution for the best rotation to relate two sets of vectors." *Acta Crystallographica* A32, 922-923 (1976).
This document shows how to update model conformation dynamically using the `ModelWithCoordinates` transforms. If this does not work well with your particular use case, it is suggested to write a custom version of `ModelWithCoordinates` with similar usage as outlined in this document.
This section shows a high level example for loading trajectory from custom data in specialized plugin instances. A more complete solution is available for example in form of the [G3D format extension](https://github.com/molstar/molstar/tree/master/src/extensions/g3d).
PluginCommands.Canvas3D.SetSettings(plugin,{settings:{renderer:{...renderer,backgroundColor: ColorNames.red/* or: 0xff0000 as Color */}}});
```
Similarly, `highlightColor` and `selectColor` can be updated.
## Interactivity
Interactivity in Mol* is based on the concept of ``Loci``. A ``Loci`` usually references a collection of objects and can be created by a [``Selection``](selections.md). For example, the
``Loci`` captures all atoms in the chain with label_asym_id B of a protein:
```ts
import { Script } from 'molstar/lib/mol-script/script';
import { StructureSelection } from 'molstar/lib/mol-model/structure/query';
const data = plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
const loci = StructureSelection.toLociWithSourceUnits(selection);
```
A ``Loci`` can be used to trigger custom [``Behaviors``](#behaviors).
### Log message to Mol* console
The built-in console in the bottom center of the plugin shows log entries.
```ts
plugin.log.message('This message will appear in the Mol* console');
```
Other log levels are: `info`, `warn`, and `error`.
### Show toast message
Toast messages will appear in the bottom right of the plugin and will linger for a limited time before disappearing.
```ts
import { PluginCommands } from 'molstar/lib/mol-plugin/commands';
PluginCommands.Toast.Show(plugin, {
title: 'Custom Message',
message: 'A custom toast message that will disappear after 2 seconds.',
key: 'toast-custom',
timeoutMs: 2000
});
```
## Behaviors
The state of the Mol* plugin is usually governed by dynamic behaviors which can be set up in initial plugin specification or updated during the plugin runtime. This allows for high modularity and customizability of individual plugin instances.
### Highlight ``Loci``
Highlighting adds a transient overpaint to a representation that will linger until the mouse enters hovers over another
object. Highlights can be applied to a previously defined ``Loci`` by:
```ts
plugin.managers.interactivity.lociHighlights.highlightOnly({ loci }); // loci: Loci
```
Reset all highlights by:
```ts
plugin.managers.interactivity.clearHighlights();
```
### Select ``Loci``
Selected elements will appear with distinct visuals and, if applicable, the corresponding sequence positions will be
shown in the Sequence Viewer panel. Selections persist until removed, for example by clicking the background. A ``Loci``
is selected by:
```ts
plugin.managers.interactivity.lociSelects.select({ loci }); // loci: Loci
```
Deselect a specific ``Loci`` by:
```ts
plugin.managers.interactivity.lociSelects.deselect({ loci }); // loci: Loci
Model Server is a tool for preprocessing and querying macromolecular structure data.
Installing and Running
=====================
Requires nodejs 8+.
## From GitHub
```
git clone https://github.com/molstar/molstar
npm install
```
Afterwards, build the project source:
```
npm run build-tsc
```
and run the server by
```
node lib/commonjs/servers/model/server/server
```
## From NPM
```
npm install --production molstar
./model-server
```
(or ``node node_modules\.bin\model-server`` in Windows).
The NPM package contains all the tools mentioned here as "binaries":
- ``model-server``
- ``model-server-query``
- ``model-server-preprocess``
### Production use
In production it is required to use a service that will keep the server running, such as [forever.js](https://github.com/foreverjs/forever).
### Memory issues
Sometimes nodejs might run into problems with memory. This is usually resolved by adding the ``--max-old-space-size=8192`` parameter.
## Preprocessor
The preprocessor application allows to add custom data to CIF files and/or convert CIF to BinaryCIF. ``node lib/commonjs/servers/model/preprocess`` or ``model-server-preprocess`` binary from the NPM package.
## Local Mode
The server can be run in local/file based mode using ``node lib/commonjs/servers/model/query`` (``model-server-query`` binary from the NPM package).
Custom Properties
=================
This feature is still in development.
It is possible to provide property descriptors that transform data to internal representation and define how it should be exported into one or mode CIF categories. Examples of this are located in the ``mol-model-props`` module and are linked to the server in the config and ``servers/model/properties``.
VolumeServer is a service for accessing subsets of volumetric density data. It automatically downsamples the data depending on the volume of the requested region to reduce the bandwidth requirements and provide near-instant access to even the largest data sets.
It uses the text based CIF and BinaryCIF formats to deliver the data to the client.
For quick info about the benefits of using the server, check out the [examples](examples.md).
Installing and Running
=====================
Requires nodejs 8+.
## From GitHub
```
git clone https://github.com/molstar/molstar
npm install
```
Afterwards, build the project source:
```
npm run build-tsc
```
and run the server by
```
node lib/commonjs/servers/volume/server
```
## From NPM
```
npm install --production molstar
./volume-server
```
(or ``node node_modules\.bin\volume-server`` in Windows).
The NPM package contains all the tools mentioned here as "binaries":
- ``volume-server``
- ``volume-server-pack``
- ``volume-server-query``
### Production use
In production it is required to use a service that will keep the server running, such as [forever.js](https://github.com/foreverjs/forever).
### Memory issues
Sometimes nodejs might run into problems with memory. This is usually resolved by adding the ``--max-old-space-size=8192`` parameter.
## Preparing the Data
For the server to work, CCP4/MAP (models 0, 1, 2 are supported) input data need to be converted into a custom block format.
To achieve this, use the ``pack`` application (``node lib/commonjs/servers/volume/pack`` or ``volume-server-pack`` binary from the NPM package).
## Local Mode
The program ``lib/commonjs/servers/volume/pack`` (``volume-server-query`` in NPM package) can be used to query the data without running a http server.
## Navigating the Source Code
The source code is split into 2 mains parts: ``pack`` and ``server``:
- The ``pack`` part provides the means of converting CCP4 files into the internal block format.
- The ``server`` includes
- ``query``: the main part of the server that handles a query. ``execute.ts`` is the "entry point".
- ``algebra``: linear, "coordinate", and "box" algebra provides the means for calculations necessary to concent a user query into a menaningful response.
- API wrapper that handles the requests.
Consuming the Data
==================
The data can be consumed in any (modern) browser using the [ciftools library](https://github.com/molstar/ciftools) (or any other piece of code that can read text or binary CIF).
The [Data Format](DataFormat.md) document gives a detailed description of the server response format.
As a reference/example of the server usage is available in Mol* ``mol-plugin`` module.
constanalyticsCode=`<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "c414cbae2d284ea995171a81e4a3e721"}'></script><!-- End Cloudflare Web Analytics -->`;
constanalyticsCode=`<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "c414cbae2d284ea995171a81e4a3e721"}'></script><!-- End Cloudflare Web Analytics --><iframe src="https://web3dsurvey.com/collector-iframe.html" style="width: 1px; height: 1px;"></iframe>`;
me.loadExample('cellpack-hiv1');// Load the default example on page load
window.addEventListener('unload',()=>{
me.dispose();
});
});
</script>
</body>
</html>
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.