Commit e57851e3 authored by Zolnierczuk, Piotr's avatar Zolnierczuk, Piotr
Browse files

cleanup in plot_curscan

parent ee328bfb
Loading
Loading
Loading
Loading
+54 −62
Original line number Diff line number Diff line
@@ -76,11 +76,8 @@ def plot_detector_beam(results, shift=None, xscale=1.0, outfile=None):
    if outfile:
        np.savetxt(outfile, np.vstack((wlen, det)).T)



def plot_curscan(axes, filename, ring=None, normalize=False,
                 currents=False, total=False, legend=True):
    "plot current scan"
def _read_curscan(filename):
    "read current scan"
    hdr, res = read_datfile(filename)
    #q     = hdr['q'][0]
    #tau   = hdr['tau'][0]*1e9
@@ -92,49 +89,58 @@ def plot_curscan(axes, filename, ring=None, normalize=False,
    for l in res:
        #print "========================================="
        pc = 0
        for k, v in l.items():
        for k in l:
            if k.startswith('proton_charge'):
                _phase = []
                pc = v
                pc = l[k]
            if k.startswith('detector.ring') and k.endswith('sum'):
                _phase.append([v, pc])
                _phase.append([l[k], pc])
            if k == 'phasecurrent1':
                cur.append(v)
                cur.append(l[k])
        phases.append(_phase)
    phases = np.asarray(phases)
    cur    = np.asarray(cur)
    #return dict(nphases=ntot, proton_charge=pc, current=cur, phases=phases, info=hdr['info'])
    return ntot, pc, cur, phases, hdr['info']

    def plot_counts(counts, label, fmt='ko-', normalize=None):
def _plot_counts(ax, x, cnts, label, fmt='ko-', normalize=None):
    "plot counts as a function of phase point"
    if x is None:
        x = range(1,len(cnts)+1)
    ecnts = np.sqrt(cnts*1.0)
    if normalize is not None:
        cnts  = cnts *1.0/normalize
        ecnts = ecnts*1.0/normalize
    ax.errorbar(x, cnts, yerr=ecnts, fmt=fmt, label=label)


def plot_curscan(axes, filename, ring=None, normalize=False,
                 currents=False, total=False, legend=True):
    "plot current scan"
    ntot, _, cur, phases, info = _read_curscan(filename)

    x = None
    if currents:
        x = cur
        else:
            x = range(1, len(counts)+1)
        ecounts = np.sqrt(counts*1.0)
        if normalize is not None:
            counts  = counts *1.0/normalize
            ecounts = ecounts*1.0/normalize
        axes.errorbar(x, counts, yerr=ecounts,
                      fmt=fmt, label=label) # 'Ring #%d' % (r+1))

    if total:
        counts  = np.sum(phases[:, :, 0], axis=1)
        pcharge = np.sum(phases[:, :, 1], axis=1) if normalize else None
        plot_counts(counts, fmt='ys-', label='Sum', normalize=pcharge)
        _plot_counts(axes, x, counts , fmt='ys-', label='Sum', normalize=pcharge)
    nrings  = phases.shape[1]
    for r in range(nrings):
        if ring is not None and (r+1)!=ring:
            continue
        counts  = phases[:, r, 0]
        pcharge = phases[:, r, 1] if normalize else None
        plot_counts(counts, fmt=COLOR_MAP.get(r+1, 'k')+'.-',
        _plot_counts(axes, x, counts, fmt=COLOR_MAP.get(r+1, 'k')+'.-',
                     label='Ring #%-d' % (r+1), normalize=pcharge)

    if legend:
        axes.legend(loc='upper right')
        if not currents:
            axes.set_xlim((0, ntot+8))
        axes.set_title(os.path.basename(hdr['info'].split()[-1]))
        axes.set_title(os.path.basename(info.split()[-1]))
    else:
        if not currents:
            axes.set_xlim((0, ntot+2))
@@ -169,7 +175,6 @@ def plot_datfile(inpfile, phase=-1, nx=32, ny=32, legend=True, maxz=None):
def plot_coverage(*data, **kwargs):
    """plot q-tau coverage
    """
    verbose= kwargs.pop('verbose', False) # verbose output
    center = kwargs.pop('center',  False) # plot coverage for the center of the detector
    full   = kwargs.pop('full',    False) # plot coverage for the entire detector
    errors = kwargs.pop('errors',  True)  # plot "errors"
@@ -179,55 +184,42 @@ def plot_coverage(*data, **kwargs):
    if not full and not center:
        center = True

    ndata = len(data)
    minq, maxq = np.finfo(float).max, np.finfo(float).min
    mint, maxt = np.finfo(float).max, np.finfo(float).min

    limq = np.finfo(float).max, np.finfo(float).min
    limt = np.finfo(float).max, np.finfo(float).min

    # data loop
    #for i, (lmax, qmin, result, limits, out) in enumerate(data):
    for i, dpt in enumerate(data):
        if verbose:
    colors =iter(cmap(np.linspace(0.0,1.0,len(data))))
    for dpt in data:
        if kwargs.get('verbose'):
            print(dpt.get('message'))

        acolor = cmap((i+1.0)/ndata)
        acolor = next(colors)
        points = None

        for k, (q, t1, t2) in enumerate(dpt.get('limits')):
        for q, t1, t2 in dpt.get('limits'):
            lims = np.vstack((np.hstack( (t1, t2[::-1]) ),
                              np.hstack( (q , q [::-1]) )))
            result = dpt['plot_data']
            if points is None and center:
                alpha = _ALPHA_OPAQUE
                if errors:
                    alpha=_ALPHA_TRANSPARENT
                    axes.errorbar(result[0], result[1], xerr=result[2:4], yerr=result[4:6], fmt='.',
                                  markersize=2, color=acolor,
                                  label = r'${q_{min}} %.3g\AA^{-1}\,\lambda_{max}=%.0f\AA$' % (
                                      dpt['qmin'], dpt['lmax']))
                axes.add_patch(Polygon(lims.T, closed=True, fill=True, color=acolor, alpha=alpha))

            if points is None:
                points = lims[:]
            else:
                points = np.hstack((points, lims[:]))
            limt = min(np.min(lims[0]), limt[0]), max(np.max(lims[0]), limt[1])
            limq = min(np.min(lims[1]), limq[0]), max(np.max(lims[1]), limq[1])

            minq = min(np.min(lims[1]), minq)
            maxq = max(np.max(lims[1]), maxq)
            mint = min(np.min(t1), mint)
            maxt = max(np.max(t1), maxt)
            result = dpt['plot_data']
            if not k and center:
                label = r'${q_{min}} %.3g\AA^{-1}\,\lambda_{max}=%.0f\AA$' % (dpt['qmin'],
                                                                              dpt['lmax'])
                alpha = _ALPHA_OPAQUE
                xerr = yerr = None
                msiz = 1
                if errors:
                    alpha=_ALPHA_TRANSPARENT
                    xerr = result[2:4]
                    yerr = result[4:6]
                    msiz = 2
                    axes.errorbar(result[0], result[1], xerr=xerr, yerr=yerr, fmt='.',
                                  markersize=msiz, color=acolor,label=label)
                axes.add_patch(Polygon(lims.T,
                                       closed=True, fill=True,
                                       color=acolor, alpha=alpha))
            if not full:
                break

        if full and points is not None:
            # find only perimeter points
            hull = ConvexHull(points.T)
            for simplex in hull.simplices:
            for simplex in ConvexHull(points.T).simplices:
                plt.plot(points[0,simplex], points[1,simplex], '-', color=acolor, lw=2)
    return (mint, maxt), (minq, maxq)
    return limt, limq
+1 −2
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@ Main GUI window module.
#import os

try:
    from PyQt5.QtWidgets import (qApp, QMainWindow, QMessageBox,QVBoxLayout, QTabWidget, QWidget)
    from PyQt5.QtWidgets import qApp, QMainWindow, QMessageBox,QVBoxLayout #, QTabWidget, QWidget)
except ImportError:
    pass

@@ -42,7 +42,6 @@ class MainWindow(QMainWindow, Ui_MainWindow):

    def help(self):
        "help method"
        pass

    def about_box(self):
        "help about"
+3 −3
Original line number Diff line number Diff line
@@ -55,16 +55,16 @@ def main():

    def plot_curscan(i=None):
        "callback to animation"
        axes.clear()
        if i is not None:
            print(i, args.file)
        axes.clear()
        qpl.plot_curscan(axes, args.file,
                         normalize=args.normalize, ring=args.ring,
                         total=args.total, currents=args.currents, legend=args.legend)

    plot_curscan(None)
    if args.live:
        _ = animation.FuncAnimation(fig, plot_curscan, interval=int(args.live)*1000)
    else:
        plot_curscan(None)

    if args.out:
        plt.savefig(args.out)