IMP logo
IMP Reference Guide  develop.7482b7c7af, 2026/12/05
The Integrative Modeling Platform
em2d.py
1"""@namespace IMP.pmi.restraints.em2d
2Restraints for handling electron microscopy images.
3"""
4
5import IMP
6import IMP.core
7import IMP.algebra
8import IMP.atom
9import IMP.pmi.tools
10import ihm.location
11import ihm.dataset
12
13
15 """Fit particles against a set of class averages by principal components.
16 Compares how well the principal components of the segmented class
17 average fit to the principal components of the particles.
18 """
19 def __init__(self, hier, images, pixel_size, image_resolution,
20 projection_number, resolution, micrographs_number=None,
21 n_components=1):
22 """Constructor.
23 @param hier The root hierarchy for applying the restraint
24 @param images 2D class average filenames in PGM text format
25 @param pixel_size Pixel size in angstroms
26 @param image_resolution Estimated resolution of the images
27 in angstroms
28 @param projection_number Number of projections of the model
29 to generate and fit to images. The lower the number, the
30 faster the evaluation, but the lower the accuracy
31 @param resolution Which level of
32 [model representation](@ref pmi_resolution) to use in the fit
33 @param micrographs_number Number of micrograph particles that
34 were used to generate the class averages, if known
35 @param n_components Number of the largest components to be
36 considered for the EM image
37 """
38
39 import IMP.em2d
40
41 self.datasets = []
42 for image in images:
43 loc = ihm.location.InputFileLocation(
44 image, details="Electron microscopy class average")
45 d = ihm.dataset.EM2DClassDataset(loc)
46 self.datasets.append(d)
47
48 for p, state in IMP.pmi.tools._all_protocol_outputs(hier):
49 for i in range(len(self.datasets)):
50 p.add_em2d_restraint(state, self, i, resolution, pixel_size,
51 image_resolution, projection_number,
52 micrographs_number)
53
54 # PMI2 selection
55 self.m = hier.get_model()
56 particles = IMP.atom.Selection(
57 hier, resolution=resolution).get_selected_particles()
58 self.weight = 1.0
59 self.rs = IMP.RestraintSet(self.m, 'em2d')
60 self.label = "None"
61
62 # read PGM FORMAT images
63 # format conversion recommendation - first run
64 # "e2proc2d.py $FILE ${NEW_FILE}.pgm"
65 # then, run "convert ${NEW_FILE}.pgm -compress none ${NEW_FILE2}.pgm"
66
67 # Number of the largest components to be considered for the EM image
68 if n_components >= 2:
70 particles, images, pixel_size, image_resolution,
71 projection_number, True, n_components)
72 else:
74 particles, images, pixel_size, image_resolution,
75 projection_number, True)
76 if micrographs_number:
77 em2d.set_micrographs_number(micrographs_number)
78 self._em2d_restraint = em2d
79 self._num_images = len(images)
80 self.rs.add_restraint(em2d)
81
82 def set_label(self, label):
83 self.label = label
84
85 def add_to_model(self):
86 IMP.pmi.tools.add_restraint_to_model(self.m, self.rs, add_to_rmf=True)
87
88 def get_restraint(self):
89 return self.rs
90
91 def set_weight(self, weight):
92 self.weight = weight
93 self.rs.set_weight(self.weight)
94
95 def get_output(self):
96 output = {}
97 score = self.weight*self.rs.unprotected_evaluate(None)
98 output["_TotalScore"] = str(score)
99 output["ElectronMicroscopy2D_" + self.label] = str(score)
100 # For each image, get the transformation that places the
101 # model on the image, and its cross correlation coefficient
102 for i in range(self._num_images):
103 prefix = 'ElectronMicroscopy2D_%s_Image%d' % (self.label, i+1)
104 ccc = self._em2d_restraint.get_cross_correlation_coefficient(i)
105 output[prefix + '_CCC'] = str(ccc)
106 tran = self._em2d_restraint.get_transformation(i)
107 r = tran.get_rotation().get_quaternion()
108 t = tran.get_translation()
109 for j in range(4):
110 output[prefix + '_Rotation%d' % j] = str(r[j])
111 for j in range(3):
112 output[prefix + '_Translation%d' % j] = str(t[j])
113 return output
114
115
117 """FFT based image alignment, developed by Javier Velazquez-Muriel"""
118 def __init__(self, hier, images=None, pixel_size=None,
119 image_resolution=None, projection_number=None,
120 resolution=None):
121 """Constructor.
122 @param hier The root hierarchy for applying the restraint
123 @param images SPIDER FORMAT images (format conversion should be done
124 through EM2EM)
125 @param pixel_size sampling rate of the available EM images (angstroms)
126 @param image_resolution resolution at which you want to generate the
127 projections of the model. In principle you want "perfect"
128 projections, so use the highest resolution
129 @param projection_number Number of projections of the model (coarse
130 registration) to estimate the registration parameters
131 @param resolution Which level of
132 [model representation](@ref pmi_resolution) to use in the fit
133 """
134
135 import IMP.em2d
136
137 # check input
138 if images is None:
139 raise Exception("EM2D_FFT: must pass images")
140 if pixel_size is None:
141 raise Exception("EM2D_FFT: must pass pixel size")
142 if image_resolution is None:
143 raise Exception("EM2D_FFT: must pass image resolution")
144 if projection_number is None:
145 raise Exception("EM2D_FFT: must pass projection_number")
146
147 # PMI2 selection
148 self.m = hier.get_model()
149 particles = IMP.atom.Selection(
150 hier, resolution=resolution).get_selected_particles()
151
152 self.weight = 1.0
153 self.rs = IMP.RestraintSet(self.m, 'em2d_FFT')
154 self.label = "None"
155
156 # read
158 imgs = IMP.em2d.read_images(images, srw)
159
161 pixel_size, image_resolution, projection_number)
162
163 # This method (recommended) uses preprocessing of the images and
164 # projections to speed-up the registration
165 params.coarse_registration_method = IMP.em2d.ALIGN2D_PREPROCESSING
166 params.optimization_steps = 50
167 params.simplex_initial_length = 0.1
168 params.simplex_minimum_size = 0.02
169
170 # use true if you want to save the projections from the model that
171 # best match the EM images
172 params.save_match_images = False
173
174 ######################
175 # set up the em2D restraint
176 ######################
177 score_function = IMP.em2d.EM2DScore()
178 em2d_restraint = IMP.em2d.Em2DRestraint(self.m)
179 em2d_restraint.setup(score_function, params)
180 em2d_restraint.set_images(imgs)
181 em2d_restraint.set_fast_mode(5)
182 em2d_restraint.set_name("em2d_restraint")
183
184 print("len(particles) = ", len(particles))
185 container = IMP.container.ListSingletonContainer(self.m, particles)
186 em2d_restraint.set_particles(container)
187
188 self.rs.add_restraint(em2d_restraint)
189
190 def set_label(self, label):
191 self.label = label
192
193 def add_to_model(self):
195
196 def get_restraint(self):
197 return self.rs
198
199 def set_weight(self, weight):
200 self.weight = weight
201 self.rs.set_weight(self.weight)
202
203 def get_output(self):
204 output = {}
205 score = self.weight*self.rs.unprotected_evaluate(None)
206 output["_TotalScore"] = str(score)
207 output["ElectronMicroscopy2D_FFT_" + self.label] = str(score)
208 return output
The general base class for IMP exceptions.
Definition exception.h:52
Object used to hold a set of restraints.
Select hierarchy particles identified by the biological name.
Definition Selection.h:76
Parameters used by Em2DRestraint and ProjectionFinder.
Fast scoring of Particles against electron microscopy class averages.
FFT based image alignment, developed by Javier Velazquez-Muriel.
Definition em2d.py:116
__init__(self, hier, images=None, pixel_size=None, image_resolution=None, projection_number=None, resolution=None)
Constructor.
Definition em2d.py:129
Fit particles against a set of class averages by principal components.
Definition em2d.py:14
__init__(self, hier, images, pixel_size, image_resolution, projection_number, resolution, micrographs_number=None, n_components=1)
Constructor.
Definition em2d.py:30
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
Functionality for loading, creating, manipulating and scoring atomic structures.
Basic functionality that is expected to be used by a wide variety of IMP users.
Restraints using electron microscopy 2D images (class averages).
Images read_images(const Strings &names, const ImageReaderWriter *rw)
Miscellaneous utilities.
Definition pmi/tools.py:1
add_restraint_to_model(model, restraint, add_to_rmf=False)
Add a PMI restraint to the model.
Definition pmi/tools.py:89