app.py 6.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Template Python module generated based on 'app_template', 'phantasy-ui'
is required to make it executable as a PyQt5 app.

Created by: makeBasePyQtApp.

An example to create an app template:

>>> makeBasePyQtApp --app my_great_app --template AppWindow

Show the available templates:

>>> makeBasePyQtApp -l
"""

17
18
import sys

19
from phantasy_apps.allison_scanner.data import draw_beam_ellipse_with_params
20
from PyQt5.QtCore import pyqtSlot
21
from PyQt5.QtWidgets import QMainWindow
22
from PyQt5.QtWidgets import QMessageBox
23
24

from phantasy import MachinePortal
25
26
27
28
from phantasy_ui import BaseAppForm

from .ui.ui_app import Ui_MainWindow

29
30
31
MACH, SEGM = "ARIS", "F1"
ARIS_MP = MachinePortal(MACH, SEGM)
ARIS_LAT = ARIS_MP.work_lattice_conf
32
33


34
class MyAppWindow(BaseAppForm, Ui_MainWindow):
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    def __init__(self, version, **kws):
        super(self.__class__, self).__init__()

        # app version, title
        self.setAppVersion(version)
        self.setAppTitle("My App")

        # app info in about dialog
        # self.app_about_info = "About info of My App."

        # UI
        self.setupUi(self)
        self.postInitUi()

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
        # post init
        self._post_init()

    def _post_init(self):
        """Initialize UI, user customized code put here.
        """
        # Fill comboBox quad1_name_cbb with all quad names.
        quad_name_list = [i.name for i in ARIS_MP.get_elements(type='QUAD')]
        self.quad1_name_cbb.addItems(quad_name_list)
        # connect currentTextChanged signal to slot: on_quad1_name_changed()
        self.quad1_name_cbb.currentTextChanged.connect(
            self.on_quad1_name_changed)
        # connect valueChanged signal of quad1_grad_dsbox to on_quad1_grad_changed()
        self.quad1_grad_dsbox.valueChanged.connect(self.on_quad1_grad_changed)
        # initialize quad1_name_cbb
        self.quad1_name_cbb.currentTextChanged.emit(quad_name_list[0])

    @pyqtSlot('QString')
    def on_quad1_name_changed(self, name: str) -> None:
        """When the current selected quad name is changed, do:
        show the current setting of the selected quad on quad1_grad_dsbox.
        when set value to quad1_grad_dsbox, disconnect valueChanged and
        reconnect, to avoid unnecessary trigging.
        """
        self.quad_selected = ARIS_MP.get_elements(name=name)[0]
        self.quad1_grad_dsbox.valueChanged.disconnect()
75
76
77
78
79
80
81
82
83
        try:
            self.quad1_grad_dsbox.setValue(
                self.quad_selected.current_setting('B2'))
        except TypeError:
            # current_settings('B2') is None --> most likely VA is not running
            QMessageBox.critical(self, "ARIS Beam Ellipse",
                    "Cannot reach process variables, please either start virtual accelerator or ensure Channel Access is permittable.", QMessageBox.Ok, QMessageBox.Ok)
            sys.exit(1)

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        self.quad1_grad_dsbox.valueChanged.connect(self.on_quad1_grad_changed)

    @pyqtSlot(float)
    def on_quad1_grad_changed(self, grad: float) -> None:
        """When the setting of the selected quad is changed, do:
        1. print the setting of selected quad
        2. update drawing with online simulated results
        """
        q = self.quad_selected.name
        print(f"'{q}' setting is: {grad} T/m")
        # draw ellipse
        self.update_drawing()

    def update_drawing(self):
        """This is the routine to update the figure with the updated drawing.
        Here I'm drawing the beam envelop along the entire beamline, try to
        replace with your routine for beam ellipse drawing.
        """
        try:
Doerr, Kevin's avatar
Doerr, Kevin committed
103
            self.draw_ellipse()
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
        except NotImplementedError:
            self.draw_envelope()

    def draw_envelope(self):
        """Draw beam envelop onto the figure area.
        """
        # online simulation
        ARIS_LAT.sync_settings()
        _, fm = ARIS_LAT.run()
        r, _ = fm.run(monitor='all')
        results_dict = fm.collect_data(r, 'pos', 'xrms', 'yrms')
        pos = results_dict['pos']
        xrms = results_dict['xrms']
        yrms = results_dict['yrms']
        # update drawing
        # Note: matplotlibbaseWidget is used here for generic drawing,
        # for curve visualization, matplotlibCurveWidget is a better choice.
        self.matplotlibbaseWidget.clear_figure()
        self.matplotlibbaseWidget.axes.plot(
            pos,
            xrms,
            'b-',
            pos,
            yrms,
            'r-',
        )
        self.matplotlibbaseWidget.update_figure()

132
    def draw_ellipse(self):
133
        #raise NotImplementedError
134

135
        """Draw x and y beam ellipse onto the figure area.
136
137
138
139
        """
        ARIS_LAT.sync_settings()
        _, fm = ARIS_LAT.run()
        r, s = fm.run(monitor='all')
140
141
        keys_x = [i.format(u='x') for i in ('{u}_cen', '{u}p_cen', '{u}_rms', '{u}p_rms', 'emit_{u}', 'emitn_{u}','alpha_{u}', 'beta_{u}', 'gamma_{u}', 'total_intensity')]
        vals_x = (s.xcen, s.xpcen, s.xrms, s.xprms, s.xemittance, s.xnemittance,
142
        s.xtwiss_alpha, s.xtwiss_beta, (s.xtwiss_alpha**2+1)/s.xtwiss_beta, 1)
143
        params_x = dict(zip(keys_x, vals_x))
144
        self.matplotlibbaseWidget.clear_figure()
145
        draw_beam_ellipse_with_params(params_x, color='b', factor=4, ax=self.matplotlibbaseWidget.axes, xoy='x', fill='g', anote=False)
146
        self.matplotlibbaseWidget.update_figure()
147

148
149
        keys_y = [i.format(u='y') for i in ('{u}_cen', '{u}p_cen', '{u}_rms', '{u}p_rms', 'emit_{u}', 'emitn_{u}','alpha_{u}', 'beta_{u}', 'gamma_{u}', 'total_intensity')]
        vals_y = (s.ycen, s.ypcen, s.yrms, s.yprms, s.yemittance, s.ynemittance,
150
        s.ytwiss_alpha, s.ytwiss_beta, (s.ytwiss_alpha**2+1)/s.ytwiss_beta, 1)
151
        params_y = dict(zip(keys_y, vals_y))
152
        self.matplotlibbaseWidget_1.clear_figure()
153
        draw_beam_ellipse_with_params(params_y, color='b', factor=4, ax=self.matplotlibbaseWidget_1.axes, xoy='y', fill='g', anote=True)
154
155
        self.matplotlibbaseWidget_1.update_figure()

156
157
158
159
160
161
162
163
164
165
if __name__ == "__main__":
    from PyQt5.QtWidgets import QApplication
    import sys

    version = 0.1
    app = QApplication(sys.argv)
    w = MyAppWindow(version)
    w.show()
    w.setWindowTitle("This is an app from template")
    sys.exit(app.exec_())