Debian Codegraph @

mrcz/ReliablePy.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 """
3 Python Utilities for Relion
4
5 Created on Tue Dec 1 14:26:13 2015
6 @author: Robert A. McLeod
7 @email: [email protected] OR [email protected]
8
9 This is a primarily a general parser for Relion star files. It creates a two-level dictionary, with the
10 "data_*" level at the top and the "_rln*" level at the second. Use the star.keys() function to see what values
11 the dictionary has. I.e.
12
13 rln.star.keys()
14
15 and then
16
17 rln.star['data_whatever'].keys()
18
19 Example usage:
20
21 rln = ReliablePy()
22 # Wildcards can be loaded
23 rln.load( 'PostProcess*.star' )
24
25 # Plot the Fourier Shell Correlation
26 plt.figure()
27 plt.plot( rln.star['data_fsc']['Resolution'], rln.star['data_fsc']['FourierShellCorrelationUnmaskedMaps'], '.-' )
28 plt.xlabel( "Resolution" )
29 plt.ylabel( "FSC" )
30
31 Note that all Relion strings are byte-strings (char1) rather than UTF encoded.
32
33 """
34 from __future__ import division, print_function, absolute_import
35
36
37 from . import ioDM, ioMRC
38
39 import numpy as np
40 import os, os.path
41 import glob
42 import time
43
44 from collections import OrderedDict
45
46 # The following are not requirements of python-mrcz, only ReliablePy:
47 import matplotlib.pyplot as plt
48 import scipy
49 import pandas
50
51 # Static variable decorator
52 def static_var(varname, value):
53 def decorate(func):
54 setattr(func, varname, value)
55 return func
56 return decorate
57
58
59 def apodization( name = 'butter.32', shape= [2048,2048], radius=None ):
60 """ apodization( name = 'butter.32', size = [2048,2048], radius=None )
61 Provides a 2-D filter or apodization window for Fourier filtering or image clamping.
62 Radius = None defaults to shape/2
63
64 Valid names are:
65 'hann' - von Hann cosine window on radius
66 'hann_square' as above but on X-Y
67 'hamming' - good for apodization, nonsense as a filter
68 'butter.X' Butterworth multi-order filter where X is the order of the Lorentzian
69 'butter_square.X' Butterworth in X-Y
70 'gauss_trunc' - truncated gaussian, higher performance (smaller PSF) than hann filter
71 'gauss' - regular gaussian
72 NOTE: There are windows in scipy.signal for 1D-filtering...
73 WARNING: doesn't work properly for odd image dimensions
74 """
75 # Make meshes
76 shape = np.asarray( shape )
77 if radius is None:
78 radius = shape/2.0
79 else:
80 radius = np.asarray( radius, dtype='float' )
81 # DEBUG: Doesn't work right for odd numbers
82 [xmesh,ymesh] = np.meshgrid( np.arange(-shape[1]/2,shape[1]/2), np.arange(-shape[0]/2,shape[0]/2) )
83 r2mesh = xmesh*xmesh/( np.double(radius[0])**2 ) + ymesh*ymesh/( np.double(radius[1])**2 )
84
85 try:
86 [name, order] = name.lower().split('.')
87 order = np.double(order)
88 except ValueError:
89 order = 1
90
91 if name == 'butter':
92 window = np.sqrt( 1.0 / (1.0 + r2mesh**order ) )
93 elif name == 'butter_square':
94 window = np.sqrt( 1.0 / (1.0 + (xmesh/radius[1])**order))*np.sqrt(1.0 / (1.0 + (ymesh/radius[0])**order) )
95 elif name == 'hann':
96 cropwin = ((xmesh/radius[1])**2.0 + (ymesh/radius[0])**2.0) <= 1.0
97 window = cropwin.astype('float') * 0.5 * ( 1.0 + np.cos( 1.0*np.pi*np.sqrt( (xmesh/radius[1])**2.0 + (ymesh/radius[0])**2.0 ) ) )
98 elif name == 'hann_square':
99 window = ( (0.5 + 0.5*np.cos( np.pi*( xmesh/radius[1]) ) ) *
100 (0.5 + 0.5*np.cos( np.pi*( ymesh/radius[0] ) ) ) )
101 elif name == 'hamming':
102 cropwin = ((xmesh/radius[1])**2.0 + (ymesh/radius[0])**2.0) <= 1.0
103 window = cropwin.astype('float') * ( 0.54 + 0.46*np.cos( 1.0*np.pi*np.sqrt( (xmesh/radius[1])**2.0 + (ymesh/radius[0])**2.0 ) ) )
104 elif name == 'hamming_square':
105 window = ( (0.54 + 0.46*np.cos( np.pi*( xmesh/radius[1]) ) ) *
106 (0.54 + 0.46*np.cos( np.pi*( ymesh/radius[0] ) ) ) )
107 elif name == 'gauss' or name == 'gaussian':
108 window = np.exp( -(xmesh/radius[1])**2.0 - (ymesh/radius[0])**2.0 )
109 elif name == 'gauss_trunc':
110 cropwin = ((0.5*xmesh/radius[1])**2.0 + (0.5*ymesh/radius[0])**2.0) <= 1.0
111 window = cropwin.astype('float') * np.exp( -(xmesh/radius[1])**2.0 - (ymesh/radius[0])**2.0 )
112 elif name == 'lanczos':
113 print( "TODO: Implement Lanczos window" )
114 return
115 else:
116 print( "Error: unknown filter name passed into apodization" )
117 return
118 return window
119
120 def pyFFTWPlanner( realMage, fouMage=None, wisdomFile = None, effort = 'FFTW_MEASURE', n_threads = None, doForward = True, doReverse = True ):
121 """
122 Appends an FFTW plan for the given realMage to a text file stored in the same
123 directory as RAMutil, which can then be loaded in the future with pyFFTWLoadWisdom.
124
125 NOTE: realMage should be typecast to 'complex64' normally.
126
127 NOTE: planning pickle files are hardware dependant, so don't copy them from one
128 machine to another. wisdomFile allows you to specify a .pkl file with the wisdom
129 tuple written to it. The wisdomFile is never updated, whereas the default
130 wisdom _is_ updated with each call. For multiprocessing, it's important to
131 let FFTW generate its plan from an ideal processor state.
132
133 TODO: implement real, half-space fourier transforms rfft2 and irfft2 as built
134 """
135
136 import pyfftw
137 import pickle
138 import os.path
139 from multiprocessing import cpu_count
140
141 utilpath = os.path.dirname(os.path.realpath(__file__))
142
143 # First import whatever we already have
144 if wisdomFile is None:
145 wisdomFile = os.path.join( utilpath, "pyFFTW_wisdom.pkl" )
146
147
148 if os.path.isfile(wisdomFile):
149 try:
150 fh = open( wisdomFile, 'rb')
151 except:
152 print( "Util: pyFFTW wisdom plan file: " + str(wisdomFile) + " invalid/unreadable" )
153
154 try:
155 pyfftw.import_wisdom( pickle.load( fh ) )
156 except:
157 # THis is not normally a problem, it might be empty?
158 print( "Util: pickle failed to import FFTW wisdom" )
159 pass
160 try:
161 fh.close()
162 except:
163 pass
164
165 else:
166 # Touch the file
167 os.umask(0000) # Everyone should be able to delete scratch files
168 with open( wisdomFile, 'wb') as fh:
169 pass
170
171 # I think the fouMage array has to be smaller to do the real -> complex FFT?
172 if fouMage is None:
173 if realMage.dtype.name == 'float32':
174 print( "pyFFTW is recommended to work on purely complex data" )
175 fouShape = realMage.shape
176 fouShape.shape[-1] = realMage.shape[-1]//2 + 1
177 fouDtype = 'complex64'
178 fouMage = np.empty( fouShape, dtype=fouDtype )
179 elif realMage.dtype.name == 'float64':
180 print( "pyFFTW is recommended to work on purely complex data" )
181 fouShape = realMage.shape
182 fouShape.shape[-1] = realMage.shape[-1]//2 + 1
183 fouDtype = 'complex128'
184 fouMage = np.empty( fouShape, dtype=fouDtype )
185 else: # Assume dtype is complexXX
186 fouDtype = realMage.dtype.name
187 fouMage = np.zeros( realMage.shape, dtype=fouDtype )
188
189 if n_threads is None:
190 n_threads = cpu_count()
191 print( "FFTW using " + str(n_threads) + " threads" )
192
193 if bool(doForward):
194 #print( "Planning forward pyFFTW for shape: " + str( realMage.shape ) )
195 FFT2 = pyfftw.builders.fft2( realMage, planner_effort=effort,
196 threads=n_threads, auto_align_input=True )
197 else:
198 FFT2 = None
199 if bool(doReverse):
200 #print( "Planning reverse pyFFTW for shape: " + str( realMage.shape ) )
201 IFFT2 = pyfftw.builders.ifft2( fouMage, planner_effort=effort,
202 threads=n_threads, auto_align_input=True )
203 else:
204 IFFT2 = None
205
206 # Setup so that we can call .execute on each one without re-copying arrays
207 # if FFT2 is not None and IFFT2 is not None:
208 # FFT2.update_arrays( FFT2.get_input_array(), IFFT2.get_input_array() )
209 # IFFT2.update_arrays( IFFT2.get_input_array(), FFT2.get_input_array() )
210 # Something is different in the builders compared to FFTW directly.
211 # Can also repeat this for pyfftw.builders.rfft2 and .irfft2 if desired, but
212 # generally it seems slower.
213 # Opening a file for writing is supposed to truncate it
214 # if bool(savePlan):
215 #if wisdomFile is None:
216 # with open( utilpath + "/pyFFTW_wisdom.pkl", 'wb') as fh:
217 with open( wisdomFile, 'wb' ) as fh:
218 pickle.dump( pyfftw.export_wisdom(), fh )
219
220 return FFT2, IFFT2
221
222 # TODO: put IceFilter in a ReliablePy utility function file
223 @static_var( "bpFilter", -1 )
224 @static_var( "mageShape", np.array([0,0]) )
225 @static_var( "ps", -42 )
226 @static_var( "FFT2", -42 )
227 @static_var( "IFFT2", -42 )
228 def IceFilter( mage, pixelSize=1.0, filtRad = 8.0 ):
229 """
230 IceFilter applies a band-pass filter to mage that passes the first 3
231 water ice rings, and then returns the result.
232 pixelSize is in ANGSTROMS because this is bio. Program uses this to
233 calculate the width of the band-pass filter.
234 filtRad is radius of the Gaussian filter (pixels) to apply after Fourier filtration
235 that are periodic artifacts due to multiple defocus zeros being in the band
236 """
237
238 # First water ring is at 3.897 Angstroms
239 # Second is ater 3.669 Angstroms
240 # Third is at 3.441 Angstroms
241 # And of course there is strain, so go from about 4 to 3.3 Angstroms in the mesh
242 # Test for existance of pyfftw
243 try:
244 import pyfftw
245 pyfftwFound = True
246 except:
247 pyfftwFound = False
248
249 # Check to see if we have to update our static variables
250 if ( (IceFilter.mageShape != mage.shape).any() ) or (IceFilter.bpFilter.size == 1) or (IceFilter.ps != pixelSize):
251 # Make a new IceFilter.bpFilter
252 IceFilter.mageShape = np.array( mage.shape )
253 IceFilter.ps = pixelSize
254
255 bpMin = pixelSize / 4.0 # pixels tp the 4.0 Angstrom spacing
256 bpMax = pixelSize / 3.3 # pixels to the 3.3 Angstrom spacing
257
258 # So pixel frequency is -0.5 to +0.5 with shape steps
259 # And we want a bandpass from 1.0/bpMin to 1.0/bpMax, which is different on each axis for rectangular images
260 pixFreqX = 1.0 / mage.shape[1]
261 pixFreqY = 1.0 / mage.shape[0]
262 bpRangeX = np.round( np.array( [ bpMin/pixFreqX, bpMax/pixFreqX ] ) )
263 bpRangeY = np.round( np.array( [ bpMin/pixFreqY, bpMax/pixFreqY ] ) )
264 IceFilter.bpFilter = np.fft.fftshift(
265 (1.0 - apodization( name='butter.64', size=mage.shape, radius=[ bpRangeY[0],bpRangeX[0] ] ))
266 * apodization( name='butter.64', size=mage.shape, radius=[ bpRangeY[1],bpRangeX[1] ] ) )
267 IceFilter.bpFilter = IceFilter.bpFilter.astype( 'float32' )
268
269 if pyfftwFound: [IceFilter.FFT2, IceFilter.IFFT2] = pyFFTWPlanner( mage.astype('complex64') )
270 pass
271
272 # Apply band-pass filter
273 if pyfftwFound:
274 IceFilter.FFT2.update_arrays( mage.astype('complex64'), IceFilter.FFT2.get_output_array() )
275 IceFilter.FFT2.execute()
276 IceFilter.IFFT2.update_arrays( IceFilter.FFT2.get_output_array() * IceFilter.bpFilter, IceFilter.IFFT2.get_output_array() )
277 IceFilter.IFFT2.execute()
278 bpMage = IceFilter.IFFT2.get_output_array() / mage.size
279 else:
280 FFTmage = np.fft.fft2( mage )
281 bpMage = np.fft.ifft2( FFTmage * IceFilter.bpFilter )
282
283 from scipy.ndimage import gaussian_filter
284 bpGaussMage = gaussian_filter( np.abs(bpMage), filtRad )
285 # So if I don't want to build a mask here, and if I'm just doing band-pass
286 # intensity scoring I don't need it, I don't need to make a thresholded mask
287
288 # Should we normalize the bpGaussMage by the mean and std of the mage?
289 return bpGaussMage
290
291 class ReliablePy(object):
292
293 def __init__( self, *inputs ) :
294 self.verbose = 1
295 self.inputs = list( inputs )
296
297 # _data.star file dicts
298 self.star = OrderedDict()
299
300 self.par = []
301 self.pcol = OrderedDict()
302
303 self.box = [] # Each box file loaded is indexed by its load order / dict could also be done if it's more convienent.
304
305 # Particle/class data
306 self.mrc = []
307 self.mrc_header = []
308 if inputs:
309 self.load( *inputs )
310 pass
311
312 def load( self, *input_names ):
313 # See if it's a single-string or list/tuple
314
315 if not isinstance( input_names, str ):
316 new_files = []
317 for item in input_names:
318 new_files.extend( glob.glob( item ) )
319 else:
320 new_files = list( input_names )
321
322 for filename in new_files:
323 [fileFront, fileExt] = os.path.splitext( filename )
324
325 if fileExt == '.mrc' or fileExt == '.mrcs':
326 self.inputs.append(filename)
327 self.__loadMRC( filename )
328 elif fileExt == '.star':
329 self.inputs.append(filename)
330 self.__loadStar( filename )
331 elif fileExt == '.par':
332 self.inputs.append(filename)
333 self.__loadPar( filename )
334 elif fileExt == '.box':
335 self.inputs.append(filename)
336 self.__loadBox( filename )
337 else:
338 print( "Unknown file extension passed in: " + filename )
339
340 def plotFSC( self ):
341 # Do error checking? Or no?
342 plt.rc('lines', linewidth=2.0, markersize=12.0 )
343 plt.figure()
344 plt.plot( self.star['data_fsc']['Resolution'], 0.143*np.ones_like(self.star['data_fsc']['Resolution']),
345 '-', color='firebrick', label="Resolution criteria" )
346 try:
347 plt.plot( self.star['data_fsc']['Resolution'], self.star['data_fsc']['FourierShellCorrelationUnmaskedMaps'],
348 'k.-', label="Unmasked FSC" )
349 except: pass
350 try:
351 plt.plot( self.star['data_fsc']['Resolution'], self.star['data_fsc']['FourierShellCorrelationMaskedMaps'],
352 '.-', color='royalblue', label="Masked FSC" )
353 except: pass
354 try:
355 plt.plot( self.star['data_fsc']['Resolution'], self.star['data_fsc']['FourierShellCorrelationCorrected'],
356 '.-', color='forestgreen', label="Corrected FSC" )
357 except: pass
358 try:
359 plt.plot( self.star['data_fsc']['Resolution'], self.star['data_fsc']['CorrectedFourierShellCorrelationPhaseRandomizedMaskedMaps'],
360 '.-', color='goldenrod', label="Random-phase corrected FSC" )
361 except: pass
362 plt.xlabel( "Resolution ($\AA^{-1}$)" )
363 plt.ylabel( "Fourier Shell Correlation" )
364 plt.legend( loc='upper right', fontsize=16 )
365 plt.xlim( np.min(self.star['data_fsc']['Resolution']), np.max(self.star['data_fsc']['Resolution']) )
366 print( "Final resolution (unmasked): %.2f A"%self.star['data_general']['FinalResolution'] )
367 print( "B-factor applied: %.1f"%self.star['data_general']['BfactorUsedForSharpening'] )
368
369 def plotSSNR( self ):
370 """
371 Pulls the SSNR from each class in a _model.star file and plots them, for assessing which class is the
372 'best' class
373 """
374
375 N_particles = np.sum( self.star[b'data_model_groups'][b'GroupNrParticles'] )
376 N_classes = self.star[b'data_model_general'][b'NrClasses']
377
378 plt.figure()
379 for K in np.arange( N_classes ):
380 Resolution = self.star[b'data_model_class_%d'%(K+1)][b'Resolution']
381 SSNR = self.star[b'data_model_class_%d'%(K+1)][b'SsnrMap']
382 plt.semilogy( Resolution, SSNR+1.0,
383 label="Class %d: %d" %(K+1,N_particles*self.star[b'data_model_classes'][b'ClassDistribution'][K]) )
384 plt.legend( loc = 'best' )
385 plt.xlabel( "Resolution ($\AA^{-1}$)" )
386 plt.ylabel( "Spectral Signal-to-Noise Ratio" )
387 # Let's also display the class distributions in the legend
388
389
390 def pruneParticlesNearImageEdge( self, box = None, shapeImage = [3838,3710] ):
391 """
392 Removes any particles near image edge. Relion's default behavoir is to replicate pad these,
393 which often leads to it crashing.
394
395 box is the bounding box size for the particle, in pixels. If a _model.star file is loaded
396 it is automatically detected. Otherwise it must be provided.
397
398 Image size is not stored anywhere obvious in Relion, so it must be passed in in terms of
399 it's shape in [y,x]
400 """
401 if box == None:
402 try:
403 box = self.star[b'data_model_general'][b'OriginalImageSize']
404 except:
405 print( "No box shape found in metadata, load a *_model.star file or provide box dimension" )
406 return
407
408 partCount = len( self.star[b'data_'][b'CoordinateX'] )
409
410 # Hmm... removing a row is a little painful because I index by keys in columnar format.
411 box2 = box/2
412 CoordX = self.star[b'data_'][b'CoordinateX']
413 CoordY = self.star[b'data_'][b'CoordinateY']
414 keepElements = ~((CoordX < box2)|(CoordY < box2)|(CoordX > shapeImage[1]-box2)|(CoordY > shapeImage[0]-box2))
415 for key, store in self.star[b'data_'].items():
416 self.star[b'data_'][key] = store[keepElements]
417 print( "Deleted %d"%(partCount-len(self.star[b'data_'][b'CoordinateX']) ) +
418 " particles too close to image edge" )
419 pass
420
421 def permissiveMask( self, volumeThres, gaussSigma = 5.0, gaussRethres = 0.07, smoothSigma=1.5 ):
422 """
423 Given a (tight) volumeThres(hold) measured in Chimera or IMS, this function generates a
424 Gaussian dilated mask that is then smoothed. Everything is done with Gaussian operations
425 so the Fourier space representation of the mask should be relatively smooth as well,
426 and hence ring less.
427
428 Excepts self.mrc to be loaded. Populates self.mask.
429
430 """
431 thres = self.mrc > volumeThres; thres = thres.astype('float32')
432
433 gaussThres = scipy.ndimage.gaussian_filter( thres, gaussSigma )
434 rethres = gaussThres > gaussRethres; rethres = rethres.astype('float32')
435
436 self.mask = scipy.ndimage.gaussian_filter( rethres, smoothSigma )
437 print( "permissive mask complete, use ioMRC.writeMRC(self.mrc, 'maskname.mrc') to save" )
438 pass
439
440 def box2star( self, directory = "." ):
441 """
442 Converts all EMAN .box files in a directory to the associated .star files. Relion cannot successfully
443 rescale particles if they come in .box format. Also does box pruning if they are too close to an edge.
444 """
445
446 boxList = glob.glob( os.path.join( directory, "*.box") )
447
448 starHeader = """
449 data_
450
451 loop_
452 _rlnCoordinateX #1
453 _rlnCoordinateY #2
454 """
455
456 shapeImage = [3838,3710]
457 for boxFile in boxList:
458 print( "Loading %s" % boxFile )
459 boxData = np.loadtxt(boxFile)
460
461 xCoord = boxData[:,0]
462 yCoord = boxData[:,1]
463 boxX = boxData[:,2]/2
464 boxY = boxData[:,3]/2
465
466 keepElements = ~((xCoord < boxX)|(yCoord < boxY)|(xCoord > shapeImage[1]-boxX)|(yCoord> shapeImage[0]-boxY))
467 xCoord = xCoord[keepElements]
468 yCoord = yCoord[keepElements]
469 boxX = boxX[keepElements]
470 boxY = boxY[keepElements]
471
472 starFilename = os.path.splitext( boxFile )[0] + ".star"
473 with open( starFilename, 'wb' ) as sh:
474 sh.writelines( starHeader )
475 for J in np.arange(0,len(xCoord)):
476 sh.write( "%.1f %.1f\n" % (xCoord[J]+boxX[J], yCoord[J]+boxY[J] ) )
477
478 sh.write( "\n" )
479 sh.close()
480
481 def regroupKmeans( self, partPerGroup = 100, miniBatch=True ):
482 """
483 Does a 3-D k-means clustering on DefocusU, DefocusV, and GroupScaleCorrection
484
485 partPerGroup is a suggestion, that is the number of groups is the # of particles / partPerGroup,
486 so outlier groups will tend to have far fewer particle counts that those in the bulk of the data.
487
488 miniBatch=True is faster for very large sets (>100,000 particles), but somewhat less accurate
489 miniBatch=False is faster for smaller sets, and better overall
490 """
491 # K-means clustering
492 import sklearn
493 import sklearn.cluster
494
495 # We need to make an array for all particles that has the GroupScaleCorrection
496 P = len( self.star[b'data_'][b'DefocusU'] )
497 n_clusters = np.int( P / partPerGroup )
498
499 DefocusU = self.star[b'data_'][b'DefocusU']
500 DefocusV = self.star[b'data_'][b'DefocusV']
501 DefocusMean = 0.5* (DefocusU + DefocusV)
502
503 if b'data_model_groups' in self.star:
504 SCALE_CORR_PRESENT = True
505 part_GroupScaleCorrection = np.zeros_like( self.star[b'data_'][b'DefocusU'] )
506
507 # Build a GroupScaleCorrection vector
508 for J, groupNr in enumerate( self.star[b'data_'][b'GroupNumber'] ):
509 part_GroupScaleCorrection[J] = self.star[b'data_model_groups'][b'GroupScaleCorrection'][ np.argwhere(self.star[b'data_model_groups'][b'GroupNumber'] == groupNr)[0] ]
510 else:
511 print( "No _model.star loaded, not using scale correction" )
512 SCALE_CORR_PRESENT = False
513
514 ##################
515 # K-means clustering:
516 ##################
517 print( "Running K-means clustering analysis for " + str(P) + " particles into " + str(n_clusters) + " clusters" )
518 t0 = time.time()
519 if bool(miniBatch):
520 print( "TODO: determine number of jobs for K-means" )
521 k_means = sklearn.cluster.MiniBatchKMeans( n_clusters=n_clusters, init_size=3*n_clusters+1 )
522 else:
523 k_means = sklearn.cluster.KMeans( n_clusters=n_clusters, n_jobs=12 )
524 #Kmeans_in = np.vstack( [DefocusMean, part_GroupScaleCorrection]).transpose()
525 if SCALE_CORR_PRESENT:
526 Kmeans_in = np.vstack( [DefocusU,DefocusV, part_GroupScaleCorrection]).transpose()
527 else:
528 Kmeans_in = np.vstack( [DefocusU,DefocusV]).transpose()
529 Kmeans_in = sklearn.preprocessing.robust_scale( Kmeans_in )
530 k_predict = k_means.fit_predict( Kmeans_in )
531 t1 = time.time()
532 print( "Cluster analysis finished in (s): " + str(t1-t0) )
533
534 if self.verbose >= 2:
535 plt.figure()
536 plt.scatter( DefocusMean, part_GroupScaleCorrection, c=k_predict)
537 plt.xlabel( "Defocus ($\AA$)" )
538 plt.ylabel( "Group scale correction (a.u.)" )
539 plt.title("K-means on Defocus")
540
541 ##################
542 # Save the results in a new particles .star file:
543 ##################
544 # Replace, add one to group number because Relion starts counting from 1
545
546 particleKey = b"data_"
547
548 # Add the GroupName field to the star file
549 self.star[particleKey][b'GroupName'] = [""] * len( self.star[particleKey][b'GroupNumber'] )
550 for J, groupName in enumerate( k_predict ):
551 self.star[particleKey][b'GroupName'][J] = b'G' + str(groupName + 1)
552
553 # Build a new group number count
554 groupCount = np.zeros_like( self.star[particleKey][b'GroupNumber'] )
555 for J in np.arange(0,len(groupCount)):
556 groupCount[J] = np.sum( self.star[particleKey][b'GroupNumber'] == J )
557 self.star[particleKey][b'GroupNumber'] = groupCount
558
559 # Recalculate number of particles in each group (ACTUALLY THIS SEEMS NOT NECESSARY)
560 #GroupNr = np.zeros( np.max( k_predict )+1 )
561 #for J in xrange( np.min( k_predict), np.max( k_predict ) ):
562 # GroupNr[J] = np.sum( k_predict == J )
563 # pass
564 #
565 #for J in xrange(0, len(rln.star[particleKey]['GroupNumber']) ):
566 # rln.star[particleKey]['GroupNumber'][J] = GroupNr[ k_predict[J] ]
567
568 def saveDataStar( self, outputName, particleKey = b"data_" ):
569 """
570 Outputs a relion ..._data.star file that has been pruned, regrouped, etc. to outputName
571 """
572
573 if outputName == None:
574 # Need to store input star names, and figure out which was the last loaded particles.star file.
575 # [outFront, outExt] = os.path.splitext()
576 raise IOError( "Default filenames for saveDataStar not implemented yet" )
577
578 # TODO: more general star file output
579 # Let's just hack this
580 fh = open( outputName, 'wb' )
581 fh.write( b"\ndata_\n\nloop_\n")
582
583 # Since we made self.star an OrderedDict we don't need to keep track of index ordering
584
585 headerKeys = self.star[particleKey].keys()
586
587
588 for J, key in enumerate(headerKeys):
589 # print( "Column: " + "_rln" + lookupDict[J+1] + " #" + str(J+1) )
590 fh.write( b"_rln" + key + " #" + str(J) + "\n")
591
592
593 # lCnt = len( headerKeys )
594 P = len( self.star[particleKey][ self.star[particleKey].keys()[0] ] )
595 for I in np.arange(0,P):
596 fh.write( b" ")
597 for J, key in enumerate(headerKeys):
598 fh.write( str( self.star[particleKey][key][I] ) )
599 fh.write( b" " )
600 fh.write( b"\n" )
601 fh.close()
602
603 def saveDataAsPar( self, outputPrefix, N_classes = 1, mag = None, pixelsize=None, particleKey = "data_" ):
604 """
605 Saves a Relion .star file as a Frealign .par meta-data file. Also goes through all the particles in the
606 Relion .star and generates an appropriate meta-MRC particle file for Frealign.
607
608 Usage:
609
610 saveDataAsPar( self, outputPrefix, N_classes = 1, mag = None, pixelsize=None, particleKey = "data_" )
611
612 outputPrefix will be appended with "_1_rX.par", where X is the class number.
613
614 N_classes will generate N classes with random occupancy, or 100.0 % occupancy for one class.
615
616 mag wil change the Relion magnification to the given integer.
617
618 pixelsize is also optional. Relion tends to have round-off error in the pixelsize.
619
620 Use 'relion_stack_create --i particles.star --o forFrealign' to generate the associated mrc file.
621
622 Also no comment lines are written to the .par file.
623 """
624
625
626
627 partCount = len( self.star[b'data_'][b'MicrographName'] )
628 # Need AnglePsi, AngleTilt, and AngleRot
629 if not b'AnglePsi' in self.star[b'data_']:
630 self.star[b'data_'][b'AnglePsi'] = np.zeros( partCount, dtype='float32' )
631 if not b'AngleTilt' in self.star[b'data_']:
632 self.star['data_'][b'AngleTilt'] = np.zeros( partCount, dtype='float32' )
633 if not b'AngleRot' in self.star[b'data_']:
634 self.star[b'data_'][b'AngleRot'] = np.zeros( partCount, dtype='float32' )
635 if not b'OriginY' in self.star[b'data_']:
636 self.star[b'data_'][b'OriginY'] = np.zeros( partCount, dtype='float32' )
637 if not b'OriginX' in self.star[b'data_']:
638 self.star[b'data_'][b'OriginX'] = np.zeros( partCount, dtype='float32' )
639 if not b'Magnification' in self.star[b'data_']:
640 self.star[b'data_'][b'Magnification'] = np.zeros( partCount, dtype='float32' )
641 if not b'GroupNumber' in self.star[b'data_']:
642 self.star[b'data_'][b'GroupNumber'] = np.zeros( partCount, dtype='uint16' )
643 if not b'DefocusU' in self.star[b'data_']:
644 self.star[b'data_'][b'DefocusU'] = np.zeros( partCount, dtype='float32' )
645 if not b'DefocusV' in self.star[b'data_']:
646 self.star[b'data_'][b'DefocusV'] = np.zeros( partCount, dtype='float32' )
647 if not b'DefocusAngle' in self.star[b'data_']:
648 self.star[b'data_'][b'DefocusAngle'] = np.zeros( partCount, dtype='float32' )
649
650
651 # Frealign expects shifts in Angstroms. Pixelsize is sort of sloppily
652 # kept track of in Relion with Magnification and DetectorPixelSize (which
653 # defaults to 14.0)
654
655 if pixelsize == None:
656 # Detector pixel size in um, we need pixelsize in Angstrom
657 pixelsize = self.star[b'data_'][b'DetectorPixelSize'][0]*1E4 / self.star[b'data_'][b'Magnification'][0]
658 print( "Found pixelsize of %0.f" % pixelsize )
659 if mag == None:
660 print( "Using Relion magnification of %.f and DSTEP=%.1f" % ( self.star[b'data_'][b'Magnification'][0], self.star[b'data_'][b'DetectorPixelSize'][0]) )
661 print( "For a K2 (DSTEP=5.0) the appropriate magnification would be %0.f" % 50000/pixelsize )
662 else:
663 self.star[b'data_'][b'Magnification'] = mag * np.ones_like( self.star[b'data_'][b'Magnification'] )
664
665 logP = int(-500)
666 sigma = 1.0
667 score = 20.0
668 change = 0.0
669 for K in np.arange( 1, N_classes+1 ):
670 outputName = outputPrefix + "_1_r%d.par" % K
671 if N_classes > 1:
672 # Add random occupancy
673 occupancy = np.random.uniform( low=0.0, high=100.0, size=len(self.star[b'data_'][b'DefocusU']) )
674 else:
675 occupancy = 100.0* np.ones_like( self.star[b'data_'][b'DefocusU'] )
676
677 with open( outputName, 'w' ) as fh:
678 # Frealign is very picky about the number of digits, see card10.f, line 163
679 #READ(LINE,*,ERR=99,IOSTAT=CNT)ILIST(NANG),
680 # + PSI(NANG),THETA(NANG),PHI(NANG),SHX(NANG),
681 # + SHY(NANG),ABSMAGP,FILM(NANG),DFMID1(NANG),
682 # + DFMID2(NANG),ANGAST(NANG),OCC(NANG),
683 # + LGP,SIG(NANG),PRESA(NANG)
684 #7011 FORMAT(I7,3F8.2,2F10.2,I8,I6,2F9.1,2F8.2,I10,F11.4,
685 # + F8.2)
686 for J in np.arange(partCount):
687 fh.write( "%7d"%(J+1)
688 + " %8.2f"%self.star[b'data_'][b'AnglePsi'][J]
689 + " %8.2f"%self.star[b'data_'][b'AngleTilt'][J]
690 + " %8.2f"%self.star[b'data_'][b'AngleRot'][J]
691 + " %8.2f"%(self.star[b'data_'][b'OriginX'][J] * pixelsize)
692 + " %8.2f"%(self.star[b'data_'][b'OriginY'][J] * pixelsize)
693 + " %8.0f"%self.star[b'data_'][b'Magnification'][J]
694 + " %6d"%self.star[b'data_'][b'GroupNumber'][J]
695 + " %9.1f"%self.star[b'data_'][b'DefocusU'][J]
696 + " %9.1f"%self.star[b'data_'][b'DefocusV'][J]
697 + " %8.2f"%self.star[b'data_'][b'DefocusAngle'][J]
698 + " %8.2f"%occupancy[J]
699 + " %10d"%logP
700 + " %11.4f"%sigma
701 + " %8.2f"%score
702 + " %8.2f"%change + "\n")
703 pass
704
705 # Ok and now we need to make a giant particles file?
706 #mrcName, _= os.path.splitext( outputName )
707 #mrcName = mrcName + ".mrc"
708
709 #imageNames = np.zeros_like( self.star[b'data_'][b'ImageName'] )
710 #for J, name in enumerate( self.star[b'data_'][b'ImageName'] ):
711 # imageNames[J] = name.split('@')[1]
712 #uniqueNames = np.unique( imageNames ) # Ordering is preserved, thankfully!
713
714
715 # It would be much better if we could write to a memory-mapped file rather than building the entire array in memory
716 # However this is a little buggy in numpy.
717 # https://docs.python.org/2/library/mmap.html instead?
718
719 #particleList = []
720 #for uniqueName in uniqueNames:
721 # particleList.extend( ioMRC.readMRC(uniqueName)[0] )
722
723 #print( "DONE building particle list!" )
724 #print( len(particleList) )
725
726 #particleArray = np.array( particleList )
727 # del particleList
728
729 # We do have the shape parameter that we can pass in to pre-pad the array with all zeros.
730 #ioMRC.writeMRC( particleArray, mrcName, shape=None ) # TODO: no pixelsize
731 pass
732
733 def saveCtfImagesStar( self, outputName, zorroList = "*.dm4.log", physicalPixelSize=5.0, amplitudeContrast=0.08 ):
734 """
735 Given a glob pattern, generate a list of zorro logs, or alternatively one can pass in a list. For each
736 zorro log, load it, extract the pertinant info (defocus, etc.). This is a file ready for particle
737 extraction, with imbedded Ctf information.
738 """
739 import zorro
740
741 zorroList = glob.glob( zorroList )
742
743 headerDict = { b'MicrographName':1, b'CtfImage':2, b'DefocusU':3, b'DefocusV':4, b'DefocusAngle':5,
744 b'Voltage':6, b'SphericalAberration':7, b'AmplitudeContrast':8, b'Magnification':9,
745 b'DetectorPixelSize':10, b'CtfFigureOfMerit': 11 }
746 lookupDict = dict( zip( headerDict.values(), headerDict.keys() ) )
747 data = OrderedDict()
748 for header in headerDict:
749 data[header] = [None]*len(zorroList)
750
751 zorroReg = zorro.ImageRegistrator()
752 for J, zorroLog in enumerate(zorroList):
753 zorroReg.loadConfig( zorroLog, loadData=False )
754
755 data[b'MicrographName'][J] = zorroReg.files['sum']
756 data[b'CtfImage'][J] = os.path.splitext( zorroReg.files['sum'] )[0] + ".ctf:mrc"
757 # CTF4Results = [Micrograph number, DF1, DF2, Azimuth, Additional Phase shift, CC, max spacing fit-to]
758 data[b'DefocusU'][J] = zorroReg.CTF4Results[1]
759 data[b'DefocusV'][J] = zorroReg.CTF4Results[2]
760 data[b'DefocusAngle'][J] = zorroReg.CTF4Results[3]
761 data[b'CtfFigureOfMerit'][J] = zorroReg.CTF4Results[5]
762 data[b'Voltage'][J] = zorroReg.voltage
763 data[b'SphericalAberration'][J] = zorroReg.C3
764 data[b'AmplitudeContrast'][J] = amplitudeContrast
765 data[b'DetectorPixelSize'][J] = physicalPixelSize
766 data[b'Magnification'][J] = physicalPixelSize / (zorroReg.pixelsize * 1E-3)
767
768 with open( outputName, 'wb' ) as fh:
769
770 fh.write( b"\ndata_\n\nloop_\n")
771 for J in np.sort(lookupDict.keys()):
772 # print( "Column: " + "_rln" + lookupDict[J+1] + " #" + str(J+1) )
773 fh.write( b"_rln" + lookupDict[J] + b" #" + str(J) + b"\n")
774
775 lCnt = len( lookupDict )
776 for I in np.arange(0,len(zorroList)):
777 fh.write( b" ")
778 for J in np.arange(0,lCnt):
779 fh.write( str( data[lookupDict[J+1]][I] ) )
780 fh.write( b" " )
781 fh.write( b"\n" )
782
783 def gctfHistogramFilter( self, defocusThreshold = 40000, astigThreshold = 800,
784 fomThreshold = 0.0, resThreshold = 6.0,
785 starName = "micrographs_all_gctf.star", outName = "micrographs_pruned_gctf.star" ):
786 """
787 gctfHistogramFilter( self, defocusThreshold = 40000, astigThreshold = 800,
788 fomThreshold = 0.0, resThreshold = 6.0,
789 starName = "micrographs_all_gctf.star", outName = "micrographs_pruned_gctf.star" )
790
791 Calculates histograms of defocus, astigmatism, figure-of-merit (Pearson correlation coefficient),
792 and resolution limit, and applies the thresholds as specified in the keyword arguments.
793 Plots are generated showing the threshold level.
794
795 The output star file `outName` rejects all micrographs that fail any of the thresholds.
796 """
797 self.load( starName )
798
799 defocusU = self.star['data_']['DefocusU']
800 defocusV = self.star['data_']['DefocusV']
801 finalResolution = self.star['data_']['FinalResolution']
802 ctfFoM = self.star['data_']['CtfFigureOfMerit']
803
804 defocusMean = 0.5 * defocusU + 0.5 * defocusV
805 astig = np.abs( defocusU - defocusV )
806
807 [hDefocus, cDefocus] = np.histogram( defocusMean,
808 bins=np.arange(np.min(defocusMean),np.max(defocusMean),500.0) )
809 hDefocus = hDefocus.astype('float32')
810 cDefocus = cDefocus[:-1] +500.0/2
811
812 [hAstig, cAstig] = np.histogram( astig,
813 bins=np.arange(0, np.max(astig), 500.0) )
814 hAstig = hAstig.astype('float32')
815 cAstig = cAstig[:-1] +500.0/2
816
817 [hFoM, cFoM] = np.histogram( ctfFoM,
818 bins=np.arange(0.0,np.max(ctfFoM),0.002) )
819 hFoM = hFoM.astype('float32')
820 cFoM = cFoM[:-1] +0.002/2.0
821
822 [hRes, cRes] = np.histogram( finalResolution,
823 bins=np.arange(np.min(finalResolution),np.max(finalResolution),0.20) )
824 hRes = hRes.astype('float32')
825 cRes = cRes[:-1] +0.20/2.0
826
827 plt.figure()
828 plt.fill_between( cDefocus, hDefocus, np.zeros(len(hDefocus)), facecolor='steelblue', alpha=0.5 )
829 plt.plot( [defocusThreshold, defocusThreshold], [0, np.max(hDefocus)], "--", color='firebrick' )
830 plt.xlabel( "Defocus, $C_1 (\AA)$" )
831 plt.ylabel( "Histogram counts" )
832
833 plt.figure()
834 plt.fill_between( cAstig, hAstig, np.zeros(len(hAstig)), facecolor='forestgreen', alpha=0.5 )
835 plt.plot( [astigThreshold, astigThreshold], [0, np.max(hAstig)], "--", color='firebrick' )
836 plt.xlabel( "Astigmatism, $A_1 (\AA)$" )
837 plt.ylabel( "Histogram counts" )
838
839 plt.figure()
840 plt.fill_between( cFoM, hFoM, np.zeros(len(hFoM)), facecolor='darkorange', alpha=0.5 )
841 plt.plot( [fomThreshold, fomThreshold], [0, np.max(hFoM)], "--", color='firebrick' )
842 plt.xlabel( "Figure of Merit, $R^2$" )
843 plt.ylabel( "Histogram counts" )
844
845 plt.figure()
846 plt.fill_between( cRes, hRes, np.zeros(len(hRes)), facecolor='purple', alpha=0.5 )
847 plt.plot( [resThreshold, resThreshold], [0, np.max(hRes)], "--", color='firebrick' )
848 plt.xlabel( "Fitted Resolution, $r (\AA)$" )
849 plt.ylabel( "Histogram counts" )
850
851
852 #keepIndices = np.ones( len(defocusU), dtype='bool' )
853 keepIndices = ( ( defocusMean < defocusThreshold) & (astig < astigThreshold) &
854 (ctfFoM > fomThreshold ) & (finalResolution < resThreshold) )
855
856 print( "KEEPING %d of %d micrographs" %(np.sum(keepIndices), defocusU.size) )
857
858 for key in self.star['data_']:
859 self.star['data_'][key] = self.star['data_'][key][keepIndices]
860
861 self.saveDataStar( outName )
862
863 def __loadPar( self, parname ):
864 """
865 Frealign files normally have 16 columns, with any number of comment lines that start with 'C'
866 """
867 # Ergh, cannot have trailing comments with np.loadtxt?
868 self.parCol = [b"N", b"PSI", b"THETA", b"PHI", b"SHX", b"SHY", b"MAG", b"FILM", b"DF1", b"DF2", \
869 b"ANGAST", b"OCC", b"LogP", b"SIGMA", b"SCORE", b"CHANGE" ]
870
871 self.par = pandas.read_table( parname, engine='c', sep=' ', header=None, names =self.parCol, quotechar='C' )
872 #self.par.append( np.loadtxt( parname, comments=b'C' ) )
873 # TODO: split into a dictionary?
874 # TODO: read comments as well
875 # TODO: use pandas instead?
876 #self.parCol = {b"N":0, b"PSI":1, b"THETA":2, b"PHI":3, b"SHX":4, b"SHY":5, b"MAG":6, b"FILM":7, b"DF1":8, b"DF2":9,
877 # b"ANGAST":10, b"OCC":11, b"LogP":12, b"SIGMA":13, b"SCORE":14, b"CHANGE":15 }
878 #self.parComments = np.loadtxt( parname, comments=b' ' )
879
880
881 def __loadStar( self, starname ):
882 with open( starname, 'rb' ) as starFile:
883 starLines = starFile.readlines()
884
885 # Remove any lines that are blank
886 blankLines = [I for I, line in enumerate(starLines) if ( line == "\n" or line == " \n") ]
887 for blank in sorted( blankLines, reverse=True ):
888 del starLines[blank]
889
890 # Top-level keys all start with data_
891 headerTags = []; headerIndices = []
892 for J, line in enumerate(starLines):
893 if line.startswith( b"data_" ): # New headerTag
894 headerTags.append( line.strip() )
895 headerIndices.append( J )
896 # for end-of-file
897 headerIndices.append(-1)
898
899 # Build dict keys
900 for K, tag in enumerate( headerTags ):
901 self.star[tag] = OrderedDict()
902 # Read in _rln lines and assign them as dict keys
903
904 lastHeaderIndex = 0
905 foundLoop = False
906
907 if headerIndices[K+1] == -1: #-1 is not end of the array for indexing
908 slicedLines = starLines[headerIndices[K]:]
909 else:
910 slicedLines = starLines[headerIndices[K]:headerIndices[K+1]]
911
912 for J, line in enumerate( slicedLines ):
913 if line.startswith( b"loop_" ):
914 foundLoop = True
915 elif line.startswith( b"_rln" ):
916 lastHeaderIndex = J
917 # Find all the keys that start with _rln, they are sub-dict keys
918 newKey = line.split()[0][4:]
919 try:
920 newValue = line.split()[1]
921 # If newValue starts with a #, strip it
922 newValue = newValue.lstrip( b'#' )
923 except:
924 # Some really old Relion star files don't have the column numbers, so assume it's ordered
925 newValue = J
926
927 # Try to make newValue an int or float, or leave it as a string if that fails
928 try:
929 self.star[tag][newKey] = np.int( newValue )
930 except:
931 try:
932 self.star[tag][newKey] = np.float( newValue )
933 except: # leave as a string
934 self.star[tag][newKey] = newValue
935
936 # Now run again starting at lastHeaderIndex
937 if foundLoop:
938 # Need to check to make sure it's not an empty dict
939 if self.star[tag] == OrderedDict():
940 continue
941
942 # Sometimes we have an empty line on the end.
943 for J in np.arange(len(slicedLines)-1,0,-1):
944 if bool( slicedLines[J].strip() ):
945 break
946 slicedLines = slicedLines[:J]
947
948 endIndex = len(slicedLines)
949
950
951
952 # Reverse sub-dictionary so we can determine by which column goes to which key
953 lookup = dict( zip( self.star[tag].values(), self.star[tag].keys() ) )
954 print( "DEBUG: lookup = %s" % lookup )
955 # Pre-allocate, we can determine types later.
956 itemCount = endIndex - lastHeaderIndex - 1
957 testSplit = slicedLines[lastHeaderIndex+1].split()
958 for K, test in enumerate( testSplit ):
959 self.star[tag][lookup[K+1]] = [None] * itemCount
960
961 # Loop through and parse items
962 for J, line in enumerate( slicedLines[lastHeaderIndex+1:endIndex] ):
963 for K, item in enumerate( line.split() ):
964 self.star[tag][lookup[K+1]][J] = item
965 pass
966
967 # Try to convert to int, then float, otherwise leave as a string
968 for key in self.star[tag].keys():
969 try:
970 self.star[tag][key] = np.asarray( self.star[tag][key], dtype='int' )
971 except:
972 try:
973 self.star[tag][key] = np.asarray( self.star[tag][key], dtype='float' )
974 except:
975 self.star[tag][key] = np.asarray( self.star[tag][key] )
976 pass
977
978 def __loadMRC( self, mrcname ):
979 mrcimage, mrcheader = ioMRC.readMRC( mrcname, pixelunits=u'nm' )
980 self.mrc.append( mrcimage )
981 self.mrc_header.append( mrcheader )
982
983 def __loadBox( self, boxname ):
984 self.box.append( np.loadtxt( boxname ) )
985
986 # End of relion class
987
988
989