Exemple #1
0
def dev(volume, template, mask=None, volumeIsNormalized=False):
    """
    dev: Calculates the squared deviation of volume and template in real space
    @param volume: A volume
    @type volume:  L{pytom_volume.vol}
    @param template: A template that is searched in volume. Must be of same size as volume.
    @type template:  L{pytom_volume.vol}
    @param mask: mask to constrain correlation
    @type mask: L{pytom_volume.vol}
    @param volumeIsNormalized: speed up if volume is already normalized
    @type volumeIsNormalized: L{bool}
    @return: deviation
    @raise exception: Raises a runtime error if volume and template have a different size.
    @author: FF
    """
    from pytom_volume import vol,sum
    from pytom.tools.macros import volumesSameSize

    assert type(volume) == vol, "dev: volume has to be of type vol!"
    assert type(template) == vol, "dev: template has to be of type vol!"
    if not volumesSameSize(volume,template):
        raise RuntimeError('Volume and template must have same size!')

    if not mask:
        p = volume.numelem()
        result = volume-template
    else:
        assert type(mask) == vol, "dev: mask has to be of type vol!"
        p = sum(mask)
        result = (volume-template)*mask

    deviat = sum(result**2)
    deviat = deviat / float(p)

    return deviat
Exemple #2
0
def xcc(volume,template,mask=None, volumeIsNormalized=False):
    """
    xcc: Calculates the cross correlation coefficient in real space
    @param volume: A volume
    @type volume:  L{pytom_volume.vol}
    @param template: A template that is searched in volume. Must be of same size as volume.
    @type template:  L{pytom_volume.vol}
    @param mask: mask to constrain correlation
    @type mask: L{pytom_volume.vol}
    @param volumeIsNormalized: only used for compatibility with nxcc - not used
    @type volumeIsNormalized: L{bool}
    @return: A unscaled value
    @raise exception: Raises a runtime error if volume and template have a different size.  
    @author: Thomas Hrabe 
    """
    from pytom_volume import sum
    from pytom.tools.macros import volumesSameSize
    
    if not volumesSameSize(volume,template):
        raise RuntimeError('Volume and template must have same size!')
   
    if mask: # mask is given
        result = mask * volume * template
    else:
        result = volume * template
    
    cc = sum(result)
    
    cc = cc / float(volume.numelem())
    
    return cc 
Exemple #3
0
def nxcc(volume, template, mask=None, volumeIsNormalized=False):
    """
    nxcc: Calculates the normalized cross correlation coefficient in real space
    @param volume: A volume
    @type volume:  L{pytom_volume.vol}
    @param template: A template that is searched in volume. Must be of same size as volume.
    @type template:  L{pytom_volume.vol}
    @param mask: mask to constrain correlation
    @type mask: L{pytom_volume.vol}
    @param volumeIsNormalized: speed up if volume is already normalized
    @type volumeIsNormalized: L{bool}
    @return: A value between -1 and 1
    @raise exception: Raises a runtime error if volume and template have a different size.
    @author: Thomas Hrabe 
    @change: flag for pre-normalized volume, FF
    """

    from pytom_volume import vol,sum,limit
    from pytom.tools.macros import volumesSameSize
    
    if not volumesSameSize(volume,template):
        raise RuntimeError('Volume and template must have same size!')
    
    if not mask:
        from pytom.basic.normalise import mean0std1
        if not volumeIsNormalized:
           v = mean0std1(volume, True)
        t = mean0std1(template, True)
        p = volume.numelem()
        result = v*t
    else:
        from pytom_numpy import vol2npy
        from pytom.basic.normalise import normaliseUnderMask
        if not volumeIsNormalized:
            (v,p) = normaliseUnderMask(volume, mask)
            (t,p) = normaliseUnderMask(template, mask, p)
            t = t * mask # multiply with the mask
            result = v * t
        else:
            (t,p) = normaliseUnderMask(template,mask)
            t = t * mask # multiply with the mask
            result = volume * t
    
    ncc = sum(result)
    ncc = ncc / float(p)

    return ncc 
Exemple #4
0
    def apply(self, volume):
        """
        apply: Applies weighting defined in this object to value. The return value can be modified if needed. 
        @param volume: A volume
        @return: self.weight * volume
        @author: Thomas Hrabe 
        """
        from pytom.tools.macros import volumesSameSize
        from pytom.tools.files import checkFileExists

        if not self.isInitialized() and (not checkFileExists(self._filename)):
            self.initVolume(volume.sizeX(), volume.sizeY(), volume.sizeZ())
        elif not self.isInitialized():
            self.fromFile()

        assert volumesSameSize(self._weight,
                               volume)  #make sure both have same size

        return self._weight * volume
Exemple #5
0
    def apply(self, volume, bypassFlag=False, downscale=1, particle=None):
        """
        apply: Performs preprocessing of volume and reference
        @param volume: volume to be pre-processed
        @type volume: L{pytom_volume.vol}
        @param bypassFlag: Set if only bandpassFilter needed. False otherwise and all routines will be processed.
        @param downscale: not used anymore
        @param particle: particle Volume to be subtracted from input volume
        @type particle: L{pytom_volume.vol}
        @return: Returns modified volume
        @author: Thomas Hrabe  
        """

        from pytom_volume import vol

        if self._bandpassOn:

            from pytom.basic.filter import bandpassFilter

            # if frequencies specified in Nyquist, 0.5 being highest
            # fixed wrong adjustment of frequencies upon binning - FF
            if self._highestFrequency < 1:
                highestFrequency = self._highestFrequency * volume.sizeX()
                lowestFrequency = self._lowestFrequency * volume.sizeX()
            else:
                highestFrequency = self._highestFrequency
                lowestFrequency = self._lowestFrequency

            v = bandpassFilter(volume=volume,
                               lowestFrequency=lowestFrequency,
                               highestFrequency=highestFrequency,
                               bpf=0,
                               smooth=self._bandpassSmooth)
            volume = v[0]

        if self._prerotateOn and (not bypassFlag):

            from pytom_volume import rotate

            rot = vol(volume.sizeX(), volume.sizeY(), volume.sizeZ())
            rotation = self.prerotate
            rotate(volume, rot, rotation[0], rotation[1], rotation[2])
            volume = rot

        if self._weightingOn and (not bypassFlag):

            from pytom_volume import read
            from pytom_freqweight import weight
            from pytom.basic.fourier import fft, ifft

            wedgeSum = read(self._weightingFile)

            fVolume = fft(volume)
            weighting = weight(wedgeSum)
            weighting.apply(fVolume)
            volume = ifft(fVolume)

        if self._substractParticle and particle.__class__ == vol:
            volume -= particle

        if self._taper > 0:
            from pytom.tools.macros import volumesSameSize
            if self._taperMask is None or not volumesSameSize(
                    volume, self._taperMask):
                from pytom.basic.functions import taper_edges
                volume, self._taperMask = taper_edges(volume, self._taper)
            else:
                volume = volume * self._taperMask

        return volume
Exemple #6
0
    def __init__(self,
                 vol1,
                 vol2,
                 score,
                 mask=None,
                 iniRot=None,
                 iniTrans=None,
                 opti='fmin_powell',
                 interpolation='linear',
                 verbose=False):
        """
        alignment of a particle against a reference

        @param vol1: (constant) volume
        @type vol1: L{pytom_volume.vol}
        @param vol2: volume that is matched to reference
        @type vol2: L{pytom_volume.vol}
        @param score: score for alignment - e.g., pytom.basic.correlation.nxcc
        @type score: L{pytom.basic.correlation}
        @param mask: mask correlation is constrained on
        @type mask: L{pytom_volume.vol}
        @param iniRot: initial rotation of vol2
        @type iniRot: L{pytom.basic.Rotation}
        @param iniTrans: initial translation of vol2
        @type iniTrans: L{pytom.basic.Shift}
        @param opti: optimizer ('fmin_powell', 'fmin', 'fmin_cg', 'fmin_slsqp', 'fmin_bfgs')
        @param interpolation: interpolation type - 'linear' (default) or 'spline'
        @type interpolation: str
        @type opti: L{str}

        @author: FF
        """
        from pytom.basic.normalise import normaliseUnderMask, mean0std1
        from pytom.tools.macros import volumesSameSize
        from pytom_volume import vol
        from pytom.basic.structures import Rotation, Shift
        assert isinstance(interpolation,
                          str), "interpolation must be of type str"

        self.verbose = verbose
        if not volumesSameSize(vol1, vol2):
            raise RuntimeError('Vol1 and vol2 must have same size!')

        # normalize constant volume
        if mask:
            (v, p) = normaliseUnderMask(vol1, mask)
        else:
            v = mean0std1(vol1, True)

        self.vol1 = v
        self.vol2 = vol2
        self.rotvol2 = vol(self.vol1.sizeX(), self.vol2.sizeY(),
                           self.vol2.sizeZ())
        self.mask = mask

        if not iniRot:
            iniRot = Rotation()
        if not iniTrans:
            iniTrans = Shift()
        self.rot_trans = self.transRot2vector(rot=iniRot, trans=iniTrans)

        self.score = score
        self.val = -100000.
        self.centX = int(self.vol1.sizeX() // 2)
        self.centY = int(self.vol1.sizeY() // 2)
        self.centZ = int(self.vol1.sizeZ() // 2)
        self.binning = 1
        self.interpolation = interpolation

        # set optimizer
        self.opti = opti
        if opti == 'fmin':
            self.optimizer = scipy.optimize.fmin
        elif opti == 'fmin_slsqp':
            self.optimizer = scipy.optimize.fmin_slsqp
        elif opti == 'fmin_cg':
            self.optimizer = scipy.optimize.fmin_cg
        elif opti == 'fmin_bfgs':
            self.optimizer = scipy.optimize.fmin_bfgs
        elif opti == 'fmin_powell':
            self.optimizer = scipy.optimize.fmin_powell
        else:
            raise TypeError('opti must be of type str')
Exemple #7
0
def FSC(volume1,volume2,numberBands,mask=None,verbose=False, filename=None):
    """
    FSC - Calculates the Fourier Shell Correlation for two volumes
    @param volume1: volume one
    @type volume1: L{pytom_volume.vol}
    @param volume2: volume two
    @type volume2: L{pytom_volume.vol}
    @param numberBands: number of shells for FSC
    @type numberBands: int
    @param filename: write FSC to ascii file if specified
    @type filename: string

    @return: Returns a list of cc values 
    @author: Thomas Hrabe  
    @rtype: list[floats]
    """
    
    from pytom.basic.correlation import bandCC
    from pytom.tools.macros import volumesSameSize
    from pytom.basic.structures import Mask
    import pytom_volume
    
    if not volumesSameSize(volume1, volume2):
        raise RuntimeError('Volumes must have the same size!')
    
    if mask:
        if mask.__class__ == pytom_volume.vol:
            volume1 = volume1 * mask
            volume2 = volume2 * mask
          
        elif mask.__class__ == Mask:
            mask = mask.getVolume()
            volume1 = volume1 * mask
            volume2 = volume2 * mask
        elif mask.__class__ == str:
            mask = pytom_volume.read(mask)
            volume1 = volume1 * mask
            volume2 = volume2 * mask 
        else:
            raise RuntimeError('FSC: Mask must be a volume OR a Mask object OR a string path to a mask!')  
        
    fscResult = []
    band = [-1,-1]
    
    increment = int(volume1.sizeX()/2 * 1/numberBands)
    
    for i in range(0,volume1.sizeX()//2, increment):
        
        band[0] = i
        band[1] = i + increment
        
        if verbose:
            print('Band : ' ,band)
            
        res = bandCC(volume1,volume2,band,verbose)
        
        if i == 0 and increment == 1:
            #force a 1 for correlation of the zero frequency 
            res[0] = 1
  
        if verbose:
            print('Correlation ' ,res[0])

        fscResult.append(res[0])

    if filename:
        f = open(filename,'w')
        for item in fscResult:
            f.write("%s\n" % item)
        f.close()

    return fscResult