# MicrographCleaner
**MicrographCleaner** (micrograph_cleaner_em) is a python package designed to segment cryo-EM
micrographs into:
- carbon/high-contrast or contaminated regions
- good regions
so that incorrectly picked coordinates can be easily ruled out
To get a complete description of usage execute
`cleanMics -h`
##### Example
`cleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b 180 -s 1.0 -i /path/to/micrographs/ --predictedMaskDir path/to/store/masks --deepThr 0.5`
## INSTALLATION:
### anaconda (recommended if NVIDIA GPU available )
If your system have no GPUs available, see the pip installation instead
1) Install anaconda Python 3x version from https://www.anaconda.com/distribution/
2) Create an environment for MicrographCleaner
`conda create -n env_micrograph_cleaner_em python=3.6`
3) Activate environment (each time you want to use micrograph_cleaner you will need to activate it)
`conda activate env_micrograph_cleaner_em`
4) Install micrograph_cleaner_em from repository
` conda install -c rsanchez1369 -c anaconda -c conda-forge micrograph-cleaner-em`
5) Download deep learning model
`cleanMics --download`
6) Ready!
### pip/source option:
1) install CUDA and cudnn in such a way that tensorflow (https://www.tensorflow.org/) can be executed.
micrograph_cleaner is compatible with CUDA-9 and CUDA-10.
Tensorflow version will be automatically selected according your CUDA version and installed later.
CUDA is available at https://developer.nvidia.com/cuda-toolkit and cudnn is available at
https://developer.nvidia.com/cudnn.
Easy cudnn instalation can be performed automatically at step 2 using python module cudnnenv
1.1) (optional) create virtual environment
```
pip install virtualenv
virtualenv --system-site-packages -p python3 ./env_micrograph_cleaner_em
source ./env_micrograph_cleaner_em/bin/activate
```
2) Install micrograph_cleaner_em
```
git clone https://github.com/rsanchezgarc/micrograph_cleaner_em.git
cd micrograph_cleaner_em
python setup.py install
```
or
`pip install micrograph_cleaner_em`
2.1) If cudnn not installed yet, install install cudnnenv
`pip install cudnnenv`
and execute
`cudnnenv install [VERSION]`, where recommended versions are "v6-cuda8" for CUDA-8, "v7.0.1-cuda9" for CUDA-9 and
"v7.4.1-cuda10" for CUDA-10.
3) Download deep learning model
`cleanMics --download`
4) Ready!
### scipion option:
1) Install scipion version 2.0+ from http://scipion.i2pc.es/
2) Install xmipp either from plugin manager or from command line
`scipion installp -p scipion-em-xmipp`
3) Install deepLearningToolkit either from plugin manager or from command line
`scipion installb deepLearningToolkit`
4) Ready!
## USAGE
MicrographCleaner employs an U-net-based deep learning model to segmentate micrographs into good regions and bad regions. Thus, it is mainly used as a post-processing step after particle picking in which coordinates selected in high contrast artefacts, such as carbon, will be ruled out. Additionally, it can be employed to generate binary masks so that particle pickers can be prevented from considering problematic regions.
Thus, micrograph_cleaner employs as a mandatory argument a(some) micrograph(s) fileneame(s) and the particle size in pixels (with respect input mics). Additionally it can recive as input:
1) A directory where picked coordinates are located and another directory where scored/cleaned coordiantes will be saved. Coordinates will be saved in pos format or plain text (columns whith header colnames x and y) are located.
There must be one different coordinates file for each micrograph named as the micrograph and the output coordiantes will preserve the naming.
E.g. -c path/to/inputCoordsDirectory/ -o /path/to/outputCoordsDirectory/
Allowed formats are xmipp pos, relion star and raw text tab separated with at least two columns named as xcoor, ycoor in the header.
Raw text file example:
```
micFname1.tab:
###########################################
xcoor ycoor otherInfo1 otherInfo2
12 143 -1 0.1
431 4341 0 0.2
323 321 1 0.213
###########################################
```
2) A directory where predicted masks will be saved (mrc format).
E.g. --predictedMaskDir path/where/predictedMasksWillBeSaved/
3) A downsampling factor (can be less than 1 if actually upsampling was performed) in case the coordinates where picked from
micrographs at different scale.
E.g. -s 2 will downsample coordinates by a factor 2 and then it will apply the predicted mask that is as big as the input micrographs. This
case corresponds to an example in which we use for particle picking raw micrographs but we are using MicrographCleaner with downsampled mics
4) Any combination of previous options.
Trained MicrographCleaner model is available at http://campins.cnb.csic.es/micrograph_cleaner/ and can be automatically download executing
`cleanMics --download`
Beware that if you installed micrograph_cleaner using pip/source, then CUDA and cudnn libraries should be
available prior execution, so if CUDA is not found, export its path prior execution
```
export LD_LIBRARY_PATH=/path/to/cuda/cuda-9.0/lib64:$LD_LIBRARY_PATH
```
and then execute `cleanMics` program
#### Examples
```
#Donwload deep learning model
cleanMics --download
#Compute masks from imput micrographs and store them
cleanMics -b $BOX_SIXE -i /path/to/micrographs/ --predictedMaskDir path/to/store/masks
#Rule out input bad coordinates (threshold<0.5) and store them into path/to/outputCoords
cleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b $BOX_SIXE -s $DOWN_FACTOR -i /path/to/micrographs/ --deepThr 0.5
#Compute goodness scores from input coordinates and store them into path/to/outputCoords
cleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b $BOX_SIXE -s $DOWN_FACTOR -i /path/to/micrographs/ --deepThr 0.5
```
## API:
The fundamental class employed within MicrographCleaner is MaskPredictor, a class designed to predict a contamination/carbon
mask given a micrograph.
##### class micrograph_cleaner_em.MaskPredictor
Usage: predicts masks of shape HxW given one numpy array of shape HxW that represents a micrograph.
Mask values range from 0. to 1., being 0. associated to clean regions and 1. to contamination.
##### builder
```
micrograph_cleaner_em.MaskPredictor(boxSize, deepLearningModelFname=DEFAULT_PATH , gpus=[0], strideFactor=2)
:param boxSize (int): estimated particle boxSize in pixels
:param deepLearningModelFname (str): a path where the deep learning model will be loaded. DEFAULT_PATH="~/.local/share/micrograph_cleaner_em/models/defaultModel.keras"
:param gpus (list of gpu ids (ints) or None): If None, CPU only mode will be employed.
:param strideFactor (int): Overlapping between windows. Micrographs are divided into patches and each processed individually.
The overlapping factor indicates how many times a given row/column is processed by the network. The
bigger the better the predictions, but higher computational cost.
```
##### methods
```
predictMask(self, inputMic, preproDownsampleMic=1, outputPrecision=np.float32):
Obtains a contamination mask for a given inputMic
:param inputMic (np.array shape HxW): the micrograph to clean
:param preproDownsampleMic: the downsampling factor applied to the micrograph before processing. Make it bigger if
large carbon areas are not identified
:param outputPrecision: the type of the floating point number desired as input. Default float32
:return: mask (np.array shape HxW): a mask that ranges from 0. to 1. ->
0. meaning clean area and 1. contaminated area.
```
```
getDownFactor(self):
MaskPredictor preprocess micrographs before Nnet computation. First step is donwsampling using a donwsampling factor
that depends on particle boxSize. This function computes the downsampling factor
:return (float): the donwsampling factor that MaskPredictor uses internally when preprocessing the micrographs
close(self):
Used to release memory
```
##### example
The following lines show how to compute the mask for a given micrograph
```
import numpy as np
import mrcfile
import micrograph_cleaner_em as mce
boxSize = 128 #pixels
# Load the micrograph data, for mrc files you can use mrcifle
# but you can use any other method that return a numpy array
with mrcfile.open('/path/to/micrograph.mrc') as mrc:
mic = mrc.data
# By default, the mask predictor will try load the model at
# "~/.local/share/micrograph_cleaner_em/models/"
# provide , deepLearningModelFname= modelPath argument to the builder
# if the model is placed in other location
with mce.MaskPredictor(boxSize, gpus=[0]) as mp:
mask = mp.predictMask(mic) #by default, mask is float32 numpy array
# Then write the mask as a file
with mrcfile.new('mask.mrc', overwrite=True) as maskFile:
maskFile.set_data(mask.astype(np.half)) # as float
```
Raw data
{
"_id": null,
"home_page": "https://github.com/rsanchezgarc/micrograph_cleaner_em",
"name": "micrograph-cleaner-em",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "cryo-EM deep learning",
"author": "Ruben Sanchez-Garcia",
"author_email": "rsanchez@cnb.csic.es",
"download_url": "https://files.pythonhosted.org/packages/0d/32/6d7a003b769afc0752f947f5cc593ed06abe806c3ded222376cccc25e1db/micrograph_cleaner_em-0.37.tar.gz",
"platform": null,
"description": "# MicrographCleaner\n**MicrographCleaner** (micrograph_cleaner_em) is a python package designed to segment cryo-EM\n micrographs into:\n\n - carbon/high-contrast or contaminated regions \n - good regions\n \nso that incorrectly picked coordinates can be easily ruled out\n\nTo get a complete description of usage execute\n\n`cleanMics -h`\n\n##### Example\n\n`cleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b 180 -s 1.0 -i /path/to/micrographs/ --predictedMaskDir path/to/store/masks --deepThr 0.5`\n\n\n## INSTALLATION:\n\n### anaconda (recommended if NVIDIA GPU available )\n If your system have no GPUs available, see the pip installation instead\n1) Install anaconda Python 3x version from https://www.anaconda.com/distribution/\n\n2) Create an environment for MicrographCleaner \n `conda create -n env_micrograph_cleaner_em python=3.6`\n\n3) Activate environment (each time you want to use micrograph_cleaner you will need to activate it) \n `conda activate env_micrograph_cleaner_em`\n \n4) Install micrograph_cleaner_em from repository \n ` conda install -c rsanchez1369 -c anaconda -c conda-forge micrograph-cleaner-em`\n\n5) Download deep learning model \n `cleanMics --download`\n\n6) Ready!\n \n### pip/source option:\n\n\n1) install CUDA and cudnn in such a way that tensorflow (https://www.tensorflow.org/) can be executed. \n micrograph_cleaner is compatible with CUDA-9 and CUDA-10.\n Tensorflow version will be automatically selected according your CUDA version and installed later.\n CUDA is available at https://developer.nvidia.com/cuda-toolkit and cudnn is available at\n https://developer.nvidia.com/cudnn. \n Easy cudnn instalation can be performed automatically at step 2 using python module cudnnenv\n\n1.1) (optional) create virtual environment \n```\npip install virtualenv\nvirtualenv --system-site-packages -p python3 ./env_micrograph_cleaner_em\nsource ./env_micrograph_cleaner_em/bin/activate\n```\n2) Install micrograph_cleaner_em \n```\ngit clone https://github.com/rsanchezgarc/micrograph_cleaner_em.git\ncd micrograph_cleaner_em\npython setup.py install\n```\n or \n`pip install micrograph_cleaner_em`\n\n2.1) If cudnn not installed yet, install install cudnnenv \n`pip install cudnnenv` \n \n and execute \n`cudnnenv install [VERSION]`, where recommended versions are \"v6-cuda8\" for CUDA-8, \"v7.0.1-cuda9\" for CUDA-9 and\n\"v7.4.1-cuda10\" for CUDA-10. \n \n3) Download deep learning model \n`cleanMics --download`\n \n4) Ready! \n\n### scipion option:\n\n1) Install scipion version 2.0+ from http://scipion.i2pc.es/ \n\n2) Install xmipp either from plugin manager or from command line \n `scipion installp -p scipion-em-xmipp` \n\n3) Install deepLearningToolkit either from plugin manager or from command line \n `scipion installb deepLearningToolkit` \n\n4) Ready!\n\n## USAGE\n\nMicrographCleaner employs an U-net-based deep learning model to segmentate micrographs into good regions and bad regions. Thus, it is mainly used as a post-processing step after particle picking in which coordinates selected in high contrast artefacts, such as carbon, will be ruled out. Additionally, it can be employed to generate binary masks so that particle pickers can be prevented from considering problematic regions.\nThus, micrograph_cleaner employs as a mandatory argument a(some) micrograph(s) fileneame(s) and the particle size in pixels (with respect input mics). Additionally it can recive as input:\n\n1) A directory where picked coordinates are located and another directory where scored/cleaned coordiantes will be saved. Coordinates will be saved in pos format or plain text (columns whith header colnames x and y) are located. \nThere must be one different coordinates file for each micrograph named as the micrograph and the output coordiantes will preserve the naming. \nE.g. -c path/to/inputCoordsDirectory/ -o /path/to/outputCoordsDirectory/ \nAllowed formats are xmipp pos, relion star and raw text tab separated with at least two columns named as xcoor, ycoor in the header.\nRaw text file example:\n```\nmicFname1.tab:\n###########################################\nxcoor ycoor otherInfo1 otherInfo2\n12 143 -1 0.1\n431 4341 0 0.2\n323 321 1 0.213\n###########################################\n```\n2) A directory where predicted masks will be saved (mrc format).\nE.g. --predictedMaskDir path/where/predictedMasksWillBeSaved/ \n\n3) A downsampling factor (can be less than 1 if actually upsampling was performed) in case the coordinates where picked from\nmicrographs at different scale.\nE.g. -s 2 will downsample coordinates by a factor 2 and then it will apply the predicted mask that is as big as the input micrographs. This\ncase corresponds to an example in which we use for particle picking raw micrographs but we are using MicrographCleaner with downsampled mics \n\n4) Any combination of previous options. \n\nTrained MicrographCleaner model is available at http://campins.cnb.csic.es/micrograph_cleaner/ and can be automatically download executing \n`cleanMics --download`\n\n\nBeware that if you installed micrograph_cleaner using pip/source, then CUDA and cudnn libraries should be\navailable prior execution, so if CUDA is not found, export its path prior execution \n```\nexport LD_LIBRARY_PATH=/path/to/cuda/cuda-9.0/lib64:$LD_LIBRARY_PATH\n```\nand then execute `cleanMics` program \n\n#### Examples\n\n```\n#Donwload deep learning model\ncleanMics --download\n \n#Compute masks from imput micrographs and store them\ncleanMics -b $BOX_SIXE -i /path/to/micrographs/ --predictedMaskDir path/to/store/masks\n\n#Rule out input bad coordinates (threshold<0.5) and store them into path/to/outputCoords\ncleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b $BOX_SIXE -s $DOWN_FACTOR -i /path/to/micrographs/ --deepThr 0.5\n\n#Compute goodness scores from input coordinates and store them into path/to/outputCoords\ncleanMics -c path/to/inputCoords/ -o path/to/outputCoords/ -b $BOX_SIXE -s $DOWN_FACTOR -i /path/to/micrographs/ --deepThr 0.5 \n```\n\n## API:\n\n\nThe fundamental class employed within MicrographCleaner is MaskPredictor, a class designed to predict a contamination/carbon\nmask given a micrograph.\n\n\n##### class micrograph_cleaner_em.MaskPredictor\n\nUsage: predicts masks of shape HxW given one numpy array of shape HxW that represents a micrograph.\nMask values range from 0. to 1., being 0. associated to clean regions and 1. to contamination.\n\n\n##### builder\n```\nmicrograph_cleaner_em.MaskPredictor(boxSize, deepLearningModelFname=DEFAULT_PATH , gpus=[0], strideFactor=2)\n \n :param boxSize (int): estimated particle boxSize in pixels\n :param deepLearningModelFname (str): a path where the deep learning model will be loaded. DEFAULT_PATH=\"~/.local/share/micrograph_cleaner_em/models/defaultModel.keras\"\n :param gpus (list of gpu ids (ints) or None): If None, CPU only mode will be employed.\n :param strideFactor (int): Overlapping between windows. Micrographs are divided into patches and each processed individually.\n The overlapping factor indicates how many times a given row/column is processed by the network. The \n bigger the better the predictions, but higher computational cost.\n```\n\n##### methods\n\n\n```\npredictMask(self, inputMic, preproDownsampleMic=1, outputPrecision=np.float32):\n Obtains a contamination mask for a given inputMic\n\n :param inputMic (np.array shape HxW): the micrograph to clean\n :param preproDownsampleMic: the downsampling factor applied to the micrograph before processing. Make it bigger if\n large carbon areas are not identified\n :param outputPrecision: the type of the floating point number desired as input. Default float32\n :return: mask (np.array shape HxW): a mask that ranges from 0. to 1. ->\n 0. meaning clean area and 1. contaminated area.\n```\n\n```\ngetDownFactor(self):\n MaskPredictor preprocess micrographs before Nnet computation. First step is donwsampling using a donwsampling factor\n that depends on particle boxSize. This function computes the downsampling factor\n \n :return (float): the donwsampling factor that MaskPredictor uses internally when preprocessing the micrographs\n \nclose(self):\n Used to release memory\n```\n\n##### example\nThe following lines show how to compute the mask for a given micrograph\n\n```\nimport numpy as np\nimport mrcfile\nimport micrograph_cleaner_em as mce\n\nboxSize = 128 #pixels\n\n# Load the micrograph data, for mrc files you can use mrcifle\n# but you can use any other method that return a numpy array\n\nwith mrcfile.open('/path/to/micrograph.mrc') as mrc:\n mic = mrc.data\n\n# By default, the mask predictor will try load the model at \n# \"~/.local/share/micrograph_cleaner_em/models/\"\n# provide , deepLearningModelFname= modelPath argument to the builder \n# if the model is placed in other location \n\nwith mce.MaskPredictor(boxSize, gpus=[0]) as mp:\n mask = mp.predictMask(mic) #by default, mask is float32 numpy array\n \n# Then write the mask as a file\n\nwith mrcfile.new('mask.mrc', overwrite=True) as maskFile:\n maskFile.set_data(mask.astype(np.half)) # as float\n```",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Deep learning for cryo-EM micrograph cleaning",
"version": "0.37",
"project_urls": {
"Homepage": "https://github.com/rsanchezgarc/micrograph_cleaner_em"
},
"split_keywords": [
"cryo-em",
"deep",
"learning"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "0d326d7a003b769afc0752f947f5cc593ed06abe806c3ded222376cccc25e1db",
"md5": "df8d86060eda1a9417bdd41aaaeeb777",
"sha256": "26c551341750cf55eef458c3c74de145e0b3be6ef256ff5d83dce8de58783bad"
},
"downloads": -1,
"filename": "micrograph_cleaner_em-0.37.tar.gz",
"has_sig": false,
"md5_digest": "df8d86060eda1a9417bdd41aaaeeb777",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 19633,
"upload_time": "2024-09-09T21:18:33",
"upload_time_iso_8601": "2024-09-09T21:18:33.550696Z",
"url": "https://files.pythonhosted.org/packages/0d/32/6d7a003b769afc0752f947f5cc593ed06abe806c3ded222376cccc25e1db/micrograph_cleaner_em-0.37.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-09 21:18:33",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "rsanchezgarc",
"github_project": "micrograph_cleaner_em",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "micrograph-cleaner-em"
}