Commit 5fd9462e authored by Zolnierczuk, Piotr's avatar Zolnierczuk, Piotr
Browse files

option fixes

parent f2b345b5
Loading
Loading
Loading
Loading
+21 −16
Original line number Diff line number Diff line
@@ -52,6 +52,7 @@ def action_xyz(filenames, **kwargs):
    "default action for xyz"
    outdir    = kwargs.pop('outdir')
    overwrite = kwargs.pop('overwrite')
    savefig   = kwargs.pop('savefig')
    hfiles = []
    for filename in filenames:
        _ , ext = os.path.splitext(os.path.basename(filename))
@@ -60,13 +61,16 @@ def action_xyz(filenames, **kwargs):
        else:
            hfiles.append(filename)
    plot_xyz(*hfiles, **kwargs)
    if savefig:
        plt.savefig(savefig)


def action_diffrun(filenames, **kwargs):
    "action for diffrun"
    savefig  =  kwargs.pop('savefig')
    savefile =  kwargs.pop('savefile')
    _, axis = plt.subplots(figsize=(8,8))
    plot_diffrun(axis, filenames, **kwargs)
    plot_diffrun(axis, filenames, output=savefile, **kwargs)
    if savefig:
        plt.savefig(savefig)

@@ -244,15 +248,15 @@ def arguments_common():
                        version='%(prog)s pysen={version}'.format(version=version(full=True)))
    # save figure/data options
    pars.add_argument('--save-figure', '-S', dest='savefig', metavar='file',
                        help='save figure to a file (do not show)')
                        help='save the output figure to a file and do not show it.')
    pars.add_argument('--save-file', '-s', dest='savefile', metavar='file',
                        help='save output data to a file')
                        help='save resulting data (if any) to a file.')
    # mutually exclusive [ -v | -q ]
    verbose = pars.add_mutually_exclusive_group()
    verbose.add_argument('--verbose', '-v', dest='loglevel', action='count',
                        help='verbose output')
    verbose.add_argument('--quiet',   '-q', dest='loglevel', action='store_const', const=0,
                        help='suppres output')
                        help='suppress terminal output')
    return pars


@@ -262,9 +266,9 @@ def arguments_selection_tof():
    pars.set_defaults(tbin1=0, tbin2=None)
    grp  = pars.add_argument_group('options to select TOF bins')
    grp.add_argument('--t1' , '-b',  dest='tbin1', type=int,
                     help='set min TOF bin (default=%(default)s)')
                     help='set min. TOF bin (default=%(default)s)')
    grp.add_argument('--t2' , '-B',  dest='tbin2', type=int,
                     help='set max TOF bin (default=%(default)s)')
                     help='set max. TOF bin (default=%(default)s)')
    return pars

def arguments_selection_pix():
@@ -273,13 +277,13 @@ def arguments_selection_pix():
    grp  = pars.add_argument_group('options to select pixels')
    grp.set_defaults(xpix1=10,xpix2=-10,ypix1=10,ypix2=-10, whole_detector=False)
    grp.add_argument('--x1' , dest='xpix1', type=int,
                     help='set min X pix (default=%(default)s)')
                     help='set min. X pix (default=%(default)s)')
    grp.add_argument('--x2' , dest='xpix2', type=int,
                     help='set max X pix (default=%(default)s)')
                     help='set max. X pix (default=%(default)s)')
    grp.add_argument('--y1' , dest='ypix1', type=int,
                     help='set min Y pix (default=%(default)s)')
                     help='set min. Y pix (default=%(default)s)')
    grp.add_argument('--y2' , dest='ypix2', type=int,
                     help='set max Y pix (default=%(default)s)')
                     help='set max. Y pix (default=%(default)s)')
    grp.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
                     help='show sum over entire detector area')
    return pars
@@ -288,10 +292,10 @@ def arguments_z_scale():
    """vertical scale arguments"""
    pars = argparse.ArgumentParser(add_help=False)
    grp  = pars.add_argument_group('options to set z (vertical) scale')
    grp.add_argument('--vmin' , dest='vmin', type=int,
                     help='set min vertical scale (default=%(default)s)')
    grp.add_argument('--vmax' , dest='vmax', type=int,
                     help='set max vertical scale (default=%(default)s)')
    grp.add_argument('--vmin' , dest='vmin', type=float,
                     help='set min. vertical scale (default=%(default)s)')
    grp.add_argument('--vmax' , dest='vmax', type=float,
                     help='set max. vertical scale (default=%(default)s)')
    grp.add_argument('--logz' , dest='logz', action='store_true',
                     help='detector image log vertical scale')
    grp.add_argument('--normalize', '-n' , dest='normalize', action='store_true',
@@ -344,6 +348,7 @@ def add_xyz_options(subparser, parents=None):
                      help='xyz plot (.dat or .h5 files)',
                      description='create xyz analysis plot')
    pars.set_defaults(overwrite=False, qmin=0, qmax=np.inf, deltaq=0.001)
    pars.add_argument('file', metavar='filename', help='file to process', nargs='+')
    pars.add_argument('--qmin', dest='qmin', type=float,
                      help='qmin (default=%(default)s)')
    pars.add_argument('--qmax', dest='qmax', type=float,
+11 −9
Original line number Diff line number Diff line
@@ -19,7 +19,7 @@ from .echo import plot_single_echo

MAX_CHI2_DEFAULT_BFIELD = 1e-2 # TODO: explain the meaning of this

def norm_pix(x1, x2, nx, whole_detector=False):
def _norm_pix(x1, x2, nx, whole_detector=False):
    "normalize pixel"
    if whole_detector:
        return 0, nx
@@ -156,8 +156,8 @@ def plot_atari(hdfile, iecho=None, **kwargs):
    nph     = n_idx['dn']
    comment = hdfile.attrs['master_comment']

    xpix1, xpix2 = norm_pix(xpix1, xpix2, nx, whole_detector)
    ypix1, ypix2 = norm_pix(ypix1, ypix2, ny, whole_detector)
    xpix1, xpix2 = _norm_pix(xpix1, xpix2, nx, whole_detector)
    ypix1, ypix2 = _norm_pix(ypix1, ypix2, ny, whole_detector)

    for echo in list(hdfile['/data'].values()):
        if not (iecho is None or echo.attrs['id'] in iecho):
@@ -465,8 +465,8 @@ def plot_echo(hdfile, iecho=None, **kwargs):
    nph     = n_idx['dn']
    miny, maxy    = np.inf, 0

    xpix1, xpix2 = norm_pix(xpix1, xpix2, nx, whole_detector)
    ypix1, ypix2 = norm_pix(ypix1, ypix2, nx, whole_detector)
    xpix1, xpix2 = _norm_pix(xpix1, xpix2, nx, whole_detector)
    ypix1, ypix2 = _norm_pix(ypix1, ypix2, nx, whole_detector)

    if  center_only:
        ntaus = 0
@@ -536,13 +536,13 @@ def plot_echo(hdfile, iecho=None, **kwargs):
                R = 2*res['amplitude'][0]/( res['up'][0] - res['dn'][0] )
                resolution.append((tau0, R))
                log.info("tau={0:.3g}ns R={1:.3g}".format(tau0,R))
            title = (r'%s | %s | $\lambda$=%.2g$\AA$ $Q$=%.3f$\AA^{-1}$ ' %
                     (sample, base, lam0/ANGSTROM, q0))
            fig0.suptitle(title)
            #
            if resolution_plot:
                continue
            ax = fig0.add_subplot(nxtau, nytau, itau)
            title = (r'%s | %s | $\lambda$=%.2g$\AA$ $Q$=%.3f$\AA^{-1}$ ' %
                     (sample, base, lam0/ANGSTROM, q0))
            fig0.suptitle(title)
            plot_single_echo(ax, (cur, y, ey), (nph,n_idx['up']), fit=(xef, yef),
                             res=res, label=r'$\tau$=%.3gns' % tau0, savefile=savefile,
                             only_echo=only_echo,
@@ -618,7 +618,6 @@ def plot_echo(hdfile, iecho=None, **kwargs):
                        ax.set_facecolor('yellow')
                if absy:
                    ax.set_ylim(bottom=min(0,miny), top=max(absy,maxy))

        fig.suptitle(r'%s | %s | $\lambda$=%.2g$\AA$ $Q$=%.3f$\AA^{-1}$ $\tau$=%.3gns' %
                     (sample, base, lam0/ANGSTROM, q0,tau0))

@@ -639,4 +638,7 @@ def plot_echo(hdfile, iecho=None, **kwargs):
        ax.set_xscale('log')
        #ax.set_yscale('log')
        ax.set_ylim(bottom=min(0.1,min(res[:,1])), top=max(1.1,max(res[:,1])))
        ax.set_xlabel(r'$\tau$ [ns]')
        if resolution_plot:
            ax.set_ylabel(r'$R(Q,\tau)$')
        ax.grid(True)
+16 −6
Original line number Diff line number Diff line
@@ -10,6 +10,8 @@ import collections
import itertools
import numpy as np

from io import StringIO

from matplotlib import cm
from matplotlib.patches import Polygon
from matplotlib.colors import LogNorm
@@ -444,7 +446,9 @@ def plot_transmission(ax0, ax1, filenames, **kwargs):
        first=False
        if savefile:
            header = [label, "%13.13s%13.13s%13.13s" % ("lambda(A)","counts/pchg","ecounts/pchg")]
            np.savetxt('%s-%s-spectrum.csv' % (savefile,base), np.asarray((wlen,cnts,ecnts)).T,
            savebase, savext = os.path.splitext(savefile)
            savext = savext or '.csv'
            np.savetxt('%s-%s-spectrum%s' % (savebase,base,savext), np.asarray((wlen,cnts,ecnts)).T,
                       fmt='%13.6f',header="\n".join(header), delimiter=',')

    if logscale:
@@ -462,6 +466,7 @@ def plot_transmission(ax0, ax1, filenames, **kwargs):
        return

    _,(_,c0,e0)  =  tcounts.popitem(last=False)
    out = StringIO()
    for (_,s),(w,c,e) in list(tcounts.items()):
        tfac = c/c0
        if echodet:
@@ -472,18 +477,23 @@ def plot_transmission(ax0, ax1, filenames, **kwargs):
        p = ax1.step(w, tfac, where='mid', label = "%s T=%.3f" % (s,tavg))
        color=p[0].get_color()
        ax1.errorbar(w, tfac, yerr=efac, fmt='.', color=color, ms=0.01, lw=1.0)
        if polyfit is not None:
        if polyfit is None:
            ax1.axhline(tavg, color=color, ls='--', lw=0.5)
            out.write("%-20.20s %.4g +/- %.4g\n" % (s, tavg, etavg))
        else:
            a = np.polyfit(w, tfac, deg=polyfit)
            print("%-20.20s\n%s" % (s, np.poly1d(a, variable='lambda')))
            ax1.plot(w, np.polyval(a,w), '--',lw=0.5, color=color)
        else:
            print("%-20.20s %.4g +/- %.4g" % (s, tavg, etavg))
            ax1.axhline(tavg, color=color, ls='--', lw=0.5)
            out.write("%-20.20s\n%s\n" % (s, np.poly1d(a, variable='lambda')))
    ax1.set_xlabel(r'Neutron Wavelength [$\AA$]')
    ax1.set_ylabel('Tsam/T0')
    if echodet:
        ax1.set_ylabel('T0/Tsam')
    ax1.grid(True)
    if savefile:
        with open(savefile, 'w', encoding='ascii') as fd:
            fd.write(out.getvalue())
    else:
        print(out.getvalue())
    return


+34 −17
Original line number Diff line number Diff line
@@ -2,6 +2,9 @@
"xyz analysis plots"

import os.path
import logging

from io import StringIO

import numpy as np
import h5py
@@ -10,6 +13,13 @@ from matplotlib import colors

from pysen import config, get_q, ANGSTROM

def _norm_pix(x1, x2, nx, whole_detector=False):
    "normalize pixel"
    if whole_detector:
        return 0, nx
    return np.mod(x1,nx), np.mod(x2,nx)


def plot_xyz_single(hdfile, fig, axis, axis1=None, **kwargs):
    "xyz plot"
    #
@@ -42,9 +52,8 @@ def plot_xyz_single(hdfile, fig, axis, axis1=None, **kwargs):
    ny      = detector['detector'].attrs['ybins']
    nx      = detector['detector'].attrs['xbins']

    if whole_detector:
        xpix1, xpix2 = 0, nx
        ypix1, ypix2 = 0, ny
    xpix1, xpix2 = _norm_pix(xpix1, xpix2, nx, whole_detector)
    ypix1, ypix2 = _norm_pix(ypix1, ypix2, ny, whole_detector)

    try:
        lmax = params['lambdatable']
@@ -109,7 +118,9 @@ def plot_xyz_single(hdfile, fig, axis, axis1=None, **kwargs):
        ax2.grid(True, which='both')

    if logz:
        norm = colors.LogNorm(max(1,vmin), vmax)
        vmin = vmin or np.min(img) or 1
        vmax = vmax or np.max(img) or 1
        norm = colors.LogNorm(vmin, vmax)
        im = axis.imshow(img , aspect='equal', norm=norm)
    else:
        norm = colors.Normalize(vmin, vmax)
@@ -128,7 +139,7 @@ def plot_xyz_single(hdfile, fig, axis, axis1=None, **kwargs):



def xyz_analysis(results, axis, norm=False):
def xyz_analysis(results, axis, norm=False, output=None):
    "XYZ decomposition"

    pcha = []
@@ -163,23 +174,31 @@ def xyz_analysis(results, axis, norm=False):
    axis.xaxis.set_ticks(range(len(keys)))
    axis.set_xticklabels(keys, rotation=25 , ha='right')

    out = StringIO()
    out.write("#label   count rate \taverage q \taverage wavelength\n")
    for key, cval in cnorm.items():
        if norm:
            print("%-8.8s %+12.6f" % (key, cval), end='')
            out.write("%-8.8s %10.6f" % (key, cval))
        else:
            print("%-8.8s %+12.1f" % (key, cval), end='')
            out.write("%-8.8s %10.1f" % (key, cval))
        if key != 'mag':
            vals = results.get(key)
            if vals is not None:
                print("\t%6.4f %6.4f" % vals.get('qave'), end='')
                print("\t%5.2f %5.2f" % vals.get('lave'), end='')
        print()
                out.write("\t%6.4f %6.4f" % vals.get('qave'))
                out.write("\t%5.2f %5.2f" % vals.get('lave'))
        out.write('\n')
    if output:
        with open(output, 'w', encoding='ascii') as fd:
            fd.write(out.getvalue())
    else:
        print(out.getvalue())



def plot_xyz(*hdfiles, **kwargs):
    "plot xyz"
    normalize = kwargs.pop('normalize', False)
    savefig   = kwargs.pop('savefig', None)
    savefile  = kwargs.pop('savefile', None)

    index_map = dict(z_up=(0,0), y_up=(0,1), x_up=(0,2),
                     z_dn=(1,0), y_dn=(1,1), x_dn=(1,2))
@@ -194,6 +213,7 @@ def plot_xyz(*hdfiles, **kwargs):
    for idx in index_map.values():
        axes[idx] = fig.add_subplot(gs[idx])

    log = logging.getLogger()
    #
    gs1 = gs[2,:].subgridspec(1,3)
    ax7 = fig.add_subplot(gs1[0])
@@ -201,7 +221,7 @@ def plot_xyz(*hdfiles, **kwargs):
    ax9 = fig.add_subplot(gs1[2] )
    #
    for hfilename in hdfiles:
        print(hfilename)
        log.info('processing %s', hfilename)
        basename , _ = os.path.splitext(os.path.basename(hfilename))
        with h5py.File(hfilename, 'r') as hdf5file:
            idx = 0,0
@@ -218,10 +238,8 @@ def plot_xyz(*hdfiles, **kwargs):
                axis1=(ax8, ax9)
            res = plot_xyz_single(hdf5file, fig, ax, axis1=axis1, label=label, **kwargs)
            results.update({label:res})
        if savefig:
            plt.savefig(basename+'-'+savefig)
    #
    xyz_analysis(results, ax7, norm=normalize)
    xyz_analysis(results, ax7, norm=normalize, output=savefile)

    #
    title = title.replace('_', ' ')
@@ -229,5 +247,4 @@ def plot_xyz(*hdfiles, **kwargs):
    if z_up:
        title = r'%s    $\lambda_{max}$=%.3g $\AA$  $q_{min}$=%.3g $\AA^{-1}$' % (title, z_up.get('lmax'), z_up.get('qmin'))
    plt.suptitle(title)
    #if not savefig:
    #    plt.show()
+2 −2
Original line number Diff line number Diff line
@@ -3,8 +3,8 @@ PySEN revision module
"""
import sys
__version__  = "1.0"
__release__  = "rc2"
__date__     = "Aug 22, 2022"
__release__  = "rc3"
__date__     = "Aug 23, 2022"

def version(full=False):
    "get pysen version number"