Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
MolAR - a Molecular Analysis and modeling library for Rust.
Table of contents
- What is MolAR?
- Features
- Current status
- Design and performance
- Installation
- Selection syntax
- Tutorial
- Doing things in parallel
- Analysis tasks
- Python bindings
What is molar?
MolAR is a library for molecular modeling and analysis written in Rust with an emphasis on memory safety and performance.
Molar is designed to simplify the analysis of molecular dynamics trajectories and to implement new analysis algorithms. Molar is intended to provide facilities, which are routinely used in all molecular analysis programs, namely input/output of popular file formats, powerful and flexible atom selections, geometry transformations, RMSD fitting and alignment, etc.
MolAR is a logical successor of Pteros molecular modeling library, which is written in C++ and become hard to develop and maintain due to all C++ idiosyncrasies.
Features
- Reading and writing PDB, GRO, XYZ, XTC, TPR files
- Reading and writing Gromacs XTC format with random access.
- Reading Gromacs TPR files (if Gromacs is installed).
- Recognizes any VMD molfile plugins.
- Selections using the syntax similar to VMD and Pteros.
- Memory-safe selections for serial and parallel analysis tasks.
- Powerful subselections and selection splitting.
- SASA calculations with the fastest PowerSasa method.
- RMSD fitting and alignment.
- Basic algorithm (center of mass, center of geometry, etc.).
- Seamless PBC treatment.
- Trajectory processing with powerful built-in features.
- Python bindings.
Design and Performance
Initial design is described in the MolAR paper. However, this concept appeared to be too complex in practice and didn't cover all the real world scenarios properly. Starting from version 1.0 it was changed completely. Now selections are just indices of selected atoms, which have to "bound" to [System] (that is an actual container for atoms and coordinates) to do useful work. The API becomes more noisy but you get proper compile-time borrow checking, soundness and all Rust memory safety guarantees. The "binding" of selections is very cheap (one integer comparison), so it should not affect the performance reported in the paper.
Current status
Molar is usable in real-life projects and is close to be feature complete. Documentation is still rudimentary.
Installation
Molar requires Rust 1.83 or above and a C/C++ compiler for compiling third-party libraries. Any sufficiently modern gcc or clang compiler should work.
To add MolAR to your Rust project just use cargo add molar.
For installation of the Python bindings look here.
Linking to Gromacs
In order to be able to read Gromacs TPR files MolAR should link to locally installed Gromacs. Unfortunately, modern versions of Gromacs do not expose all needed functionality in the public API, so MolAR has to hack into the internals and thus requires an access to the whole Gromacs source and build directories. This means that you have to compile Gromacs on your local machine from source.
In order to link with Gromacs create a .cargo/config.toml file in the root directory of your project with the following content:
[]
# Location of Gromacs source tree
= "<path-to-gromacs-source>/gromacs"
# Location of Gromacs *build* directory (for generated headers)
= "<path-to-gromacs-source>/gromacs/build"
# Location of installed gromacs libraries (where libgromacs.so is located)
= "<path-to-installed-gromacs>/lib64"
You may use a template: mv config.toml.template config.toml.
Selection syntax
MolAR uses a powerful and flexible selection language similar to VMD and Pteros. Selections are composed of logical expressions that combine keywords, comparisons, and geometric criteria to identify specific atoms.
Keywords
Keywords select atoms by their properties:
| Keyword | Aliases | Description | Example |
|---|---|---|---|
index |
— | Atom index (0-based) | index 0 10 20:30 |
resid |
— | Residue ID | resid 1 5:10 |
resindex |
— | Residue index (0-based) | resindex 0:5 |
resname |
— | Residue name | resname ALA GLY |
name |
— | Atom name | name CA CB |
chain |
— | Chain ID | chain A B C |
Keyword syntax
Integer keywords (index, resid, resindex) accept ranges and single values:
resid 5 # Single residue
resid 1:10 # Range (inclusive)
resid 1 5 10:20 # Multiple selections, implicit OR
String keywords (name, resname, chain) accept multiple values and regex patterns:
resname ALA GLY # Multiple residues
name CA CB CG # Multiple atom names
name /C.+/ # Regex pattern: C followed by at least one symbol
chain A /[AB]/ # Chain A or chains matching [AB]
Molecular groups
Pre-defined selections for common molecular groups:
| Keyword | Description |
|---|---|
protein |
All protein atoms |
backbone |
Protein backbone atoms (N, CA, C, O) |
sidechain |
Protein sidechain atoms |
water |
Water molecules |
hydrogen |
All hydrogen atoms |
not_water or now |
All non-water atoms |
not_hydrogen or noh |
All non-hydrogen atoms |
Examples:
protein # All protein atoms
backbone and chain A # Backbone of chain A
water or hydrogen # Water or hydrogens
not hydrogen # Everything except hydrogens
Comparisons
Compare numeric properties using mathematical expressions:
x < 5.0 # X coordinate less than 5
y >= 10.0 and y <= 20.0 # Y between 10 and 20
z 15.0:25.0 # Shorthand for chained comparison
mass > 12.0 # Atomic mass greater than 12
charge != 0.0 # Non-neutral atoms
vdw < 2.0 # Van der Waals radius less than 2
occupancy > 0 # non-zero occupancy
beta > 0.5 # B-factors above 0.5
Comparison operators
==— Equal!=— Not equal<— Less than<=— Less than or equal>— Greater than>=— Greater than or equal
Chained comparisons
Compare between two values:
10 < resid < 20 # Residues between 10 and 20
0 <= x <= 5.0 # X coordinate between 0 and 5
15.0 < y < 25.0 # Y strictly between 15 and 25
Mathematical expressions
Use math operations and functions in comparisons:
sqrt(x^2 + y^2) < 10.0 # Distance from origin in XY plane less than 10
abs(z) > 5.0 # Absolute Z coordinate
sin(x) * 2.0 == 1.0 # Trigonometric operations
Supported functions: abs, sqrt, sin, cos
Geometric expressions
Distance-based selections
Distance to point
dist point [1.0, 2.0, 3.0] < 1.0 # Within 5 Å of a given point
dist pbc point [1.0, 2.0, 3.0] > 2.0 # With periodic boundary conditions
Distance to line
dist line [1,2,3] [4,5,6] < 3.0 # Two points defining the line
dist line [1,2,3] dir [1,0,0] >= 1.3 # Point and direction
Distance to plane
dist plane [0,0,0] [1,0,0] [0,1,0] < 1.0 # Three-point definition
dist plane [0,0,0] normal [0,0,1] < 1.0 # Point and normal
Center of mass/geometry
Calculate geometric properties of selections:
within 5.0 of com of protein # Within 5 Å of protein COM
within 3.0 pbc of cog of chain A # Within 3 Å of chain A COG
within 2.0 of com pbc yyn of water # PBC only in X and Y
within 2.0 of com pbc 110 of water # PBC only in X and Y
PBC options
Periodic boundary condition modes for geometric expressions:
pbc— Apply PBC in all dimensionspbc 1 0 1orpbc yny— Apply PBC selectively (X, Y, Z), spaces are optionalnopbc— No periodic boundary conditions (default)
Logical operators
Combine selections using logical operations:
| Operator | Description | Example |
|---|---|---|
and |
Both conditions true | name CA and chain A |
or |
Either condition true | resname ALA or resname GLY |
not |
Negate condition | not water |
Operator precedence (highest to lowest)
not— Negationsame ... as— Same residue/chainwithin ... of— Distance selectionsand— Logical ANDor— Logical OR
Parentheses can be used to override precedence:
(resname ALA or resname GLY) and backbone # Parentheses for clarity
name CA or (name CB and chain A) # Different grouping
Same residue/chain
Select atoms in the same residue or chain as matched atoms:
same residue as name CB # All atoms in residues containing CB atoms
same chain as resid 5 # All atoms in chains containing residue 5
Complete examples
// Simple selections
"name CA" // Alpha carbons
"resname ALA" // Alanine residues
"chain A" // Chain A
// Combined with logic
"protein and backbone" // Protein backbone
"not water and not hydrogen" // Non-water, non-hydrogen
"(resname ALA or resname GLY) and backbone"
// Numeric comparisons
"x < 0 and y < 0" // Negative X and Y
"10 < resid < 20" // Residues 10-20
// Geometric selections
"within 5.0 of [0, 0, 0]" // Within 5 Å of origin
"within 3.0 pbc of com of protein" // Near protein center of mass with pbc
"same residue as within 2.0 of com of water" // Residues near water
// Complex combined
"backbone and chain A and resid 1:50"
"(protein or water) and within 10.0 of com of protein"
Tutorial
We will write an example program that reads a file of some molecular system containing TIP3P water molecules, convert all water to TIP4P and saves this as a new file. TIP3P water has 3 particles (oxygen and two hydrogens), while TIP4P has 4 (oxygen, two hydrogens and a dummy particle). Our goal is to add these dummy particles to each water molecule.
Preparing the stage
First, let's create a new Rust project called tip3to4:
cargo new tip3to4
Then, let's add dependencies: the MolAR itself and anyhow crate for easy error reporting:
cargo add molar anyhow
In src/main.rs add needed boilerplate:
// For processing command line arguments
use env;
// Import all basic things from molar
use *;
// For error handling
use Result;
Now we can start writing our program.
Reading an input file
The simples way of loading the molecular system in MolAR is to use a Source - an object that holds a Topology and State of the system and is used to create atom selections for manipulating this data:
// Load the source file from the first command line argument
let src = from_file?;
The file type (PDB, GRO, etc) is automatically recognized by its extention.
If reading the file fails for whatever reason the ? operator will return an error, which will be nicely printed by anyhow crate.
Making selections
Now we need to select all waters that are going to be converted to TIP4. We also need to select all non-water part of the system to keep it as is.
In MolAR selection (Sel) is just a list of atom indexes, which has to be "bound" to the System to do useful work using system.bind(&sel) for read-only acces or
system.bind_mut(&sel) for read-write access. There are also convenience methods that produce bound selection right away. This is useful if you know that you won't re-bind the same System for different type of access often.
let water = sys.select_bound?;
let non_water = sys.select_bound?;
Selections are created with the syntax that is very similar to one used in VMD Pteros and Gromacs. Here we select water and non-water by residue name.
In MolAR empty selections are not permitted, so if no atoms are selected (or if anything else goes wrong) the error will be reported.
Looping over indiviudual water molecules
We selected all water molecules as a single selection but we need to loop over individual water molecules to add an additional dummy particle to each of them. In order to do this we are splitting a selection to fragments by the residue index:
// Go over water molecules one by one
for mol in water.split_resindex_bound
The method split_resindex_bound() returns a Rust iterator, which produces contigous bound selections containig distinct residue index each. There are many other ways of splitting selections into parts using arbitrary logic in MolAR, but this simplest one is what we need now.
Working with coordinates
Now we need to get the coordinates of atoms for current water molecules and compute a position of the dummy atom.
// Go over water molecules one by one
for mol in water.split_resindex_bound
First, we are getting the coordinates of oxigen and two hydrogens. get_pos(n) returns the position of n-th atom in selection. Since n may potentially be out of range, it returns an Option<&Pos>. We are sure that there are just 3 atoms in water molecule, so we just unwrapping an option.
Then we are computing the position of the dummy atom, which is on the bisection of H-O-H angle at the distance of 0.01546 from the oxygen.
Finally, we are constructing a new Atom with name 'M', residue name 'TIP4' and all other fields (resid,resindex, etc) the same as in our water molecule.
We are printing our new dummy atom and its position just to be sure that everything works as intended.
Constructing output system
All this is fine, but we still have no system to write our converted water molecules to. Let's fix this and modify the beginning of our main funtion like this:
// Load the source file from the first command line argument
let sys = from_file?;
// Make empty output system
let mut out = default;
The first thing that we add to out new empty system is all non-water atoms:
// Add non-water atoms to the output
out.append;
Now, at the end of our loop over water molecules, we can add new dummy atoms properly to the new system:
// Add new converted water molecule
// We assume that the dummy is the last atom.
let added = out.append_coords?;
This code snippet may look a bit puzzling for non-rustaceans, so let's go through it.
append_atoms()method accepts two iterators: the first yielding atoms and the second yielding their corresponding coordinates.- Our selected water molecule
molhas methodsiter_atoms()anditer_pos()for getting these iterators. cloned()adaptor is used to get copies of existing atoms and coordinates instead of references to them.- We add our new dummy atom at the end of water molecule by "chaining" another iterator at the end of the current one.
std::iter::once(value)returns an iterator yielding a single value and allows us to add newly constructedm_atandm_posto the corrsponding iterators.
We also need to change the resname of the old atoms of water molecule from TIP3 to TIP4. As you noticed, append_atoms_coords() returns a selection with added atoms, so we can bind it mutably to the output system and set new residue name:
// Change resname for added atoms
// Note the use of bind_mut()!
out.bind_mut.set_same_resname;
Writing the output file
Out output system is now fully constructed but it still lacks an important element - the periodic box description. Most molecular systems originating from MD are periodic and the information about the periodic box has to be copied to our newly constructed system:
// Transfer the box from original file
out.set_box_from;
Here we provide a reference to the input system, so the box is cloned from it to the output system.
Finally we are ready to write the output file:
// Write out new system
out.save?;
Again, file format will be determined by extension. The file name is provided by the second command line argument.
The final result
The complete program looks like this:
// For processing command line arguments
use env;
// Import all baic things from molar
use *;
// For error handling
use Result;
Doing things in parallel
Iterating in parallel within selection
You can iterate over coordinates, atoms and particles within the selection in parallel using "par" versions of the corresponding iterators:
// Import all basic things from molar
use *;
// For error handling
use Result;
Parallel splits
You may perform operations on non-overlapping selections in parallel, which typically gives a huge speed up in such tasks as removing periodicity for individual molecules, which are rather heavy computationally.
Here is how you can do this:
// Import all baic things from molar
use *;
// For error handling
use Result;
Analysis tasks
Motivation
The vast majority of molecular dynamics trajectory analysis tasks follows the same pattern:
- Do initialization and pre-processing (read and process the parameters, allocate and initialize data structures, create atom selections, etc.)
- On each trajectory frame call an analysis function, which computes needed properties.
- Do post-processing (compute averages, write results to file).
Reading trajectories themselves also requires some standard options:
- Ability to start from given frame or time stamp.
- Ability to stop at given frame or time stamp.
- Ability to read each N-th frame (decimation).
- Ability to report the progress with given periodicity.
These patterns are so common that it very quickly become annoynig and repetitive to implement them from scratch for each analysis task. That is why MolAR provides [AnalysisTask] trait, which automates all the common steps and takes care of all the boilerplate.
Implementing analysis tasks
Here is an example of implementing custom analysis task, which prints a center of mass for a user provided selection on each frame and also computes an average center of mass over the trajectory:
// Import all basic things from molar
use *;
// For error handling
use Result;
// For processing custom command line arguments
use Args;
// User-defined command line arguments
// Our analysis task type
// Implement AnalysisTask trait
// The type with custom parameters is provided as generic parameter
// Run our task
Trajectory processing aguments
All analysis tasks accept a number of common command line arguments (see [TrajAnalysisArgs]) allowing to select which frames to process and which files to read.
For example, the following command line will run our analysis task sequencially for two trajectories starting from frame 150 and ending when reaching 100 ns, while reporting progress each 100 frames. Custom selection is provided in the --sel argument, which is declared and recognised by ComTask
analysis_task -f structure.pdb traj_1.xtc traj_2.xtc -b 150 -e 100ns -log 100 --sel "resid 10:20"
Python bindings
MolAR provides convenient Python bindings, creatively named pymolar, which has its own "Pythonic" API. The bindings are made as performant as possible, but they are not as fast as the Rust functions.
Installation
It is highly recommended to use a Python virtual environment. It is assumed that pip is used for installation, but you can use any Python package manager.
#1. Install maturin in the current virtual environment
pip install maturin
#2. Go to molar_python subfolder of molar source tree
cd <path_to_molar>/molar_python
#3. Compile the bindings
maturin build -r
#4. Install the bindings in the current virtual environment
python -m pip install .
Usage
Pymolar bindings could be used in two modes: manual and as analysis tasks. In the first case you have a full fine-grained control on how you read your input files, but this may involve a lot of boilerplate. In contrast, "analysis tasks" hide most of the input handling from the user providing a very simple command-line interface to load structure and trajectory files, skip frames, begin and end reading at particular frame or time stamp, etc. The user only needs to implement three methods: pre_process, process_frame and post_process, which are called during the analysis.
As an example we will write a script that prints center of mass of CA protein atoms on each trajectory frame and then computes the average center of masses for the whole trajectory:
#file: average.py
# Import pymolar
# Create an analysis task
# Register a custom command line argument for selection
# This method is called before starting trajectory processing
# Create a selection using selection string from the command line
# self.src contains a Source with the first state read
=
# Average center of masses
=
# This method is called on each trajectory frame
=
+=
# This method is called after trajectory processing is finished
/=
# Run the analysis task.
This script can be run as following:
python3 average.py -f struct.gro traj.xtc -e 100 --sel "resid 1:10"