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

nseplot almost done

parent 4819fb11
Loading
Loading
Loading
Loading

misc/show-all-help.sh

0 → 100755
+15 −0
Original line number Diff line number Diff line
#!/bin/bash

nseplotcmd=./pysen/plot/nseplot.py 
commands=$($nseplotcmd -h  | grep '^\s*{' | head -1 | tr '{},' ' ')
echo $commands
echo 
#
for c in $commands; do 
    echo "====> command: $c" 
    $nseplotcmd $c --help
    echo 
done


# vim: filetype=bash
+1 −0
Original line number Diff line number Diff line
@@ -4,3 +4,4 @@ echo fit/plot module

from .fit    import fit_echo_current, Spectrum       # NOQA
from .reduce import get_symmetry_phase, reduce_echo  # NOQA
from .make_phase_table import make_phase_table       # NOQA
+8 −92
Original line number Diff line number Diff line
#!/usr/bin/env python
"PHASE TABLE"
import time
import sys
import os.path

import logging
import argparse

import numpy as np
import h5py
import matplotlib.pyplot as plt

from scipy.interpolate import interp2d

from pysen import config, setup_logger
from pysen.echo import get_symmetry_phase
from pysen.inout import convert_to_hdf
from pysen import config
from pysen.mathutil import simple_cluster

def brute_force_interpolation(vals, xvals, yvals, x, y):
@@ -33,7 +27,7 @@ def brute_force_interpolation(vals, xvals, yvals, x, y):
    return res


def make_phase_table(phtab, polyfit=0, ncur=9, nphi=11, pos=2, threshold=0.2):
def make_phase_table(phtab, polyfit=0, ncur=10, nphi=11, pos='p2', threshold=0.2):
    "make phase table"
    #
    log = logging.getLogger()
@@ -50,8 +44,8 @@ def make_phase_table(phtab, polyfit=0, ncur=9, nphi=11, pos=2, threshold=0.2):
    phase = phtab[:,:,2]

    if polyfit>0:
        mini00, maxi00 =  0.0, 80.0 # FIXME: hard coded
        minphi, maxphi = -2.0, config.phi_limits('p%d' % pos)[1]
        mini00, maxi00 =  0.0, 90.0 # FIXME: hard coded
        minphi, maxphi = -2.0, config.phi_limits(pos)[1]
    else:
        mini00, maxi00 = np.amin(i00), np.amax(i00)
        minphi, maxphi = np.amin(phi), np.amax(phi)
@@ -83,11 +77,10 @@ def make_phase_table(phtab, polyfit=0, ncur=9, nphi=11, pos=2, threshold=0.2):
            # fill in data
            z[:,i] = np.polyval(a,yphi)
            plt.plot(yphi, np.polyval(a,yphi), '--', lw=1, label=r'i$_{00}$=%.1f' % c)
        f = interp2d(x,y,z, kind='linear', fill_value=None, bounds_error=False) #, fill_value=0)
        f = interp2d( x, y, z, kind='linear', fill_value=None, bounds_error=False)
    else:
        # interpolate using measured data
        f = interp2d(i00, phi, phase, kind='linear',
                     fill_value=None, bounds_error=False) #, fill_value=0)
        f = interp2d(i00, phi, phase, kind='linear', fill_value=None, bounds_error=False)
        x, y  = np.meshgrid(i00_set, phi_set)
        z = f(i00_set, phi_set)

@@ -112,7 +105,6 @@ def make_phase_table(phtab, polyfit=0, ncur=9, nphi=11, pos=2, threshold=0.2):
                    max_abs = abs(ph_dif)
                if abs(ph_rel) > max_rel:
                    max_rel = abs(ph_rel)

                log.info("i00=%9.5f phi=%9.5f, i5_fit=%8.5f i5_tab=%8.5f i5_int=%8.5f diff=(%+.4fA, %+.3f%%)",
                        maincur, theta0, ph_fit, ph_tab, ph_int, ph_dif, ph_rel)
        log.info("max(diff)=(%.4fA,%.3f%%)", max_abs, max_rel)
@@ -128,81 +120,5 @@ def make_phase_table(phtab, polyfit=0, ncur=9, nphi=11, pos=2, threshold=0.2):
    plt.xlabel(r'$\phi$ [deg]')
    plt.ylabel(r'i$_{00}$ [A]')
    #
    plt.suptitle('Phase Table')

    plt.suptitle('Phase Table Plot')
    return xi00, yphi, phase_table, (max_abs, max_rel)



def main():
    "the main"
    # default bin selection
    selection = dict(tbin1=4, tbin2=38, xpix1=5, xpix2=27, ypix1=5, ypix2=27)
    #
    parser = argparse.ArgumentParser(description='phase table plot')
    parser.set_defaults(loglevel=1, pos=2, polyfit=2, figfile=None, threshold=0.2)
    parser.add_argument('file', metavar='filename', help='file to process', nargs='+')
    parser.add_argument('--pos', '-p', dest='pos', type=int,
                        help='set instrument position  (default=%(default)s)')
    parser.add_argument('--polyfit', '-f', dest='polyfit', type=int,
                        help='use polyfit')
    parser.add_argument('--savefig', '-S', dest='figfile', metavar='filename',
                            help='save plot to a file')
    parser.add_argument('--threshold', dest='threshold', metavar='thr', type=float,
                            help='clustering threshold (advanced option)')
    parser.add_argument('--verbose', '-v', dest='loglevel', action='count',
                           help='verbose output')
    parser.add_argument('--quiet', '-q', dest='loglevel', action='store_const',
                           const=0,  help='verbose output')
    args = parser.parse_args()

    log = setup_logger(args.loglevel)
    log.debug('program arguments %s', args)

    phtab = None
    for filename in args.file:
        _ , ext = os.path.splitext(os.path.basename(filename))
        if ext==".echo":
            hfile = convert_to_hdf(filename, '.', data_type='echo')
        else:
            hfile = filename
        log.info('======> input data %s', filename)
        with h5py.File(hfile, 'r') as hdf5file:
            res = get_symmetry_phase(hdf5file, **selection)
            #res = get_symmetry_phase(hdf5file)
            if phtab is None:
                phtab = res
            else:
                phtab = np.vstack((phtab,res))

    plt.figure(figsize=(12,5))


    i00, phi, phase, max_diff = make_phase_table(phtab, args.polyfit, pos=args.pos, threshold=args.threshold)


    if args.pos:
        print("input phasetable")
        print("phasetable pos%s rebuild" % args.pos)
        print("c time: ", time.asctime())
        print("c max interpolation error [%.3gA, %.3f%%]" % (max_diff[0],max_diff[1]))
        print("c command used:")
        print("c ", " ".join(sys.argv))
        print("*\t angles ", end='')
        for p in phi:
            print("%7.4f " % p, end='')
        print("\nc amperes(main) --- phase current(i5)")
        for i,c in enumerate(i00):
            print("*\t%7.3f " % c,end='')
            for j,_ in enumerate(phi):
                print("%7.4f " % phase[j,i], end='')
            print()
        print("eof")

    if args.figfile:
        plt.savefig(args.figfile)
    else:
        plt.show()

if __name__ == "__main__":
    main()
+75 −8
Original line number Diff line number Diff line
@@ -3,11 +3,13 @@
nseplot: command line interface to pysen modules

"""
import sys
import os.path
import argparse
import functools
import logging
import h5py
import time

import numpy as np
import matplotlib as mpl
@@ -16,6 +18,7 @@ import matplotlib.pyplot as plt
from pysen        import version, setup_logger, DEFAULT_LOG_LEVEL
from pysen.config import INST_POSITIONS, INST_MODES, DEFAULT_ACCELERATOR_POWER, coverage
from pysen.inout  import convert_to_hdf
from pysen.echo   import get_symmetry_phase, make_phase_table
from pysen.plot   import ( plot_echo, plot_atari, plot_map,
                           plot_xyz, plot_magnetic_fields,
                           plot_coverage,
@@ -142,6 +145,64 @@ def action_qtau(filenames, **kwargs):
    if savefig:
        plt.savefig(savefig)

def action_phase_table(filenames, **kwargs):
    """"""
    phtab = None
    log = logging.getLogger()
    savefig   = kwargs.pop('savefig')
    savefile  = kwargs.pop('savefile')
    polyfit   = kwargs.pop('polyfit')
    pos       = kwargs.pop('pos')
    threshold = kwargs.pop('threshold') 
    for filename in filenames:
        _ , ext = os.path.splitext(os.path.basename(filename))
        if ext==".echo":
            hfile = convert_to_hdf(filename, '.', data_type='echo')
        else:
            hfile = filename
        log.info('======> input data %s', filename)
        with h5py.File(hfile, 'r') as hdf5file:
            res = get_symmetry_phase(hdf5file, **kwargs)
            if phtab is None:
                phtab = res
            else:
                phtab = np.vstack((phtab,res))

    plt.figure(figsize=(12,5))
    i00, phi, phase, max_diff = make_phase_table(phtab, polyfit, pos=pos, threshold=threshold)
    if savefig:
        plt.savefig(savefig)

    def print_phase_table(stream=None):
        if stream:
            orig_stdout = sys.stdout
            sys.stdout  = stream
        print("input phasetable")
        print("phasetable pos%s rebuild" % pos[-1])
        print("c time: ", time.asctime())
        print("c max interpolation error [%.3gA, %.3f%%]" % (max_diff[0],max_diff[1]))
        print("c command used:")
        print("c %s" % " ".join(sys.argv))
        print("*\t angles ", end='')
        for p in phi:
            print("%7.4f " % p, end='')
        print("\nc amperes(main) --- phase current(i5)")
        for i,c in enumerate(i00):
            print("*\t%7.3f " % c,end='')
            for j,_ in enumerate(phi):
                print("%7.4f " % phase[j,i], end='')
            print()
        print("eof")
        if stream:
            sys.stdout = orig_stdout
        
    if savefile:
        with open(savefile, 'w+') as fd:
            print_phase_table(fd)
    else:
        print_phase_table()
            


# ============================================================================================
# arguments
@@ -158,7 +219,7 @@ def arguments_common():
    pars.add_argument('--save-figure', '-S', dest='savefig', metavar='file',
                        help='save figure to a file (do not show)')
    pars.add_argument('--save-file', '-s', dest='savefile', metavar='file',
                        help='save data to a .csv file')
                        help='save data to a file')
    # mutually exclusive [ -v | -q ]
    verbose = pars.add_mutually_exclusive_group()
    verbose.add_argument('--verbose', '-v', dest='loglevel', action='count',
@@ -389,9 +450,16 @@ def add_ptab_options(subparser, parents=None):
    pars = subparser.add_parser('phase_table', parents=parents,
                       help='phase table',
                       description='phase table')
    pars.set_defaults(axis=-1)
    pars.add_argument('--axis', dest='axis', type=int,
                       help='set axis to plot  (default=%(default)s)')
    pars.set_defaults(pos='p2', polyfit=2, threshold=0.2)
    # defaults 
    pars.set_defaults(tbin1=4, tbin2=38, xpix1=5, xpix2=27, ypix1=5, ypix2=27)
    pars.add_argument('file', metavar='filename', help='file to process', nargs='+')
    pars.add_argument('--pos' , '-p', dest='pos',  choices=INST_POSITIONS,
                        help='set instrument position: (default %(default)s)')
    pars.add_argument('--polyfit', '-f', dest='polyfit', type=int,
                     help='use polyfit')
    pars.add_argument('--threshold', dest='threshold', metavar='thr', type=float,
                     help='clustering threshold (advanced option)')

# ============================================================================================
# the main command line interface
@@ -407,10 +475,9 @@ def main():

    parser      = argparse.ArgumentParser(description=description)
    parser.set_defaults(loglevel=DEFAULT_LOG_LEVEL)
    subparsers  = parser.add_subparsers(dest='plot', required=True,
    subparsers  = parser.add_subparsers(dest='plot', required=False,
                                        help='plot command',
                                        description=None)
    parser.add_argument('--commands', action='version', version='waka')
    parser.add_argument('--version', '-V', action='version',
                        version='%(prog)s pysen={version}'.format(version=version(full=True)))
    # echo plot
@@ -432,7 +499,7 @@ def main():
    # qtau plot
    add_qtau_options(subparsers, parents=[pars_com,])
    # phase table
    add_ptab_options(subparsers, parents=[pars_com,])
    add_ptab_options(subparsers, parents=[pars_com,pars_tof, pars_pix])

    # ===================================
    args = parser.parse_args()
@@ -447,7 +514,7 @@ def main():

    action = dict(  echo=action_echo, atari=action_atari,   maps=action_maps, bfield=action_bfield,
                    xyz=action_xyz, diffrun=action_diffrun, transmission=action_transmission,
                    datreat=action_datreat, qtau=action_qtau).get(args.plot, None)
                    datreat=action_datreat, qtau=action_qtau, phase_table=action_phase_table).get(args.plot, None)
    if action is None:
        raise RuntimeError('missing in action')

+2 −0
Original line number Diff line number Diff line
@@ -449,9 +449,11 @@ def plot_echo(hdfile, iecho=0, **kwargs):
    n_idx   = { 'dn': hdfile['/'].attrs['point_to_down'],
                'up': hdfile['/'].attrs['point_to_up'] ,
                'nphases': hdfile['/'].attrs['no_of_phases'] }
    #TODO: this does not work for J-NSE data
    nt      = hdfile['/detector'].attrs['no_t_channels']
    ny      = hdfile['/detector'].attrs['no_y_channels']
    nx      = hdfile['/detector'].attrs['no_x_channels']

    nph     = n_idx['dn']
    miny, maxy    = np.inf, 0

Loading