Membrane-aware MiLoPYP tutorial (beta)

This tutorial explains the workflow for surface-constrained MiLoPYP and demonstrates the full pipeline by detecting spike proteins from SARS-CoV-2 virions.

Dataset

We will use 10 tilt-series from EMPIAR-10453 . The data were acquired using a Titan Krios with a K2 detector in counting mode. The pixel size is 1.329 Å and the tilt range is from -60° to +60° with a 3° increment.

To download the subset of 10 tilt-series, run the following command in your terminal:

for i in 049 050 071 121 162 244 271 288 291 297;
do
    wget --no-directories ftp://ftp.ebi.ac.uk/empiar/world_availability/10453/data/tilt_series/TS_${i}.mrc;
done

Note

The subset of tilt-series was chosen randomly, you are free to hand-pick other tomograms or use less/more.

Preparation

Step 1. Import raw tilt-series
  • Click Import Data, open the Tomography tab, and choose Raw Data. The new block appears on the project page

  • Open the Parameters tab (double-click the block on the project page, or use Actions → Edit). On the Sources tab:

    • Click Add path and browse to the folder where you downloaded the tilt-series

    • Type *.mrc into the filter box (lower right) and click the icon

    • Click Choose File Pattern to add the path

  • On the Grouping tab:

    • Enable No movie frames (these are single-image tilts)

  • On the Microscope parameters tab:

    • Set Pixel size (A) to 1.329

    • Set Acceleration voltage (kV) to 300

    • Set Tilt-axis angle (degrees) to 84.8

  • Click Run

  • After the run finishes, the View tab is populated and a thumbnail is displayed inside the block on the project page. Later runs update the View tab and block thumbnail the same way

Step 2. Pre-processing

We will create two pre-processing blocks with slightly different parameters as the best parameters for segmentation quality and particle picking can be different.

  • Click on Tilt-series (output of the Tomography (from Raw Data) block) and select Pre-processing. The new block appears on the project page

  • First block (for segmentation):

    • Open the Parameters tab. (There is no Frame alignment tab because import enabled No movie frames.)

    • On the CTF determination tab:

      • Set Max resolution (A) to 10

    • On the Tilt-series alignment tab:

      • Disable Reshape tilt-images into squares

    • On the Tomogram reconstruction tab:

      • Set Tomogram thickness (unbinned voxels) to 1536

      • Set 2D filtering to “none”

      • Enable Erase fiducials

      • Set High-frequency filtering to “hamming (as in tomo3d)”

  • Second block (for particle picking):

    Use the same parameters as the previous block except:

    • On the Tomogram reconstruction tab:

      • Set Radial filtering to “fakeSIRT (mimic SIRT reconstruction)”

Segmentation

Segmentation quality is very important and can affect all downstream tasks as we use binary segmentations for surface constraints.

Calculating segmentations

We will again create two different blocks. One of them will not have any filtering while the other one will filter out unwanted connected components. We are doing this because it can be beneficial to keep unfiltered segmentations as filtering can also remove good components.

  • First block (unfiltered):

    • Click on Tomograms (output of the first Pre-processing block) and select Segmentation (pre-trained models). The new block appears on the project page

    • Open the Parameters tab. On the Tomogram segmentation tab:

      • Set Method to “membrain-seg (membranes)”

        • Enable Pre-process tomograms

          • Set Pixel size rescaling to 11

          • Enable Deconvolution filter

      • Set the Pre-trained model (*.ckpt) to the location of v10_alpha downloaded from membrain-seg GitHub page.

      • Enable Test time augmentation

      • Set Sliding window size to 96

  • Second block (filtered):

    Use the same parameters as the previous block except:

    • On the Tomogram reconstruction tab:

      • Set Filter connected components to “by number”

        • Set Components to keep to 10

      • Set Thickness of slab to keep (unbinned voxels) to 1228

  • Example segmentation:

    ../_images/segmentation_unfiltered.webp
    ../_images/segmentation_filtered.webp
Improving segmentations

Sometimes the segmentations might not be as good as preferred. This mainly happens in two different ways. Either an actual membrane does not get segmented or non-membrane features get segmented. It is possible to experiment with different parameters to improve the results.

  • Pre-processing block:

    Sometimes the parameters that make the particles more prominent actually hurt the segmentation. Because of this, as we did in this tutorial, it can be useful to try different reconstruction methods for segmentation. imod is usually a safe choice, with hamming high-frequency filtering usually improving things even further. Another choice can be to use fakeSIRT with higher number of iterations than the block used for particle picking.

  • Segmentation block:

    Our suggestions for the segmentation parameters are:

    • Pre-processing:

      • Pixel size rescaling:

        It is a good idea to try values between 10 to 12 if your tomograms have different effective pixel sizes, as the membrain-seg models are trained with this range.

      • Deconvolution filter:

        This can help if the SNR of the tomograms is low. Try changing its parameters or disabling if it causes artifacts.

    • Filter connected components:

      • By number:

        This is usually a good choice, especially since it can filter out large connected components, which are usually reconstruction artifacts or carbon edges, while also removing smaller components that are not important.

      • By size:

        This can be a good choice if the membranes have a relatively fixed size or there are too many small artifacts.

    • Thickness of slab to keep (unbinned voxels):

      This can be very useful at filtering out artifacts since most of the artifacts span close to the lower and upper ends of the tomogram. You should choose the smallest thickness you can that would not remove too many features you actually want to keep. In fact, it can be a good idea to keep the actual tomogram thickness slightly larger than necessary, just to have a better chance for this filtering to work well.

    • Test time augmentation:

      This usually helps the segmentations but it makes the processing time longer.

    • Sliding window size:

      This can have different effects depending on the dataset. While it is better to try different values, we find 96 to be good for this dataset. Lowering this value also reduces the memory requirements.

Exploration phase

In the exploration phase, we use the segmentations to automatically filter out the candidate particle locations that are too close or too distant to any surface. We also orient the patches so that they are normal to the surface, making all the spike proteins aligned.

We also use a feature called iterative exploration, which is one of the main strengths of this pipeline. Even after the initial filtering, it can still initially be difficult to cluster all the good patches we want since their numbers are usually quite low compared to bad patches. Luckily, it is usually much easier to cluster bad patches (such as background and carbon edges). We use this to our advantage by doing multiple iterations of exploration, where each iteration removes clusters with bad patches rather than trying to find clusters with only good patches.

Iteration 1
  • Click on Tomograms (output of the second Pre-processing block) and select MiLoPYP (train). The new block appears on the project page

  • Open the Parameters tab. On the Pattern Mining tab:

    • Set Input type to “3D only”

    • Set Epochs to 50

    • Set Bounding box (binned voxels) to 72

    • Set Learning rate to 0.00001

    • Set Interval to perform validation to 5

    • Enable Surface constrained

      • Click next to Segmentation and choose the filtered segmentation block. Later MiLoPYP and particle picking blocks keep Segmentation at auto and use this choice

      • Set Use DoG to “DoG”

      • Set Min distance to 5

      • Set Max distance to 25

      • Enable Remove segmentation

    • Enable Enable Compilation

After we run the block, we can see that we initially have 4,937 patches.

  • Click on MiLoPYP Model (output of the first MiLoPYP (train) block) and select MiLoPYP (eval). The new block appears on the project page

  • Open the Parameters tab. On the Pattern mining tab:

    • Set Trained model (*.pth) to the location of the model you want to evaluate

    • Set Clusters to 30

Tip

If you want to see metrics to evaluate the performance of the model:

  • On the Pattern mining tab:

    • Enable Calculate metrics

The metrics are logged as diagnostic messages, so after the run set the level control in the log to Debug to see them. Refer to the end of this tutorial for their descriptions.

../_images/iteration_1_embedding.webp

UMAP embedding

We can see some patches with the spike proteins in the UMAP embedding but not all of them are close to each other. Meanwhile, bad patches such as the ones centered at the virion, membrane, carbon edge, background, or any other unwanted features seem easier to cluster.

../_images/iteration_1_labels.webp

Cluster embeddings

Here we can see the clusters. Out of all these clusters, we want to keep only the ones that have a membrane at the bottom. However, we need to be conservative at filtering, as we do not want to filter out a cluster that might have good patches this early. We can look at these cluster embeddings to better understand how close the clusters are, which can help us not remove clusters that are too close to a good clusters. However, in general, the cluster matrix is the main tool we will use (the whole matrix is not shown due to its large size).

../_images/iteration_1_matrix_example.webp

Example clusters

Here, we can see that the cluster 15 mostly has patches centered inside the membrane while 16 mostly has background. This means we would prefer to filter them out. Cluster 13 seems to have bad patches as well. However, it also has some patches that seem to be centered at spike proteins. Since we can eliminate bad patches in a future iteration but we cannot recover filtered out good patches, we will act conservatively and keep this cluster.

To not waste too much time, it can be easier to simply keep all clusters that have a membrane at the bottom, without looking at the center. After checking all rows of the matrix, we decide to only keep these clusters:

2, 4, 5, 6, 8, 9, 11, 12, 13, 14, 19, 23, 27, 28
Iteration 2
  • Click on MiLoPYP particles (output of the first MiLoPYP (eval) block) and select MiLoPYP (train). The new block appears on the project page

  • Open the Parameters tab. Use the same parameters as the previous block except:

  • On the Pattern mining tab:

    • Set Epochs to 100

    • Set Interval to perform validation to 10

    • Enable Iterate

    • Set Patch coordinate location to the location of the /train/interactive_info_parquet.gzip file in the first evaluation block.

    • Set Class labels to 2, 4, 5, 6, 8, 9, 11, 12, 13, 14, 19, 23, 27, 28

    After we run the block, we can see that we decreased our patch count from 4,937 to 1,919.

  • Click on MiLoPYP Model (output of the second MiLoPYP (train) block) and select MiLoPYP (eval). The new block appears on the project page

  • Open the Parameters tab. On the Pattern mining tab:

    • Set Trained model (*.pth) to the location of the model you want to evaluate

    • Set Clusters to 40

../_images/iteration_2_embedding.webp

UMAP embedding

We can see that we eliminated a significant amount of bad patches and the good patches take up much more space. There are still some patches that do not seem to have a membrane at the bottom, but they are very scarce, which makes it difficult to filter them out. It is possible to choose a few clusters if filtering out a few true positives is not considered important. However, we will instead skip filtering for this iteration and zoom in to the patch centers in the next iteration.

Iteration 3

In this iteration we decrease the patch size to focus more on the centers, since we already eliminated most of the non-membrane patches.

  • Click on MiLoPYP particles (output of the second MiLoPYP (eval) block) and select MiLoPYP (train). The new block appears on the project page

  • Open the Parameters tab. Use the same parameters as the previous block except:

  • On the Pattern mining tab:

    • Set Epochs to 200

    • Set Bounding box (binned voxels) to 36

    • Set Learning rate to 0.001

    • Set Interval to perform validation to 20

    • Disable Remove segmentation

    • Set Patch coordinate location to the location of the /train/interactive_info_parquet.gzip file in the second evaluation block.

    • Keep Class labels empty

    • Enable Exclude labels

    After we run the block, we can see that our patch count is still 1,919, as we did not do any filtering.

  • Click on MiLoPYP model (output of the third MiLoPYP (train) block) and select MiLoPYP (eval). The new block appears on the project page

  • Open the Parameters tab. On the Pattern Mining tab:

    • Set Trained model (*.pth) to the location of the model you want to evaluate

    • Set Clusters to 50

../_images/iteration_3_embedding.webp

UMAP embedding

Our task now is trying to eliminate patches by focusing on their centers. Specifically, we want to eliminate patches that have a carbon edge, gold particle, artifact, or simply nothing at all, latter of which can be more difficult.

When we look at the cluster matrix, we see that there are a lot of clusters that seem to have bad patches but also some patches with spike proteins, which we would like to keep. As such, we have three options:

  1. Stop the iterations and continue to refinement phase with what we have.

  2. Continue iterations while still filtering conservatively, at the cost of having to spend more time.

  3. Continue iterations but become less conservative at filtering, hoping that we do not filter out too many good patches.

We will do the third option to save time while also showing one more iteration.

After checking all rows of the matrix, we decide to filter out these clusters:

0, 1, 3, 5, 9, 12, 16, 17, 20, 21, 24, 25, 28, 32, 33, 35, 38, 39, 41, 49
Iteration 4

In this iteration we decrease the patch size even further to focus on the spike proteins.

  • Click on MiLoPYP particles (output of the third MiLoPYP (eval) block) and select MiLoPYP (train). The new block appears on the project page

  • Open the Parameters tab. Use the same parameters as the previous block except:

  • On the Pattern mining tab:

    • Set Bounding box (binned voxels) to 24

    • Set Patch coordinate location to the location of the /train/interactive_info_parquet.gzip file in the third evaluation block.

    • Set Class labels to 0, 1, 3, 5, 9, 12, 16, 17, 20, 21, 24, 25, 28, 32, 33, 35, 38, 39, 41, 49

    After we run the block, we can see that we further decreased our patch count from 1,919 to 1,159.

  • Click on MiLoPYP model (output of the fourth MiLoPYP (train) block) and select MiLoPYP (eval). The new block appears on the project page

  • Open the Parameters tab. On the Pattern mining tab:

    • Set Trained model (*.pth) to the location of the model you want to evaluate

    • Set Clusters to 60

../_images/iteration_4_embedding.webp

UMAP embedding

We successfully eliminated all patches that were clearly bad. We can still see some patches with no obvious spike protein, but it’s not easy to discriminate if they are actually background or just faint or noisy spikes. Nevertheless, we get to filter clusters once more without doing one more iteration before moving onto the refinement phase, so we try to eliminate as much as we can, including patches with carbon edges and artifacts.

After checking all rows of the matrix, we decide to filter out these clusters:

6, 7, 15, 17
Exploration phase summary

We did 4 iterations for the exploration phase in this tutorial. However, the strategies can be changed depending on the preferred trade off between time and accuracy. If the refinement phase is going to be used, then it is less problematic to delete some amount of true positives or keep small amount of false positives. If not, then it is likely better to be more careful during the iterations, and possibly change the parameters such as min/max distance or DoG sizes to start with more candidate locations.

Embeddings:

../_images/no_surface_embedding.webp
../_images/iteration_1_embedding.webp
../_images/iteration_2_embedding.webp
../_images/iteration_3_embedding.webp
../_images/iteration_4_embedding.webp

Example Tomograms:

../_images/no_surface_tomogram.webp
../_images/iteration_1_tomogram.webp
../_images/iteration_2_tomogram.webp
../_images/iteration_3_tomogram.webp
../_images/iteration_4_tomogram.webp

Refinement phase

Refinement phase also uses the segmentations to constrain particle picking to surfaces. This is done by creating a binary mask based on the distance from the segmentation. This binary mask is then used to filter input and output coordinates, in the loss function, or to modify the input tomograms to directly remove any signal outside the mask.

Refinement
  • Click on MiLoPYP particles (output of the fourth MiLoPYP (eval) block) and select Particle picking (train). The new block appears on the project page

  • Open the Parameters tab. On the Training/Evaluation tab:

    • Set Coordinates for training to “class labels from MiLoPYP”

      • Set Class IDs to 0,1,2,3,4,5,8,9,10,11,12,13,14,16,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59

    • Set Epochs to 25

    • Set Max number of particles to 300

    • Set Learning rate to 0.001

    • Set Validation interval (epochs) to 3

    • Enable Use masking

      • Keep Segmentation at auto to use the segmentation chosen for MiLoPYP, or click and choose another segmentation block (for example the unfiltered one if your filters eliminate too many good components, you do not have many false positives from exploration phase, or you simply do not want to filter too much)

      • Set Mask radius to 25

    • Enable Enable compilation

      • Set Compile mode to “max autotune”

After we run the block, we can see that we further decreased our patch count from 1,159 to 1,083.

This block usually takes a while to run. You can increase or decrease the epoch count or the patch downscaling based on available time.

  • Click on Particles model (output of the Particle picking (train) block) and select Particle picking (eval). The new block appears on the project page

  • Open the Parameters tab. Use the same parameters as the previous block except:

  • On the Training/Evaluation tab:

    • Set Trained model (*.pth) to the location of the model you want to evaluate

    • Set Particle radius (A) to 80

    • Set Threshold for soft/hard positives 0.85

Metrics

Exploration metrics
  • mean_std_norm:

    Average per-dimension standard deviation of L2-normalized embeddings. Very low values indicate possibly degenerate embeddings.

  • pairwise_cosine:

    Cosine similarities of randomly sampled embeddings. High values indicate that embeddings are close to each other.

  • nearest_neighbor_cosine:

    Cosine similarities of nearest neighbors of randomly sampled embeddings. Very high values indicate many near-identical embeddings.

  • participation_ratio:

    Effective dimensionality of the embeddings. Low values indicate most of the variability in the embeddings are concentrated in only a few directions.

  • within_cos:

    Average cosine similarity to the cluster centroid. Higher values indicate tighter clusters.

  • between_cos:

    Average cosine similarity between cluster centroids. Lower values indicate better seperated clusters.

  • gap:

    within_cos - between_cos, higher values generally indicate better clustering.

  • davies_bouldin:

    Davies–Bouldin index on the clusters. Lower values indicate better clustering.

  • calinski_harabasz:

    Calinski–Harabasz index on the clusters. Higher values indicate better clustering.

  • centroid_participation_ratio:

    Effective dimensionality of the cluster centroids. Low values indicate most of the variability in the clusters are concentrated in only a few directions.

  • ari_mean:

    Average Adjusted Rand Index across repeated clusterings. Higher values indicate more consistent clustering.

  • ari_std:

    Standard deviation of Adjusted Rand Index across repeated clusterings. Lower values indicate more consistent clustering.