Exemple #1
0
def split_matrix(parId, iterator):
        
    x0 = -1
    y0 = -1
    z0 = -1
    t0 =  0 
    for x in iterator:
        x0 = x[1][0]
        y0 = x[1][1]
        z0 = x[1][2]
        t0 += 1
    
    
    vol10 = npy2vol(BC_vol1.value, 3)
    vol20 = npy2vol(BC_vol2.value, 3)
    boxhalf_x1 = BC_sizeX.value / 2 
    boxhalf_y1 = BC_sizeY.value / 2 
    boxhalf_z1 = BC_sizeZ.value / 2 
    vol1_sub = subvolume(vol10, x0 - boxhalf_x1, y0 - boxhalf_y1, z0 - boxhalf_z1, BC_sizeX.value, BC_sizeY.value, BC_sizeZ.value)
    vol2_sub = subvolume(vol20, x0 - boxhalf_x1, y0 - boxhalf_y1, z0 - boxhalf_z1, BC_sizeX.value, BC_sizeY.value, BC_sizeZ.value)
    
    
    avg1 = mean(vol1_sub)
    vol1_sub1 = hanning_taper(vol1_sub, avg1)
    avg2 = mean(vol2_sub)
    vol2_sub1 = hanning_taper(vol2_sub, avg2)


    res = fsc2_v(vol1_sub1, vol2_sub1, BC_fsc_criterion.value, BC_max_resolution.value, BC_pixelSize.value, x0, y0, z0)
    tup = (round(res,6), x0, y0, z0)
     
    del avg1, avg2, vol1_sub1, vol2_sub1
    del vol1_sub, vol2_sub, res, vol10, vol20, boxhalf_x1, boxhalf_y1, boxhalf_z1, x0, y0, z0, t0
    
    return tup
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
Exemple #3
0
def convolutionCTF(volume, defocus, pixelSize=None, voltage=None, Cs=None, sigma=None):
    """
    convolutionCTF:
    @param volume: input volume to be convolved with CTF
    @type volume: L{pytom_volume.vol}
    @param defocus: Negative value = underfocus (in microns)
    @param pixelSize: Size of pixels / voxels (in Anstroms)
    @param voltage: 
    @param Cs:
    @param sigma: 
    @return: CTF filtered volume
    @rtype L{pytom_volume.vol}
    @author: FF
    """
    from pytom_volume import subvolume, complexRealMult
    from pytom.basic.fourier import ftshift, fft, ifft
    from pytom.basic.filter import volCTF
    
    dimX = volume.sizeX()
    dimY = volume.sizeY()
    dimZ = volume.sizeZ()

    ctf = volCTF(defocus, dimX, dimY, dimZ, pixelSize, voltage, Cs, sigma)
    filterCTF = subvolume(ftshift(ctf,inplace=False), 0, 0, 0, dimX, dimY, (dimZ/2)+1)
    
    filteredVolume = ifft( complexRealMult(fft(volume), filterCTF) )
    
    return filteredVolume
Exemple #4
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
Exemple #5
0
def averagePlanes(volume, sliceStart, sliceEnd, sliceStep=1, axis='Z'):
    """
    averagePlanes:
    @param volume:
    @param sliceStart:
    @param sliceEnd:
    @param axis:
    @author:     
    """

    from pytom_volume import subvolume

    planes = []

    for i in range(sliceStart, sliceEnd, sliceStep):

        if axis == 'X':
            v = subvolume(volume, 0, 0, i, volume.sizeX(), volume.sizeY(), 1)
            planes.append(v)

        if axis == 'Y':
            v = subvolume(volume, 0, 0, i, volume.sizeX(), volume.sizeY(), 1)
            planes.append(v)

        if axis == 'Z':
            v = subvolume(volume, 0, 0, i, volume.sizeX(), volume.sizeY(), 1)
            planes.append(v)

    if len(planes) > 0:
        p = planes[0]

        for i in range(len(planes) - 1):

            p += planes[i + 1]

        return p

    else:

        raise RuntimeError(
            'Could not select on single plane from your parameters.')
Exemple #6
0
def transformFourierSpline(volume,z1,z2,x,shiftX,shiftY,shiftZ,twice=False):
    """
    transformFourierSpline: Rotate and shift a volume in fourierspace
    @param volume:
    @param z1:
    @param z2:
    @param x:
    @param shiftX: Shift after rotation
    @param shiftY: Shift after rotation 
    @param shiftZ: Shift after rotation
    @param twice: Zero pad volume into a twice sized volume and perform calculation there.
    @return: The transformed volume.   
    @author: Yuxiang Chen and Thomas Hrabe
    """
    from pytom.basic.fourier import fft, ifft, ftshift, iftshift
    from pytom_volume import vol, pasteCenter, subvolume, transformFourierSpline
    
    if z1 == 0 and z2 == 0 and x == 0:
        return vol(volume)
    
    if twice:
        # paste into a twice sized volume
        v = vol(volume.sizeX()*2, volume.sizeY()*2, volume.sizeZ()*2)
        pasteCenter(volume, v)
    else:
        v = volume
    
    fvol = fft(iftshift(v, inplace=False)) # these steps have to be done in python level because of the fft

    resF = transformFourierSpline(fvol,z1,z2,x,shiftX,shiftY,shiftZ)
    
    res = ftshift(ifft(resF),inplace=False) / v.numelem() # reverse it back
    
    if twice:
        # cut the center part back
        res = subvolume(res, (volume.sizeX()+1)/2, (volume.sizeY()+1)/2, (volume.sizeZ()+1)/2, volume.sizeX(), volume.sizeY(), volume.sizeZ())
    
    return res
Exemple #7
0
def particleVolume(particleList,
                   templateVolume,
                   dimX,
                   dimY,
                   dimZ,
                   volume=None):

    from pytom_volume import vol, paste, rotate, subvolume

    if volume == None:
        volume = vol(dimX, dimY, dimZ)
        volume.setAll(0.0)

    for p in particleList:

        x = p.getPickPosition().getX()
        y = p.getPickPosition().getY()
        z = p.getPickPosition().getZ()

        z1 = p.getRotation().getZ1()
        z2 = p.getRotation().getZ2()
        x1 = p.getRotation().getX()

        tempTemplate = vol(templateVolume.sizeX(), templateVolume.sizeY(),
                           templateVolume.sizeZ())
        tempTemplate.setAll(0.0)
        rotate(templateVolume, tempTemplate, z1, z2, x1)
        tempTemplate = tempTemplate + subvolume(
            volume, int(x - templateVolume.sizeX() / 2),
            int(y - templateVolume.sizeY() / 2),
            int(z - templateVolume.sizeZ() / 2), templateVolume.sizeX(),
            templateVolume.sizeY(), templateVolume.sizeZ())
        paste(tempTemplate, volume, int(x - templateVolume.sizeX() / 2),
              int(y - templateVolume.sizeY() / 2),
              int(z - templateVolume.sizeZ() / 2))

    return volume
Exemple #8
0
    def parallelStart_splitVol(self,
                               job,
                               splitX,
                               splitY,
                               splitZ,
                               verbose=True):
        """
        """

        self.parallelInit()

        import pytom_mpi
        mpi_myid = pytom_mpi.rank()
        if mpi_myid == 0:  # manager
            # distribute the job to the workers and get the original size of the volume
            self.splitVolumes(job, splitX, splitY, splitZ, verbose)

            [vsizeX, vsizeY, vsizeZ] = self.jobInfo["originalSize"]

            # gather results and post processing
            from pytom_volume import vol
            volume = vol(vsizeX, vsizeY, vsizeZ)
            volume.setAll(0)
            orient = vol(vsizeX, vsizeY, vsizeZ)
            orient.setAll(0)

            i = 0
            while i < splitX * splitY * splitZ:
                mpi_msgString = getMsgStr()
                msg = self.getResMsg(mpi_msgString)
                resFromWorker = self.resFromMsg(msg)

                if verbose == True:
                    print("Manager: processing result from worker " +
                          msg.getSender())

                resV = resFromWorker.result.getVolume()
                resO = resFromWorker.orient.getVolume()
                jobID = resFromWorker.jobID

                [sizeX, sizeY, sizeZ] = self.jobInfo["splitSize"]

                [sub_start, start] = self.jobInfo[jobID]

                from pytom_volume import subvolume, putSubVolume
                sub_resV = subvolume(resV, sub_start[0], sub_start[1],
                                     sub_start[2], sizeX, sizeY, sizeZ)
                sub_resO = subvolume(resO, sub_start[0], sub_start[1],
                                     sub_start[2], sizeX, sizeY, sizeZ)

                putSubVolume(sub_resV, volume, start[0], start[1], start[2])
                putSubVolume(sub_resO, orient, start[0], start[1], start[2])

                i = i + 1

            # write the final result back to the disk
            volume.write(self.name + '_res.em')
            orient.write(self.name + '_orient.em')

            # delete the temporary files on the disk
            import os
            files = os.listdir('.')
            for name in files:
                if 'job' in name and '.em' in name and not 'sum' in name and not 'sqr' in name:
                    os.remove(name)

            # rename the result files name
            os.rename('node_0_res.em', 'scores{}{}.em'.format(suffix))
            os.rename('node_0_orient.em', 'angles{}{}.em'.format(suffix))

            # finishing, stop all workers
            self.parallelEnd(verbose)

            if verbose == True:
                print("Manager: end")

        else:  # worker
            worker = PeakWorker()
            worker.parallelRun(verbose)

        pytom_mpi.finalise()
Exemple #9
0
    def summarize(self, result, jobID, verbose=True):
        """
        summarize: Get the result and do the summarization accordingly.\
        (Send back, or update result, or write to the disk).

        @param result: result
        @type result: L{pytom.localization.peak_job.PeakResult}
        @param jobID: ID of job
        @type jobID: integer
        """
        resV = result[0]
        orientV = result[1]

        if self.jobInfoPool == {}:  # leaf node
            assert self.backTo != None

            #self.parallelEnd(verbose)
            if not self.backTo is None:
                result = self.writeRes(resV, orientV, jobID)
                result.send(self.mpi_id, self.backTo)
            else:
                self.writeRes(resV, orientV, None)
                self.parallelEnd(verbose)
            return

        # non leaf node, update the result
        if self.jobInfoPool[jobID].splitType == "Ang":
            self.jobInfoPool[
                "numDoneJobsA"] = self.jobInfoPool["numDoneJobsA"] + 1
            offset = self.jobInfoPool[jobID].angleOffset
            #            print self.name + ': JobID ' + str(jobID) + ' Offset ' + str(offset)
            orientV = orientV + offset

            if self.resVolA == None or self.resOrientA == None:
                from pytom_volume import vol
                self.resVolA = vol(resV.sizeX(), resV.sizeY(), resV.sizeZ())
                self.resOrientA = vol(orientV.sizeX(), orientV.sizeY(),
                                      orientV.sizeZ())
                self.resVolA.copyVolume(resV)
                self.resOrientA.copyVolume(orientV)
            else:
                from pytom_volume import updateResFromVol
                updateResFromVol(self.resVolA, resV, self.resOrientA, orientV)

            if self.jobInfoPool["numDoneJobsA"] == self.jobInfoPool[
                    "numJobsA"] and self.jobInfoPool["numJobsV"] > 0:
                self.summarize([self.resVolA, self.resOrientA],
                               self.jobInfoPool[jobID].originalJobID, verbose)
                return
        elif self.jobInfoPool[jobID].splitType == "Vol":
            self.jobInfoPool[
                "numDoneJobsV"] = self.jobInfoPool["numDoneJobsV"] + 1
            [originX, originY, originZ] = self.jobInfoPool[jobID].origin
            if self.resVol == None or self.resOrient == None:
                from pytom_volume import vol
                [vsizeX, vsizeY, vsizeZ] = self.jobInfoPool[jobID].originalSize

                self.resVol = vol(vsizeX, vsizeY, vsizeZ)
                self.resVol.setAll(0)
                self.resOrient = vol(vsizeX, vsizeY, vsizeZ)
                self.resOrient.setAll(0)

            [vsizeX, vsizeY, vsizeZ] = self.jobInfoPool[jobID].originalSize
            [sizeX, sizeY, sizeZ] = self.jobInfoPool[jobID].splitSize
            sub_start = self.jobInfoPool[jobID].sub_start
            start = self.jobInfoPool[jobID].whole_start

            stepSizeX = min(vsizeX - sub_start[0], sizeX)
            stepSizeY = min(vsizeY - sub_start[1], sizeY)
            stepSizeZ = min(vsizeZ - sub_start[2], sizeZ)

            from pytom_volume import subvolume, putSubVolume
            sub_resV = subvolume(resV, sub_start[0], sub_start[1],
                                 sub_start[2], stepSizeX, stepSizeY, stepSizeZ)
            sub_resO = subvolume(orientV, sub_start[0], sub_start[1],
                                 sub_start[2], stepSizeX, stepSizeY, stepSizeZ)

            putSubVolume(sub_resV, self.resVol, start[0] - originX,
                         start[1] - originY, start[2] - originZ)
            putSubVolume(sub_resO, self.resOrient, start[0] - originX,
                         start[1] - originY, start[2] - originZ)
        else:
            raise RuntimeError("Unclear split type!")

        # if all results are there, write back to disk and return to high level
        if self.jobInfoPool["numDoneJobsA"] + self.jobInfoPool[
                "numDoneJobsV"] == self.jobInfoPool[
                    "numJobsA"] + self.jobInfoPool["numJobsV"]:
            if self.jobInfoPool["numJobsV"] == 0:
                self.resVol = self.resVolA
                self.resOrient = self.resOrientA

            if self.backTo != None:
                result = self.writeRes(self.resVol, self.resOrient,
                                       self.jobInfoPool[jobID].originalJobID)
                if verbose == True:
                    print(self.name + ': sending back result to ' +
                          str(self.backTo))
                result.send(self.mpi_id, self.backTo)
            else:
                # write the final result to the disk
                self.writeRes(self.resVol, self.resOrient)
                self.parallelEnd(verbose)
Exemple #10
0
def subPixelPeak(scoreVolume,
                 coordinates,
                 cubeLength=8,
                 interpolation='Spline',
                 verbose=False):
    """
    subPixelPeak: Will determine the sub pixel area of peak. Utilizes spline, fourier or parabolic interpolation.

    @param verbose: be talkative
    @type verbose: L{str}
    @param scoreVolume: The score volume
    @param coordinates: [x,y,z] coordinates where the sub pixel peak will be determined
    @param cubeLength: length of cube - only used for Spline and Fourier interpolation
    @type cubeLength: int (even)
    @param interpolation: interpolation type: 'Spline', 'Quadratic', or 'Fourier'
    @type interpolation: str
    @return: Returns [peakValue,peakCoordinates] with sub pixel accuracy

    last change: 02/07/2013 FF: 2D functionality added
    """
    assert type(
        interpolation) == str, 'subPixelPeak: interpolation must be str'
    if (interpolation.lower() == 'quadratic') or (interpolation.lower()
                                                  == 'parabolic'):
        (peakValue,
         peakCoordinates) = subPixelPeakParabolic(scoreVolume=scoreVolume,
                                                  coordinates=coordinates,
                                                  verbose=verbose)
        return [peakValue, peakCoordinates]

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

    from pytom_volume import vol, subvolume, rescaleSpline, peak
    from pytom.basic.transformations import resize

    #extend function for 2D
    twoD = (scoreVolume.shape) == 2

    cubeStart = cubeLength // 2
    sizeX = scoreVolume.sizeX()
    sizeY = scoreVolume.sizeY()
    sizeZ = scoreVolume.sizeZ()

    if twoD:
        if (coordinates[0]-cubeStart < 1 or coordinates[1]-cubeStart < 1) or\
            (coordinates[0]-cubeStart + cubeLength >= sizeX or coordinates[1]-cubeStart + cubeLength >= sizeY):
            if verbose:
                print(
                    "SubPixelPeak: position too close to border for sub-pixel")
            return [
                scoreVolume(coordinates[0], coordinates[1], coordinates[2]),
                coordinates
            ]

        subVolume = subvolume(scoreVolume, coordinates[0] - cubeStart,
                              coordinates[1] - cubeStart, 0, cubeLength,
                              cubeLength, 1)
    else:
        if (coordinates[0]-cubeStart < 1 or coordinates[1]-cubeStart < 1 or coordinates[2]-cubeStart < 1) or \
                (coordinates[0]-cubeStart + cubeLength >= sizeX or coordinates[1]-cubeStart + cubeLength >= sizeY or \
                 coordinates[2]-cubeStart + cubeLength >= sizeZ):
            if verbose:
                print(
                    "SubPixelPeak: position too close to border for sub-pixel")
            return [
                scoreVolume(coordinates[0], coordinates[1], coordinates[2]),
                coordinates
            ]

        subVolume = subvolume(scoreVolume, coordinates[0] - cubeStart,
                              coordinates[1] - cubeStart,
                              coordinates[2] - cubeStart, cubeLength,
                              cubeLength, cubeLength)

    #size of interpolated volume
    scaleSize = 10 * cubeLength

    #ratio between interpolation area and large volume
    scaleRatio = 1.0 * cubeLength / scaleSize

    #resize into bigger volume
    if interpolation == 'Spline':
        if twoD:
            subVolumeScaled = vol(scaleSize, scaleSize, 1)
        else:
            subVolumeScaled = vol(scaleSize, scaleSize, scaleSize)
        rescaleSpline(subVolume, subVolumeScaled)
    else:
        subVolumeScaled = resize(volume=subVolume, factor=10)[0]

    peakCoordinates = peak(subVolumeScaled)

    peakValue = subVolumeScaled(peakCoordinates[0], peakCoordinates[1],
                                peakCoordinates[2])

    #calculate sub pixel coordinates of interpolated peak
    peakCoordinates[
        0] = peakCoordinates[0] * scaleRatio - cubeStart + coordinates[0]
    peakCoordinates[
        1] = peakCoordinates[1] * scaleRatio - cubeStart + coordinates[1]
    if twoD:
        peakCoordinates[2] = 0
    else:
        peakCoordinates[
            2] = peakCoordinates[2] * scaleRatio - cubeStart + coordinates[2]
    if (peakCoordinates[0] > scoreVolume.sizeX()
            or peakCoordinates[1] > scoreVolume.sizeY()
            or peakCoordinates[2] > scoreVolume.sizeZ()):
        if verbose:
            print(
                "SubPixelPeak: peak position too large :( return input value")
        #something went awfully wrong here. return regular value
        return [
            scoreVolume(coordinates[0], coordinates[1], coordinates[2]),
            coordinates
        ]

    return [peakValue, peakCoordinates]
Exemple #11
0
        pi = particle.getPickPosition()
        try:
            x = int(pi.getX() - cubeSize / 2)
            y = int(pi.getY() - cubeSize / 2)
            z = int(pi.getZ() - cubeSize / 2)

            if x < cubeSize or y < cubeSize or z < cubeSize or\
               x+cubeSize > volX or y+cubeSize > volY or z+cubeSize > volZ:
                print('Coordinate out of bounds (', x, y, z, ') for ')
                print(particle)
                print('Particle could not be cut out from origin volume!')
                print('')
                continue

            v = subvolume(vol, x, y, z, cubeSize, cubeSize,
                          cubeSize)  # faster this way

            newParticleList.append(
                particle)  # this part should be inside the try block
            v.write(particle.getFilename())
        except:
            print('Error for')
            print(particle)
            print('Particle could not be cut out from origin volume!')
            print('')
            continue

    if len(particleList) != len(newParticleList):
        new_plFilename = None
        if '/' in plFilename:
            new_plFilename = plFilename[:-4] + 'New.xml'
Exemple #12
0
def readSubvolumeFromFourierspaceFile(filename, sizeX, sizeY, sizeZ):
    """
    readSubvolumeFromFourierspaceFile: This function is required when data \
    (in real space) is read in binned mode and a related fourier space file 
    like a wedge needs to be read alongside. 
    Works only if fourier file is reduced complex without any shift applied.      
    @param filename: The fourier space file name
    @param sizeX: X final size of subvolume if it was complete 
    (what L{pytom.basic.structures.Wedge.returnWedgeVolume} with 
    humanUnderstandable == True returns)
    @param sizeY: Y final size of subvolume if it was complete 
    (what L{pytom.basic.structures.Wedge.returnWedgeVolume} 
    with humanUnderstandable == True returns)
    @param sizeZ: Z final size of subvolume if it was complete 
    (what L{pytom.basic.structures.Wedge.returnWedgeVolume} 
    with humanUnderstandable == True returns)
    @return: A subvolume 
    @author: Thomas Hrabe
    """
    from pytom_volume import vol, subvolume, paste
    from pytom.basic.fourier import fourierSizeOperation
    [newX, newY, newZ] = fourierSizeOperation(sizeX,
                                              sizeY,
                                              sizeZ,
                                              reducedToFull=False)
    newVolume = vol(newX, newY, newZ)
    newVolume.setAll(0)
    newX = newX / 2
    newY = newY / 2

    if filename.__class__ == str:
        originalVolume = read(filename)
    elif filename.__class__ == vol:
        # open a backdoor for this function to take volumes, but
        # this should be rather an exception -> not fully documented
        originalVolume = filename
    else:
        raise TypeError('Filename must be a string')

    originalSizeX = int(originalVolume.sizeX())
    originalSizeY = int(originalVolume.sizeY())

    # the original volume is reduced complex without shift ->
    # zero frequency is in outer corner (0,0,0)
    # read a subvolume around every corner with a subvolume
    # of half x,y of the final volume with constant z

    if filename.__class__ == str:
        firstSubvolume = read(filename, subregion=[0, 0, 0, newX, newY, newZ])
    else:
        firstSubvolume = subvolume(filename, 0, 0, 0, newX, newY, newZ)

    if filename.__class__ == str:
        secondSubvolume = read(
            filename, subregion=[originalSizeX - newX, 0, 0, newX, newY, newZ])
    else:
        secondSubvolume = subvolume(filename, originalSizeX - newX, 0, 0, newX,
                                    newY, newZ)

    if filename.__class__ == str:
        thirdSubvolume = read(
            filename, subregion=[0, originalSizeY - newY, 0, newX, newY, newZ])
    else:
        thirdSubvolume = subvolume(filename, 0, originalSizeY - newY, 0, newX,
                                   newY, newZ)

    if filename.__class__ == str:
        fourthSubvolume = read(filename,
                               subregion=[
                                   originalSizeX - newX, originalSizeY - newY,
                                   0, newX, newY, newZ
                               ])
    else:
        fourthSubvolume = subvolume(filename, originalSizeX - newX,
                                    originalSizeY - newY, 0, newX, newY, newZ)

    # merge the volumes to the final volume
    paste(firstSubvolume, newVolume, 0, 0, 0)
    paste(secondSubvolume, newVolume, newX, 0, 0)
    paste(thirdSubvolume, newVolume, 0, newY, 0)
    paste(fourthSubvolume, newVolume, newX, newY, 0)

    return newVolume
    def maskOut(self, mask, center, size):
        """
        maskOut: Set part of mask volume to all zero. The region is specified by center and size.
        @param mask: volume that you handle with
        @type mask: L{pytom_volume.vol}
        @param center: center of the region
        @type center: [x,y,z]
        @param size: size of the region
        @type size: [sizeX, sizeY, sizeZ] or radius
        """

        from pytom_volume import vol, putSubVolume

        if size.__class__ == list:
            p_sizeX = size[0]
            p_sizeY = size[1]
            p_sizeZ = size[2]
        elif size.__class__ == vol:
            mm = size
            p_sizeX = mm.sizeX()
            p_sizeY = mm.sizeY()
            p_sizeZ = mm.sizeZ()
        else:
            radius = size
            p_sizeX = radius * 2
            p_sizeY = radius * 2
            p_sizeZ = radius * 2

        maskSize = [mask.sizeX(), mask.sizeY(), mask.sizeZ()]

        if maskSize < center:
            raise RuntimeError('Center out of range!')

        # [)
        # mask out double size. CHANGED!!!
        startX = int(center[0] - p_sizeX / 2)
        endX = int(center[0] + p_sizeX / 2)
        startY = int(center[1] - p_sizeY / 2)
        endY = int(center[1] + p_sizeY / 2)
        startZ = int(center[2] - p_sizeZ / 2)
        endZ = int(center[2] + p_sizeZ / 2)

        # only used for radius
        sub_startX = 0
        sub_startY = 0
        sub_startZ = 0

        if startX < 0:
            sub_startX = -startX
            startX = 0
        if endX > maskSize[0]:
            endX = maskSize[0]
        if startY < 0:
            sub_startY = -startY
            startY = 0
        if endY > maskSize[1]:
            endY = maskSize[1]
        if startZ < 0:
            sub_startZ = -startZ
            startZ = 0
        if endZ > maskSize[2]:
            endZ = maskSize[2]

        sizeX = endX - startX
        sizeY = endY - startY
        sizeZ = endZ - startZ

        if size.__class__ == list:
            subV = vol(sizeX, sizeY, sizeZ)
            subV.setAll(0)
        elif size.__class__ == vol:
            from pytom_volume import limit, subvolume
            subV = (mm - 1) / -1
            limit(subV, 0.999, 0, 0, 0, True, False)
            subV = subvolume(subV, sub_startX, sub_startY, sub_startZ, sizeX,
                             sizeY, sizeZ)
            tempV = subvolume(mask, startX, startY, startZ, sizeX, sizeY,
                              sizeZ)
            subV = subV * tempV  # AND operation
        else:
            from pytom_volume import initSphere, subvolume
            subV = vol(radius * 2, radius * 2, radius * 2)
            initSphere(subV, radius, 0, 0, radius, radius, radius)
            tempV = vol(radius * 2, radius * 2, radius * 2)
            tempV.setAll(1)
            subV = tempV - subV
            subV = subvolume(subV, sub_startX, sub_startY, sub_startZ, sizeX,
                             sizeY, sizeZ)
            tempV = subvolume(mask, startX, startY, startZ, sizeX, sizeY,
                              sizeZ)
            subV = subV * tempV  # AND operation

        putSubVolume(subV, mask, startX, startY, startZ)
Exemple #14
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 #15
0
def _display(volume, sliceNumber=0, projectionAxis='z'):
    """
    _display: Generate image for volume display
    @author: Thomas Hrabe
    @param volume: The image / volume
    @param sliceNumber: Slice number at which the volume will be cut
    @param projectionAxis: Defines the axis. Default is z, means you look on the xy plane. (x equals to 'yz' plane, y to 'xz') 
    """
    import Image
    from pytom_volume import min, max, mean, variance, limit, subvolume
    from math import sqrt

    if projectionAxis == 'x':
        size1 = volume.sizeY()
        size2 = volume.sizeZ()
    if projectionAxis == 'y':
        size1 = volume.sizeX()
        size2 = volume.sizeZ()
    if projectionAxis == 'z':
        size1 = volume.sizeX()
        size2 = volume.sizeY()

    img = Image.new('L', (size1, size2))

    if sliceNumber > 0:

        if projectionAxis == 'x':
            volume = subvolume(volume, sliceNumber, 0, 0, 1, size1, size2)
        elif projectionAxis == 'y':
            volume = subvolume(volume, 0, sliceNumber, 0, size1, 1, size2)
        elif projectionAxis == 'z':
            volume = subvolume(volume, 0, 0, sliceNumber, size1, size2, 1)

    elif sliceNumber == 0 and volume.sizeZ() > 1:
        sliceNumber = int(volume.sizeZ() / 2)

        if projectionAxis == 'x':
            volume = subvolume(volume, sliceNumber, 0, 0, 1, size1, size2)
        elif projectionAxis == 'y':
            volume = subvolume(volume, 0, sliceNumber, 0, size1, 1, size2)
        elif projectionAxis == 'z':
            volume = subvolume(volume, 0, 0, sliceNumber, size1, size2, 1)

    minValue = min(volume)
    volume.shiftscale(-minValue, 1)
    maxValue = max(volume)
    if maxValue == 0:
        maxValue = 1
    volume.shiftscale(0, 255.0 / maxValue)

    for i in range(size1):
        for j in range(size2):
            if projectionAxis == 'x':
                value = volume(0, i, j)
            elif projectionAxis == 'y':
                value = volume(i, 0, j)
            elif projectionAxis == 'z':
                value = volume(i, j, 0)

            img.putpixel((i, j), int(value))

    return img
Exemple #16
0
def _dspcub(volume, sigma=None, projectionAxis='z'):
    """
    _dspcub: Creates a dspcub image
    dspcub2PNG: display z-slices in 2D image
    @param volume: The input volume
    @type volume: L{pytom_volume.vol}
    @parameter sigma: thresholding as multiples of standard deviation sigma
    @type sigma: float
    @param projectionAxis: Defines the axis. Default is z, means you look on the xy plane. (x equals to 'yz' plane, y to 'xz') 
    @return: Image
    @rtype: Image
    @@author: Pia Unverdorben 
    """

    if volume.sizeZ() == 1:
        raise Exception('You can use ')

    import Image
    from pytom_volume import min, max, mean, variance, limit, subvolume
    from math import sqrt, ceil, floor

    sizeX = volume.sizeX()
    sizeY = volume.sizeY()
    sizeZ = volume.sizeZ()

    if projectionAxis == 'x':
        imagesPerRow = int(floor(sqrt(sizeX)))
        size1 = float(sizeX)
        sizeI = sizeY
        sizeJ = sizeZ
    elif projectionAxis == 'y':
        imagesPerRow = int(floor(sqrt(sizeY)))
        size1 = float(sizeY)
        sizeI = sizeX
        sizeJ = sizeZ
    elif projectionAxis == 'z':
        imagesPerRow = int(floor(sqrt(sizeZ)))
        size1 = float(sizeZ)
        sizeI = sizeX
        sizeJ = sizeY

    numberIterations = imagesPerRow * imagesPerRow

    if size1 < numberIterations:
        iterationSteps = float(numberIterations / size1)
    else:
        iterationSteps = float(size1 / numberIterations)

    iterationSteps = int(iterationSteps)

    if projectionAxis == 'x':
        img = Image.new('L', (sizeY * imagesPerRow, sizeZ * imagesPerRow))
    elif projectionAxis == 'y':
        img = Image.new('L', (sizeX * imagesPerRow, sizeZ * imagesPerRow))
    elif projectionAxis == 'z':
        img = Image.new('L', (sizeX * imagesPerRow, sizeY * imagesPerRow))

    # normalize according to standard deviation if sigma is specified
    if sigma:
        meanv = mean(volume)
        stdv = sqrt(variance(volume, False))
        minValue = meanv - float(sigma) * stdv
        maxValue = meanv + float(sigma) * stdv
    else:
        minValue = min(volume)
        maxValue = max(volume)

    for sliceNumber in range(0, numberIterations, iterationSteps):

        if projectionAxis == 'x':
            png = Image.new('L', (sizeY, sizeZ))
        elif projectionAxis == 'y':
            png = Image.new('L', (sizeX, sizeZ))
        elif projectionAxis == 'z':
            png = Image.new('L', (sizeX, sizeY))

        (yvalue, xvalue) = divmod(sliceNumber, imagesPerRow)

        if projectionAxis == 'x':
            vol = subvolume(volume, sliceNumber, 0, 0, 1, sizeY, sizeZ)
        elif projectionAxis == 'y':
            vol = subvolume(volume, 0, sliceNumber, 0, sizeX, 1, sizeZ)
        elif projectionAxis == 'z':
            vol = subvolume(volume, 0, 0, sliceNumber, sizeX, sizeY, 1)

        vol.shiftscale(-minValue, 1)
        vol.shiftscale(0, 255 / maxValue)

        for i in range(sizeI):
            for j in range(sizeJ):

                if projectionAxis == 'x':
                    value = vol(0, i, j)
                elif projectionAxis == 'y':
                    value = vol(i, 0, j)
                elif projectionAxis == 'z':
                    value = vol(i, j, 0)

                png.putpixel((i, j), int(value))

        img.paste(png, (xvalue * sizeI, yvalue * sizeJ))

    return img