Exemple #1
0
    def PeakJobMsg_Test(self):
        from pytom.localization.peak_job_msg import PeakJobMsg
        from pytom.localization.peak_job import PeakJob
        from pytom.basic.structures import Mask, Reference, WedgeInfo
        from pytom.localization.structures import Volume
        from pytom.score.score import FLCFScore
        from pytom.angles.angleList import AngleList

        v = Volume(self.testfilename)
        ref = Reference(self.testfilename)
        m = Mask(self.testfilename)
        w = WedgeInfo(30)
        s = FLCFScore()

        rot = AngleList([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

        j = PeakJob(v, ref, m, w, rot, s)

        a = PeakJobMsg(str(0), str(1))
        a.setJob(j)
        xmlObj = a.toXML()
        b = PeakJobMsg()
        b.fromXML(xmlObj)

        self.assertTrue(b.getSender() == a.getSender(), msg='')
        self.assertTrue(b.getRecipient() == a.getRecipient(), msg='')
Exemple #2
0
    def PeakJob_Test(self):
        from pytom.localization.peak_job import PeakJob
        from pytom.basic.structures import Mask, Reference, WedgeInfo
        from pytom.localization.structures import Volume
        from pytom.score.score import FLCFScore
        from pytom.angles.angleList import AngleList

        v = Volume(self.testfilename)
        ref = Reference(self.testfilename)
        m = Mask(self.testfilename)
        w = WedgeInfo(30)
        s = FLCFScore()

        rot = AngleList([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

        a = PeakJob(v, ref, m, w, rot, s, 1)
        xmlObj = a.toXML()
        b = PeakJob()
        b.fromXML(xmlObj)

        self.assertTrue(b.volume.getFilename() == a.volume.getFilename(),
                        msg='')
        self.assertTrue(b.jobID == a.jobID, msg='')
        self.assertTrue(b.reference.getReferenceFilename() ==
                        a.reference.getReferenceFilename(),
                        msg='')
        self.assertTrue(b.mask.getFilename() == a.mask.getFilename(), msg='')
        self.assertTrue(b.wedge.getWedgeAngle() == a.wedge.getWedgeAngle(),
                        msg='')
        self.assertTrue(b.score.getScoreFunc() == a.score.getScoreFunc(),
                        msg='')
Exemple #3
0
def simulationDescriptionToParticleList(directory,prefix = ''):
    """
    simulationDescriptionToParticleList: 
    """
    lenDir = len(directory)
    
    if not directory[lenDir-1] == '/':
        directory = directory + '/'
        
    xmlFile = directory + 'desc.xml'
    
    from lxml import etree
    
    simulationXML = etree.parse(xmlFile)
    
    #print etree.tostring(simulationXML,pretty_print=True)
    particles = simulationXML.xpath('particle')
    parameters = simulationXML.xpath('Simulation_Parameters')
    
    wedge = int(parameters[0].get('wangleEnd'))/2
    
    from pytom.basic.structures import Particle,ParticleList,WedgeInfo

    wi = WedgeInfo(wedge,[0.0,0.0,0.0])
    
    pl = ParticleList(directory)
    
    for particle in particles:
        
        filename = prefix + particle.get('filename')
        rotation = particle.get('rotation')
        rotation = rotation.replace('[','')
        rotation = rotation.replace(']','')
        rotation = rotation.split(',')
        rotation = [float(rotation[0]),float(rotation[1]),float(rotation[2])]
        
        shift = particle.get('shift')
        shift = shift.replace('[','')
        shift = shift.replace(']','')
        shift = shift.split(',')
        shift = [int(round(float(shift[0]))),int(round(float(shift[1]))),int(round(float(shift[2])))]
        
        p = Particle(filename,rotation = rotation,shift = shift,wedge=wi)
        
        pl.append(p)
    
    #al.toXMLFile(directory+'AlignmentList.xml')
    
    return pl
Exemple #4
0
    def setUp(self):
        """set up"""
        from pytom_volume import vol, initSphere
        from pytom.basic.structures import WedgeInfo
        from pytom.simulation.EMSimulation import simpleSimulation

        self.wedge = 0.
        self.shift = [-1, 2, 3]
        self.rotation = [0, 0, 0]
        # create sphere
        self.v = vol(32, 32, 32)
        self.mask = vol(32, 32, 32)
        initSphere(self.v, 10, 2, 0, 15, 15, 15)
        # there is a slight inconsistency when smoothing > 0 -
        # cleaner implementation would be multipliction with sqrt(mask) in corr function
        initSphere(self.mask, 13, 0, 0, 16, 16, 16)
        self.wi = WedgeInfo(wedgeAngle=self.wedge,
                            rotation=[10.0, 20.0, 30.0],
                            cutoffRadius=0.0)
        self.s = simpleSimulation(volume=self.v,
                                  rotation=self.rotation,
                                  shiftV=self.shift,
                                  wedgeInfo=self.wi,
                                  SNR=10.)
from pytom.basic.structures import WedgeInfo
from pytom.localization.extractPeaks import extractPeaks
from pytom.angles.fromFile import AngleListFromEM
from pytom.basic.normalise import mean0std1
from pytom.simulation.whiteNoise import add
from pytom.basic.correlation import nxcc

v = read('/fs/home/ychen/matlab/template/binning/temp80SRibosome_bin2.em')
b = 32
v2 = vol(v)

w = np.array(create_wedge_sf(-60, 60, b))
m = np.ones(4 * b**2)

mask = read('/fs/home/ychen/matlab/test_frm/mask_11.em')
wedge = WedgeInfo(30.0)
angles = AngleListFromEM("")
angles.readRotationsFromEMFile("angles_12.85_7112.em")
# angles.readRotationsFromEMFile("angles_17.86_3040.em")


def frm_fourier_constrained_vol(vf, mf, vg, mg):
    radius = vf.sizeX() / 2 - 3  # intepolation in the outer part is nonsense

    from pytom.basic.fourier import fft, ifft, ftshift, iftshift

    vf = ftshift(reducedToFull(fft(iftshift(vf, inplace=False))),
                 inplace=False)
    vg = ftshift(reducedToFull(fft(iftshift(vg, inplace=False))),
                 inplace=False)
Exemple #6
0
def weightedXCC(volume, reference, numberOfBands, wedgeAngle=-1, gpu=False):
    """
    weightedXCC: Determines the band weighted correlation coefficient for a volume and reference. Notation according Steward/Grigorieff paper
    @param volume: A volume
    @type volume: L{pytom_volume.vol}
    @param reference: A reference of same size as volume
    @type reference: L{pytom_volume.vol}
    @param numberOfBands: Number of bands
    @param wedgeAngle: A optional wedge angle
    @return: The weighted correlation coefficient
    @rtype: float
    @author: Thomas Hrabe
    """

    if gpu:
        import cupy as xp
    else:
        import numpy as xp

    from pytom.tompy.transform import fft, fourier_reduced2full
    from pytom.basic.structures import WedgeInfo

    result = 0
    numberVoxels = 0

    #volume.write('vol.em');
    #reference.write('ref.em');

    wedge = WedgeInfo(wedgeAngle)
    wedgeVolume = wedge.returnWedgeVolume(volume.shape[0], volume.shape[1],
                                          volume.shape[2])

    increment = int(volume.shape[0] / 2 * 1 / numberOfBands)
    band = [0, 100]
    for i in range(0, volume.shape[0] / 2, increment):

        band[0] = i
        band[1] = i + increment

        r = bandCC(volume, reference, band, gpu=gpu)
        cc = r[0]

        #print cc;
        filter = r[1]

        #get bandVolume
        bandVolume = filter.getWeightVolume(True)

        filterVolumeReduced = bandVolume * wedgeVolume
        filterVolume = fourier_reduced2full(filterVolumeReduced)

        #determine number of voxels != 0
        N = (filterVolume != 0).sum()

        w = xp.sqrt(1 / float(N))

        #add to number of total voxels
        numberVoxels = numberVoxels + N
        #print 'w',w;
        #print 'cc',cc;
        #print 'N',N;

        cc2 = cc * cc
        #print 'cc2',cc2;
        if cc <= 0.0:
            cc = cc2
        else:
            cc = cc2 / (cc + w)

        #print 'cc',cc;
        cc = cc * cc * cc
        #no abs
        #print 'cc',cc;

        #add up result
        result = result + cc * N

    return result * (1 / float(numberVoxels))
def interpretRequestParameters(parameters):
    from pytom.localization.peak_job import PeakJob
    from pytom.localization.structures import Volume
    from pytom.basic.structures import Mask, Reference, WedgeInfo
    from pytom.angles.globalSampling import GlobalSampling
    from pytom.basic.structures import BandPassFilter
    from pytom.frontend.serverpages.serverMessages import FileMessage

    if 'tomo' in parameters:
        vol = Volume(parameters['tomo'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'ref' in parameters:
        ref = Reference(parameters['ref'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'mask' in parameters:
        mask = Mask(parameters['mask'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'angle' in parameters:
        ang = GlobalSampling(parameters['angle'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'dest' in parameters:
        dest = parameters['dest']
    else:
        dest = './'

    if 'low' in parameters:
        low = float(parameters['low'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'high' in parameters:
        high = float(parameters['high'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'smooth' in parameters:
        smooth = float(parameters['smooth'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'w1' in parameters:
        w1 = float(parameters['w1'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'w2' in parameters:
        w2 = float(parameters['w2'])
    else:
        raise RuntimeError('Parameter missing in request!')

    if 'x' in parameters:
        x = float(parameters['x'])
    else:
        x = 0

    if 'y' in parameters:
        y = float(parameters['y'])
    else:
        y = 0

    if 'z' in parameters:
        z = float(parameters['z'])
    else:
        z = 0

    bp = BandPassFilter(low, high, smooth)
    wedge = WedgeInfo([w1, w2])

    from pytom.score.score import FLCFScore
    sc = FLCFScore()
    job = PeakJob(vol,
                  ref,
                  mask,
                  wedge,
                  ang,
                  dstDir=dest,
                  score=sc,
                  bandpass=bp)

    jobXMLFile = ''

    if 'jobFile' in parameters:
        jobXMLFile = parameters['jobFile']
        job.toXMLFile(jobXMLFile)

        if jobXMLFile[-4:] == '.xml':
            jobRunFile = jobXMLFile[0:-4]
        else:
            jobRunFile = jobXMLFile

        createRunscripts(jobRunFile + '.sh', jobXMLFile, x, y, z)

    return FileMessage('LocalizationJob', jobXMLFile, 'created')
Exemple #8
0
def weightedXCC(volume,reference,numberOfBands,wedgeAngle=-1):
        """
        weightedXCC: Determines the band weighted correlation coefficient for a volume and reference. Notation according Steward/Grigorieff paper
        @param volume: A volume
        @type volume: L{pytom_volume.vol}
        @param reference: A reference of same size as volume
        @type reference: L{pytom_volume.vol}
        @param numberOfBands: Number of bands
        @param wedgeAngle: A optional wedge angle
        @return: The weighted correlation coefficient
        @rtype: float  
        @author: Thomas Hrabe   
        """    
        import pytom_volume
        from pytom.basic.fourier import fft
        from math import sqrt
        import pytom_freqweight
        result = 0
        numberVoxels = 0
        
        #volume.write('vol.em');
        #reference.write('ref.em');
        fvolume = fft(volume)
        freference = fft(reference)
        numelem = volume.numelem()
        
        fvolume.shiftscale(0,1/float(numelem))
        freference.shiftscale(0,1/float(numelem))
        from pytom.basic.structures import WedgeInfo
        wedge = WedgeInfo(wedgeAngle)
        wedgeVolume = wedge.returnWedgeVolume(volume.sizeX(),volume.sizeY(),volume.sizeZ())
        
        increment = int(volume.sizeX()/2 * 1/numberOfBands)
        band = [0,100]
        for i in range(0,volume.sizeX()/2, increment):
        
            band[0] = i
            band[1] = i + increment
    
            r = bandCC(volume,reference,band)
            cc = r[0]
            
            #print cc;
            filter = r[1]
            #get bandVolume
            bandVolume = filter.getWeightVolume(True)
            
            filterVolumeReduced = bandVolume * wedgeVolume
            filterVolume = pytom_volume.reducedToFull(filterVolumeReduced)
            
            #determine number of voxels != 0    
            N = pytom_volume.numberSetVoxels(filterVolume)
            
            w = sqrt(1/float(N))
            
            #add to number of total voxels
            numberVoxels=numberVoxels + N
            #print 'w',w;
            #print 'cc',cc;
            #print 'N',N;
            
            cc2 = cc*cc
            #print 'cc2',cc2;
            if cc <= 0.0:
                cc = cc2
            else:
                cc = cc2/(cc+w)
            
            #print 'cc',cc;
            cc = cc *cc *cc; #no abs
            #print 'cc',cc;
            
            #add up result
            result = result + cc*N
        
        return result*(1/float(numberVoxels))
Exemple #9
0
 if not dest_dir:
     dest_dir = '.'
 
 from pytom_volume import read, subvolume
 v = read(vol_filename)
 
 from pytom.basic.structures import ParticleList, Particle, WedgeInfo
 pl = ParticleList("./")
 pl.fromXMLFile(pl_filename)
 
 def regulaize(xx, dim):
     if xx*binning-radius < 0:
         if 2*radius > dim:
             raise Exception("Volume size to be cut is too big!")
         return 0
     if xx*binning+radius > dim:
         if dim-2*radius < 0:
             raise Exception("Volume size to be cut is too big!")
         return dim-2*radius
     return xx*binning-radius
 
 res = ParticleList(dest_dir)
 for p in pl:
     x,y,z = p.getPickPosition().toVector()
     x = regulaize(int(x), v.sizeX()); y = regulaize(int(y), v.sizeY()); z = regulaize(int(z), v.sizeZ())
     new_vol = subvolume(v, x, y, z, 2*radius, 2*radius, 2*radius)
     name = dest_dir+'/'+p.getFilename()
     new_vol.write(name) # write the subtomograms to the disk
     res.append(Particle(name, p.getRotation(), None, WedgeInfo(w), 1, p.getPickPosition(), p.getScore())) # append it to the particle list for alignment
 
 res.toXMLFile(dest_dir+'/'+res_name)
Exemple #10
0
def xu_align_vol(vf, wf, vg, wg, b, radius=None, mask=None, peak_offset=None):
    """Implementation of Xu's approach for alignment. For detail, please check the paper.

    Parameters
    ----------
    vf: The volume you want to match.
        pytom_volume.vol

    wf: The single tilt wedge information of volume vf.
        [missing_wedge_angle1, missing_wedge_angle2]. Note this is defined different with frm_align im frm.py!

    vg: The reference volume.
        pytom_volume.vol

    wg: The single tilt wedge information of volume vg.
        [missing_wedge_angle1, missing_wedge_angle2]. Note this is defined different with frm_align im frm.py!

    b: The adaptive bandwidth of spherical harmonics.
       List [min_bandwidth, max_bandwidth], min_bandwidth, max_bandwidth in the range [4, 64].
       Or integer, which would then mean to use fixed bandwidth: min_bandwidth = max_bandwidth = integer.

    radius: The maximal radius in the Fourier space, which is equal to say the maximal frequency involved in calculation.
            Integer. By default is half of the volume size.

    peak_offset: The maximal offset which allows the peak of the score to be.
                 Or simply speaking, the maximal distance allowed to shift vg to match vf.
                 This parameter is needed to prevent shifting the reference volume out of the frame.
                 Integer. By default is half of the volume size.

    Returns
    -------
    The best translation and rotation (Euler angle, ZXZ convention [Phi, Psi, Theta]) to transform vg to match vf.
    (best_translation, best_rotation, correlation_score)
    """
    from pytom_volume import vol, rotateSpline, peak
    from pytom.basic.transformations import shift
    from pytom.basic.correlation import nXcf
    from pytom.basic.filter import lowpassFilter
    from pytom.basic.structures import Mask
    from pytom_volume import initSphere
    from pytom_numpy import vol2npy

    if vf.sizeX()!=vg.sizeX() or vf.sizeY()!=vg.sizeY() or vf.sizeZ()!=vg.sizeZ():
        raise RuntimeError('Two volumes must have the same size!')

    if mask is None:
        mask = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(mask, vf.sizeX()/2, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif mask.__class__ == vol:
        pass
    elif mask.__class__ == Mask:
        mask = mask.getVolume()
    elif isinstance(mask, int):
        mask_radius = mask
        mask = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(mask, mask_radius, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    else:
        raise RuntimeError('Given mask has wrong type!')

    if peak_offset is None:
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, vf.sizeX()/2, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif isinstance(peak_offset, int):
        peak_radius = peak_offset
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, peak_radius, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif peak_offset.__class__ == vol:
        pass
    else:
        raise RuntimeError('Peak offset is given wrong!')

    # cut out the outer part which normally contains nonsense
    vf = vf*mask

    position = None
    if position is None: # if position is not given, we have to find it ourself
        # first roughtly determine the orientation (only according to the energy info)
        # get multiple candidate orientations
        orientations = frm_determine_orientation(vf, wf, vg, wg, b, radius, None, None, False)
    else:
        # the position is given by the user
        vf2 = shift(vf, -position[0]+vf.sizeX()/2, -position[1]+vf.sizeY()/2, -position[2]+vf.sizeZ()/2, 'spline')
        res = frm_fourier_adaptive_wedge_vol(vf2, wf, vg, wg, b, radius, None, None, False)
        orientation, max_value = frm_find_best_angle_interp(res)

        return position, orientation, max_value

    
    from pytom.basic.structures import WedgeInfo
    from pytom.tools.maths import euclidianDistance
    max_iter = 1 # maximal number of iterations
    wedge = WedgeInfo([90+wf[0], 90-wf[1]])
    old_pos = [-1, -1, -1]
    vg2 = vol(vg.sizeX(), vg.sizeY(), vg.sizeZ())
    lowpass_vf = lowpassFilter(vf, radius, 0)[0]
    
    peak_value = 0.0
    position = None
    ang = None
    for orientation in orientations:
        orientation = orientation[0]

        rotateSpline(vg, vg2, orientation[0], orientation[1], orientation[2]) # first rotate
        vg2 = wedge.apply(vg2) # then apply the wedge
        vg2 = lowpassFilter(vg2, radius, 0)[0]
        res = nXcf(lowpass_vf, vg2) # find the position
        pos = peak(res, peak_offset)
        # val = res(pos[0], pos[1], pos[2])
        pos, val = find_subpixel_peak_position(vol2npy(res), pos)
        if val > peak_value:
            position = pos
            ang = orientation
            peak_value = val

    return position, ang, peak_value
Exemple #11
0
def bart_align_vol(vf, wf, vg, wg, b, radius=None, peak_offset=None):
    """Implementation of Bartesaghi's approach for alignment. For detail, please check the paper.

    Parameters
    ----------
    vf: The volume you want to match.
        pytom_volume.vol

    wf: The single tilt wedge information of volume vf.
        [missing_wedge_angle1, missing_wedge_angle2]. Note this is defined different with frm_align im frm.py!

    vg: The reference volume.
        pytom_volume.vol

    wg: The single tilt wedge information of volume vg.
        [missing_wedge_angle1, missing_wedge_angle2]. Note this is defined different with frm_align im frm.py!

    b: The bandwidth of spherical harmonics.
       Integer in the range [4, 64]

    radius: The maximal radius in the Fourier space, which is equal to say the maximal frequency involved in calculation.
            Integer. By default is half of the volume size.

    peak_offset: The maximal offset which allows the peak of the score to be.
                 Or simply speaking, the maximal distance allowed to shift vg to match vf.
                 This parameter is needed to prevent shifting the reference volume out of the frame.
                 Integer. By default is half of the volume size.

    Returns
    -------
    The best translation and rotation (Euler angle, ZXZ convention [Phi, Psi, Theta]) to transform vg to match vf.
    (best_translation, best_rotation, correlation_score)
    """
    from pytom_volume import vol, rotateSpline, max, peak
    from pytom.basic.correlation import nXcf
    from pytom.basic.filter import lowpassFilter
    from pytom.basic.structures import WedgeInfo
    from pytom_volume import initSphere

    if not radius: # set the radius
        radius = vf.sizeX()/2

    if peak_offset is None:
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, vf.sizeX()/2, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif isinstance(peak_offset, int):
        peak_radius = peak_offset
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, peak_radius, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif peak_offset.__class__ == vol:
        pass
    else:
        raise RuntimeError('Peak offset is given wrong!')
    
    from pytom.basic.fourier import fft, ifft, ftshift, iftshift
    from pytom_volume import vol, reducedToFull, rescale, abs, real
    from .vol2sf import vol2sf
    from pytom_numpy import vol2npy
    from math import log, ceil, pow

    # IMPORTANT!!! Should firstly do the IFFTSHIFT on the volume data (NOT FFTSHIFT since for odd-sized data it matters!),
    # and then followed by the FFT.
    ff = abs(ftshift(reducedToFull(fft(iftshift(vf, inplace=False))), inplace=False))
    ff = real(ff)
    gg = abs(ftshift(reducedToFull(fft(iftshift(vg, inplace=False))), inplace=False))
    gg = real(gg)
    
    sf = None
    sg = None
    mf = create_wedge_sf(wf[0], wf[1], b)
    mg = create_wedge_sf(wg[0], wg[1], b)

    for r in range(3, radius+1): # Should start from 3 since the interpolation in the first 2 bands is not accurate.
        if sf is None:
            sf = vol2sf(ff, r, b)
            sg = vol2sf(gg, r, b)
        else:
            sf += vol2sf(ff, r, b)
            sg += vol2sf(gg, r, b)
    
    corr = frm_constrained_corr(sf, mf, sg, mg)
    ang, val = frm_find_best_angle_interp(corr)

    tmp = vol(vg.sizeX(),vg.sizeY(),vg.sizeZ())
    rotateSpline(vg, tmp, ang[0], ang[1], ang[2])
    wedge_f = WedgeInfo(90+wf[0], 90-wf[1])
    wedge_g = WedgeInfo(90+wg[0], 90-wg[1])
    cc = nXcf(lowpassFilter(wedge_g.apply(vf), radius, 0)[0], lowpassFilter(wedge_f.apply(tmp), radius, 0)[0])
    pos = peak(cc, peak_offset)
    pos, score = find_subpixel_peak_position(vol2npy(cc), pos)

    return (pos, ang, score)
Exemple #12
0
def frm_align_vol_rscore(vf, wf, vg, wg, b, radius=None, mask=None, peak_offset=None, weights=None, position=None):
    """Obsolete.
    """
    from pytom_volume import vol, rotateSpline, peak
    from pytom.basic.transformations import shift
    from pytom.basic.correlation import xcf
    from pytom.basic.filter import lowpassFilter
    from pytom.basic.structures import Mask
    from pytom_volume import initSphere
    from pytom_numpy import vol2npy

    if vf.sizeX()!=vg.sizeX() or vf.sizeY()!=vg.sizeY() or vf.sizeZ()!=vg.sizeZ():
        raise RuntimeError('Two volumes must have the same size!')

    if mask is None:
        mask = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(mask, vf.sizeX()/2, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif mask.__class__ == vol:
        pass
    elif mask.__class__ == Mask:
        mask = mask.getVolume()
    elif isinstance(mask, int):
        mask_radius = mask
        mask = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(mask, mask_radius, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    else:
        raise RuntimeError('Given mask has wrong type!')

    if peak_offset is None:
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, vf.sizeX()/2, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif isinstance(peak_offset, int):
        peak_radius = peak_offset
        peak_offset = vol(vf.sizeX(), vf.sizeY(), vf.sizeZ())
        initSphere(peak_offset, peak_radius, 0,0, vf.sizeX()/2,vf.sizeY()/2,vf.sizeZ()/2)
    elif peak_offset.__class__ == vol:
        pass
    else:
        raise RuntimeError('Peak offset is given wrong!')

    # cut out the outer part which normally contains nonsense
    vf = vf*mask

    # # normalize them first
    # from pytom.basic.normalise import mean0std1
    # mean0std1(vf)
    # mean0std1(vg)

    if position is None: # if position is not given, we have to find it ourself
        # first roughtly determine the orientation (only according to the energy info)
        # get multiple candidate orientations
        orientations = frm_determine_orientation_rscore(vf, wf, vg, wg, b, radius, weights)
    else:
        # the position is given by the user
        vf2 = shift(vf, -position[0]+vf.sizeX()/2, -position[1]+vf.sizeY()/2, -position[2]+vf.sizeZ()/2, 'spline')
        res = frm_fourier_adaptive_wedge_vol_rscore(vf2, wf, vg, wg, b, radius, weights)
        orientation, max_value = frm_find_best_angle_interp(res)

        return position, orientation, max_value

    # iteratively refine the position & orientation
    from pytom.basic.structures import WedgeInfo
    from pytom.tools.maths import euclidianDistance
    max_iter = 10 # maximal number of iterations
    wedge = WedgeInfo([90+wf[0], 90-wf[1]])
    old_pos = [-1, -1, -1]
    vg2 = vol(vg.sizeX(), vg.sizeY(), vg.sizeZ())
    lowpass_vf = lowpassFilter(vf, radius, 0)[0]
    for i in range(max_iter):
        peak_value = 0.0
        position = None
        for orientation in orientations:
            orientation = orientation[0]

            rotateSpline(vg, vg2, orientation[0], orientation[1], orientation[2]) # first rotate
            vg2 = wedge.apply(vg2) # then apply the wedge
            vg2 = lowpassFilter(vg2, radius, 0)[0]
            res = xcf(lowpass_vf, vg2) # find the position
            pos = peak(res, peak_offset)
            # val = res(pos[0], pos[1], pos[2])
            pos, val = find_subpixel_peak_position(vol2npy(res), pos)
            if val > peak_value:
                position = pos
                peak_value = val

        if euclidianDistance(position, old_pos) <= 1.0:
            break
        else:
            old_pos = position

        # here we shift the target, not the reference
        # if you dont want the shift to change the energy landscape, use fourier shift
        vf2 = shift(vf, -position[0]+vf.sizeX()/2, -position[1]+vf.sizeY()/2, -position[2]+vf.sizeZ()/2, 'fourier')
        res = frm_fourier_adaptive_wedge_vol_rscore(vf2, wf, vg, wg, b, radius, weights)
        orientations = frm_find_topn_angles_interp(res)

    return position, orientations[0][0], orientations[0][1]
Exemple #13
0
    @param splitType: split type of the job
    @type splitType: "Ang" or "Vol"
    """
    def __init__(self, jobID=-1, originalJobID=-1, splitType=None):
        self.jobID = jobID
        self.originalJobID = originalJobID
        self.splitType = splitType


if __name__ == '__main__':
    from pytom.basic.structures import Mask, Reference, WedgeInfo
    from pytom.localization.structures import Volume
    from pytom.score.score import FLCFScore, xcfScore
    from pytom.localization.peak_job import PeakJob

    v = Volume('/fs/pool/pool-foerster/apps/src/molmatch/test/testvol.em')
    ref = Reference('/fs/pool/pool-foerster/apps/src/molmatch/test/templ.em')
    m = Mask('/fs/pool/pool-foerster/apps/src/molmatch/test/mask_15.em', True)

    w = WedgeInfo(0)
    s = FLCFScore()

    from pytom.angles.globalSampling import GlobalSampling
    r = GlobalSampling(
        '/fs/home/ychen/develop/pytom/trunk/pytom/pytomc/libs/libtomc/data/common_data/angles_90_26.em'
    )

    job = PeakJob(v, ref, m, w, r, s)
    job.toXMLFile('JobInfo.xml')
    job.toHTMLFile('JobInfo.html')