Beispiel #1
0
    def test_FRM(self):
        import swig_frm
        from sh_alignment.frm import frm_align
        from pytom_volume import vol, rotate, shift
        from pytom.basic.structures import Rotation, Shift
        from pytom.tools.maths import rotation_distance

        v = vol(32,32,32)
        v.setAll(0)
        vMod = vol(32,32,32)
        vRot = vol(32,32,32)
        v.setV(1,10,10,10)
        v.setV(1,20,20,20)
        v.setV(1,15,15,15)
        v.setV(1,7,21,7)
        
        rotation = Rotation(10,20,30)
        shiftO = Shift(1,-3,5)
        
        rotate(v,vRot,rotation.getPhi(),rotation.getPsi(),rotation.getTheta())
        shift(vRot,vMod,shiftO.getX(),shiftO.getY(),shiftO.getZ())
        
        pos, ang, score = frm_align(vMod, None, v, None, [4, 64], 10)
        rotdist = rotation_distance(ang1=rotation, ang2=ang)
        diffx = shiftO[0] - (pos[0] - 16)
        diffy = shiftO[1] - (pos[1] - 16)
        diffz = shiftO[2] - (pos[2] - 16)

        self.assertTrue( rotdist < 5., msg='Rotations are different')
        self.assertTrue( diffx < .5, msg='x-difference > .5')
        self.assertTrue( diffy < .5, msg='y-difference > .5')
        self.assertTrue( diffz < .5, msg='z-difference > .5')
Beispiel #2
0
def stdUnderMask(volume, mask, p, meanV):
    """
    stdUnderMask: calculate the std volume under the given mask
    @param volume: input volume
    @type volume:  L{pytom_volume.vol}
    @param mask: mask
    @type mask:  L{pytom_volume.vol}
    @param p: non zero value numbers in the mask
    @type p: L{int}
    @param meanV: mean volume under mask, which should already been caculated
    @type meanV:  L{pytom_volume.vol}
    @return: the calculated std volume under mask
    @rtype:  L{pytom_volume.vol}
    @author: Yuxiang Chen
    """
    from pytom.basic.fourier import fft, ifft, iftshift
    from pytom_volume import vol, power, limit
    
    copyV = vol(volume.sizeX(), volume.sizeY(), volume.sizeZ())
    copyV.copyVolume(volume)
    power(copyV, 2) #calculate the square of the volume
    
    copyMean = vol(meanV.sizeX(), meanV.sizeY(), meanV.sizeZ())
    copyMean.copyVolume(meanV)
    power(copyMean, 2)

    result = meanUnderMask(copyV, mask, p) - copyMean

#    from pytom_volume import abs
#    abs(result)
    limit(result, 1e-09, 1, 0, 0, True, False) # this step is needed to set all those value (close to 0) to 1
    power(result, 0.5)

    return result
Beispiel #3
0
def distance(p, ref, freq, mask, binning):
    from pytom.basic.correlation import nxcc
    from pytom_volume import vol, initSphere, read, pasteCenter
    from pytom.basic.filter import lowpassFilter
    from pytom.basic.transformations import resize
    v = p.getTransformedVolume(binning)
    w = p.getWedge()
    r = ref.getVolume()
    a = lowpassFilter(w.apply(v, p.getRotation().invert()), freq)[0]
    b = lowpassFilter(w.apply(r, p.getRotation().invert()), freq)[0]

    if not mask:
        mask = vol(r)
        initSphere(mask,
                   r.sizeX() // 2 - 3, 3, 0,
                   r.sizeX() // 2,
                   r.sizeY() // 2,
                   r.sizeZ() // 2)
    else:
        #THE MASK is binning (sampled every n-points). This does lead to a reduction of the smoothing of the edges.
        maskBin = read(mask, 0, 0, 0, 0, 0, 0, 0, 0, 0, binning, binning,
                       binning)
        if a.sizeX() != maskBin.sizeX() or a.sizeY() != maskBin.sizeY(
        ) or a.sizeZ() != maskBin.sizeZ():
            mask = vol(a.sizeX(), a.sizeY(), a.sizeZ())
            mask.setAll(0)
            pasteCenter(maskBin, mask)
        else:
            mask = maskBin

    s = nxcc(a, b, mask)

    d2 = 2 * (1 - s)

    return d2
Beispiel #4
0
def theta_vol_projection(vol_src, theta):

    from pytom_volume import vol
    from pytom_volume import rotate
    from pytom_volume import subvolume
    from pytom_volume import sum

    vol_src_dim_x = vol_src.sizeX()
    vol_src_dim_y = vol_src.sizeY()
    vol_src_dim_z = vol_src.sizeZ()

    vol_dst = vol(vol_src_dim_x, vol_src_dim_y, vol_src_dim_z)
    vol_dst.setAll(0.0)

    rotate(vol_src, vol_dst, 270, 90, theta)

    vol_img = vol(vol_src_dim_x, vol_src_dim_y, 1)
    vol_img.setAll(0.0)

    for i in range(vol_src_dim_x):
        for j in range(vol_src_dim_y):

            vol_img.setV(sum(subvolume(vol_dst, i, j, 0, 1, 1, vol_src_dim_z)),
                         i, j, 0)

    return vol_img
Beispiel #5
0
def rotateWeighting(weighting, z1, z2, x, mask=None, isReducedComplex=None, returnReducedComplex=False, binarize=False):
    """
    rotateWeighting: Rotates a frequency weighting volume around the center. If the volume provided is reduced complex, it will be rescaled to full size, ftshifted, rotated, iftshifted and scaled back to reduced size.
    @param weighting: A weighting volume
    @type weighting: L{pytom_volume.vol}
    @param z1: Z1 rotation angle
    @type z1: float
    @param z2: Z2 rotation angle
    @type z2: float
    @param x: X rotation angle
    @type x: float
    @param mask:=None is there a rotation mask? A mask with all = 1 will be generated otherwise. Such mask should be \
        provided anyway.
    @type mask: L{pytom_volume.vol}
    @param isReducedComplex: Either set to True or False. Will be determined otherwise
    @type isReducedComplex: bool
    @param returnReducedComplex: Return as reduced complex? (Default is False)
    @type returnReducedComplex: bool
    @param binarize: binarize weighting
    @type binarize: bool
    @return: weight as reduced complex volume
    @rtype: L{pytom_volume.vol_comp}
    """
    from pytom_volume import vol, limit, vol_comp
    from pytom_volume import rotate
    assert type(weighting) == vol or  type(weighting) == vol_comp, "rotateWeighting: input neither vol nor vol_comp"
    
    isReducedComplex = isReducedComplex or int(weighting.sizeX()/2)+1 == weighting.sizeZ();

    if isReducedComplex:
        #scale weighting to full size
        from pytom_fftplan import fftShift
        from pytom_volume import reducedToFull
        weighting = reducedToFull(weighting)
        fftShift(weighting, True)

    if not mask:
        mask = vol(weighting.sizeX(),weighting.sizeY(),weighting.sizeZ())
        mask.setAll(1)

    weightingRotated = vol(weighting.sizeX(),weighting.sizeY(),weighting.sizeZ())

    rotate(weighting,weightingRotated,z1,z2,x)
    weightingRotated = weightingRotated * mask
    
    if returnReducedComplex:
        from pytom_fftplan import fftShift
        from pytom_volume import fullToReduced
        fftShift(weightingRotated,True)
        returnVolume = fullToReduced(weightingRotated)
    else:
        returnVolume = weightingRotated

    if binarize:
        limit(returnVolume,0.5,0,0.5,1,True,True)
    
    return returnVolume
 def setUp(self):
     """set up"""
     # a point somewhere
     self.myVol = vol(256, 256, 1)
     self.myVol.setAll(0.)
     self.myVol.setV(1., 200, 128, 0)
     self.r = array([200 - 128, 0])
     self.origin = vol(256, 256, 1)
     self.origin.setAll(0.)
     self.origin.setV(1., 128, 128, 0)
     self.m = 0.8
Beispiel #7
0
def writeCroppedParticles(particleListName, output, center, cubesize):
    """
    @param particleListName: name of particle list
    @type particleListName: str
    @param output: Name of output particles
    @type output: str
    @param center: center of output particles in template orientation
    @type center: list
    @param cubesize: Size of output particles in pixel
    @type cubesize: int

    """
    from pytom.basic.structures import ParticleList, Particle, Shift
    from pytom_volume import transformSpline as transform
    from pytom_volume import subvolume, vol


    pl = ParticleList()
    pl.fromXMLFile(filename=particleListName)
    #copy particle list for list of cropped particles
    pl_new = pl.copy()
    pvol = pl[0].getVolume()
    sizeX = pvol.sizeX() 
    sizeY = pvol.sizeY()
    sizeZ = pvol.sizeZ() 
    pvol_ali = vol(sizeX, sizeY, sizeZ) 
    subV = vol(cubesize, cubesize, cubesize)

    sub_startX = center[0]-cubesize/2
    sub_startY = center[1]-cubesize/2
    sub_startZ = center[2]-cubesize/2
    if (sub_startX < 0) or (sub_startY < 0) or (sub_startZ < 0):
        raise ValueError('cubesize too large :(')

    for (ipart, part) in enumerate(pl):
        pvol_ali.setAll(0) 
        subV.setAll(0)
        pvol = part.getVolume()
        rot = part.getRotation()
        rotinvert = rot.invert()
        shiftV = part.getShift() 
        transform(pvol, pvol_ali, rotinvert[0], rotinvert[1], rotinvert[2], 
                  sizeX/2, sizeY/2, sizeZ/2, -shiftV[0], -shiftV[1], -shiftV[2], 0, 0, 0) 
        # box out subvolume
        subV = subvolume(pvol_ali,  sub_startX, sub_startY, sub_startZ, cubesize, cubesize, cubesize)
        transform(subV, subV, rot[0], rot[1], rot[2], cubesize/2, cubesize/2, cubesize/2, 0, 0, 0, 0, 0, 0)
        fname = part.getFilename()
        idx = fname.split('_')[-1].split('.')[0] 
        nfname = output+'_'+idx+'.em'
        print("write file " + nfname)
        subV.write(nfname)
        pl_new[ipart].setFilename(newFilename=nfname)
        pl_new[ipart].setShift(shift=Shift(0,0,0))
    return pl_new
Beispiel #8
0
    def sum_sub_pl(self, pl, name_prefix):
        """This is a sub-routine for average_sub_pl.
        """
        from pytom_volume import vol
        from pytom_volume import transformSpline as transform
        from pytom.basic.normalise import mean0std1

        result = None
        wedgeSum = None
        for p in pl:
            particle = p.getVolume()
            mean0std1(particle)
            wedgeInfo = p.getWedge()

            if result is None:
                sizeX = particle.sizeX()
                sizeY = particle.sizeY()
                sizeZ = particle.sizeZ()

                newParticle = vol(sizeX, sizeY, sizeZ)
                # make consistent for python3
                centerX = sizeX // 2
                centerY = sizeY // 2
                centerZ = sizeZ // 2

                result = vol(sizeX, sizeY, sizeZ)
                result.setAll(0)

                wedgeSum = wedgeInfo.returnWedgeVolume(sizeX, sizeY, sizeZ)
                wedgeSum.setAll(0)

            # create wedge weighting
            rotation = p.getRotation()

            wedge = wedgeInfo.returnWedgeVolume(sizeX, sizeY, sizeZ, False,
                                                rotation.invert())
            wedgeSum = wedgeSum + wedge

            # shift and rotate particle
            shift = p.getShift()
            newParticle.setAll(0)
            transform(particle, newParticle, -rotation[1], -rotation[0],
                      -rotation[2], centerX, centerY, centerZ, -shift[0],
                      -shift[1], -shift[2], 0, 0, 0)

            result = result + newParticle

        # write them back to disk
        result.write(name_prefix + '-PreWedge.em')
        wedgeSum.write(name_prefix + '-WedgeSumUnscaled.em')
Beispiel #9
0
 def showRotations(self,volume,directory,mask=None):
     """
     showRotations: Will store x,y,z slice through volume after each rotation was applied 
     """
     from pytom.tools.toImage import volumeToPNG
     from pytom.tools.files import dump2TextFile
     from pytom_volume import vol,rotateSpline
     from pytom.tools.files import getPytomPath,readStringFile
     from pytom.frontend.htmlDefines import headResponse200,copyright
 
     pytomPath = getPytomPath()
     cssDefines = readStringFile(pytomPath + '/frontend/htmlDefines/CSS.css')
 
     html = '<html>' + cssDefines
     html = html + '\n<title>PyTom Alignment</title>\n'
     html = html + '<body><center><h1 type="Main">List of Rotations</h1></center>\n'
     html = html + '</br></br></br></br></br></br></br></br><center>\n'
     html = html + '<table>\n'
     html = html + '<tr><td>Z1 (Phi) Z2 (Psi) X(Theta)</td><td>x-Slice</td><td>y-Slice</td><td>z-Slice</td></tr>'
     
     rotated = vol(volume.sizeX(),volume.sizeY(),volume.sizeZ())
     
     if not mask:
         mask = vol(volume.sizeX(),volume.sizeY(),volume.sizeZ())
         mask.setAll(1)
         
     volume = volume * mask    
     
     self.reset()
     
     rotation = self.nextRotation()
     rotationCounter = 0
     
     while not rotation == [None,None,None]:
     
         rotateSpline(volume,rotated,rotation[0],rotation[1],rotation[2])
         html = html + '<tr><td>' + str(rotation[0]) + ' ' + str(rotation[1]) + ' ' + str(rotation[2]) +'</td>/n'
         volumeToPNG(rotated,directory + str(rotationCounter) + '-x.png',rotated.sizeX()/2,'x')
         html = html + '<td><img src="' + directory + str(rotationCounter) + '-x.png"/></td>'
         volumeToPNG(rotated,directory + str(rotationCounter) + '-y.png',rotated.sizeY()/2,'y')
         html = html + '<td><img src="' + directory + str(rotationCounter) + '-y.png"/></td>'
         volumeToPNG(rotated,directory + str(rotationCounter) + '-z.png',rotated.sizeZ()/2,'z')
         html = html + '<td><img src="' + directory + str(rotationCounter) + '-z.png"/></td>'
         
         rotation = self.nextRotation()
         rotationCounter = rotationCounter + 1 
     
     html = html + '</body></html>'
     
     dump2TextFile(directory + 'rotations.html',html)
Beispiel #10
0
def create_bfactor_vol(size, ps, bfactor, FSC=None, apply_range=None):
    """Create a B-factor volume in Frequency space.
    @param size: The size of the volume, assuming it is a cube
    @param ps: The pixel size in angstrom
    @param bfactor: B factor
    @param FSC: Fourier Shell Correlation
    @param apply_range: The apply range (also in angstrom) of the B factor correction
    """
    if FSC is None:
        FSC = np.ones(size / 2)

    # transfer the pixel size to angstrom
    x = (ps * size) / np.arange(1, size / 2 + 1, 1)  # starts from 1!
    if apply_range is None:
        apply_range_pixel = [1, size / 2]  # starts from 1!
    else:
        assert apply_range[0] > apply_range[1]
        apply_range_pixel = [
            size * ps / apply_range[0], size * ps / apply_range[1]
        ]

    # create the FSC weight
    FSC_weight = np.sqrt((2 * np.array(FSC)) / (1 + np.array(FSC)))

    # calculate the decay function
    decay = FSC_weight * np.exp(-bfactor / (np.power(x, 2) * 4))

    # make the decay volume
    v = sph2cart(decay, size)

    # transfer to the volume format and multiple with the mask
    from pytom_volume import vol, initSphere
    from pytom_numpy import npy2vol
    vv = npy2vol(np.array(v, dtype='float32', order='F'), 3)

    if apply_range_pixel[0] == 1:
        mask = vol(size, size, size)
        initSphere(mask, apply_range_pixel[1] - 1, 0, 0, size / 2, size / 2,
                   size / 2)  # minus 1 to make it consistent with python
    else:
        mask1 = vol(size, size, size)
        mask2 = vol(size, size, size)
        initSphere(mask1, apply_range_pixel[0] - 1, 0, 0, size / 2, size / 2,
                   size / 2)
        initSphere(mask2, apply_range_pixel[1] - 1, 0, 0, size / 2, size / 2,
                   size / 2)
        mask = mask2 - mask1

    return vv * mask
Beispiel #11
0
    def setUp(self):
        from helper_functions import create_RandomParticleList
        from pytom.tompy.io import read_size
        from pytom_volume import vol, initSphere

        self.reffile = './testData/ribo.em'
        self.pl_filename = 'pl.xml'
        self.pdir = './testparticles'
        self.pl = create_RandomParticleList(reffile=self.reffile,
                                            pl_filename=self.pl_filename,
                                            pdir=self.pdir,
                                            nparticles=10)

        # set parameters for GLocal
        self.settings = {}
        self.settings["binning"] = 4
        self.settings["niteration"] = 1
        self.settings["mask"] = './testData/ribo_mask.em'
        dims = read_size(self.reffile)
        maskvol = vol(int(dims[0]), int(dims[1]), int(dims[2]))
        initSphere(maskvol, 30, 5, 0, int(dims[0] / 2), int(dims[1] / 2),
                   int(dims[2] / 2))
        maskvol.write(self.settings["mask"])
        self.settings["destination"] = './'
        #self.settings["score"] = 'nxcf'
        self.settings["score"] = 'flcf'
        self.settings["pixelsize"] = 2.
        self.settings["diameter"] = 250.
        self.settings["job"] = './myGLocal.xml'
Beispiel #12
0
def rampFilter(sizeX, sizeY):
    """
    rampFilter: Generates the weighting function required for weighted backprojection - y-axis is tilt axis

    @param sizeX: size of weighted image in X
    @param sizeY: size of weighted image in Y

    @return: filter volume
    
    """
    from pytom_volume import vol
    from math import exp
    import time

    s = time.time()
    centerX = sizeX // 2

    centerY = sizeY // 2
    sizeY = (sizeY // 2) + 1

    Ny = sizeX // 2

    filter_vol = vol(sizeX, sizeY, 1)
    filter_vol.setAll(0.0)

    for i in range(sizeX):
        distX = abs(float(i - centerX))
        ratio = distX / Ny
        for j in range(sizeY):
            filter_vol.setV(ratio, i, j, 0)
    print('ramp filter takes: ', time.time() - s, sizeX, sizeY)
    return filter_vol
Beispiel #13
0
    def rotationDistanceMatrix(self):
        """
        rotationDistanceMatrix: Generate a matrix of rotation distances. The 
        distance is determined by L{pytom.angles.quaternions.Quaternion.distance}.
        @return: L{pytom_volume.vol} of rotation distances
        @author: Thomas Hrabe
        """
        from pytom_volume import vol
        from pytom.tools.maths import rotation_distance
        numberOfRotations = len(self)

        distanceMatrix = vol(numberOfRotations,numberOfRotations,1)
        distanceMatrix.setAll(0)

        for i in range(len(self)):
            if i < len(self):
                for j in range(i+1,len(self)):
                    ri = self[i]
                    rj = self[j]

                    d = rotation_distance(ri,rj)

                    distanceMatrix(d,i,j,0)
                    distanceMatrix(d,j,i,0)

            distanceMatrix(0,i,i,0)

        return distanceMatrix
Beispiel #14
0
    def average(self, mask=None):
        """
        average Image Stack

        @param mask: mask is multiplied with average if specified
        @type mask: L{pytom_volume.vol}
        @return: average
        @rtype: L{ptom_volume.vol}
        """
        from pytom.basic.transformations import general_transform2d

        if self.averageData == None:
            self.averageData = vol(self.dimX, self.dimY, 1)
        self.averageData.setAll(0.)
        for ii in range(0, len(self.images)):
            self.imageCopies[ii].data = general_transform2d(
                v=self.images[ii].data,
                rot=-self.images[ii].rotation,
                shift=[-self.images[ii].shiftX, -self.images[ii].shiftY],
                scale=1.,
                order=[2, 1, 0],
                crop=True)
            self.averageData = self.averageData + self.imageCopies[ii].data
        if mask:
            self.averageData = self.averageData * mask
        return self.averageData
Beispiel #15
0
 def toEMFile(self,filename, inputIsRadians=False):
     """
     toEMFile: Will save all rotations to EM file. The EM file can be read out by L{pytom.angles.fromFile.AngleListFromEM}
     @param filename: Name of file to save to 
     @param inputIsRadians: 
     """
     from pytom_volume import vol
     
     no = self.numberRotations()
      
     anglesVolume = vol(3,no,1) 
     
     rotations = self.getAllRotations()
     
     i = 0
     for rotation in rotations:
         if rotation == [None, None, None]:
             break
         if inputIsRadians:
             anglesVolume.setV(rotation[0],0,i,0)
             anglesVolume.setV(rotation[1],1,i,0)
             anglesVolume.setV(rotation[2],2,i,0)
         else:
             from pytom.angles.angle import deg2rad
             anglesVolume.setV(rotation[0]*deg2rad,0,i,0)
             anglesVolume.setV(rotation[1]*deg2rad,1,i,0)
             anglesVolume.setV(rotation[2]*deg2rad,2,i,0)               
         
         i = i+1
         
     anglesVolume.write(filename)
Beispiel #16
0
def powerspectrum(volume):
    """
    compute power spectrum of a volume
    
    @param volume: input volume
    @type volume: L{pytom_volume.vol}
    @return: power spectrum of vol
    @rtype: L{pytom_volume.vol}

    @author: FF
    """
    from pytom.basic.fourier import fft, ftshift
    from pytom_volume import vol
    from pytom_volume import reducedToFull

    fvol = ftshift(reducedToFull(fft(volume)),inplace=False)
    nx=fvol.sizeX()
    ny=fvol.sizeY()
    nz=fvol.sizeZ()
    ps = vol(nx,ny,nz)
    sf = 1./(nx*ny*nz)

    for ix in range(0,nx):
        for iy in range(0,ny):
            for iz in range(0,nz):
                temp = fvol.getV(ix,iy,iz)
                temp = temp*temp.conjugate()*sf
                ps.setV(float(temp.real),ix,iy,iz)
    return ps
Beispiel #17
0
    def toMotif(self, filename):
        """
        toMotif:
        @param filename: 
        @type filename: L{str}
        @todo: add unit test
        """
        from pytom_volume import vol
        l = self.len()
        motif = vol(20, l, 1)
        motif.setAll(0)
        for i in range(l):

            #correlation coefficient
            motif.setV(1, 0, i, 0)

            motif.setV(i + 1, 3, i, 0)

            res = self._alignmentList[i]
            shift = res.getShift()
            motif.setV(shift[0], 10, i, 0)
            motif.setV(shift[1], 11, i, 0)
            motif.setV(shift[2], 12, i, 0)

            rotation = res.getRotation()
            motif.setV(rotation[0], 16, i, 0)
            motif.setV(rotation[1], 17, i, 0)
            motif.setV(rotation[2], 18, i, 0)

        motif.write(filename)
Beispiel #18
0
def readSpider(filename):
    """
    readSpider: Reads a spider file and returns a volume
    @param filename: The file name 
    @return: L{pytom_volume.vol}
    """
    
    if not checkFileExists(filename):
        raise IOError('File ' + filename + ' not found!')
    
    from pytom_volume import vol
    import struct
    from math import ceil
    
    fileHandle = open(filename,'rb')
    z = int(struct.unpack('f',fileHandle.read(4))[0]) #nslice
    x = int(struct.unpack('f',fileHandle.read(4))[0]) #nrows
    
    fileHandle.seek(44)
    
    y = int(struct.unpack('f',fileHandle.read(4))[0]) #nsam

    volume = vol(x,y,z)
    
    fileHandle.seek(int(ceil(256.0/float(y)) * y * 4))
    
    for z in range(volume.sizeZ()):
        for y in range(volume.sizeY()):
            for x in range(volume.sizeX()):
                value = float(struct.unpack('f',fileHandle.read(4))[0])
                volume(value,x,y,z)
    
    fileHandle.close()
    
    return volume
Beispiel #19
0
def fourierFilterShift_ReducedComplex(filter):
    """
    fourierFilterShift: NEEDS Documentation
    @param filter: NEEDS Documentation
    """
    from pytom_volume import vol

    widthX = filter.sizeX()
    centerX = filter.sizeX()//2
    boxX = filter.sizeX()//2

    widthY = filter.sizeY()
    centerY = filter.sizeY()//2
    boxY = filter.sizeY()//2

    shifted_filter = vol(widthX, widthY, 1)
    shifted_filter.setAll(0.0)

    for i in range(widthX):
        rx = (boxX-i)%widthX

        for j in range(widthY):
            ry = (boxY-j)%widthY

            shifted_filter.setV(filter.getV(i, j, 0), rx, widthY-j-1, 0)

    return shifted_filter
Beispiel #20
0
def circleFilter(sizeX,sizeY, radiusCutoff):
    """
    circleFilter: NEEDS Documentation
    @param sizeX: NEEDS Documentation 
    @param sizeY: NEEDS Documentation
    @param radiusCutoff: NEEDS Documentation
    """
    from pytom_volume import vol
    
    centerX = sizeX//2
        
    centerY = sizeY//2
    sizeY = (sizeY//2) +1
        
    filter_vol = vol(sizeX, sizeY, 1)
    filter_vol.setAll(0.0)
    
    for i in range(sizeX):        
        for j in range(sizeY):
                        
            radius = ((i-centerX)*(i-centerX)+(j-centerY)*(j-centerY))**0.5
                                                
            if radius <= radiusCutoff:
                filter_vol.setV(1.0, i, j, 0)
                
    return filter_vol
    def test_resize2D(self):
        """
        test re-sizing in Fourier space
        """
        from pytom.basic.transformations import resize
        from pytom_volume import vol
        from pytom.basic.fourier import fft

        dim = 32
        px = 11
        py = 19
        scf = dim * dim
        myVol = vol(dim, dim, 1)
        myVol.setAll(0.)
        myVol.setV(1., px, py, 0)
        #fmyVol = fft(myVol)
        (resizeVol, resizefVol) = resize(volume=myVol,
                                         factor=2.,
                                         interpolation='Fourier')
        resizeVol.write('test1.em')
        ftresizeVol = fft(data=resizeVol)
        for ix in range(resizefVol.sizeX()):
            for iy in range(resizefVol.sizeY()):
                diff = ftresizeVol.getV(
                    ix, iy, 0) - scf * 4 * resizefVol.getV(ix, iy, 0)
                self.assertTrue(expr=abs(diff) < .05,
                                msg="inconsistency FFT/IFFT for magnification")
        (resizeVol, resizefVol) = resize(volume=resizeVol,
                                         factor=.5,
                                         interpolation='Fourier')
        from pytom_volume import variance
        diff = myVol - resizeVol
        self.assertTrue(expr=variance(diff, False) < .0000001,
                        msg="2D image before and after rescales differs")
Beispiel #22
0
def add(volume, SNR=1):
    """
    add Adds white noise to volume
    @param volume: A volume
    @param SNR: Signal to Noise ratio of result
    @type SNR: int or float > 0 
    @return: Volume containing noise with SNR == SNR
    @author: Thomas Hrabe  
    """

    if (SNR < 0):
        return volume

    from math import sqrt
    from pytom_volume import vol, mean, variance, gaussianNoise

    m = mean(volume)
    s = sqrt(variance(volume, False) / SNR)  # SNR = Var(signal) / Var(noise)

    #    s = sqrt(variance(volume,False)/SNR)-variance(volume,False)
    #
    #    if s<0:
    #        return volume
    #    elif s==0:
    #        s =1

    noise = vol(volume.sizeX(), volume.sizeY(), volume.sizeZ())

    gaussianNoise(noise, m, s)  # s is actually the std

    result = volume + noise

    return result
Beispiel #23
0
def initSphere(cubeSize,
               radius,
               smoothing=0,
               centerX=None,
               centerY=None,
               centerZ=None):
    """
    initSphere: Initilizes a volume with a sphere
    @param cubeSize: The size of the whole volume
    @param radius: Radius of the sphere
    @param smoothing: Smoothing at the edges of the sphere
    @param centerX: Center of shpere along X axis
    @param centerY: Center of shpere along Y axis
    @param centerZ: Center of shpere along Z axis  
    """
    from pytom_volume import vol, initSphere

    sphere = vol(cubeSize, cubeSize, cubeSize)
    sphere.setAll(0)

    if centerX is None:
        centerX = cubeSize / 2 - 1

    if centerY is None:
        centerY = cubeSize / 2 - 1

    if centerZ is None:
        centerZ = cubeSize / 2 - 1

    initSphere(sphere, radius, smoothing, 0, centerX, centerY, centerZ)

    return sphere
Beispiel #24
0
def rampFilter( sizeX, sizeY, crowtherFreq=None):
    """
    rampFilter: Generates the weighting function required for weighted backprojection - y-axis is tilt axis

    @param sizeX: size of weighted image in X
    @param sizeY: size of weighted image in Y

    @return: filter volume
    
    """
    from pytom_volume import vol
    from math import exp

    centerX = sizeX//2
    
    centerY = sizeY//2
    sizeY = (sizeY//2) +1

    if crowtherFreq is None:
        Ny = sizeX//2
    else:
        Ny = crowtherFreq

    filter_vol = vol(sizeX, sizeY, 1)
    filter_vol.setAll(0.0)
    
    for i in range(sizeX):        
        distX = abs(float(i-centerX))
        ratio = min(1, distX/Ny)
        for j in range(sizeY):            
            filter_vol.setV(ratio, i, j, 0)

    return filter_vol
Beispiel #25
0
def hanning_taper(volume1, avg):
    
    import math
    
    sizex = volume1.sizeX()
    sizey = volume1.sizeY()
    sizez = volume1.sizeZ()
    cx0 = math.pi * 2.0 /(sizex - 1)
    cx1 = math.pi * 2.0 /(sizey - 1)
    cx2 = math.pi * 2.0 /(sizez - 1)
    volume2 = vol(sizex,sizey,sizez)
    volume2.setAll(0)
 
    for zz in xrange(0, sizez):
        han2 = 0.5 * (1.0 - math.cos(cx2 * zz))
        for yy in xrange(0, sizey):
            han1 = 0.5 * (1.0 - math.cos(cx1 * yy))
            for xx in xrange(0, sizex):
               han0 = 0.5 * (1.0 - math.cos(cx0 * xx))
               vol_han = han0 * han1 * han2
               value2 = (volume1(xx,yy,zz) - avg)*vol_han + avg
               volume2.setV(round(value2,6),xx,yy,zz)

    del cx0,cx1,cx2,sizex,sizey,sizez,han0,han1,han2,value2,vol_han
    return volume2
Beispiel #26
0
def power(volume, exponent, inplace=False):
    """
    power: Pixelwise power 
    @param volume: The volume
    @type volume: L{pytom_volume.vol}
    @param exponent: The exponent
    @type exponent: L{float}
    @param inplace: Perform power inplace? Default is False   
    @type inplace: L{bool}
    @return: volume
    @rtype: L{pytom_volume.vol}
    """

    if inplace:
        from pytom_volume import power

        power(volume, exponent)

    else:
        #return new volume object
        from pytom_volume import vol, power

        volume2 = vol(volume.sizeX(), volume.sizeY(), volume.sizeZ())
        volume2.copyVolume(volume)

        power(volume2, exponent)

        return volume2
Beispiel #27
0
def frm_proxy(p, ref, freq, offset, binning, mask):
    from pytom_volume import read, pasteCenter, vol
    from pytom.basic.transformations import resize
    from pytom.basic.structures import Shift, Rotation
    from sh_alignment.frm import frm_align
    import time

    v = p.getVolume(binning)

    if mask.__class__ == str:
        maskBin = read(mask, 0, 0, 0, 0, 0, 0, 0, 0, 0, binning, binning,
                       binning)
        if v.sizeX() != maskBin.sizeX() or v.sizeY() != maskBin.sizeY(
        ) or v.sizeZ() != maskBin.sizeZ():
            mask = vol(v.sizeX(), v.sizeY(), v.sizeZ())
            mask.setAll(0)
            pasteCenter(maskBin, mask)
        else:
            mask = maskBin

    pos, angle, score = frm_align(v, p.getWedge(), ref.getVolume(), None,
                                  [4, 64], freq, offset, mask)

    return (Shift([
        pos[0] - v.sizeX() // 2, pos[1] - v.sizeY() // 2,
        pos[2] - v.sizeZ() // 2
    ]), Rotation(angle), score, p.getFilename())
Beispiel #28
0
def calculate_difference_map_proxy(r1, band1, r2, band2, mask, focus_mask, binning, iteration, sigma, threshold, outdir='./'):
    from pytom_volume import read, vol, pasteCenter
    from pytom.basic.structures import Particle, Mask
    import os
    from pytom.basic.transformations import resize

    v1 = r1.getVolume()
    v2 = r2.getVolume()
    if mask:
        maskBin = read(mask, 0,0,0,0,0,0,0,0,0, binning, binning, binning)
        if v1.sizeX() != maskBin.sizeX() or v1.sizeY() != maskBin.sizeY() or v1.sizeZ() != maskBin.sizeZ():
            mask = vol(v1.sizeX(), v1.sizeY(), v1.sizeZ())
            mask.setAll(0)
            pasteCenter(maskBin, mask)
        else:
            mask = maskBin

    else:
        mask = None

    if focus_mask:
        focusBin = read(focus_mask, 0,0,0,0,0,0,0,0,0, binning, binning, binning)
        if v1.sizeX() != focusBin.sizeX() or v1.sizeY() != focusBin.sizeY() or v1.sizeZ() != focusBin.sizeZ():
            focus_mask = vol(v1.sizeX(), v1.sizeY(), v1.sizeZ())
            focus_mask.setAll(0)
            pasteCenter(focusBin, focus_mask)
        else:
            focus_mask = focusBin
    else:
        focus_mask = None

    if not focus_mask is None and not mask is None:
        if mask.sizeX() != focus_mask.sizeX():
            raise Exception('Focussed mask and alignment mask do not have the same dimensions. This cannot be correct.')

    (dmap1, dmap2) = calculate_difference_map(v1, band1, v2, band2, mask, focus_mask, True, sigma, threshold)
    fname1 = os.path.join(outdir, 'iter'+str(iteration)+'_dmap_'+str(r1.getClass())+'_'+str(r2.getClass())+'.em')
    dmap1.write(fname1)
    fname2 = os.path.join(outdir, 'iter'+str(iteration)+'_dmap_'+str(r2.getClass())+'_'+str(r1.getClass())+'.em')
    dmap2.write(fname2)

    dp1 = Particle(fname1)
    dp1.setClass(r1.getClass())
    dp2 = Particle(fname2)
    dp2.setClass(r2.getClass())

    return (dp1, dp2)
Beispiel #29
0
def create_bfactor_restore_vol(size, ps, bfactor, FSC=None, apply_range=None):
    from pytom_volume import vol
    v = create_bfactor_vol(size, ps, bfactor, FSC, apply_range)
    unit = vol(v)
    unit.setAll(1)
    restore = unit / v

    return restore
Beispiel #30
0
def applySymmetryToVolume(volume,symmetryObject,wedgeInfo):
    """
    applySymmetryToVolume
    @deprecated: use L{pytom.basic.structures.Symmetry.apply} instead!
    """
    from pytom_volume import read,rotate,shift,vol,initSphere,complexDiv
    from pytom_freqweight import weight
    from pytom.basic.fourier import fft,ifft,ftshift
    from pytom.basic.filter import filter
    from pytom.alignment.structures import ExpectationResult
    from pytom.basic.structures import Reference,Symmetry
    from pytom.tools.maths import epsilon
    
    
    if not volume.__class__ == vol:
        raise Exception('You must provide a volume as first parameter to applySymmetryToObject')
    
    if not symmetryObject.__class__ == Symmetry:
        raise Exception('You must provide a Symmetry object as second parameter to applySymmetryToObject')
    
    result = vol(volume.sizeX(),volume.sizeY(),volume.sizeZ())
    result.copyVolume(volume)
    
    sizeX = volume.sizeX()
    sizeY = volume.sizeY()
    sizeZ = volume.sizeZ()
    
    rot = vol(sizeX,sizeY,sizeZ)
    
    wedgeSum = vol(sizeX,sizeY,sizeZ/2+1)
    wedgeSum.setAll(0.0)
    
    angleList = symmetryObject.getAngleList()
    
    rotation = angleList.nextRotation() 
    
    while not rotation == [None,None,None]:
        
          rotate(volume,rot,rotation[0],rotation[1],rotation[2])          
          result = result + rot
          
          rotation = angleList.nextRotation()
    

    result.shiftscale(0.0,1/float(angleList.numberRotations()))
    return result