Files
tina/tina.py
2024-07-03 16:17:55 +02:00

270 lines
8.9 KiB
Python

"""Tina.py module for measuring the number of turns
"""
import inspect
import os
import platform
import sys
import time
from qtpy.QtCore import __version__ as QT_VERSION_STR
from qtpy.QtCore import PYQT_VERSION_STR, Signal, Slot
from qtpy.QtWidgets import QApplication, QMessageBox
from apps4ops.bdbase.base import BaseWindow
from apps4ops.bdbase import h5_storage, utils
#from apps4ops.bdbase.utils import _line
from apps4ops.bdbase.enumkind import Facility, MsgSeverity, UserMode
from apps4ops.bdbase.helpbrowser import HelpBrowser
from apps4ops.hipa.sendeloghipa import QSendToELOG
from apps4ops.hipa.enumkind import ElogHIPA
from src.gui import AppGui
from pyrcc5 import tina_resources
_pymodule = os.path.basename(__file__)
_appname, _appext = _pymodule.split(".")
_abspath = os.path.dirname(os.path.abspath(__file__))
_appversion = "0.0.1"
_title = "No of Turns Measurement"
_appname = "Tina"
class StartMain(BaseWindow):
trigger_log_message = Signal(str, str, int, str, dict)
def __init__(self, parent=None):
super().__init__(
parent=parent, pymodule=_pymodule, appversion=_appversion,
title=_title, user_mode=UserMode.OPERATION, facility=Facility.HIPA,
has_optics=False, has_procedure=True)
self.appname = _appname
self.source_file = _abspath #required for HDF
self.elog_enum = ElogHIPA()
self.gui = AppGui(self)
def prepare_elog_message(self):
"""Define elog parameters and define message
"""
self.projekt_idx = self.elog_enum.projekt.NONE
self.system_idx = self.elog_enum.system.BEAMDYNAMICS
self.eintrag_idx = self.elog_enum.eintrag.INFO
self.ort_idx = self.elog_enum.ort.RING_CYCLOTRON #else INJECTOR2
self.status_idx = self.elog_enum.status.NONE
self.effekt_idx = self.elog_enum.effekt.NO
self.attach_files = []
simulation = self.input_parameters["simulation"]
if self.all_data:
if self.all_data["Input data"] is not None:
try:
simulation = self.all_data["Input data"]["simulation"]
except KeyError:
simulation = self.input_parameters["simulation"]
pass
self.logbook = "Sandkasten" if simulation else "HIPA"
self.title = _title
self.no_turns = 180
self.message = "The number of turns measured in the ring = {0}".format(
self.no_turns)
@Slot()
def analysis_thread_finished(self):
BaseWindow.analysis_thread_finished(self)
self.gui_frame.central_tab_widget.setCurrentIndex(1)
@Slot()
def save_to_hdf(self, from_dialog=False):
if not self.verify_save_to_hdf():
return False
if self.all_data is not None:
self.save_hdf_thread = self.HDFSave(self, from_dialog)
# self.save_hdf_thread.started.connect(self.save_to_hdf_started)
# self.save_hdf_thread.finished.connect(self.save_to_hdf_finished)
self.save_hdf_thread.start()
self.hdf_save_completed = True
time.sleep(0.05) # Wait a tick
return True
def add_to_hdf(self, dataH5, proc=True, raw=False):
"""User supplied hdf data
"""
if self.all_data is not None:
self.all_data['Raw data']['Input_data'] = self.all_data[
'Input data']
self.all_data['Raw data']['Ambient_data'] = self.all_data[
'Ambient data']
self.all_data['Raw data']['Processed_data'] = self.all_data[
'Processed data']
self.all_data['Raw data']['Raw_data'] = self.all_data[
'Application Raw data']
h5_storage.saveH5Recursive(
self.hdf_filename, self.all_data['Raw data'], dataH5)
@Slot()
def send_to_elog(self):
"""Override abstract method
"""
@Slot()
def save_fig_thread_finished():
"""Can take a few seconds to send to elog,
hence choose do this in a thread.
"""
time.sleep(0.2)
if self.all_data:
QSendToELOG(self, logbook=self.logbook,
projektIdx=self.projekt_idx,
eintragIdx=self.eintrag_idx,
systemIdx=self.system_idx,
statusIdx=self.status_idx,
ortIdx=self.ort_idx,
effektIdx=self.effekt_idx,
title=self.title,
message=self.message,
attachFile=self.attach_files)
time.sleep(0.5)
self.prepare_elog_message()
print(self.message, flush=True)
if not self.all_data:
QSendToELOG(self, logbook=self.logbook,
projektIdx=self.projekt_idx,
eintragIdx=self.eintrag_idx,
systemIdx=self.system_idx,
statusIdx=self.status_idx,
ortIdx=self.ort_idx,
effektIdx=self.effekt_idx,
title=self.title,
message=self.message,
attachFile=self.attach_files)
return
folder_name = self.elog_dest
if not os.path.exists(folder_name):
os.makedirs(folder_name)
time_in_seconds = self.all_data["Ambient data"]["Time in seconds"]
try:
reanalysis_time = self.all_data["Processed data"][
"Reanalysis time in seconds"]
except KeyError:
reanalysis_time = None
self.folder_name = folder_name
save_fig_thread = self.SaveFigureThread(
self, self.folder_name, time_in_seconds, reanalysis_time)
save_fig_thread.finished.connect(save_fig_thread_finished)
save_fig_thread.start()
time.sleep(0.05)
def save_to_epics(self):
""" Write the number of turns calculated to an EPICS PV
"""
print(self.all_data)
if not BaseWindow.verify_save_to_epics(self):
return False
dict_bunch = {}
nturns = 0
debug = True
dry_run = False
pv = self.settings.data["PVnturns"]["Cyclotron"]
dict_bunch[pv] = nturns
if not dry_run:
status, status_list = self.send_to_epics(dict_bunch)
if status == self.cyca.ICAFE_NORMAL:
message = "Saved data to EPICS - No of turns = ".format(nturns)
sev = MsgSeverity.INFO
else:
message = "Value (nturns) not saved to epics"
sev = MsgSeverity.ERROR
self.show_log_message(sev.name, _pymodule, utils.line_no(), message)
return True
@Slot()
def closeEvent(self, event):
""" Close application only if conditions allow
"""
if not self.verify_close_event():
event.ignore()
return
BaseWindow.closeEvent(self, event)
@Slot()
def show_about(self):
""" Behind the scences information
"""
QApplication.processEvents()
QMessageBox.about(
self, "About",
"""<b>{0}</b> v {1}
<p>Copyright &copy; Paul Scherrer Institut (PSI).
All rights reserved.</p>
<p>Authors: P.-A. Duperrex, W. Koprek, J. Chrin </p>
<p>A python implementation of the LabVIEW measurement developed by P.-A. Duperrex <br>
Ref: P.-A. Duperrex and A. Facchetti <br>
Number of Turn Measurements on the HIPA Cyclotrons at PSI <br>
doi:10.18429/JACoW-IPAC2018-WEPAL067 </p>
<p>Responsible: W. Koprek, WBBA/315, Tel. x3765,
waldemar.koprek@psi.ch </p>
<p>A main-window style application for the measurement of
the number of turns in the HIPA cyclotron and injector </p>
<p>Python {2} - Qt {3} - PyQt {4} <br>
cafe {5} - epics {6} on {7}""".format(
_pymodule, _appversion, platform.python_version(),
QT_VERSION_STR, PYQT_VERSION_STR,
self.cafe.CAFE_version(), self.cafe.EPICS_version(),
platform.system()))
QApplication.processEvents()
@Slot()
def show_help(self):
""" Invoke help pages from tina_resources
"""
index_html = "index.html"
help_base = ":"
help_page = HelpBrowser(help_base, index_html, self)
help_page.show()
#########################################################################
if __name__ == "__main__":
app = QApplication(sys.argv)
splash = BaseWindow.initialize_application(
app, appname=_appname, delay=20, facility=Facility.HIPA)
myapp = StartMain()
myapp.show()
if splash is not None:
splash.finish(myapp)
app.exec_()