Commit 15d38694 authored by Zolnierczuk, Piotr's avatar Zolnierczuk, Piotr
Browse files

added new base class in scans

cleanups and factored out some repeatings definitions
(motors, b_sensors) into nexus
parent 90712129
Loading
Loading
Loading
Loading
+26 −30
Original line number Diff line number Diff line
@@ -8,35 +8,33 @@ import matplotlib.pyplot as plt
from pysen.inout.scans import XYZScan
from pysen.plot.xyzplotlib import xyz_decomposition, plot_xyz_nexus

class XYZ_Plot(XYZScan):
    "XYZ PLOT"
    def xyz_analysis(self):
        """ xyz analysis"""
        rates = {}
def plot_xyz(filename, **kwargs):
    scan = XYZScan()
    scan.read_nexus(filename, **kwargs)

    plot_xyz_nexus(scan.data, scan.info, **kwargs)

    log = logging.getLogger()

        for key, data in self.xyz.items():
    rates = {}
    base  = scan.info['base']
    for key, data in scan.data.items():
        rates[key]=0.0
        if data['pcharge']>0:
            rates[key] = data['selection_counts']/data['pcharge']*1e12
                self.log.info("%s: %-6.6s = %10.2f counts/C", self.info['base'], key.upper(), rates[key])
            log.info("%s: %-6.6s = %10.2f counts/C", base, key.upper(), rates[key])
        #
    res = xyz_decomposition(rates)
    #
    stot = res['sum_ave']
        self.log.info("%s:", self.info['base'])
    log.info("%s:", base)
    for key in ('n_coh', 'i_inc', 'm_mag'):
            self.log.info("%s: %-6.6s = %10.2f counts/C  (%.2f%%)",
                self.info['base'], key.upper(), res[key], res[key]/stot*100)
        log.info("%s: %-6.6s = %10.2f counts/C  (%.2f%%)",
            base, key.upper(), res[key], res[key]/stot*100)
    for key in ('m_up/2', 'm_dn/2',):
            self.log.info("%s: %-6.6s = %10.2f counts/C",
                self.info['base'], key.upper(), res[key])
        self.log.info("%s: TOT    = %10.2f counts/C", self.info['base'], stot)
        #

    def plot(self, **kwargs):
        "plot xyz"
        plot_xyz_nexus(self.xyz, self.info, **kwargs)
        self.xyz_analysis()
        log.info("%s: %-6.6s = %10.2f counts/C",
            base, key.upper(), res[key])
    log.info("%s: TOT    = %10.2f counts/C", base, stot)


def main():
@@ -75,9 +73,7 @@ def main():
    kwargs = vars(args)
    filenames = kwargs.pop('filename')
    for file_name in filenames:
        scan = XYZ_Plot()
        scan.read_nexus(file_name, **kwargs)
        scan.plot(**kwargs) #vmax=100)
        plot_xyz(file_name, **kwargs)

    if args.show:
        plt.show()
+2 −0
Original line number Diff line number Diff line
@@ -13,6 +13,8 @@ import pandas as pd
from ..iostrings import decode
from .utils import get_open_file

#pylint: disable=consider-using-f-string,invalid-name

try:
    from tqdm import tqdm
except ImportError:
+2 −0
Original line number Diff line number Diff line
@@ -10,6 +10,8 @@ from .. import config, get_theta, get_q
from ..constants import ANGSTROM, NANOSECOND, OMEGA_N, KAPPA_N
from ..echo      import fit as efit

#pylint: disable=consider-using-f-string,invalid-name,fixme


# FIXME: move these constants to a config file
# constants to make "fake" data somewhat realistic
+15 −1
Original line number Diff line number Diff line
@@ -36,6 +36,21 @@ Y0_PIX = 518
XWID2     =   813//2 # 410 # half-width
YWID2     =   821//2 # 410

MOTORS    = ('mophi', 'mopsi', 'mo_z', 'moana', 'mo_l', 'moatt')

B_SENSORS = {'b_sample': 'sample'  ,
             'b_encl1' : 'fpi21'   ,
             'b_encl2' : 'fpi22'   ,
             'b_ext1'  : 'external',
             'b_ext2'  : 'external',
             'b_ext3'  : 'external',
             'b_ext4'  : 'external',
             'b_ext5'  : 'external'}

#



def pixel_decompose(pixel):
    "helper function to decompose pixel into x and y coordinates"
    ypix   = (pixel >> TDC_SHIFT) & TDC_MAXCH
@@ -212,7 +227,6 @@ def process_nexus(filename, **kwargs):
                res = process_scan_point(events, pcharge, ltot=info['mo_l'],
                        begin=scan_index[i]['time'], end=scan_index[k]['time'],
                        values=values)

                # FIXME: get tau ....
                for key in ('tau', 'j1', 'j2'):
                    it =  info[key]['time']<=scan_index[i]['time'] # tau set before scan
+54 −56
Original line number Diff line number Diff line
@@ -24,15 +24,46 @@ def get_tau_index(scan_idx):
    idx   = scan_idx['value']
    return (idx // TAU_IDX, idx %  TAU_IDX)


class EchoScan:
    """Read SNS-NSE EPICS/NeXus echo scan file"""
class BaseScan:
    """Base scan to avoid code repetition"""
    def __init__(self):
        "the constructor"
        self.log  = logging.getLogger()
        self.data = {}
        self.info = None

    def phasepoint_callback(self, _data, **_kwargs):
        "phase point callback"
        return True

    def read_nexus(self, nxsfile, **kwargs):
        """read nexus file"""
        self.log.info("reading nexus file %s", nxsfile)
        #
        kwargs.setdefault('npix', NPIX)
        kwargs.setdefault('ntof', NTOF)
        scan_type = kwargs.setdefault('scan_type', None)
        #
        self.info = process_nexus(nxsfile, scanpoint_cb=self.phasepoint_callback,
                                  scan_type=scan_type)
        if self.info is None:
            return False
        self.info.update(**kwargs)
        #
        lmin = self.info.get('lmin', 5.0)
        lmax = self.info.get('lmax', 8.0)
        self.info['xbin'] = np.linspace(X0_PIX-XWID2, X0_PIX+XWID2, self.info['npix']+1)
        self.info['ybin'] = np.linspace(Y0_PIX-YWID2, Y0_PIX+YWID2, self.info['npix']+1)
        self.info['tbin'] = np.linspace(lmin, lmax, self.info['ntof']+1)
        #
        # debug
        self.log.debug("nexus info: %s", print_nexus_info(self.info))
        return True


class EchoScan(BaseScan):
    """Read SNS-NSE EPICS/NeXus echo scan file"""

    def phasepoint_callback(self, data, **kwargs):
        "phase point callback"
        filename = kwargs.get('filename', '<unset>')
@@ -79,7 +110,8 @@ class EchoScan:
                has_up = True
                p.remove(UP_IDX)
            if not (has_dn and has_up):
                self.log.warning('%s: up and/or down phase missing for tau=%d', self.info['base'], t)
                self.log.warning('%s: up and/or down phase missing for tau=%d',
                                self.info['base'], t)
            if not nphases:
                nphases=len(p)
            if nphases!=len(p):
@@ -90,74 +122,40 @@ class EchoScan:

    def read_nexus(self, nxsfile, **kwargs):
        """read nexus file"""
        self.log.info("reading nexus file %s", nxsfile)
        #
        kwargs.setdefault('npix', NPIX)
        kwargs.setdefault('ntof', NTOF)
        kwargs.setdefault('phase_step', DEFAULT_PHASE_STEP)
        #
        self.info = process_nexus(nxsfile, scanpoint_cb=self.phasepoint_callback, scan_type='echo')
        if self.info is None:
        if not super().read_nexus(nxsfile, scan_type='echo', **kwargs):
            return False
        self.info.update(**kwargs)

        ntaus, nphases = self.get_taus_and_phases()
        self.log.info('%s: found %s taus, with %d phases in each tau', self.info['base'], ntaus, nphases)

        lmin = self.info.get('lmin', 5.0)
        lmax = self.info.get('lmax', 8.0)
        self.info['xbin'] = np.linspace(X0_PIX-XWID2, X0_PIX+XWID2, self.info['npix']+1)
        self.info['ybin'] = np.linspace(Y0_PIX-YWID2, Y0_PIX+YWID2, self.info['npix']+1)
        self.info['tbin'] = np.linspace(lmin, lmax, self.info['ntof']+1)
        self.info['nphases'] = nphases
        # debug
        self.log.debug("nexus info: %s", print_nexus_info(self.info))
        self.log.info('%s: found %s taus, with %d phases in each tau',
            self.info['base'], ntaus, nphases)
        return True

class XYZScan:
    """Read SNS-NSE EPICS/NeXus xyz scan file"""
    def __init__(self):
        "the constructor"
        self.log  = logging.getLogger()
        self.xyz  =  {}
        self.info = None
class XYZScan(BaseScan):
    """Read SNS-NSE EPICS/NeXus xyz scan file

    def phasepoint_callback(self, data, **kwargs):
        "phase point callback"
        filename = kwargs.get('filename', '<unset>')
        begin = kwargs.get('begin')
        xyz   = { 10: 'z_up',
    """
    XYZ_MAP = { 10: 'z_up',
                11: 'z_dn',
                20: 'y_up',
                21: 'y_dn',
                30: 'x_up',
                  31: 'x_dn',}.get(begin['value'])
                31: 'x_dn',}

    def phasepoint_callback(self, data, **kwargs):
        "phase point callback"
        filename = kwargs.get('filename', '<unset>')
        begin = kwargs.get('begin')
        xyz   = self.XYZ_MAP.get(begin['value'])
        rate=0.0
        if data['pcharge']>0:
            rate = data['neutron'].shape[1]/data['pcharge']*1e12
        self.xyz.setdefault(xyz, data)
        self.log.debug("%s: processing xyz=%s, pc=%.5f, rate=%10.1f", filename, xyz, data['pcharge']*1e-12, rate)
        self.data.setdefault(xyz, data)
        self.log.debug("%s: processing xyz=%s, pc=%.5f, rate=%10.1f",
            filename, xyz, data['pcharge']*1e-12, rate)
        return True

    def read_nexus(self, nxsfile, **kwargs):
        """read nexus file"""
        self.log.info("reading nexus file %s", nxsfile)
        #
        kwargs.setdefault('npix', NPIX)
        kwargs.setdefault('ntof', NTOF)
        #
        self.info = process_nexus(nxsfile, scanpoint_cb=self.phasepoint_callback, scan_type='xyz')
        if self.info is None:
            return False
        self.info.update(**kwargs)
        #

        lmin = self.info.get('lmin', 5.0)
        lmax = self.info.get('lmax', 8.0)
        self.info['xbin'] = np.linspace(X0_PIX-XWID2, X0_PIX+XWID2, self.info['npix']+1)
        self.info['ybin'] = np.linspace(Y0_PIX-YWID2, Y0_PIX+YWID2, self.info['npix']+1)
        self.info['tbin'] = np.linspace(lmin, lmax, self.info['ntof']+1)
        self.log.debug("nexus info: %s", print_nexus_info(self.info))
        return True
        return super().read_nexus(nxsfile, scan_type='xyz', **kwargs)
# EOF
Loading