Beispiel #1
0
    def __init__(self, parent=None, backend=None, logger=None, title="Plot2D"):

        super(Plot2D, self).__init__(parent=parent, backend=backend)

        self._logger = logger or getLogger("Plot2D")
        self._index = None
        self._title = title
        self.setWindowTitle(self._title)
        self._image = None
        self._mask = None
        self._origin = (0, 0)
        self._scale = (1, 1)
        self._xlabel = 'X'
        self._ylabel = 'Y'
        self.setKeepDataAspectRatio(True)
        self.getDefaultColormap().setName('viridis')
Beispiel #2
0
Utilities to work with 2D grids and interpolation
=================================================
"""
from __future__ import division, print_function

import warnings
import numpy as np

# suppress warnings
try:
    import numexpr
except ImportError:
    pass

from larch.utils.logging import getLogger
_logger = getLogger('gridxyz')

### GLOBAL VARIABLES ###
MODNAME = '_math'


def gridxyz(xcol, ycol, zcol, xystep=None, lib='scipy', method='cubic'):
    """Grid (X, Y, Z) 1D data on a 2D regular mesh

    Parameters
    ----------
    xcol, ycol, zcol : 1D arrays repesenting the map (z is the intensity)
    xystep : the step size of the XY grid
    lib : library used for griddata
          [scipy]
          matplotlib
Beispiel #3
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RIXS GUI APPLICATION
====================
"""
import sys
import argparse
import signal

from larch.utils.logging import getLogger
_logger = getLogger('lach.qtrixs.application')


def createParser():
    """Application parser"""
    parser = argparse.ArgumentParser(description="Larch-RIXS GUI parser")

    return parser


def mainQtApp(options):
    """Part of the main application depending on Qt"""
    try:
        # it should be loaded before h5py
        import hdf5plugin  # noqa
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)
    import h5py

    import silx
Beispiel #4
0
#!/usr/bin/env python
"""
Convert an Athena Project file to HDF5
"""

import os
import h5py
from silx.io.dictdump import dicttoh5
from larch.io.athena_project import AthenaProject
from larch.utils.logging import getLogger

_logger = getLogger("athena_to_hdf5", level="INFO")


def athena_to_hdf5(
    filename,
    fileout=None,
    overwrite=False,
    match=None,
    do_preedge=True,
    do_bkg=True,
    do_fft=True,
    use_hashkey=False,
    _larch=None,
):
    """Read Athena project file (.prj) and write to HDF5 (.h5)

    Arguments:
        filename (string): name of Athena Project file
        fileout (None or string): name of the output file [None -> filename_root.h5]
        overwrite (boolean): force overwrite if fileout exists [False]
Beispiel #5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module provides base classes to implement models for
spectroscopy data.
"""
from __future__ import absolute_import, division
import os

from silx.gui import qt
import silx.io

from .items import (ExperimentItem, GroupItem, FileItem, ScanItem)

from larch.utils.logging import getLogger
_logger = getLogger('larch.qtlib.view')


class HorizontalHeaderView(qt.QHeaderView):
    def __init__(self, parent=None):
        super(HorizontalHeaderView, self).__init__(qt.Qt.Horizontal, parent)

        # Some properties
        self.setStretchLastSection(True)
        # self.setSectionsMovable(True)

        # Context menu
        self.setContextMenuPolicy(qt.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

    def showContextMenu(self, position):
        menu = qt.QMenu('Horizontal Header View Menu', self)
Beispiel #6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RIXS data object
================
"""
import numpy as np
from scipy.interpolate import griddata
from silx.io.dictdump import (dicttoh5, h5todict)

from larch.math.gridxyz import gridxyz
from larch.utils.logging import getLogger
_logger = getLogger('rixsdata')  #: module logger


def _tostr(arr):
    """Numpy array to string"""
    return arr.tostring().decode()


class RixsData(object):
    """RIXS plane object"""

    #: loaded from dictionary/HDF5 -> self.load_from_h5()
    sample_name = 'Unknown'
    counter_all, counter_signal, counter_norm = None, None, None
    _x, _y, _z = None, None, None
    ene_in, ene_out, rixs_map = None, None, None
    ene_et, rixs_et_map = None, None
    ene_grid, ene_unit = None, None
Beispiel #7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module provides classes to implement model items for spectroscopy data.
"""
from __future__ import absolute_import, division
import weakref

from silx.gui import qt
from silx.utils.weakref import WeakList

from larch.utils.logging import getLogger
_logger = getLogger('larch.qtlib.items')

__authors__ = ['Marius Retegan', 'Mauro Rovezzi']


class Signal(object):
    """Base class for signal objects."""

    def __init__(self):
        self._slots = WeakList()

    def connect(self, slot):
        """Register a slot.

        Adding an already registered slot has no effect.

        :param callable slot: The function or method to register.
        """
        if slot not in self._slots:
Beispiel #8
0
"""
from silx.gui import qt
from silx.gui.plot.actions import PlotAction
from silx.gui.plot.tools.roi import RegionOfInterestManager
from silx.gui.plot.tools.roi import RegionOfInterestTableWidget
# from silx.gui.plot.items.roi import RectangleROI
from silx.gui.plot.items import LineMixIn, SymbolMixIn
from larch.utils.logging import getLogger
from larch.qtlib.plotarea import PlotArea, MdiSubWindow
from larch.qtlib.plot1D import Plot1D
from larch.qtlib.plot2D import Plot2D
from .profiletoolbar import (_DEFAULT_OVERLAY_COLORS, RixsProfileToolBar)
from .view import RixsListView
from .model import RixsListModel

_logger = getLogger("larch.qtrixs.plotrixs")


class RixsROIManager(RegionOfInterestManager):
    def __init__(self, plot, color='pink'):
        super(RixsROIManager, self).__init__(plot)
        self.setColor(color)
        self.sigRoiAdded.connect(self.updateAddedRegionOfInterest)

    def updateAddedRegionOfInterest(self, roi):
        """Called for each added region of interest: set the name"""
        if roi.getLabel() == '':
            roi.setLabel('%d' % len(self.getRois()))
        if isinstance(roi, LineMixIn):
            roi.setLineWidth(2)
            roi.setLineStyle('--')
Beispiel #9
0
===========================================

.. note: RIXS stands for Resonant Inelastic X-ray Scattering

.. note: 13-ID-E is GSECARS-CAT

"""
import os
import time
import glob
import numpy as np

from silx.io.dictdump import dicttoh5

from larch.utils.logging import getLogger
_logger = getLogger('io_rixs_gsecars')


def _parse_header(fname):
    """Get parsed header

    Return
    ------
    header : dict
        {
        'columns': list of strings,
        'Analyzer.Energy': float,
        }
    """
    with open(fname) as f:
        lines = f.read().splitlines()
Beispiel #10
0
    def __init__(self, parent=None, with_ipykernel=True, logger=None):
        """Constructor"""

        self._logger = logger or getLogger('RixsAppWindow')

        super(RixsAppWindow, self).__init__(parent=parent)

        if parent is not None:
            #: behave as a widget
            self.setWindowFlags(qt.Qt.Widget)
        else:
            #: main window
            self.setWindowTitle('RIXS_VIEW')

            # TODO: Add icon to the application
            #ico = qt.QIcon(os.path.join(_resourcesPath, "logo",
            #                            "xraysloth_logo_04.svg"))
            #self.setWindowIcon(ico)

        #: IPython kernel status
        self._with_ipykernel = with_ipykernel

        #: Model/view
        self._model = RixsModel()
        self._view = RixsView(parent=self)
        self._view.setModel(self._model)

        # Add additional sections to the header.
        values = [
            HeaderSection(name='Plot',
                          roles={qt.Qt.DisplayRole: 'currentPlotWindowIndex',
                                 qt.Qt.EditRole: 'plotWindowsIndexes'
                                 },
                          delegate=ComboBoxDelegate),
            ]

        for value in values:
            section = len(self._model.header)
            orientation = qt.Qt.Horizontal
            self._model.setHeaderData(section, orientation, value)

        # Add (empty) menu bar -> contents added later
        self._menuBar = qt.QMenuBar()
        self.setMenuBar(self._menuBar)
        self._initAppMenu()

        #: Plot Area
        self._plotArea = RixsPlotArea(self)
        self.setCentralWidget(self._plotArea)

        #: TreeView dock widget
        self._dockDataWidget = qt.QDockWidget(parent=self)
        self._dockDataWidget.setObjectName('Data View')
        self._dockDataWidget.setWidget(self._view)
        self.addDockWidget(qt.Qt.LeftDockWidgetArea, self._dockDataWidget)

        #: Plots update
        self._model.dataChanged.connect(self.updatePlot)
        self._plotArea.changed.connect(self.updateModel)

        #: Console
        if self._with_ipykernel:
            # Initialize internal ipykernel
            self._ipykernel = InternalIPyKernel()
            self._ipykernel.init_kernel(backend='qt')
            self._ipykernel.add_to_namespace('view', self._view)
            self._ipykernel.add_to_namespace('model', self._model)
            self._ipykernel.add_to_namespace('plot', self._plotArea)

            # Add IPython console at menu
            self._initConsoleMenu()
        else:
            self._ipykernel = None