diff --git a/ModuleFixTarget.py b/ModuleFixTarget.py index adc6e88..40cba6a 100644 --- a/ModuleFixTarget.py +++ b/ModuleFixTarget.py @@ -91,8 +91,8 @@ class MarkerDelegate(QItemDelegate): editor.setText("{}".format(index.model().data(index))) def setModelData(self, editor, model, index): - print("model {}".format(model)) - print( + _log.debug("model {}".format(model)) + _log.debug( "delegate setData: {}x{} => {}".format( index.row(), index.column(), editor.text() ) @@ -101,7 +101,7 @@ class MarkerDelegate(QItemDelegate): model.setData(index, float(editor.text()), Qt.UserRole) def emitCommitData(self): - print("imagedelegate emitting") + _log.debug("imagedelegate emitting") self.commitData.emit(self.sender()) @@ -402,7 +402,7 @@ class WndFixTarget(QWidget): def dump_data(self): - print(self._data) + _log.info(f'{self._data}') #for ref, x, y, cx, cy, ox, oy in self.get_data(): # print(f"fiducial:{ref} [{x}, {y}, {cx}, {cy}]") diff --git a/camera.py b/camera.py index 099baef..3c56e38 100755 --- a/camera.py +++ b/camera.py @@ -103,7 +103,7 @@ class epics_cam(object): chid: integer channel ID cb_info: (index, self) tuple containing callback ID and the PV object""" - print('camera.new_frame_pv_cb') + _log.debug('camera.new_frame_pv_cb') def get_image(self): _log.warning('this can be very slow. Use callbacks if possible.') diff --git a/ctadaq.py b/ctadaq.py index a1fd656..1ae29ee 100644 --- a/ctadaq.py +++ b/ctadaq.py @@ -10,6 +10,7 @@ slic interface class for CTAAcquisition based on xxx code snipplets ''' +import logging import numpy as np from tqdm import tqdm from time import time @@ -22,6 +23,8 @@ from slic.core.acquisition import SFAcquisition from slic.core.acquisition.sfacquisition import BSChannels, transpose_dicts, print_response from slic.core.task import DAQTask +_log=logging.getLogger(__name__) + class CTAAcquisition(SFAcquisition): @@ -48,29 +51,29 @@ class CTAAcquisition(SFAcquisition): if not is_scan_step: run_number = self.client.next_run() - print(f"Advanced run number to {run_number}.") + _log.info(f"Advanced run number to {run_number}.") else: run_number = self.client.run_number - print(f"Continuing run number {run_number}.") + _log.info(f"Continuing run number {run_number}.") # if not filename or filename == "/dev/null": # print("Skipping retrieval since no filename was given.") # return if detectors is None: - print("No detectors specified, using default detector list.") + _log.debug("No detectors specified, using default detector list.") detectors = self.default_detectors if pvs is None: - print("No PVs specified, using default PV list.") + _log.debug("No PVs specified, using default PV list.") pvs = self.default_pvs if channels is None: - print("No channels specified, using default channel list.") + _log.debug("No channels specified, using default channel list.") channels = self.default_channels n_block_size = n_block_size or self.n_block_size #print("block size:", n_block_size) @@ -98,7 +101,7 @@ class CTAAcquisition(SFAcquisition): abort_evt.wait(10) ###? (returns early on abort) time_start = time() start_pid = self.cta.get_start_pid() - print("CTA start pid:", start_pid) + _log.info(f"CTA start pid: {start_pid}") stop_pid = start_pid + n_pulses #print("CTA stop pid:", stop_pid) pids = np.arange(start_pid, stop_pid) @@ -114,7 +117,7 @@ class CTAAcquisition(SFAcquisition): # abort pulse id, until a block is empty stop_pid = self._abort_pid pb = pb[pb <= stop_pid] if stop_pid is not None else pb[:0] - print(f"CTA acquisition aborted at pulse id {stop_pid}: retrieve {len(pb)} pulses of this block") + _log.warning(f"CTA acquisition aborted at pulse id {stop_pid}: retrieve {len(pb)} pulses of this block") if len(pb) == 0: break sleep(0.2) @@ -132,12 +135,12 @@ class CTAAcquisition(SFAcquisition): while self.cta.is_running() and not abort_evt.is_set(): abort_evt.wait(self.wait_time) delta_time = time() - time_start - print(f"Waiting since {delta_time} seconds for CTA sequence to finish") + _log.info(f"Waiting since {delta_time:.0f} seconds for CTA sequence to finish") return filenames except Exception as e: - print("error we should get: ", e) + _log.error(f"CTA acquisition: {e}") def stopper(): client.stop() @@ -149,7 +152,7 @@ class CTAAcquisition(SFAcquisition): try: task.wait() except KeyboardInterrupt: - print("Stopped current DAQ task:") + _log.warning("Stopped current DAQ task") return task diff --git a/epics_widgets/MotorTweak.py b/epics_widgets/MotorTweak.py index 3df1e1c..41a040a 100644 --- a/epics_widgets/MotorTweak.py +++ b/epics_widgets/MotorTweak.py @@ -409,10 +409,7 @@ class MotorTweak(QWidget, Ui_MotorTweak): try: self.label.setText(target[self._label_style].format(rbv=m.readback)) except ValueError as e: - _log.error(e) - print(self._label_style) - print(m.readback) - print(m) + _log.error(f'{e}: label_style={self._label_style} readback={m.readback} motor={m}') def paintEvent(self, e): qp = QPainter() diff --git a/geometry.py b/geometry.py index a23d5b0..07670a0 100755 --- a/geometry.py +++ b/geometry.py @@ -51,7 +51,7 @@ class geometry: import matplotlib.pyplot as plt if sys.gettrace(): # in debuggingmode plt.interactive(True) #uncomment to debug - print('DEBUG MODE') + _log.debug('DEBUG MODE') fig, ax=plt.subplots() ax.invert_yaxis() ax.grid() @@ -464,9 +464,9 @@ class autofocus: if abs(p-self._pDst)<0.01 or idx>mtr.shape[0]: _log.debug(f'DONE->{self._idx}') del cam.process - print(mtr[:idx,:]) + _log.debug(f'autofocus measurements:\n{mtr[:idx,:]}') mtr[:idx,0]=np.linspace(mtr[0,0],mtr[idx-1,0],idx) # smoothing the positions with equally spaced distances - print(mtr[:idx,:]) + _log.debug(f'autofocus measurements (smoothed positions):\n{mtr[:idx,:]}') mx=mtr[:,1].argmax() self._af=self.interpolate(mtr[:idx,0], mtr[:idx,1]) return diff --git a/psi_device.py b/psi_device.py index abf8f1a..41db50e 100644 --- a/psi_device.py +++ b/psi_device.py @@ -6,11 +6,8 @@ _log=logging.getLogger(__name__) class DataCollectionAbort(Exception): """Raised when acquisition configuration is invalid and the current scan should abort.""" -logging.basicConfig(level=logging.DEBUG,format='%(name)s:%(levelname)s:%(module)s:%(lineno)d:%(funcName)s:%(message)s ') logging.getLogger('matplotlib').setLevel(logging.INFO) -print('past logging') - if socket.gethostname()=='ganymede': base=os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(base,'../PBSwissMX/python'))) @@ -38,8 +35,7 @@ try: from ctadaq import CTAAcquisition from jfjoch_device import JFJ except ImportError as e: - print(f"error {e}") - _log.warning(e) + _log.warning(f'import failed: {e}') class Shutter: @@ -230,7 +226,6 @@ class Jungfrau: self.jfj = JFJ("http://sf-daq-2:8080") self.detectors=None _log.info(f'JungFrauJoch connected') - print('JungFrauJoch connected') except NameError as e: self.jfj = None _log.critical(f'JungfrauJoch not connected: {e}') @@ -325,7 +320,7 @@ class Jungfrau: self.mode_ssz = ssz self.mode_apperture_group_size = apperture_group_size self.mode_number_of_apperture_groups = number_of_apperture_groups - print(f"number_of_apperture_groups = {number_of_apperture_groups}") + _log.debug(f"number_of_apperture_groups = {number_of_apperture_groups}") #print(f"actually want 162//8 * {162//7} (or 162//8 * 162//7) which = 460, so 460*8*7=25760") transition_pulses = smv #on_off_ratio = 2 #1 on to 1 off which means 2 in the whole sequence @@ -348,9 +343,8 @@ class Jungfrau: cta.seq[219] = xray_sequence # detector trigger cta.cfg.repetitions = number_of_apperture_groups # number of repeitions is now number of times we repeat the loop self.images=number_of_apperture_groups*apperture_group_size - print(f"length of sequence = {len(cta.seq[200])}") - print(f"apperture in group = {apperture_group_size}") - print(f"number_of_apperture_groups = {number_of_apperture_groups}") + _log.info(f"mode 6: length of sequence={len(cta.seq[200])} apperture in group={apperture_group_size} " + f"number_of_apperture_groups={number_of_apperture_groups}") #print(f"n_pulses = {self.n_pulses_run} and n_appertures and images = {number_of_appertures}") elif motion_mode==7: @@ -426,11 +420,10 @@ class Jungfrau: cta.cfg.repetitions = number_of_rows self.images = number_of_apperture_groups*apperture_group_size - print(f"mode 7: apperture_group_size={apperture_group_size} sections_per_row={sections_per_row} " - f"number_of_rows={number_of_rows} number_of_apperture_groups={number_of_apperture_groups}") - print(f"section_transition_pulses={section_transition_pulses} row_transition_pulses={row_transition_pulses} " - f"wait_pulses={wait_pulses}") - print(f"length of one row sequence = {len(cta.seq[200])}") + _log.info(f"mode 7: apperture_group_size={apperture_group_size} sections_per_row={sections_per_row} " + f"number_of_rows={number_of_rows} number_of_apperture_groups={number_of_apperture_groups} " + f"section_transition_pulses={section_transition_pulses} row_transition_pulses={row_transition_pulses} " + f"wait_pulses={wait_pulses} length of one row sequence={len(cta.seq[200])}") else: _log.info('not mode 5 or 6') @@ -505,32 +498,10 @@ class Jungfrau: f"n_pulses_run={self.n_pulses_run}" ) - print( - f"motion_mode = {motion_mode}" - ) - - print( - f"images = {self.images}" - ) - - print( - f"images_per_cycle = " - f"{self.images_per_cycle}" - ) - - print( - f"pulses_per_cycle = " - f"{self.pulses_per_cycle}" - ) - - print( - f"n_pulses_run = " - f"{self.n_pulses_run}" - ) - - print( - f"block_size_to_slic = " - f"{self.block_size_to_slic}" + _log.info( + f"motion_mode={motion_mode} images={self.images} " + f"images_per_cycle={self.images_per_cycle} pulses_per_cycle={self.pulses_per_cycle} " + f"n_pulses_run={self.n_pulses_run} block_size_to_slic={self.block_size_to_slic}" ) except Exception as e: @@ -653,16 +624,13 @@ class Jungfrau: block_size = self.block_size_to_slic - print( - f'using exact pulse/image mapping: ' - f'block_size_to_slic = {block_size}' - ) + _log.info(f'using exact pulse/image mapping: block_size_to_slic={block_size}') else: block_size = run['block_size'] - print(f'using simple block size = {block_size}') + _log.info(f'using simple block size={block_size}') if type(self._daq) is CTAAcquisition: @@ -786,6 +754,7 @@ class Jungfrau: if __name__ == "__main__": import os import argparse + logging.basicConfig(level=logging.DEBUG,format='%(name)s:%(levelname)s:%(module)s:%(lineno)d:%(funcName)s:%(message)s ') if hostname=='ganymede': # use EPICS locally # os.environ['EPICS_CA_ADDR_LIST']='localhost' diff --git a/pyqtUsrObj.py b/pyqtUsrObj.py index 3719520..c0e4523 100644 --- a/pyqtUsrObj.py +++ b/pyqtUsrObj.py @@ -34,26 +34,26 @@ def obj_tree(obj,p=''): obj_tree(o,p+'.') def obj_info(obj,p=''): - print(f"{p}obj_info:{obj}") + _log.debug(f"{p}obj_info:{obj}") try: pos=obj.pos() - print(f"{p}pos:({pos.x():.6g},{pos.y():.6g})") # in coordinate value on the scene (no change by zooming) + _log.debug(f"{p}pos:({pos.x():.6g},{pos.y():.6g})") # in coordinate value on the scene (no change by zooming) except AttributeError: pass try: sz=obj.size() - print(f"{p}size:({sz.x():.6g},{sz.y():.6g})") # in coordinate value on the scene (no change by zooming) + _log.debug(f"{p}size:({sz.x():.6g},{sz.y():.6g})") # in coordinate value on the scene (no change by zooming) except AttributeError: pass try: for k, v in (('Viewport', obj.viewport()), ('Window', obj.window())): - print( + _log.debug( f"{p}{k} (x,y)(w,h):({v.x():.6g},{v.y():.6g})({v.width():.6g},{v.height():.6g})") # in coordinate value on the scene (no change by zooming) except AttributeError: pass try: scnPos=obj.scenePos() - print(f"{p}scenePos:({scnPos.x():.6g},{scnPos.y():.6g})") # in pixel on the scene (changes by zooming) + _log.debug(f"{p}scenePos:({scnPos.x():.6g},{scnPos.y():.6g})") # in pixel on the scene (changes by zooming) except AttributeError: pass try: @@ -61,9 +61,9 @@ def obj_info(obj,p=''): t=obj else: t=obj.transform() - print(f"{p}QTransform:{t.m11():8.5g} {t.m12():8.5g} {t.m13():8.5g}") - print(f"{p} {t.m21():8.5g} {t.m22():8.5g} {t.m23():8.5g}") - print(f"{p} {t.m31():8.5g} {t.m32():8.5g} {t.m33():8.5g}") + _log.debug(f"{p}QTransform:{t.m11():8.5g} {t.m12():8.5g} {t.m13():8.5g}") + _log.debug(f"{p} {t.m21():8.5g} {t.m22():8.5g} {t.m23():8.5g}") + _log.debug(f"{p} {t.m31():8.5g} {t.m32():8.5g} {t.m33():8.5g}") except AttributeError: pass diff --git a/swissmx.py b/swissmx.py index cf2ba38..4405b2b 100755 --- a/swissmx.py +++ b/swissmx.py @@ -35,16 +35,18 @@ class col: u='\033[4m' # underline def listLoggers(): + lines=[] rootlogger=logging.getLogger() - print(rootlogger) + lines.append(f'{rootlogger}') for h in rootlogger.handlers: - print(' %s'%h) + lines.append(' %s'%h) for nm, lgr in logging.Logger.manager.loggerDict.items(): - print('+ [%-20s] %s '%(nm, lgr)) + lines.append('+ [%-20s] %s '%(nm, lgr)) if not isinstance(lgr, logging.PlaceHolder): for h in lgr.handlers: - print(' %s'%h) + lines.append(' %s'%h) + logging.getLogger('swissmx').debug('loggers:\n'+'\n'.join(lines)) class logHandler(logging.StreamHandler): def __init__(self): @@ -95,7 +97,7 @@ class timestamp(): self.t=time.time() def log(self,txt): t=time.time() - print(txt+f'{t-self.t:6.3g}') + _log.info(txt+f'{t-self.t:6.3g}') self.t=t ts=timestamp() ts.log('Import part 1/8:') @@ -2796,7 +2798,7 @@ if __name__=="__main__": args = parser.parse_args() _log.info('Arguments:{}'.format(args.__dict__)) if args.log!=2: - for l in ('app_config', 'app_utils', 'backlight', 'camera', 'daq_worker', 'epics_widgets', + for l in ('app_config', 'app_utils', 'backlight', 'camera', 'ctadaq', 'daq_worker', 'epics_widgets', 'geometry', 'illumination', 'ModuleFixTarget', 'MXMotion', 'pbtools', 'psi_device', 'pyqtUsrObj', 'shapepath', 'swissmx', 'zoom',): try: