def recenterVolume(volume, densityNegative=False): from scipy.ndimage import center_of_mass from pytom.tompy.io import read, write from pytom.tompy.tools import paste_in_center from pytom.gpu.initialize import xp from pytom_numpy import vol2npy import os try: a = vol2npy(volume).copy() vol = True except: a = volume vol = False if densityNegative: a *= -1 x, y, z = list(map(int, center_of_mass(a))) cx, cy, cz = a.shape[0] // 2, a.shape[1] // 2, a.shape[2] // 2 sx = min(x, a.shape[0] - x) sy = min(y, a.shape[0] - y) sz = min(z, a.shape[0] - z) ac = a[x - sx:x + sx, y - sy:y + sy, z - sz:z + sz] b = xp.zeros_like(a) b = paste_in_center(ac, b) if densityNegative: b *= -1 if vol: write('recenteredDBV21.em', b) from pytom.basic.files import read vol = read('recenteredDBV21.em') os.system('rm recenteredDBV21.em') return vol else: return b
def FLCF(volume, template, mask=None, stdV=None, gpu=False): '''Fast local correlation function @param volume: target volume @param template: template to be searched. It can have smaller size then target volume. @param mask: template mask. If not given, a default sphere mask will be used. @param stdV: standard deviation of the target volume under mask, which do not need to be calculated again when the mask is identical. @return: the local correlation function ''' if gpu: import cupy as xp else: import numpy as xp from pytom.tompy.tools import paste_in_center from pytom.tompy.transform import rfft, irfft, fftshift from pytom.tompy.tools import create_sphere if volume.shape[0] < template.shape[0] or volume.shape[1] < template.shape[ 1] or volume.shape[2] < template.shape[2]: raise Exception('Template size is bigger than the target volume!') # generate the mask if mask is None: mask = create_sphere(template.shape) else: if template.shape[0] != mask.shape[0] and template.shape[ 1] != mask.shape[1] and template.shape[2] != mask.shape[2]: raise Exception('Template and mask sizes are not the same!') # normalize the template under mask meanT = mean_under_mask(template, mask) stdT = std_under_mask(template, mask, meanT) temp = (template - meanT) / stdT temp = temp * mask # construct both the template and the mask which has the same size as target volume tempV = temp if volume.shape[0] != temp.shape[0] or volume.shape[1] != temp.shape[ 1] or volume.shape[2] != temp.shape[2]: tempV = np.zeros(volume.shape) tempV = paste_in_center(temp, tempV) maskV = mask if volume.shape[0] != mask.shape[0] or volume.shape[1] != mask.shape[ 1] or volume.shape[2] != mask.shape[2]: maskV = np.zeros(volume.shape) maskV = paste_in_center(mask, maskV) # calculate the mean and std of volume meanV = mean_vol_under_mask(volume, maskV) stdV = std_vol_under_mask(volume, maskV, meanV) size = volume.shape fT = xp.fft.rfft(tempV) fT = xp.conjugate(fT) result = xp.fft.fftshift(xp.fft.irfft(fT * xp.fft.rfft(volume), size)) / stdV return result / np.sum(mask)
sox, soy, soz = tempNDA.shape spx, spy, spz = voluNDA.shape #GPUARRAYS voluGPU = gu.to_gpu(voluNDA.astype(np.float32)) tempGPU = gu.to_gpu(tempNDA.astype(np.float32)) maskGPU = gu.to_gpu(maskNDA) #Pytom C arrays voluVOL = readd('tomo.mrc') tempVOL = readd('template.em') maskVOL = readd('mask.em') # PASTE TEMPLATE IN CENTER tempCentNDA = np.zeros_like(voluNDA) tempCentNDA = paste_in_center(tempNDA, tempCentNDA) tempCentGPU = gu.zeros_like(voluGPU) paste_in_center_gpu(tempCentGPU, np.int32(spx), np.int32(spy), np.int32(spz), tempGPU, np.int32(sox), np.int32(soy), np.int32(soz), block=(10, 10, 10), grid=(8, 1, 1)) TCG = tempCentGPU.get() tempCentVOL = vol(voluVOL.sizeX(), voluVOL.sizeY(), voluVOL.sizeZ())
def scale(volume, factor, interpolation='Spline'): """ scale: Scale a volume by a factor in REAL SPACE - see also resize function for more accurate operation in Fourier \ space @param volume: input volume @type volume: L{pytom_volume.vol} @param factor: a factor > 0. Factors < 1 will de-magnify the volume, factors > 1 will magnify. @type factor: L{float} @param interpolation: Can be Spline (default), Cubic or Linear @type interpolation: L{str} @return: The scaled volume @author: Thomas Hrabe """ from pytom.voltools import transform from pytom.tompy.tools import paste_in_center if factor <= 0: raise RuntimeError('Scaling factor must be > 0!') interpolation_dict = { 'Spline': 'filt_bspline', 'Linear': 'linear', 'Cubic': 'filt_bspline', 'filt_bspline': 'filt_bspline', 'linear': 'linear' } interpolation = interpolation_dict[interpolation] volume = volume.squeeze() sizeX = volume.shape[0] sizeY = volume.shape[1] sizeZ = 1 newSizeX = int(xp.floor(sizeX * float(factor) + 0.5)) newSizeY = int(xp.floor(sizeY * float(factor) + 0.5)) newSizeZ = 1 if len(volume.shape) == 3: sizeZ = volume.shape[2] newSizeZ = int(xp.floor(sizeZ * factor + 0.5)) scaleF = [1 / factor, 1 / factor, 1 / factor] else: scaleF = [1 / factor, 1 / factor, 1] volume = xp.expand_dims(volume, 2) if factor == 1: rescaledVolume = volume elif factor > 1: newVolume = xp.zeros((newSizeX, newSizeY, newSizeZ), dtype=volume.dtype) newVolume = paste_in_center(volume, newVolume) rescaledVolume = xp.zeros_like(newVolume) transform(newVolume, scale=scaleF, output=rescaledVolume, device=device, interpolation=interpolation) else: rescaledVolumeFull = xp.zeros_like(volume) transform(volume, scale=scaleF, output=rescaledVolumeFull, device=device, interpolation=interpolation) rescaledVolume = xp.zeros((newSizeX, newSizeY, newSizeZ), dtype=volume.dtype) rescaledVolume = paste_in_center(rescaledVolumeFull, rescaledVolume) return rescaledVolume
def CorrectProjection_proxy(fname, new_fname, p, metadata, gs, fs, binning_factor, rotation_angle, def_grad_strip=2.5): """ """ print('Correct projection:', fname) # load the metadata #from numpy import loadtxt # Alignment parameter Tiltaxis = rotation_angle Tiltangle = metadata['TiltAngle'][p] dz1 = -1 * metadata['DefocusU'][p] dz2 = -1 * metadata['DefocusV'][p] alpha = metadata['DefocusAngle'][p] Voltage = metadata['Voltage'][p] Cs = metadata['SphericalAberration'][p] A = metadata['AmplitudeContrast'][p] Imdim = metadata['ImageSize'][p] Objectpixelsize = metadata['PixelSpacing'][p] * 0.1 * binning_factor from pytom.tompy.io import read, write from pytom.tompy.tools import paste_in_center # Load projection # Fast options are 3840, 3888, 4096 size = 3888 projInit = np.array(read(fname)) projInit = np.squeeze(projInit) # squeeze it to 2D proj = np.zeros((size, size)) proj = paste_in_center(projInit, proj) B = (proj.shape[0] - projInit.shape[0]) // 2 sx, sy = proj.shape[0] // 2, proj.shape[1] // 2 x, y = np.meshgrid(np.arange(-sx, sx), np.arange(-sx, sx)) import time s = time.time() projc = CorrectProjection2(proj, dz1, dz2, alpha + Tiltaxis, Tiltangle, Tiltaxis, dfgrad=def_grad_strip, Border=B, ObjectPixelSize=Objectpixelsize, Voltage=Voltage, CS=Cs, AmpContrast=A, x=x, y=y) print(time.time() - s) # Save projection try: mrcfile.new(new_fname, projc.T.get().astype('float32'), overwrite=True) except: mrcfile.new(new_fname, projc.T.astype('float32'), overwrite=True) #write(new_fname, projc, Tiltangles[p]) return True
#print(time.time()-s) mask = tcp.copy() meanT = meanUnderMask(tcp, mask, gpu=gpu) stdT = stdUnderMask(tcp, mask, meanT, gpu=gpu) if stdT > 1E-09: temp2 = (tcp - meanT) / stdT temp2 = temp * mask else: temp2 = tcp mask2 = mask if vcp.shape[0] != temp2.shape[0] or vcp.shape[1] != temp2.shape[ 1] or vcp.shape[2] != temp2.shape[2]: tempV = xp.zeros(vcp.shape) temp2 = paste_in_center(temp2, tempV, gpu=gpu) if vcp.shape[0] != mask.shape[0] or vcp.shape[1] != mask.shape[ 1] or vcp.shape[2] != mask.shape[2]: maskV = xp.zeros(vcp.shape) mask2 = paste_in_center(mask, maskV, gpu=gpu) meanV = meanVolUnderMask(vcp, temp2, gpu=gpu) stdV = stdVolUnderMask(vcp, mask2, meanV, gpu=gpu) from pytom.tompy.transform import rotate3d s = time.time() for i in range(num_angles): tcp2 = xp.array(rotate3d(temp, 10, 10, 10)) m = FLCF(vcp, temp2, mask=mask2, stdV=stdV, gpu=gpu)
wedgeVolume = wedgeFilter.getWeightVolume(True) filterVolume = pytom_volume.reducedToFull(wedgeVolume) wedgeV = vol2npy(filterVolume).copy() from pytom.tompy.io import read import mrcfile print(start, end) volume = mrcfile.open('tomo.mrc', permissive=True).data.copy() volume = volume[start:end, :csize, :csize] assert wedgeV.shape == volume.shape temp = read('template.em') mask = read("mask.em") mask2 = paste_in_center(mask, np.zeros_like(volume)) from pytom.tompy.correlation import meanVolUnderMask, stdVolUnderMask import pytom.basic.correlation as corr from pytom.basic.files import read as readd from pytom.basic.files import write_em from pytom_numpy import vol2npy, npy2vol from pytom_volume import pasteCenter, vol vv = readd('tomo.mrc', subregion=[0, 0, start, 464, 464, end - start]) mm = readd('mask.em') if vv.sizeX() != mm.sizeX() or vv.sizeY() != mm.sizeY() or vv.sizeZ( ) != mm.sizeZ(): maskV = vol(vv.sizeX(), vv.sizeY(), vv.sizeZ()) maskV.setAll(0) pasteCenter(mm, maskV)