Commit 85d7a80e authored by Zolnierczuk, Piotr's avatar Zolnierczuk, Piotr
Browse files

toward the grand unification

incorporated diffrun and transmission into nseplot
parent 1c751479
Loading
Loading
Loading
Loading
+3 −1
Original line number Diff line number Diff line

A bunch of Python scripts useful (hopefully) for neutron spin echo experiments.
The pysen package is a collection of Python modules and scripts
for the SNS-NSE instrument (BL-15)
but may be also useful for any neutron spin echo experimenter.
+180 −62
Original line number Diff line number Diff line
@@ -8,15 +8,97 @@ import h5py
import matplotlib.pyplot as plt

from pysen        import version, setup_logger
from pysen.config import DEFAULT_ACCELERATOR_POWER
from pysen.inout  import convert_to_hdf
from pysen.plot  import plot_echo, plot_atari, plot_map, plot_magnetic_fields
from pysen.plot   import ( plot_echo, plot_atari, plot_map, plot_magnetic_fields,
                           plot_diffrun, plot_transmission )

def action_default(filenames, **kwargs):
    action  = kwargs.pop('action')
    tau     = kwargs.pop('tau')
    outdir  = kwargs.pop('outdir')
    savefig = kwargs.pop('savefig')
    log = kwargs.pop('log')
    to_show = False
    for filename in filenames:
        try:
            basename , ext = os.path.splitext(os.path.basename(filename))
            if ext != ".h5":
                log.info('converting %s to HDF', basename)
                filename = convert_to_hdf(filename, outdir, data_type='echo')
            #
            with h5py.File(filename, 'r') as hdf5file:
                action(hdf5file, tau, **kwargs)
            if savefig:
                plt.savefig(basename+'-'+savefig)
            else:
                to_show = True
        except FileNotFoundError as exc:
            print(exc)
    return to_show

def action_diffrun(filenames, **kwargs):
    savefig = kwargs.pop('savefig')
    log = kwargs.pop('log')
    _, axis = plt.subplots(figsize=(8,8))
    plot_diffrun(axis, filenames, **kwargs)
    if savefig:
        plt.savefig(savefig)
    else:
        to_show = True
    return to_show

def action_transmission(filenames, **kwargs):
    savefig       = kwargs.pop('savefig')
    spectrum_only = kwargs.pop('spectrum_only')
    log = kwargs.pop('log')

    to_show = True
    ax1 = None
    if spectrum_only:
        _, ax0        = plt.subplots(1,1, figsize=(8,6))
    else:
        _, (ax0, ax1) = plt.subplots(2,1, figsize=(8,6), sharex=True)
        #_, (ax0, ax1) = plt.subplots(2,1, figsize=(args.figwidth, args.figheight), sharex=True)

    try:
        plot_transmission(ax0, ax1, filenames, **kwargs)
    except (OSError,RuntimeError) as e:
        print(e)

    if savefig:
        plt.savefig(savefig)
    else:
        to_show = True

    return to_show



def arguments_selection(pars, pix=True, tof=True):
    """
    """
    if tof:
        pars.add_argument('--t1' , '-b',  dest='tbin1', type=int,
                          help='set min TOF bin (default=%(default)s)')
        pars.add_argument('--t2' , '-B',  dest='tbin2', type=int,
                          help='set max TOF bin (default=%(default)s)')
    if pix:
        pars.add_argument('--x1' , dest='xpix1', type=int,
                          help='set min X pix (default=%(default)s)')
        pars.add_argument('--x2' , dest='xpix2', type=int,
                          help='set max X pix (default=%(default)s)')
        pars.add_argument('--y1' , dest='ypix1', type=int,
                          help='set min Y pix (default=%(default)s)')
        pars.add_argument('--y2' , dest='ypix2', type=int,
                          help='set max Y pix (default=%(default)s)')
        pars.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
                          help='show sum over entire detector area')

def main():
    "the main"

    plot_action = dict(echo=plot_echo, atari=plot_atari, maps=plot_map, bfield=plot_magnetic_fields)
    plot_action = dict(echo=plot_echo, atari=plot_atari, maps=plot_map, bfield=plot_magnetic_fields, diffrun=plot_diffrun)
    description = "SNS NSE plotting tool"

    parser_top  = argparse.ArgumentParser(description=description)
@@ -35,8 +117,6 @@ def main():
                        map_type='all', phase0=None,
                        incoherent=False, max_chi2=1e3)
    parser.add_argument('file', metavar='filename', help='file to process', nargs='+')
    parser.add_argument('--tau', '-t',  dest='tau', type=int,
                        help='set tau to display (default=%(default)s)')
    parser.add_argument('--save-figure', '-S', dest='savefig',
                        help='save figure to a file (do not show)')
    parser.add_argument('--save-file', '-s', dest='savefile',
@@ -53,8 +133,10 @@ def main():


    # echo plot
    parser_echo = subparsers.add_parser('echo', help='plot echo', parents=[parser])
    parser_echo = subparsers.add_parser('echo', help='plot echo (.echo or .h5 files)', parents=[parser])
    grp_echo = parser_echo.add_argument_group('echo plot options')
    grp_echo.add_argument('--tau', '-t',  dest='tau', type=int,
                          help='set tau to display (default=%(default)s)')
    grp_echo.add_argument('--center-only'   , '-C', dest='center_only', action='store_true',
                          help='show only center patch')
    grp_echo.add_argument('--only-echo', dest='only_echo', action='store_true',
@@ -65,43 +147,47 @@ def main():
                          help='use the same vertical scale for all pixels')
    grp_echo.add_argument('--num-pix', '-N', dest='npix', metavar='N', type=int,
                          help='set pixel binning (default=%(default)s)')
    grp_echo.add_argument('--t1' , '-b',  dest='tbin1', type=int,
                          help='set min TOF bin (default=%(default)s)')
    grp_echo.add_argument('--t2' , '-B',  dest='tbin2', type=int,
                          help='set max TOF bin (default=%(default)s)')
    grp_echo.add_argument('--x1' , dest='xpix1', type=int,
                          help='set min X pix (default=%(default)s)')
    grp_echo.add_argument('--x2' , dest='xpix2', type=int,
                          help='set max X pix (default=%(default)s)')
    grp_echo.add_argument('--y1' , dest='ypix1', type=int,
                          help='set min Y pix (default=%(default)s)')
    grp_echo.add_argument('--y2' , dest='ypix2', type=int,
                          help='set max Y pix (default=%(default)s)')
    grp_echo.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
                          help='show sum over entire detector area')
    arguments_selection(grp_echo)
    #grp_echo.add_argument('--t1' , '-b',  dest='tbin1', type=int,
    #                      help='set min TOF bin (default=%(default)s)')
    #grp_echo.add_argument('--t2' , '-B',  dest='tbin2', type=int,
    #                      help='set max TOF bin (default=%(default)s)')
    #grp_echo.add_argument('--x1' , dest='xpix1', type=int,
    #                      help='set min X pix (default=%(default)s)')
    #grp_echo.add_argument('--x2' , dest='xpix2', type=int,
    #                      help='set max X pix (default=%(default)s)')
    #grp_echo.add_argument('--y1' , dest='ypix1', type=int,
    #                      help='set min Y pix (default=%(default)s)')
    #grp_echo.add_argument('--y2' , dest='ypix2', type=int,
    #                      help='set max Y pix (default=%(default)s)')
    #grp_echo.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
    #                      help='show sum over entire detector area')
    grp_echo.add_argument('--resolution', '-R', dest='resolution_plot', action='store_true',
                          help='TBD')
    # atari plot
    parser_atari  = subparsers.add_parser('atari',  help='atari plot', parents=[parser])
    parser_atari  = subparsers.add_parser('atari',  help='atari plot (.echo or .h5 files)', parents=[parser])
    grp_atari = parser_atari.add_argument_group('atari plot options')
    grp_atari.add_argument('--tau', '-t',  dest='tau', type=int,
                          help='set tau to display (default=%(default)s)')
    grp_atari.add_argument('--only-echo', dest='only_echo', action='store_true',
                           help='show only echo (no up/down)')
    grp_atari.add_argument('--incoherent', '-I', dest='incoherent', action='store_true',
                          help='treat data as from incoherent scatterer')
    grp_atari.add_argument('--t1' , '-b',  dest='tbin1', type=int,
                           help='set min TOF bin (default=%(default)s)')
    grp_atari.add_argument('--t2' , '-B',  dest='tbin2', type=int,
                           help='set max TOF bin (default=%(default)s)')
    grp_atari.add_argument('--x1' , dest='xpix1', type=int,
                           help='set min X pix (default=%(default)s)')
    grp_atari.add_argument('--x2' , dest='xpix2', type=int,
                           help='set max X pix (default=%(default)s)')
    grp_atari.add_argument('--y1' , dest='ypix1', type=int,
                           help='set min Y pix (default=%(default)s)')
    grp_atari.add_argument('--y2' , dest='ypix2', type=int,
                           help='set max Y pix (default=%(default)s)')
    grp_atari.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
                           help='select the entire detector area')
    arguments_selection(grp_atari)
    #grp_atari.add_argument('--t1' , '-b',  dest='tbin1', type=int,
    #                       help='set min TOF bin (default=%(default)s)')
    #grp_atari.add_argument('--t2' , '-B',  dest='tbin2', type=int,
    #                       help='set max TOF bin (default=%(default)s)')
    #grp_atari.add_argument('--x1' , dest='xpix1', type=int,
    #                       help='set min X pix (default=%(default)s)')
    #grp_atari.add_argument('--x2' , dest='xpix2', type=int,
    #                       help='set max X pix (default=%(default)s)')
    #grp_atari.add_argument('--y1' , dest='ypix1', type=int,
    #                       help='set min Y pix (default=%(default)s)')
    #grp_atari.add_argument('--y2' , dest='ypix2', type=int,
    #                       help='set max Y pix (default=%(default)s)')
    #grp_atari.add_argument('--whole-detector', '-W', dest='whole_detector', action='store_true',
    #                       help='select the entire detector area')
    grp_atari.add_argument('--vmin' , dest='vmin', type=float,
                           help='detector image min vertical scale (default=%(default)s) ')
    grp_atari.add_argument('--vmax' , dest='vmax', type=float,
@@ -113,26 +199,67 @@ def main():
    grp_atari.add_argument('--phase0' , dest='phase0', type=float,
                           help='set inital phase for echo fitting (default=%(default)s)')

    # transmission plot


    # map plot
    parser_map = subparsers.add_parser('maps', help='plot maps', parents=[parser])
    parser_map = subparsers.add_parser('maps', help='plot maps (.echo or .h5 files)', parents=[parser])
    grp_map = parser_map.add_argument_group('map plot options')

    grp_map.add_argument('--tau', '-t',  dest='tau', type=int,
                         help='set tau to display (default=%(default)s)')
    grp_map.add_argument('--map-type', dest='map_type', choices=['all', 'up', 'down'],
                         help='(default: %(default)s)')
    grp_map.add_argument('--num-pix', '-N', dest='npix', type=int,
                         help='set pixel binning (default=%(default)s)')
    # magnetic field
    parser_bfield = subparsers.add_parser('bfield', help='plot magnetic fields', parents=[parser])
    parser_bfield = subparsers.add_parser('bfield', help='plot magnetic fields (.echo or .h5 files)', parents=[parser])
    grp_bfield = parser_bfield.add_argument_group('magnetic field plot options')
    grp_bfield.add_argument('--tau', '-t',  dest='tau', type=int,
                            help='set tau to display (default=%(default)s)')
    grp_bfield.add_argument('--max-chi2', dest='max_chi2', type=float, default=1e-2,
                            help='set max chi-square (default=%(default)s)')
    grp_bfield.add_argument('--axis', dest='axis', type=int, default=-1,
                            help='set axis to plot  (default=%(default)s)')

    # diffraction plot
    parser_diffrun = subparsers.add_parser('diffrun', help='plot diffraction scan', parents=[parser])
    grp_diffrun= parser_diffrun.add_argument_group('diffraction scan plot options')
    grp_diffrun.set_defaults(selection=None, power=DEFAULT_ACCELERATOR_POWER)
    grp_diffrun.add_argument('--up',      '-u', dest='selection', action='append_const', const='up',
                       help="plot 'up' counts")
    grp_diffrun.add_argument('--down',    '-d', dest='selection', action='append_const', const='down',
                       help="plot 'down' counts")
    grp_diffrun.add_argument('--coherent', '-c', dest='selection', action='append_const', const='coherent',
                       help="plot coherent deconvoluted")
    grp_diffrun.add_argument('--incoherent', '-i', dest='selection', action='append_const', const='incoherent',
                       help="plot incoherent deconvoluted")
    grp_diffrun.add_argument('--ratio',    '-r', dest='selection', action='append_const',  const='flip_ratio',
                       help="plot flip ratio (up/down)")
    grp_diffrun.add_argument('--average',  '-a', dest='selection', action='append_const', const='average',
                       help="plot (up+down)/2 sum")
    grp_diffrun.add_argument('--coherent-ratio', '-C', dest='selection', action='append_const', const='coherent_ratio',
                       help="plot coherent/incoherent ratio")
    #
    arguments_selection(grp_diffrun, pix=False)
    grp_diffrun.add_argument('--logscale', '-l', dest='log_scale', action='store_true',
                        help="plot in semilogy")
    grp_diffrun.add_argument('--att', '-A', dest='att_table', action='store_true',
                        help="use attenuation table")

    # transmission plot
    parser_trans = subparsers.add_parser('transmission', help='plot transmission data', parents=[parser])
    grp_trans= parser_trans.add_argument_group('transmission plot options')
    grp_trans.set_defaults(log_scale=False, spectrum_only=False, pos='p2')
    grp_trans.add_argument('--pos' , '-p', dest='pos' ,
                           help='set instrument position: p1, p2, p3 or p4 (default %(default)s)')
    arguments_selection(grp_trans, pix=False)
    grp_trans.add_argument('--logscale', '-l', dest='logscale', action='store_true',
                        help="plot in semilogy")
    grp_trans.add_argument('--spectrum-only', '-w', dest='spectrum_only', action='store_true',
                        help="plot only wavelength spectrum")
    grp_trans.add_argument('--poly', '-P', type=int, dest='polyfit', metavar='deg',
                        help='set polynomial degree to fit (default=%(default)s)')
    grp_trans.add_argument('--echodet', '-e', dest='echodet', action='store_true',
                        help='report transmission for echodet 1/T')

    # ===================================
    args = parser_top.parse_args()
    log = setup_logger(args.loglevel)
    log.debug('program arguments %s', args)
@@ -141,24 +268,15 @@ def main():
    if args.savefig:
        plt.switch_backend('Agg')


    kwargs = vars(args)
    to_show = False
    for filename in args.file:
        try:
            basename , ext = os.path.splitext(os.path.basename(filename))
            if ext != ".h5":
                log.info('converting %s to HDF', basename)
                filename = convert_to_hdf(filename, args.outdir, data_type='echo')
            #
            with h5py.File(filename, 'r') as hdf5file:
                plot_action[args.what](hdf5file, iecho=args.tau, **kwargs)
            if args.savefig:
                plt.savefig(basename+'-'+args.savefig)
            else:
                to_show = True
        except FileNotFoundError as exc:
            print(exc)

    plot_action = dict(echo=plot_echo, atari=plot_atari, maps=plot_map, bfield=plot_magnetic_fields, diffrun=plot_diffrun)
    if args.what in ('echo', 'atari', 'maps', 'bfield'):
        to_show = action_default(args.file, action=plot_action[args.what], log=log, **kwargs)
    if args.what in ('diffrun', ):
        to_show = action_diffrun(args.file, log=log, **kwargs)
    if args.what in ('transmission', ):
        to_show = action_transmission(args.file, log=log, **kwargs)
    if to_show:
        plt.show()

+12 −12
Original line number Diff line number Diff line
@@ -262,9 +262,9 @@ def _get_q(q, wavelength, t1=0, t2=-1):
def plot_diffrun(axis, filenames, **kwargs):
    "process files"

    what   = kwargs.pop('what',   None) or ('up', 'down')
    t1     = kwargs.pop('tmin',   None)
    t2     = kwargs.pop('tmax',   None)
    selection   = kwargs.pop('selection',   None) or ('up', 'down')
    t1     = kwargs.pop('tbin1',   None)
    t2     = kwargs.pop('tbin2',   None)
    logscale  = kwargs.pop('log_scale', False)
    output    = kwargs.pop('output', None)
    power     = kwargs.pop('power',  1.4)
@@ -349,30 +349,30 @@ def plot_diffrun(axis, filenames, **kwargs):
            if out:
                np.savetxt(out, data.T, fmt='%.3g', header = "%s\nQ counts err" % label)

        if 'up' in what:
        if 'up' in selection:
            _make_plot(axis, (q0, cup, ecup ), marker='^', lbl='up')
            axis0 = axis
        if 'down' in what:
        if 'down' in selection:
            _make_plot(axis, (q1, cdn, ecdn ), marker='v', lbl='down')
            axis0 = axis
        if 'coherent' in what:
        if 'coherent' in selection:
            _make_plot(axis, (qmean, coherent, ecoherent ),     marker='^', lbl='C')
            axis0 = axis
        if 'incoherent' in what:
        if 'incoherent' in selection:
            _make_plot(axis, (qmean, incoherent, eincoherent ), marker='v', lbl='I')
            axis0 = axis
        if 'average' in what:
        if 'average' in selection:
            average  = (coherent+incoherent)/2
            eaverage = sqrt(ecoherent**2+eincoherent**2)
            _make_plot(axis, (qmean, average, eaverage), marker='s', lbl='<A>')
            axis0 = axis

        # ratios
        if 'flip_ratio' in what:
        if 'flip_ratio' in selection:
            #fratio = np.where(fratio>1.0, fratio, 1.0/fratio)
            if axis1 is None: axis1 = axis.twinx()
            _make_plot(axis1, (qmean, fratio, eratio ), marker='o', lbl='FR')
        if 'coherent_ratio' in what:
        if 'coherent_ratio' in selection:
            cratio  = (2*fratio - 1)/3
            ecratio = (2*eratio)/3
            if axis1 is None: axis1 = axis.twinx()
@@ -404,8 +404,8 @@ def plot_transmission(ax0, ax1, filenames, **kwargs):
    polyfit  = kwargs.get('polyfit', None)
    echodet  = kwargs.get('echodet', False)
    pos  = kwargs.get('pos', 'p2')
    tmin = kwargs.get('tmin', 0)
    tmax = kwargs.get('tmax', None)
    tmin = kwargs.get('tbin1', 0)
    tmax = kwargs.get('tbin2', None)

    tcounts = collections.OrderedDict()

+10 −10
Original line number Diff line number Diff line
@@ -14,31 +14,31 @@ from pysen.plot import plot_diffrun
def main():
    "main entry"
    parser = argparse.ArgumentParser()
    parser.set_defaults(what=None,
    parser.set_defaults(selection=None,
                        log_scale=False, tmin=None, tmax=-1, att_table=None,
                        power=DEFAULT_ACCELERATOR_POWER,
                        plotfile=None, output=None)
    parser.add_argument('file', metavar='filename',
                        help='file to process', nargs='+')
    parser.add_argument('--up',      '-u', dest='what', action='append_const', const='up',
    parser.add_argument('--up',      '-u', dest='selection', action='append_const', const='up',
                       help="plot 'up' counts")
    parser.add_argument('--down',    '-d', dest='what', action='append_const', const='down',
    parser.add_argument('--down',    '-d', dest='selection', action='append_const', const='down',
                       help="plot 'down' counts")
    parser.add_argument('--coherent', '-c', dest='what', action='append_const', const='coherent',
    parser.add_argument('--coherent', '-c', dest='selection', action='append_const', const='coherent',
                       help="plot coherent and incoherent deconvoluted")
    parser.add_argument('--incoherent', '-i', dest='what', action='append_const', const='incoherent',
    parser.add_argument('--incoherent', '-i', dest='selection', action='append_const', const='incoherent',
                       help="plot coherent and incoherent deconvoluted")
    #
    parser.add_argument('--ratio',    '-r', dest='what', action='append_const',  const='flip_ratio',
    parser.add_argument('--ratio',    '-r', dest='selection', action='append_const',  const='flip_ratio',
                       help="plot flip ratio")
    parser.add_argument('--average',  '-a', dest='what', action='append_const', const='average',
    parser.add_argument('--average',  '-a', dest='selection', action='append_const', const='average',
                       help="plot (up+down)/2 sum")
    parser.add_argument('--coherent-ratio', '-C', dest='what', action='append_const', const='coherent_ratio',
    parser.add_argument('--coherent-ratio', '-C', dest='selection', action='append_const', const='coherent_ratio',
                       help="plot coherent/incoherent ratio")
    #
    parser.add_argument('--tmin', '-t', dest='tmin', type=int,
    parser.add_argument('--tmin', '-t', metavar='tmin', dest='tbin1', type=int,
                        help='')
    parser.add_argument('--tmax', '-T', dest='tmax', type=int,
    parser.add_argument('--tmax', '-T', metavar='tmax', dest='tbin2', type=int,
                        help='')
    parser.add_argument('--logscale', '-l', dest='log_scale', action='store_true',
                        help="plot in semilogy")
+2 −2
Original line number Diff line number Diff line
@@ -24,9 +24,9 @@ def main():
                        help="plot in semilogy")
    parser.add_argument('--spectrum-only', '-w', dest='spectrum_only', action='store_true',
                        help="plot only wavelength spectrum")
    parser.add_argument('--tmin', '-t', type=int, dest='tmin',
    parser.add_argument('--tmin', '-t', type=int, dest='tbin1', metavar='tmin',
                        help='set min TOF channel (default=%(default)s)')
    parser.add_argument('--tmax', '-T', type=int, dest='tmax',
    parser.add_argument('--tmax', '-T', type=int, dest='tbin2', metavar='tmax',
                        help='set max TOF channel (default=%(default)s)')
    parser.add_argument('--poly', '-P', type=int, dest='polyfit', metavar='deg',
                        help='set polynomial degree to fit (default=%(default)s)')