예제 #1
0
    def _plotHistogram(self, param=None):
        """ First we parse the MSA plt:
        first column: cumulative percent.
        second column: iteration number.
        """

        iters = []
        cumPercents = []
        fn = self.protocol.getOutputPlt()
        with open(fn) as f:
            lines_after_2 = f.readlines()[2:]
            for line in lines_after_2:
                values = line.split()
                cumPercents.append(float(values[0]))
                iters.append(int(float(values[1])))
        f.close()

        width = 0.85
        xplotter = EmPlotter()
        a = xplotter.createSubPlot(
            'Behaviour of sum of eigenvalues during analysis',
            'Iteration number', '%')
        a.bar(iters, cumPercents, width, color='b')

        return [xplotter]
    def _visualizeHistogram(self, e=None):
        views = []
        numberOfBins = self.visualizeHistogram.get()
        goodScores = []
        badScores = []
        if hasattr(self.protocol, "outputParticles"):
            goodScores += [
                part._xmipp_scoreEmptiness.get()
                for part in self.protocol.outputParticles
            ]

        if hasattr(self.protocol, "eliminatedParticles"):
            badScores += [
                part._xmipp_scoreEmptiness.get()
                for part in self.protocol.eliminatedParticles
            ]

        plotter = EmPlotter()
        plotter.createSubPlot("Emptiness Score", "Emptiness Score (a.u.)",
                              "# of Particles")

        values = [goodScores, badScores]
        labels = ["Passed particles", "Discarded particles"]
        colors = ['green', 'red']

        plotMultiHistogram(values, colors, labels, numberOfBins, plotter,
                           views)

        return views
예제 #3
0
    def _plotFactorMaps(self, param=None):
        # Parse the file
        fn = self.protocol._getFileName('imcFile')
        f = open(fn)
        values = f.readline().split()
        n = int(values[0])  # Number of images
        nf = int(values[1])  # Number of factors

        x = self.firstFactor.get()
        y = self.secondFactor.get()
        xFactors = []
        yFactors = []
        i = 0
        while i < n:
            imgFactors = []
            while len(imgFactors) < nf:
                values = f.readline().split()
                imgFactors += [float(v) for v in values]
            xFactors.append(imgFactors[x - 1])
            yFactors.append(imgFactors[y - 1])
            i += 1
        f.close()

        # Create the plot
        xplotter = EmPlotter(1, 1)
        a = xplotter.createSubPlot("Factor %d vs %d" % (x, y), "Factor %d" % x,
                                   "Factor %d" % y)
        a.plot(xFactors, yFactors, 'o')

        return [xplotter]
예제 #4
0
    def plot1D(self, ctfSet, ctfId):
        ctfModel = ctfSet[ctfId]
        psdFn = ctfModel.getPsdFile()
        fn = os.path.join(
            pwutils.removeExt(psdFn).replace("_ctf", "") + '_EPA.log')

        xplotter = EmPlotter(windowTitle='GCTF results')
        plot_title = '%s # %d\n' % (ctfSet.getTsId(),
                                    ctfId) + getPlotSubtitle(ctfModel)
        a = xplotter.createSubPlot(plot_title, 'Resolution (Angstroms)', 'CTF')
        a.invert_xaxis()
        version = Plugin.getActiveVersion()
        curves = [1, 4, 5] if version == '1.18' else [1, 3, 4]

        for i in curves:
            _plotCurve(a, i, fn)
        xplotter.showLegend([
            'simulated CTF',
            # 'equiphase avg.',
            # 'bg', #  only for v1.18
            'equiphase avg. - bg',
            'cross correlation'
        ])
        a.grid(True)

        return xplotter
예제 #5
0
    def _showMollweide(self, param=None):
        """ This plot script is based on two scripts by their respective authors:
            - PlotOD.py from cryoEF package
            - https://github.com/PirateFernandez/python3_rln_scripts/blob/main/rln_star_2_mollweide_any_star.py
        """
        import numpy as np
        from matplotlib import spines
        from scipy.stats import gaussian_kde

        views = []
        xplotter = EmPlotter(
            windowTitle="Mollweide projection plot of orientation distribution"
        )
        fn = np.genfromtxt(self.protocol._getFileName('anglesFn'),
                           delimiter=' ')
        phi = fn[:, 0]
        theta = fn[:, 1]

        # Convert degrees to radians and obey angular range conventions
        x = phi / 180 * np.pi  # x is the phi angle (longitude)
        y = theta / 180 * np.pi  # y is the theta angle (latitude)
        y = -1 * y + np.pi / 2  # The convention in RELION is [0, 180] for theta,
        # whereas for the projection function it is [90, -90], so this conversion is required.
        vertical_rad = np.vstack([y, x])
        m = gaussian_kde(vertical_rad)(vertical_rad)

        ax = xplotter.createSubPlot('', 'phi', 'theta', projection="mollweide")
        # Plot your points on the projection
        #ax.plot(x, y, ',', alpha=0.5, color='#64B5F6')  # alpha - transparency (from 0 to 1), color - specify hex code
        a = ax.scatter(x, y, cmap='plasma', c=m, s=2, alpha=0.4)
        # Draw the horizontal and the vertical grid lines. Can add more grid lines if required.
        major_ticks_x = [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]
        major_ticks_y = [-np.pi / 2, -np.pi / 4, 0, np.pi / 4, np.pi / 2]
        ax.set_xticks(major_ticks_x)
        ax.set_yticks(major_ticks_y)
        ax.set_xticklabels([
            '-180$^\circ$', '-90$^\circ$', '0$^\circ$', '90$^\circ$',
            '180$^\circ$'
        ],
                           color='grey')
        ax.set_yticklabels([
            '-90$^\circ$', '-45$^\circ$', '0$^\circ$', '45$^\circ$',
            '90$^\circ$'
        ],
                           color='grey')

        # Set the color and the thickness of the grid lines
        ax.grid(which='both', linestyle='--', linewidth=1, color='#555F61')

        # Set the color and the thickness of the outlines
        for child in ax.get_children():
            if isinstance(child, spines.Spine):
                child.set_color('#555F61')

        xplotter.getColorBar(a)
        xplotter.tightLayout()
        xplotter.show()

        return views.append(xplotter)
예제 #6
0
    def _plotDendrogram(self, e=None):
        xplotter = EmPlotter()
        self.plt = xplotter.createSubPlot("Dendrogram", "", "")
        self.step = 0.25
        self.rightMost = 0.0  # Used to arrange leaf nodes at the bottom

        node = self.protocol.buildDendrogram()
        self.plotNode(node, self.minHeight.get())
        self.plt.set_xlim(0., self.rightMost + self.step)
        self.plt.set_ylim(-10, 105)

        return [xplotter]
예제 #7
0
    def visualize(self, obj, **kwargs):
        self.prot = obj

        # Experimental
        x = np.asarray([float(xi.strip()) for xi in self.prot.x.get().split(',')])
        p = np.asarray([float(xi.strip()) for xi in self.prot.p.get().split(',')])
        if self.prot.descending:
            x=np.flip(x,0)
            p=np.flip(p,0)
        logx = np.log(x)
        logx = np.insert(logx, 0, np.log(np.min(x)/2))
        p=p/np.sum(p)

        barx = []
        bary = p
        widths = []
        locx = []
        labels = []

        for i in range (0,p.shape[0]):
            barx.append(0.5*(logx[i]+logx[i+1]))
            widths.append(logx[i+1]-logx[i])
            locx.append(np.log(x[i]))
            labels.append("log(%4.2f)"%x[i])

        plotter =EmPlotter(style='seaborn-whitegrid')
        ax = plotter.createSubPlot("Particle size distribution", "log(Particle size)", "Fraction")
        ax.bar(barx, bary, width=widths, linewidth=1, label="Experimental", edgecolor="black")
        plt.xticks(locx, labels)

        # Theoretical
        fhSummary = open(self.prot._getPath("summary.txt"))
        lineno=0
        for line in fhSummary.readlines():
            if lineno==0:
                mu = float((line.split()[2]).split('=')[1])
            elif lineno==1:
                sigma = float((line.split()[2]).split('=')[1])
            lineno+=1
        fhSummary.close()

        logx = np.arange(np.min(logx),np.max(logx),(np.max(logx)-np.min(logx))/100)
        theox = norm.pdf(logx,mu,sigma)
        ax.plot(logx,theox/np.max(theox)*np.max(bary), color='red', label='Theoretical (log-normal)')

        # General
        ax.legend()
        ax.grid(True)
        plotter.show()
예제 #8
0
    def _createAngDist2D(self):
        # Common variables to use
        nparts = self.protocol._getInputParticles().getSize()
        title = "Angular Distribution"
        plotter = EmPlotter(windowTitle=title)
        sqliteFn = self.protocol._getFileName('projections')
        if not os.path.exists(sqliteFn):
            self.createAngDistributionSqlite(
                sqliteFn,
                nparts,
                itemDataIterator=iterAngles(
                    self.protocol._getFileName('anglesFn')))
        plotter.plotAngularDistributionFromMd(sqliteFn, title)

        return plotter
예제 #9
0
 def _plotMotion(self, param=None):
     if self.hasDWMics():
         output = self.protocol.outputMicrographsDoseWeighted
         columns = '_rlnAccumMotionTotal _rlnAccumMotionEarly _rlnAccumMotionLate'
         xplotter = EmPlotter.createFromFile(
             output.getFileName(),
             '',
             plotType='Plot',
             columnsStr=columns,
             colorsStr='r g b',
             linesStr='- - -',
             markersStr='. . .',
             xcolumn='id',
             ylabel='Motion per frame (A)',
             xlabel='Micrograph id',
             title='Accumulated motion per frame',
             bins=False,
             orderColumn='id',
             orderDirection='ASC')
         return [xplotter]
     else:
         return [
             self.errorMessage(
                 'Plot is available only when dose weighting is ON',
                 title="Visualization error")
         ]
예제 #10
0
    def show(self, form, *args):
        prot = form.protocol
        defocusGroups = prot.createDefocusGroups()
        print(defocusGroups)

        plotter = EmPlotter(windowTitle='%d Defocus Groups' %
                            len(defocusGroups),
                            figsize=(8, 6))
        ax = plotter.createSubPlot("", "defocus (A)", "count", 1, 1)

        for group in defocusGroups:
            ax.bar(group.minDefocus,
                   group.count,
                   group.maxDefocus - group.minDefocus,
                   align='edge')

        plotter.show()
예제 #11
0
    def _showGuinier(self, volume):
        nrefs = len(self._refsList)
        gridsize = self._getGridSize(nrefs)
        guinierFn = volume + ".guinier"

        d2 = self._getGuinierValue(guinierFn, 0)

        legends = ["lnFweighted ln(F)", "corrected ln(F)", "model"]
        xplotter = EmPlotter(*gridsize, windowTitle='Guinier Plots')
        subPlot = xplotter.createSubPlot(basename(volume),
                                         'd^-2(A^-2)',
                                         'ln(F)',
                                         yformat=False)
        for i, legend in enumerate(legends):
            y = self._getGuinierValue(guinierFn, i + 2)
            subPlot.plot(d2, y)
            xplotter.showLegend(legends)
        subPlot.grid(True)
        return xplotter
    def _displayAngDist(self, *args):
        iterations = self._getIterations()
        nparts = self.protocol.inputParticles.get().getSize()
        views = []

        if self.displayAngDist == ANGDIST_2DPLOT:
            for it in iterations:
                if it == 1:
                    print(
                        "Orientations for the first iteration cannot be plotted. "
                        "Skipping..")
                    continue
                anglesSqlite = self._getFinalPath('angular_dist_%03d.sqlite' %
                                                  it)
                title = 'Angular distribution iter %03d' % it
                plotter = EmPlotter(x=1, y=1, windowTitle=title)
                self.createAngDistributionSqlite(
                    anglesSqlite,
                    nparts,
                    itemDataIterator=self._iterAngles(it))
                plotter.plotAngularDistributionFromMd(anglesSqlite, title)
                views.append(plotter)
        else:
            it = iterations[-1]
            print("Using last iteration: ", it)
            anglesSqlite = self._getFinalPath('angular_dist_%03d.sqlite' % it)
            self.createAngDistributionSqlite(
                anglesSqlite, nparts, itemDataIterator=self._iterAngles(it))
            volumes = self.getVolumeNames(it)
            vol = self.protocol.outputVolume
            volOrigin = vol.getOrigin(force=True).getShifts()
            samplingRate = vol.getSamplingRate()

            views.append(
                ChimeraAngDist(volumes[0],
                               self.protocol._getTmpPath(),
                               voxelSize=samplingRate,
                               volOrigin=volOrigin,
                               angularDistFile=anglesSqlite,
                               format="spider"))

        return views
예제 #13
0
    def _createScatterPlot(self, rmax, colorzaxis=False):
        gridsize = self._getGridSize(1)
        xplotter = EmPlotter(x=gridsize[0],
                             y=gridsize[1],
                             windowTitle='Tilt geometry plot')
        plot_title = 'Tilt pair parameter plot'
        a = xplotter.createSubPlot(plot_title,
                                   'Tilt axis',
                                   'Tilt angle',
                                   projection='polar')

        datap, r, theta, zaxis = self._getValues()

        if colorzaxis:
            a.scatter(theta, r, c=zaxis)
        else:
            a.scatter(theta, r)
        a.set_rmax(rmax)

        return xplotter
예제 #14
0
    def _showHistogram(self, param=None):
        fn = self.protocol._getFileName('output_hist')
        with open(fn) as f:
            views = []
            numberOfBins = 10
            plotter = EmPlotter()
            plotter.createSubPlot("PSF Resolution histogram", "Resolution (A)",
                                  "Ang (str)")
            resolution = [float(line.strip()) for line in f]
        plotter.plotHist(resolution, nbins=numberOfBins)
        plotter.show()

        return views.append(plotter)
예제 #15
0
    def _plotHistogram(self, param=None):
        """ First we parse the cas_EIG file and we read:
        first line: take the number of eigen values.
        then one line per factor and we read the percent and cumulative percent.
        """
        from numpy import arange
        from matplotlib.ticker import FormatStrFormatter

        fn = self.protocol._getFileName('eigFile')
        f = open(fn)
        values = f.readline().split()
        n = int(values[0])  # Number of factors
        factors = arange(1, n + 1)
        percents = []
        cumPercents = []

        for i in factors:
            values = f.readline().split()
            percents.append(float(values[1]))
            cumPercents.append(float(values[2]))

        f.close()

        width = 0.85
        xplotter = EmPlotter()
        a = xplotter.createSubPlot('Eigenvalues histogram',
                                   'Eigenvalue number', '%')
        a.set_xticks(factors + 0.45)
        a.xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))
        bars = a.bar(factors, percents, width, color='b')

        for i, rect in enumerate(bars):
            h = rect.get_height()
            a.text(rect.get_x() + rect.get_width() / 2.,
                   h + 0.3,
                   '%d' % cumPercents[i],
                   ha='center',
                   va='bottom')
        a.set_ylim([0, percents[0] + 5])

        return [xplotter]
def plotMultiHistogram(valuesList,
                       colors=None,
                       legend=None,
                       numOfBins=100,
                       plotter=None,
                       views=None,
                       includeEmpties=False):
    """ Values list must be a n-list of list,
        where n is the number of the subhistograms to plot.
        Multiple histograms will be plot in the same chart
        If no views is passed, a new list-views will be returned with the hist.
        If no plotter is passed, a new generic one will be created.
    """

    if not all([isinstance(x, list) for x in valuesList]):
        print("Not all items in values list are lists. Returning...")
        return

    if colors is None:
        from matplotlib import colors
        from random import shuffle
        colors = colors.cnames.keys()
        shuffle(colors)

    if any([len(x) for x in valuesList]):
        if plotter is None:
            plotter = EmPlotter()
            plotter.createSubPlot("Histogram", "Score", "# of Items")

        w1 = None
        finalLegend = []
        for idx, values in enumerate(valuesList):
            if values or includeEmpties:
                if w1 is None:
                    w1 = (max(values) - min(values)) / numOfBins
                else:
                    numOfBins = int((max(values) - min(values)) / w1)

                plotter.plotHist(values, nbins=numOfBins, color=colors[idx])
                if legend:
                    finalLegend.append(legend[idx])

        if finalLegend:
            plotter.legend(labels=finalLegend)

        if views is None:
            views = [plotter]
        else:
            views.append(plotter)

        return views
예제 #17
0
    def _plotHistogram(self, param=None):
        md = MetaData()
        md.read(self.protocol._getFileName(FN_METADATA_HISTOGRAM))
        x_axis = []
        y_axis = []

        i = 0
        for idx in md:
            x_axis_ = md.getValue(MDL_X, idx)
            if i == 0:
                x0 = x_axis_
            elif i == 1:
                x1 = x_axis_
            y_axis_ = md.getValue(MDL_COUNT, idx)

            i += 1
            x_axis.append(x_axis_)
            y_axis.append(y_axis_)

        plotter = EmPlotter()
        plotter.createSubPlot("Resolutions Histogram", "Resolution (A)",
                              "# of Counts")

        barwidth = x1 - x0

        plotter.plotDataBar(x_axis, y_axis, barwidth)

        return [plotter]
예제 #18
0
def createCtfPlot(ctfSet, ctfId):
    """ Create EmPlotter instance. """
    ctfModel = ctfSet[ctfId]
    psdFn = ctfModel.getPsdFile()
    fn = removeExt(psdFn) + "_avrot.txt"
    xplotter = EmPlotter(windowTitle='CTFFind results')
    plot_title = getPlotSubtitle(ctfModel)
    a = xplotter.createSubPlot(plot_title, 'Spacial frequency (1/A)',
                               'Amplitude (or cross-correlation)')
    legendName = ['Amplitude spectrum', 'CTF Fit', 'Quality of fit']
    _plotCurves(a, fn)
    xplotter.showLegend(legendName, loc='upper right')
    a.set_ylim([-0.1, 1.1])
    a.grid(True)
    xplotter.show()
예제 #19
0
 def _plotHistogram(self, param=None):
     imageFile = self.protocol._getFileName(FN_RESOLMAP)
     img = ImageHandler().read(imageFile)
     imgData = img.getData()
     imgList = imgData.flatten()
     imgListNoZero = filter(lambda x: x > 0, imgList)
     nbins = 30
     plotter = EmPlotter(x=1, y=1, mainTitle="  ")
     plotter.createSubPlot("Resolution histogram",
                           "Resolution (A)", "# of Counts")
     plotter.plotHist(list(imgListNoZero), nbins)
     return [plotter]
예제 #20
0
 def _plotHistogram(self, param=None):
     imageFile = self.protocol._getFileName(RESMAP_VOL)
     img = ImageHandler().read(imageFile)
     imgData = img.getData()
     imgList = imgData.flatten()
     imgDataMax = self.getBackGroundValue(imgList)
     imgListNoZero = filter(lambda x: 0 < x < imgDataMax, imgList)
     nbins = 30
     plotter = EmPlotter(x=1, y=1, mainTitle="  ")
     plotter.createSubPlot("Resolution histogram", "Resolution (A)",
                           "# of Counts")
     plotter.plotHist(imgListNoZero, nbins)
     return [plotter]
 def _createAngDist2D(self, it, heatmap):
     fnDir = self.protocol._getExtraPath("Iter%03d"%it)
     fnAngles = join(fnDir,"angles.xmd")
     view=None
     if exists(fnAngles):
         fnAnglesSqLite = join(fnDir,"angles.sqlite")
         from pwem.viewers import EmPlotter
         if not exists(fnAnglesSqLite):
             from pwem.emlib.metadata import getSize
             self.createAngDistributionSqlite(fnAnglesSqLite, getSize(fnAngles), itemDataIterator=self._iterAngles(fnAngles))
         view = EmPlotter(x=1, y=1, mainTitle="Iteration %d" % it, windowTitle="Angular distribution")
         if heatmap:
             axis = view.plotAngularDistributionFromMd(fnAnglesSqLite, '', histogram=True)
             view.getFigure().colorbar(axis)
         else:
             view.plotAngularDistributionFromMd(fnAnglesSqLite, '')
     return view
예제 #22
0
def main():
    parser = argparse.ArgumentParser(prog='Scipion Plot')
    parser.add_argument('--file', help='File to visualize', required=True)
    parser.add_argument('--block', help='Block to visualize')
    parser.add_argument('--type', help='Plot type')
    parser.add_argument('--columns', help='Columns to plot')
    parser.add_argument('--xcolumn', help='X Column to plot')
    parser.add_argument('--orderColumn', help='Column to order')
    parser.add_argument('--orderDir', help='Order direction(ASC, DESC)')
    parser.add_argument('--bins',
                        help='If plot type is histogram, number of bins')
    parser.add_argument('--colors', help='Colors to plot columns')
    parser.add_argument('--styles', help='Styles to plot columns')
    parser.add_argument('--markers', help='Markers to plot columns')
    parser.add_argument('--title', help='Plot title', default='')
    parser.add_argument('--ytitle', help='Y axis title', default='')
    parser.add_argument('--xtitle', help='X axis title', default='')

    args = parser.parse_args()
    plotfile = args.file
    block = args.block if args.block else ''
    type = args.type
    columns = args.columns
    xcolumn = args.xcolumn
    orderColumn = args.orderColumn
    orderDir = args.orderDir

    bins = args.bins
    colors = args.colors
    styles = args.styles
    markers = args.markers
    title = args.title
    xtitle = args.xtitle
    ytitle = args.ytitle

    Plotter.setBackend('TkAgg')
    plotter = EmPlotter.createFromFile(plotfile, block, type, columns, colors,
                                       styles, markers, xcolumn, ytitle,
                                       xtitle, title, bins, orderColumn,
                                       orderDir)
    plotter.show(block=True)
예제 #23
0
def createCtfPlot(ctfSet, ctfId):
    ctfModel = ctfSet[ctfId]
    psdFn = ctfModel.getPsdFile()
    fn = pwutils.removeExt(psdFn) + "_EPA.log"
    xplotter = EmPlotter(windowTitle='CTF Fitting')
    plot_title = getPlotSubtitle(ctfModel)
    a = xplotter.createSubPlot(plot_title, 'Resolution (Angstroms)', 'CTF')
    a.invert_xaxis()
    version = Plugin.getActiveVersion()
    curves = [1, 4, 5] if version == '1.18' else [1, 3, 4]

    for i in curves:
        _plotCurve(a, i, fn)
    xplotter.showLegend([
        'simulated CTF',
        # 'equiphase avg.',
        # 'bg', #  only for v1.18
        'equiphase avg. - bg',
        'cross correlation'
    ])
    a.grid(True)
    xplotter.show()
예제 #24
0
    def _createAngDist2D(self, it):
        nrefs = self._getNumberOfRefs()
        gridsize = self._getGridSize(nrefs)
        self.protocol._execEmanProcess(self.protocol._getRun(), it)
        angularDist = self.protocol._getFileName("angles", iter=it)

        if os.path.exists(angularDist):
            xplotter = EmPlotter(x=gridsize[0],
                                 y=gridsize[1],
                                 mainTitle="Iteration %d" % it,
                                 windowTitle="Angular distribution")

            def plot(prefix):
                nparts = self._getNumberOfParticles(it, prefix)
                title = '%s particles' % prefix
                sqliteFn = self.protocol._getFileName('projections',
                                                      iter=it,
                                                      half=prefix)
                self.createAngDistributionSqlite(
                    sqliteFn,
                    nparts,
                    itemDataIterator=self._iterAngles(it, prefix))
                xplotter.plotAngularDistributionFromMd(sqliteFn, title)

            if self.showHalves.get() == HALF_EVEN:
                plot('even')
            elif self.showHalves.get() == HALF_ODD:
                plot('odd')
            elif self.showHalves.get() == FULL_MAP:
                plot('full')
            else:
                for prefix in ['even', 'odd', 'full']:
                    plot(prefix)
            return xplotter
        else:
            return
예제 #25
0
    def _plotHistogram(self, param=None):
        md = MetaData()
        md.read(self.protocol._getExtraPath(FN_METADATA_HISTOGRAM))
        x_axis = []
        y_axis = []

        for idx in md:
            x_axis_ = md.getValue(MDL_X, idx)
            y_axis_ = md.getValue(MDL_COUNT, idx)

            x_axis.append(x_axis_)
            y_axis.append(y_axis_)

        _plotter = EmPlotter()
        _plotter.createSubPlot("Resolutions Histogram",
                               "Resolution (A)", "# of Counts")
        barwidth = (x_axis[-1] - x_axis[0]) / len(x_axis)

        _plotter.plotDataBar(x_axis[:-2], y_axis[:-2], barwidth)

        return [_plotter]
예제 #26
0
    def getCTFViews(self, ctfSet):
        # This could be used by any CTF viewer to show CTF plus, phaseShift plot
        # if applies.
        # Return phaseShift plot if apply
        firstCtf = ctfSet.getFirstItem()

        if firstCtf.hasPhaseShift():
            phase_shift = []

            for ctf in ctfSet.iterItems():
                phShift = ctf.getPhaseShift()
                phase_shift.append(phShift)

            plotter = EmPlotter()
            plotter.createSubPlot("Phase Shift estimation", "Number of CTFs",
                                  "Phase Shift")
            plotter.plotData(np.arange(0, len(phase_shift)), phase_shift)
            self._views.append(plotter)

        # Return Standard CTF view (showJ)
        self._views.append(CtfView(self._project, ctfSet))
예제 #27
0
    def _visualizeHistogram(self, e=None):
        views = []
        numberOfBins = self.visualizeHistogram.get()

        outCoords = self.protocol.getOutput()
        if outCoords:
            mdLabel = emlib.MDL_GOOD_REGION_SCORE
            if getXmippAttribute(outCoords.getFirstItem(), mdLabel):
                plotter = EmPlotter()
                plotter.createSubPlot("Deep micrograph score",
                                      "Deep micrograph score",
                                      "Number of Coordinates")
                cScores = [getXmippAttribute(coord, mdLabel).get()
                           for coord in outCoords]
                plotter.plotHist(cScores, nbins=numberOfBins)
                views.append(plotter)
            else:
                print(" > 'outputCoordinates' don't have 'xmipp_zScoreDeepLearning2' label.")
        else:
            print(" > Output not ready yet.")

        return views
예제 #28
0
    def _showVolumeColorSlices(self, param=None):
        imageFile = self.protocol._getFileName(RESMAP_VOL)
        imgData, _, _, _ = self.getImgData(imageFile)

        xplotter = EmPlotter(x=2,
                             y=2,
                             mainTitle="Local Resolution Slices "
                             "along %s-axis." % self._getAxis())
        # The slices to be shown are close to the center. Volume size is divided
        # in segments, the fourth central ones are selected i.e. 3,4,5,6
        for i in list(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,
                                       self.lowest.get(),
                                       self.highest.get(),
                                       cmap=self.getColorMap(),
                                       interpolation="nearest")
        xplotter.getColorBar(plot)
        return [xplotter]
예제 #29
0
 def _showOneColorslice(self, param=None):
     imageFile = self.protocol._getFileName(RESMAP_VOL)
     imgData, _, _, volDims = self.getImgData(imageFile)
     print(volDims)
     xplotter = EmPlotter(x=1,
                          y=1,
                          mainTitle="Local Resolution Slices "
                          "along %s-axis." % self._getAxis())
     sliceNumber = self.sliceNumber.get()
     if sliceNumber < 0:
         sliceNumber = volDims[0] / 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,
                                self.lowest.get(),
                                self.highest.get(),
                                cmap=self.getColorMap(),
                                interpolation="nearest")
     xplotter.getColorBar(plot)
     return [xplotter]
예제 #30
0
 def schedulePlot(self, path, *args):
     # FIXME: This import should not be here
     from pwem.viewers import EmPlotter
     self.enqueue(lambda: EmPlotter.createFromFile(path, *args).show())