示例#1
0
    def _showOneColorslice(self, param=None):
        """
        It shows a single colored slice of the 3DFSC
        """
        imageFile = self.protocol._getExtraPath(OUTPUT_3DFSC)
        img = ImageHandler().read(imageFile)
        imgData = img.getData()

        xplotter = XmippPlotter(x=1,
                                y=1,
                                mainTitle="3DFSC Slices "
                                "along %s-axis." % self._getAxis())
        sliceNumber = self.sliceNumber.get()
        if sliceNumber < 0:
            x, _, _, _ = ImageHandler().getDimensions(imageFile)
            sliceNumber = int(x / 2)
        else:
            sliceNumber -= 1
        # sliceNumber has no sense to start in zero
        a = xplotter.createSubPlot("Slice %s" % (sliceNumber + 1), '', '')
        matrix = self.getSliceImage(imgData, sliceNumber, self._getAxis())
        plot = xplotter.plotMatrix(a,
                                   matrix,
                                   0,
                                   1,
                                   cmap=self.getColorMap(),
                                   interpolation="nearest")
        xplotter.getColorBar(plot)

        return [plt.show(xplotter)]
示例#2
0
    def _showVolumesChimera(self):
        tmpFileNameCMD = self.protocol._getExtraPath("chimera.cxc")
        f = open(tmpFileNameCMD, "w")
        dim = self.protocol.inputVolumes.get().getDim()[0]
        sampling = self.protocol.inputVolumes.get().getSamplingRate()
        tmpFileName = os.path.abspath(self.protocol._getExtraPath("axis.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                 bildFileName=tmpFileName,
                                 sampling=sampling)
        f.write("open %s\n" % tmpFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates
        
        _inputVol = self.protocol.inputVolumes.get()
        _outputVol = self.protocol.outputVolume
        inputVolFileName = os.path.abspath(ImageHandler.removeFileType(
            _inputVol.getFileName()))

        # input vol origin coordinates
        x_input, y_input, z_input = _inputVol.getShiftsFromOrigin()
        f.write("open %s\n" % inputVolFileName)
        f.write("volume #2 style mesh level 0.001 voxelSize %f origin "
                "%0.2f,%0.2f,%0.2f\n"
                % (_inputVol.getSamplingRate(), x_input, y_input, z_input))

        outputVolFileName = os.path.abspath(ImageHandler.removeFileType(
            _outputVol.getFileName()))

        # output vol origin coordinates
        x_output, y_output, z_output = _outputVol.getShiftsFromOrigin()
        f.write("open %s\n" % outputVolFileName)
        f.write("volume #3 style surface level 0.001 voxelSize %f origin "
                "%0.2f,%0.2f,%0.2f\n"
                % (_outputVol.getSamplingRate(), x_output, y_output, z_output))

        cMap = ['red', 'yellow', 'green', 'cyan', 'blue']
        d = {}
        innerRadius = self.protocol.innerRadius.get()
        d['outerRadius'] = self.protocol.outerRadius.get() * sampling
        if innerRadius < 0:
           innerRadius = 0
        d['innerRadius'] = innerRadius * sampling

        d['innerRadius'] = self.protocol.innerRadius.get() * sampling
        d['symmetry'] = Chimera.getSymmetry(XMIPP_TO_SCIPION[self.protocol.symmetryGroup.get()])

        if self.protocol.symmetryGroup >= XMIPP_I222:
            f.write("shape icosahedron mesh true radius %(outerRadius)d "
                    "orientation %(symmetry)s\n" % d)
        step = (d['outerRadius'] - d['innerRadius']) / float(len(cMap) - 1)
        f.write("color radial #3 center 0,0,0 palette -")
        counter = 0
        s = ""
        for color in cMap:
            s += "%d,%s:" % (d['innerRadius'] + counter * step, color)
            counter += 1
        f.write(s[:-1] + '\n')

        f.close()

        return [ChimeraView(tmpFileNameCMD)]
示例#3
0
def writeTiStack(inputTiList, outputStackFn, outputTltFn=None,
                 excludeList=None):
    """ Write a given list of tilt images as a single stack
    Params:
        inputTiList: input list of tilted images.
        outputStackFn: output path where to write the stack.
        orderBy: column to sort by, by default tilt angle (ascending)
        excludeList: a list of indexes of the images to skip (starting at 1)
    Results:
        A new stack file will be created and also a tlt file with tilt-angles
    """
    excludeList = excludeList or []
    ih = ImageHandler()
    j = 0
    f = open(outputTltFn, 'w') if outputStackFn else None

    for i, ti in enumerate(inputTiList):
        if i + 1 not in excludeList:
            j += 1
            ih.convert(ti, (j, outputStackFn))
            if f:
                f.write('%f\n' % ti.getTiltAngle())

    if f:
        f.close()
    def _pickMicrograph(self, mic, args):
        # Prepare mic folder and convert if needed
        micName = mic.getFileName()
        micDir = self._getTmpPath(pwutils.removeBaseExt(micName))
        pwutils.makePath(micDir)

        ih = ImageHandler()
        # If needed convert micrograph to mrc format, otherwise link it
        if pwutils.getExt(micName) != ".mrc":
            fnMicBase = pwutils.replaceBaseExt(micName, 'mrc')
            inputMic = os.path.join(micDir, fnMicBase)
            ih.convert(mic.getLocation(), inputMic)
        else:
            inputMic = os.path.join(micDir, os.path.basename(micName))
            pwutils.createLink(micName, inputMic)

        # Prepare environment
        from appion import Plugin
        Plugin.getEnviron()

        # Program to execute and it arguments
        program = "python2"
        outputFile = self._getExtraPath(pwutils.replaceBaseExt(
            inputMic, "txt"))

        args += " --image=%s --outfile=%s" % (inputMic, outputFile)

        dogpicker = Plugin.getHome("ApDogPicker.py")
        args = dogpicker + " " + args

        self.runJob(program, args)
示例#5
0
    def importTomogramsStep(self, pattern, samplingRate):
        """ Copy images matching the filename pattern
        Register other parameters.
        """
        self.info("Using pattern: '%s'" % pattern)

        # Create a Volume template object
        tomo = Tomogram()
        tomo.setSamplingRate(samplingRate)

        imgh = ImageHandler()

        tomoSet = self._createSetOfTomograms()
        tomoSet.setSamplingRate(samplingRate)

        self._parseAcquisitionData()
        for fileName, fileId in self.iterFiles():
            x, y, z, n = imgh.getDimensions(fileName)
            if fileName.endswith('.mrc') or fileName.endswith('.map'):
                fileName += ':mrc'
                if z == 1 and n != 1:
                    zDim = n
                    n = 1
                else:
                    zDim = z
            else:
                zDim = z

            origin = Transform()

            if self.setOrigCoord.get():
                origin.setShiftsTuple(self._getOrigCoord())
            else:
                origin.setShifts(x / -2. * samplingRate,
                                 y / -2. * samplingRate,
                                 zDim / -2. * samplingRate)

            tomo.setOrigin(origin)  # read origin from form

            newFileName = _getUniqueFileName(self.getPattern(),
                                             fileName.split(':')[0])
            tsId = removeExt(newFileName)
            tomo.setTsId(tsId)

            if fileName.endswith(':mrc'):
                fileName = fileName[:-4]
            createAbsLink(fileName, abspath(self._getExtraPath(newFileName)))
            tomo.setAcquisition(self._extractAcquisitionParameters(fileName))

            if n == 1:  # One volume per file
                tomo.cleanObjId()
                tomo.setFileName(self._getExtraPath(newFileName))
                tomoSet.append(tomo)
            else:  # A stack of volumes per file (not common)
                for index in range(1, n + 1):
                    tomo.cleanObjId()
                    tomo.setLocation(index, self._getExtraPath(newFileName))
                    tomoSet.append(tomo)

        self._defineOutputs(outputTomograms=tomoSet)
示例#6
0
    def _show3DFSCcolorSlices(self, param=None):
        """
        It opens 4 colores slices of the 3DFSC
        """
        errors = []
        if self.protocol.estimate3DFSC:
            img = ImageHandler().read(
                self.protocol._getExtraPath(OUTPUT_3DFSC))
            imgData = img.getData()

            xplotter = XmippPlotter(x=2,
                                    y=2,
                                    mainTitle="3DFSC Color Slices"
                                    "along %s-axis." % self._getAxis())
            # The slices to be shown are close to the center. Volume size is divided in
            # 9 segments, the fouth central ones are selected i.e. 3,4,5,6
            for i in range(3, 7):
                sliceNumber = self.getSlice(i, imgData)
                a = xplotter.createSubPlot("Slice %s" % (sliceNumber + 1), '',
                                           '')
                matrix = self.getSliceImage(imgData, sliceNumber,
                                            self._getAxis())
                plot = xplotter.plotMatrix(a,
                                           matrix,
                                           0,
                                           1,
                                           cmap=self.getColorMap(),
                                           interpolation="nearest")
            xplotter.getColorBar(plot)
            return [xplotter]
        else:
            errors.append("The 3dFSC estimation of the 3dFSC was not selected"
                          "in the protocol form.")
            return errors
    def createOutputStep(self, tsObjId):
        ts = self.inputSetOfTiltSeries.get()[tsObjId]
        tsId = ts.getTsId()
        extraPrefix = self._getExtraPath(tsId)

        outputSetOfTomograms = self.getOutputSetOfTomograms()

        newTomogram = Tomogram()
        newTomogram.setLocation(os.path.join(extraPrefix, ts.getFirstItem().parseFileName(extension=".mrc")))

        # Set tomogram origin
        ih = ImageHandler()
        xDim, yDim, zDim, _ = \
            ih.getDimensions(os.path.join(extraPrefix, ts.getFirstItem().parseFileName(extension=".mrc")))

        origin = Transform()
        sr = self.inputSetOfTiltSeries.get().getSamplingRate()
        origin.setShifts(xDim / -2. * sr,
                         yDim / -2. * sr,
                         zDim / -2 * sr)
        newTomogram.setOrigin(origin)

        # Set tomogram acquisition
        acquisition = TomoAcquisition()
        acquisition.setAngleMin(ts.getFirstItem().getTiltAngle())
        acquisition.setAngleMax(ts[ts.getSize()].getTiltAngle())
        acquisition.setStep(self.getAngleStepFromSeries(ts))
        newTomogram.setAcquisition(acquisition)

        outputSetOfTomograms.append(newTomogram)
        outputSetOfTomograms.update(newTomogram)
        outputSetOfTomograms.write()
        self._store()
示例#8
0
def getTomoSetFromStar(prot, starFile):
    samplingRate = prot.pixelSize.get()
    imgh = ImageHandler()
    tomoTable = Table()
    tomoTable.read(starFile)
    tomoList = [row.get(TOMO_NAME, FILE_NOT_FOUND) for row in tomoTable]
    prot.tomoList = List(tomoList)
    tomoNamesUnique = list(set(tomoList))

    # Create a Volume template object
    tomo = Tomogram()
    tomo.setSamplingRate(samplingRate)
    for fileName in tomoNamesUnique:
        x, y, z, n = imgh.getDimensions(fileName)
        if fileName.endswith('.mrc') or fileName.endswith('.map'):
            if z == 1 and n != 1:
                zDim = n
                n = 1
            else:
                zDim = z
        else:
            zDim = z
        origin = Transform()
        origin.setShifts(x / -2. * samplingRate,
                         y / -2. * samplingRate,
                         zDim / -2. * samplingRate)

        tomo.setOrigin(origin)  # read origin from form

        for index in range(1, n + 1):
            tomo.cleanObjId()
            tomo.setLocation(index, fileName)
            tomo.setAcquisition(TomoAcquisition(**prot.acquisitionParams))
            prot.tomoSet.append(tomo)
示例#9
0
    def importMaskStep(self, path, samplingRate):
        """ Copy mask from maskPath.
        """
        self.info("Using mask path: '%s'" % path)

        # Copy the image file into the project
        dst = self._getExtraPath(basename(path))
        dst, cleaned = cleanFileName(dst)
        pwutils.copyFile(path, dst)

        # Retrieve image dimensions
        imgh = ImageHandler()
        _, _, z, n = imgh.getDimensions(dst)

        # Create a 2D or 3D Mask, consider the case of n>1
        # as the case of some volume maps in mrc format
        if z > 1 or n > 1:
            mask = VolumeMask()
        else:
            mask = Mask()

        mask.setFileName(dst)
        mask.setSamplingRate(samplingRate)

        self._defineOutputs(**{self._possibleOutputs.outputMask.name: mask})
    def _prepareParams(self):
        args = " --noguiSplit %(half1)s %(half2)s"
        args += " --vxSize=%0.3f" % self.volumeHalf1.get().getSamplingRate()
        args += " --pVal=%(pVal)f --maxRes=%(maxRes)f --minRes=%(minRes)f"
        args += " --stepRes=%(stepRes)f"

        if self.show2D:
            args += " --vis2D"

        if self.applyMask:
            # convert mask to map/ccp4
            ih = ImageHandler()
            ih.convert(self.maskVolume.get().getLocation(),
                       self._getFileName('mask'))

            args += " --maskVol=%s" % os.path.basename(
                self._getFileName('mask'))

        params = {
            'half1': os.path.basename(self._getFileName('half1')),
            'half2': os.path.basename(self._getFileName('half2')),
            'pVal': self.pVal.get(),
            'maxRes': self.maxRes.get(),
            'minRes': self.minRes.get(),
            'stepRes': self.stepRes.get()
        }

        if self.useGpu:
            args += " --use_gpu=yes --set_gpu=%s" % self.gpuList.get()
            args += ' --lib_krnl_gpu="%s"' % resmap.Plugin.getGpuLib()

        if self.doBenchmarking:
            args += ' --doBenchMarking'

        return args % params
示例#11
0
    def applyAlignmentStep(self, tsObjId):
        ts = self.inputSetOfTiltSeries.get()[tsObjId]
        tsId = ts.getTsId()
        extraPrefix = self._getExtraPath(tsId)
        path.makePath(extraPrefix)
        outputTsFileName = os.path.join(extraPrefix, "%s.mrc" % tsId)

        ts.applyTransform(outputTsFileName)

        outputInterpolatedSetOfTiltSeries = self.getOutputInterpolatedSetOfTiltSeries()

        newTs = tomoObj.TiltSeries(tsId=tsId)
        newTs.copyInfo(ts)
        outputInterpolatedSetOfTiltSeries.append(newTs)

        for index, tiltImage in enumerate(ts):
            newTi = tomoObj.TiltImage()
            newTi.copyInfo(tiltImage, copyId=True)
            newTi.setLocation(index + 1, outputTsFileName)
            newTs.append(newTi)

        ih = ImageHandler()
        x, y, z, _ = ih.getDimensions(newTs.getFirstItem().getFileName())
        newTs.setDim((x, y, z))
        newTs.write()

        outputInterpolatedSetOfTiltSeries.update(newTs)
        outputInterpolatedSetOfTiltSeries.updateDim()
        outputInterpolatedSetOfTiltSeries.write()
        self._store()
示例#12
0
    def _validateImages(self):
        errors = []
        ih = ImageHandler()

        for imgFn, _ in self.iterFiles():

            if isdir(imgFn):
                errors.append("Folders can not be selected.")
                errors.append('  %s' % imgFn)
            else:
                # Check if images are correct by reading the header of the
                # imported files:
                # Exceptions:
                #  - Compressed movies (bz2 or tbz extensions)
                #  - Importing in streaming, since files may be incomplete
                #  - Bad characters in path [':' ,'%', '#']
                if (not self.dataStreaming and
                        not (imgFn.endswith('bz2') or imgFn.endswith('tbz') or
                             imgFn.endswith('eer') or ih.isImageFile(imgFn))):
                    if not errors:  # if empty add the first line
                        errors.append("Error reading the following images:")
                    errors.append('  %s' % imgFn)
                    errors += ProtImportImages.validatePath(imgFn)

            break  # validate just first image

        return errors
示例#13
0
    def convertStep(self, volFn, volDim, volSr, minDim, maxSr, nVoli):
        Xdim = volDim
        Ts = volSr
        newTs = self.targetResolution.get() * 1.0 / 3.0
        newTs = max(maxSr, newTs)
        newXdim = Xdim * Ts / newTs
        newRmax = self.Rmax.get() * Ts / newTs
        self.newRmax = min(newRmax, self.Rmax.get())
        fnOut = os.path.splitext(volFn)[0]
        fnOut = self._getExtraPath(
            os.path.basename(fnOut + self.OUTPUT_SUFFIX % nVoli))

        ih = ImageHandler()
        volFn = volFn if getExt(volFn) == '.vol' else volFn + ':mrc'
        if Xdim != newXdim:
            self.runJob("xmipp_image_resize",
                        "-i %s -o %s --dim %d" % (volFn, fnOut, newXdim))

        else:
            ih.convert(volFn, fnOut)

        if newXdim > minDim:
            self.runJob(
                "xmipp_transform_window",
                " -i %s -o %s --crop %d" % (fnOut, fnOut, (newXdim - minDim)))
    def convertInputStep(self, inputParticles, inputVolume, targetResolution):
        """ Write the input images as a Xmipp metadata file. 
        particlesId: is only need to detect changes in
        input particles and cause restart from here.
        """
        imgSet = self._getInputParticles()
        convXmp.writeSetOfParticles(imgSet, self._getInputXmd())
        newXdim =self._getNewDim()

        ih = ImageHandler()
        inputVol = self.inputVolume.get()
        fn = ih.fixXmippVolumeFileName(inputVol)
        img = ih.read(fn)
        img.scale(newXdim, newXdim, newXdim)
        img.write(self._getExtraPath("volume.vol"))

        args = '-i %(parts)s -o %(scaledStk)s --save_metadata_stack '
        args += '%(scaledXmd)s --dim %(xDim)d'

        params = {"parts" : self._getInputXmd(),
                  "scaledStk": self._getExtraPath('scaled_particles.stk'),
                  "scaledXmd": self._getExtraPath('scaled_particles.xmd'),
                  "xDim": newXdim
                  }
        self.runJob("xmipp_image_resize", args % params)
    def createOutputStep(self):
        particles = self.inputParticles.get()

        # Generate the SetOfAlignmet
        alignedSet = self._createSetOfParticles()
        alignedSet.copyInfo(particles)

        inputMd = self._getPath('aligned_particles.xmd')
        alignedSet.copyItems(particles,
                             updateItemCallback=self._updateItem,
                             itemDataIterator=md.iterRows(inputMd, sortByLabel=md.MDL_ITEM_ID))
        # Remove alignment 2D
        alignedSet.setAlignment(ALIGN_NONE)

        # Define the output average

        avgFile = self._getExtraPath("average.xmp")

        imgh = ImageHandler()
        avgImage = imgh.computeAverage(alignedSet)

        avgImage.write(avgFile)

        avg = Particle()
        avg.setLocation(1, avgFile)
        avg.copyInfo(alignedSet)

        self._defineOutputs(outputAverage=avg)
        self._defineSourceRelation(self.inputParticles, avg)

        self._defineOutputs(outputParticles=alignedSet)
        self._defineSourceRelation(self.inputParticles, alignedSet)
    def test_tomoProjectionOutputTiltSeriesDimension(self):
        ih = ImageHandler()
        outputDimensions = ih.getDimensions(
            self.protTomoProjection.outputProjectedSetOfTiltSeries.
            getFirstItem().getFirstItem().getFileName())

        self.assertTrue(outputDimensions == (256, 256, 61, 1))
    def maskVolume(self, volFn, maskFn, index, halfString):
        ih = ImageHandler()

        # Check if there is a mask if not then use a spherical mask
        if maskFn is None:
            # Compute sphere radius and make a spherical mask
            maskFn = self._getFileName('mask', index + 1)
            volSize = ih.getDimensions(volFn)[0]
            radius = volSize / 2 - 1
            emlib.createEmptyFile(maskFn, volSize, volSize, volSize)
            program = "xmipp_transform_mask"
            args = "-i %s --mask circular %d --create_mask %s " % (
                maskFn, -1 * radius, maskFn)
            self.runJob(program, args)
        else:
            putils.copyFile(maskFn, self._getFileName('mask', index + 1))
            maskFn = self._getFileName('mask', index + 1)

        # Read the volume if it is provided
        if volFn.endswith(".mrc"):
            volFn = volFn + ":mrc"
        # Apply mask to the volume
        volMasked = self._getFileName('volume', 'masked', index + 1,
                                      halfString)
        program = 'xmipp_image_operate'
        args = '-i %s --mult %s -o %s' % (volFn, maskFn, volMasked)
        self.runJob(program, args)
 def _invertScaleVol(self, fn):
     xdim = self._getInputParticles().getXDim()
     outputFn = self._getOutputVolFn(fn)
     ih = ImageHandler()
     img = ih.read(fn)
     img.scale(xdim, xdim, xdim)
     img.write(outputFn)
示例#19
0
def main():
    # Get arguments.
    args = get_parser().parse_args()

    setObj = EMSet(filename=args.setFile)
    firstItem = setObj.getFirstItem()
    root = pwutils.findRootFrom(args.setFile, firstItem.getFileName())
    print("ROOT: ", root)

    if args.output_text:
        with open(args.output, 'w') as f:
            for movie in setObj:
                f.write('%s\n' % movie.getFileName())
    elif args.print:
        for item in setObj:
            print(item.getFileName())
    elif args.copy:
        for item in setObj:
            fn = os.path.join(root, item.getFileName())
            print('Copying %s to %s' % (fn, args.output))
            pwutils.copyFile(fn, args.output)

    elif args.check_dims:
        from pwem.emlib.image import ImageHandler
        ih = ImageHandler()

        counter = {}

        for item in setObj:
            fn = os.path.join(root, item.getFileName())
            dims = ih.getDimensions(fn)
            counter[dims] = 1 if dims not in counter else counter[dims] + 1
            print('%s: %s' % (os.path.basename(fn), dims))

        pwutils.prettyDict(counter)
示例#20
0
 def _beforePreview(self):
     ImagePreviewDialog._beforePreview(self)
     self.lastObj = None
     self.rightPreviewLabel = "Filtered particle"
     self.message = "Filtering particle..."
     self.previewLabel = "Particle"
     self.rightImage = ImageHandler()._img
示例#21
0
 def _convertVol(self, vol, index):
     ih = ImageHandler()
     fn = vol.getFileName()
     if not fn.endswith('.mrc'):
         newFn = self._getFileName('input_vol', volId=index)
         ih.convert(fn, newFn)
         return newFn
     return fn
 def getMinMax(self, imageFile):
     img = ImageHandler().read(imageFile)
     imgData = img.getData()
     # Remove 0's
     imgData = imgData[np.nonzero(imgData)]
     min_res = round(np.amin(imgData) * 100) / 100
     max_res = round(np.amax(imgData) * 100) / 100
     return min_res, max_res
示例#23
0
 def _convertVolumes(self):
     ih = ImageHandler()
     makePath(self._getExtraPath('input'))
     inputVols = self.inputVolumes.get()
     for vol in inputVols:
         map = ih.read(vol)
         outputFn = self._getOutputFn(vol.getObjId())
         map.write(outputFn)
示例#24
0
 def _beforePreview(self):
     imgLocation = self.protocolParent.inputImage.get().getLocation()
     self.dim = ImageHandler().getDimensions(imgLocation)[0]
     self.lastObj = None
     self.rightPreviewLabel = "Final mask"
     self.message = "Generating mask..."
     self.ih = ImageHandler()
     self.rightImage = self.ih.createImage()
 def getMinMax(self, imageFile):
     img = ImageHandler().read(imageFile)
     imgData = img.getData()
     imgData = imgData[imgData != 0]
     min_res = round(np.amin(imgData) * 100) / 100
     max_res = round(np.amax(imgData) * 100) / 100
     median_res = round(np.median(imgData) * 100) / 100
     return min_res, max_res, median_res
    def assignTransformationMatricesStep(self):
        self.getOutputAssignedTransformSetOfTiltSeries()

        inputSetOfTiltSeries = self.inputSetOfTiltSeries.get()

        for ts in inputSetOfTiltSeries:
            tsId = ts.getTsId()

            tsFileName = ts.getFirstItem().parseFileName(extension='')

            for tmFilePath, _ in self.iterFiles():
                tmFileName = os.path.basename(os.path.splitext(tmFilePath)[0])

                if tsFileName == tmFileName:
                    alignmentMatrix = utils.formatTransformationMatrix(
                        tmFilePath)

                    newTs = tomoObj.TiltSeries(tsId=tsId)
                    newTs.copyInfo(ts)
                    self.outputAssignedTransformSetOfTiltSeries.append(newTs)

                    for index, tiltImage in enumerate(ts):
                        newTi = tomoObj.TiltImage()
                        newTi.copyInfo(tiltImage, copyId=True)
                        newTi.setLocation(tiltImage.getLocation())

                        transform = data.Transform()

                        if tiltImage.hasTransform():
                            previousTransform = tiltImage.getTransform(
                            ).getMatrix()
                            newTransform = alignmentMatrix[:, :, index]
                            previousTransformArray = np.array(
                                previousTransform)
                            newTransformArray = np.array(newTransform)
                            outputTransformMatrix = np.matmul(
                                previousTransformArray, newTransformArray)
                            transform.setMatrix(outputTransformMatrix)
                            newTi.setTransform(transform)

                        else:
                            transform.setMatrix(alignmentMatrix[:, :, index])
                            newTi.setTransform(transform)

                        newTs.append(newTi)

                    ih = ImageHandler()
                    x, y, z, _ = ih.getDimensions(
                        newTs.getFirstItem().getFileName())
                    newTs.setDim((x, y, z))

                    newTs.write(properties=False)

                    self.outputAssignedTransformSetOfTiltSeries.update(newTs)
                    self.outputAssignedTransformSetOfTiltSeries.updateDim()
                    self.outputAssignedTransformSetOfTiltSeries.write()

                    self._store()
    def importSubTomogramsStep(self, pattern, samplingRate):
        """ Copy images matching the filename pattern
        Register other parameters.
        """
        self.info("Using pattern: '%s'" % pattern)

        # Create a Volume template object
        subtomo = SubTomogram()
        subtomo.setSamplingRate(samplingRate)

        imgh = ImageHandler()

        self.subtomoSet = self._createSetOfSubTomograms()
        self.subtomoSet.setSamplingRate(samplingRate)

        # if self.importCoordinates.get():
        #     self.coords = []
        #     for coord3D in self.importCoordinates.get().iterCoordinates():
        #         self.coords.append(coord3D.clone())
        #     self.subtomoSet.setCoordinates3D(self.importCoordinates)

        self._parseAcquisitionData()
        for fileName, fileId in self.iterFiles():

            x, y, z, n = imgh.getDimensions(fileName)
            if fileName.endswith('.map'):
                fileName += ':mrc'
            if fileName.endswith('.mrc') or fileName.endswith(':mrc'):
                if z == 1 and n != 1:
                    zDim = n
                    n = 1
                else:
                    zDim = z
            else:
                zDim = z
            origin = Transform()

            origin.setShifts(x / -2. * samplingRate, y / -2. * samplingRate,
                             zDim / -2. * samplingRate)

            subtomo.setOrigin(origin)  # read origin from form

            newFileName = _getUniqueFileName(self.getPattern(), fileName)
            # newFileName = abspath(self._getVolumeFileName(fileName))

            if fileName.endswith(':mrc'):
                fileName = fileName[:-4]
            createAbsLink(fileName, self._getExtraPath(newFileName))

            if n == 1:
                self._addSubtomogram(subtomo, self._getExtraPath(fileName),
                                     self._getExtraPath(newFileName))
            else:
                for index in range(1, n + 1):
                    self._addSubtomogram(subtomo,
                                         self._getExtraPath(fileName),
                                         self._getExtraPath(newFileName),
                                         index=index)
示例#28
0
 def projectInitialVolume(self):
     fnOutputInitVolume=self._getTmpPath("initialVolume.vol")
     img = ImageHandler()
     img.convert(self.initialVolume.get(), fnOutputInitVolume)
     self.runJob("xmipp_image_resize","-i %s --dim %d %d"%(fnOutputInitVolume,self.Xdim2,self.Xdim2))
     fnGallery=self._getTmpPath('gallery_InitialVolume.stk')
     fnOutputReducedClass = self._getExtraPath("reducedClasses.xmd") 
     self.runJob("xmipp_angular_project_library", "-i %s -o %s --sampling_rate %f --sym %s --method fourier 1 0.25 bspline --compute_neighbors --angular_distance -1 --experimental_images %s"\
                           %(fnOutputInitVolume,fnGallery,self.angularSampling.get(),self.symmetryGroup.get(),fnOutputReducedClass))
示例#29
0
 def convertInputStep(self, resetId):
     """ Preprocess all volumes prior to clustering"""
     inputCls = self.inputClasses.get()
     ih = ImageHandler()
     for i, class3D in enumerate(inputCls):
         num = class3D.getObjId()
         vol = class3D.getRepresentative()
         newFn = self._getExtraPath('volume_id_%03d.mrc' % num)
         ih.convert(vol, newFn)
示例#30
0
    def sharpeningAndMonoResStep(self):
        last_Niters = -1
        last_lambda_sharpening = 1e38
        nextIter = True

        while nextIter is True:
            self.iteration = self.iteration + 1
            # print("iteration")
            print('\n====================\n'
                  'Iteration  %s' % (self.iteration))
            self.sharpenStep(self.iteration)
            mtd = md.MetaData()
            mtd.read(self._getFileName('METADATA_PARAMS_SHARPENING'))

            lambda_sharpening = mtd.getValue(MDL_COST, 1)
            Niters = mtd.getValue(MDL_ITER, 1)

            #             if (Niters == last_Niters):
            #                 nextIter = False
            #                 break

            if (abs(lambda_sharpening - last_lambda_sharpening) <= 0.2):
                nextIter = False
                break

            last_Niters = Niters
            last_lambda_sharpening = lambda_sharpening

            self.MonoResStep(self.iteration)

            imageFile = self._getFileName('OUTPUT_RESOLUTION_FILE')

            img = ImageHandler().read(imageFile)
            imgData = img.getData()
            max_res = np.amax(imgData)
            min_res = 2 * self.inputVolume.get().getSamplingRate()

            if (max_res - min_res < 0.75):
                nextIter = False
                break

        os.rename(
            self._getExtraPath('sharpenedMap_' + str(self.iteration) + '.mrc'),
            self._getExtraPath('sharpenedMap_last.mrc'))

        resFile = self.resolutionVolume.get().getFileName()
        pathres = dirname(resFile)
        if not exists(self._getFileName('OUTPUT_RESOLUTION_FILE')):

            print(
                '\n====================\n'
                ' WARNING---This is not the ideal case because resolution map has been imported.'
                ' The ideal case is to calculate it previously'
                ' in the same project using MonoRes.'
                '\n====================\n')