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)
    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)
Exemple #3
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()
Exemple #4
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()
Exemple #5
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()
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()