File: jupyter.py

package info (click to toggle)
pyfai 0.20.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,460 kB
  • sloc: python: 49,743; lisp: 7,059; sh: 225; ansic: 165; makefile: 119
file content (163 lines) | stat: -rw-r--r-- 5,960 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    Project: Azimuthal integration
#             https://github.com/silx-kit/pyFAI
#
#    Copyright (C) 2017-2018 European Synchrotron Radiation Facility, Grenoble, France
#
#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""Jupyter helper functions
"""

__author__ = "Jerome Kieffer"
__contact__ = "Jerome.Kieffer@ESRF.eu"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__date__ = "16/10/2020"
__status__ = "Production"
__docformat__ = 'restructuredtext'

import numpy
from pylab import subplots, legend
from matplotlib import lines


def display(img=None, cp=None, ai=None, label=None, sg=None, ax=None):
    """Display an image with the control points and the calibrated rings
    in Jupyter notebooks

    :param img: 2D numpy array with an image
    :param cp: ControlPoint instance
    :param ai: azimuthal integrator for iso-2th curves
    :param label: name of the curve
    :param sg: single geometry object regrouping img, cp and ai
    :param ax: subplot object to display in, if None, a new one is created.
    :return: Matplotlib subplot
    """
    if ax is None:
        _fig, ax = subplots()
    if sg is not None:
        if img is None:
            img = sg.image
        if cp is None:
            cp = sg.control_points
        if ai is None:
            ai = sg.geometry_refinement
        if label is None:
            label = sg.label

    ax.imshow(numpy.arcsinh(img).astype(numpy.float32), origin="lower", cmap="inferno")
    ax.set_title(label)
    if cp is not None:
        for lbl in cp.get_labels():
            pt = numpy.array(cp.get(lbl=lbl).points)
            if len(pt) > 0:
                ax.scatter(pt[:, 1], pt[:, 0], label=lbl)
        if ai is not None and cp.calibrant is not None:
            tth = cp.calibrant.get_2th()
            ttha = ai.twoThetaArray()
            ax.contour(ttha, levels=tth, cmap="autumn", linewidths=2, linestyles="dashed")
        legend()
    return ax


def plot1d(result, calibrant=None, label=None, ax=None):
    """Display the powder diffraction pattern in the jupyter notebook

    :param result: instance of Integrate1dResult
    :param calibrant: Calibrant instance to overlay diffraction lines
    :param label: (str) name of the curve
    :param ax: subplot object to display in, if None, a new one is created.
    :return: Matplotlib subplot
    """
    if ax is None:
        _fig, ax = subplots()

    unit = result.unit
    if result.sigma is not None:
        ax.errorbar(result.radial, result.intensity, result.sigma, label=label)
    else:
        ax.plot(result.radial, result.intensity, label=label)

    if label:
        ax.legend()
    if calibrant:
        x_values = calibrant.get_peaks(unit)
        if x_values is not None:
            for x in x_values:
                line = lines.Line2D([x, x], ax.axis()[2:4],
                                    color='red', linestyle='--')
                ax.add_line(line)

    ax.set_title("1D integration")
    ax.set_xlabel(unit.label)
    ax.set_ylabel("Intensity")

    return ax


def plot2d(result, calibrant=None, label=None, ax=None):
    """Display the caked image in the jupyter notebook

    :param result: instance of Integrate2dResult
    :param calibrant: Calibrant instance to overlay diffraction lines
    :param label: (str) name of the curve

    :param ax: subplot object to display in, if None, a new one is created.
    :return: Matplotlib subplot
    """
    img = result.intensity
    pos_rad = result.radial
    pos_azim = result.azimuthal
    if ax is None:
        _fig, ax = subplots()
    ax.imshow(numpy.arcsinh(img),
              origin="lower",
              extent=[pos_rad.min(), pos_rad.max(), pos_azim.min(), pos_azim.max()],
              aspect="auto",
              cmap="inferno")
    if label:
        ax.set_title("2D regrouping")
    else:
        ax.set_title(label)
    ax.set_xlabel(result.unit.label)
    ax.set_ylabel(r"Azimuthal angle $\chi$ ($^{o}$)")
    if calibrant:
        from pyFAI import units
        x_values = None
        twotheta = numpy.array([i for i in calibrant.get_2th() if i])  # in radian
        unit = result.unit
        if unit == units.TTH_DEG:
            x_values = numpy.rad2deg(twotheta)
        elif unit == units.TTH_RAD:
            x_values = twotheta
        elif unit == units.Q_A:
            x_values = (4.e-10 * numpy.pi / calibrant.wavelength) * numpy.sin(.5 * twotheta)
        elif unit == units.Q_NM:
            x_values = (4.e-9 * numpy.pi / calibrant.wavelength) * numpy.sin(.5 * twotheta)
        if x_values is not None:
            for x in x_values:
                line = lines.Line2D([x, x], [pos_azim.min(), pos_azim.max()],
                                    color='red', linestyle='--')
                ax.add_line(line)
    return ax