From 5a7afde16f1f622121bc8f0e577aedff983817b4 Mon Sep 17 00:00:00 2001 From: gobbo_a Date: Fri, 22 Sep 2017 10:58:17 +0200 Subject: [PATCH] Startup --- config/config.properties | 4 +- devices/Beam phase.properties | 4 +- devices/CamServer.properties | 24 ++ devices/CurrentCamera.properties | 19 +- devices/cam1.properties | 2 +- devices/cam2.properties | 2 +- devices/cam3.properties | 2 +- devices/cam_server.properties | 10 +- devices/http:/sf-daqsync-01:8881.properties | 25 ++ devices/http:/sf-daqsync-01:8888.properties | 25 ++ devices/positioner.properties | 3 +- devices/sf-daqsync-01:8888.properties | 25 ++ plugins/GunSolenoidAlignment.form | 9 +- plugins/GunSolenoidAlignment.java | 2 +- plugins/LaserGunAlignment.form | 9 +- plugins/LaserGunAlignment.java | 2 +- plugins/SchottkyScan.form | 10 +- plugins/SchottkyScan.java | 10 +- plugins/ScreenPanel.java | 36 ++- script/Alignment/Gun_solenoid_alignment.py | 90 +------ script/Alignment/Laser_gun_alignment.py | 92 +------ script/CPython/extremum.py | 12 +- script/CPython/wrapper.py | 9 + script/Devices/camtool.py | 246 ++++++++++++++++++ script/Diagnostics/CamtoolScan.py | 34 +-- .../Camtoolreadout_for_WSC_comparison.py | 42 ++- script/Diagnostics/Laser_position_scan.py | 31 +-- script/RFscan/GunEnergyScan.py | 37 +-- script/RFscan/SchottkyScan.py | 82 +++--- script/RFscan/phase_scan_caqtdm.py | 50 ++-- script/RFscan/phase_scan_caqtdm_set.py | 33 +-- script/local.py | 134 ++++++++++ script/test/CamtoolBug.py | 7 - script/test/CamtoolTest.py | 13 - script/test/GunEnergyScan_dv.py | 15 +- script/test/SchottkyScan_dv.py | 44 ++-- script/test/TestAlignmentScan.py | 74 +----- script/test/TestSeverity.py | 40 +++ script/test/phase_scan_caqtdm_dv.py | 110 ++++++++ script/test/phase_scan_caqtdm_set_dv.py | 40 +++ 40 files changed, 975 insertions(+), 483 deletions(-) create mode 100644 devices/CamServer.properties create mode 100644 devices/http:/sf-daqsync-01:8881.properties create mode 100644 devices/http:/sf-daqsync-01:8888.properties create mode 100644 devices/sf-daqsync-01:8888.properties create mode 100644 script/Devices/camtool.py delete mode 100644 script/test/CamtoolBug.py delete mode 100644 script/test/CamtoolTest.py create mode 100644 script/test/TestSeverity.py create mode 100644 script/test/phase_scan_caqtdm_dv.py create mode 100644 script/test/phase_scan_caqtdm_set_dv.py diff --git a/config/config.properties b/config/config.properties index 27f24a0..5bd1d96 100755 --- a/config/config.properties +++ b/config/config.properties @@ -1,4 +1,4 @@ -#Tue Sep 05 14:15:59 CEST 2017 +#Wed Sep 06 11:10:30 CEST 2017 autoSaveScanData=true createSessionFiles=false dataLayout=default @@ -30,5 +30,5 @@ userAuthenticator= userManagement=false versionTrackingEnabled=true versionTrackingLogin={context}/svcusr-hlapp_robot -versionTrackingManual=true +versionTrackingManual=false versionTrackingRemote=git@git.psi.ch\:pshell_config/sf-op.git diff --git a/devices/Beam phase.properties b/devices/Beam phase.properties index 8ffe649..41ae543 100644 --- a/devices/Beam phase.properties +++ b/devices/Beam phase.properties @@ -1,9 +1,9 @@ -#Fri Sep 01 09:01:32 CEST 2017 +#Wed Sep 06 08:02:31 CEST 2017 maxValue=360.0 minValue=-360.0 offset=0.0 precision=3 -resolution=0.1 +resolution=0.01 rotation=false scale=1.0 unit=deg diff --git a/devices/CamServer.properties b/devices/CamServer.properties new file mode 100644 index 0000000..5b9b381 --- /dev/null +++ b/devices/CamServer.properties @@ -0,0 +1,24 @@ +#Tue Sep 19 11:13:25 CEST 2017 +colormap=Grayscale +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/CurrentCamera.properties b/devices/CurrentCamera.properties index 813033e..eabd7d4 100644 --- a/devices/CurrentCamera.properties +++ b/devices/CurrentCamera.properties @@ -1,8 +1,9 @@ -#Tue Sep 05 13:56:15 CEST 2017 -colormap=Flame -colormapAutomatic=true -colormapMax=1000.0 -colormapMin=70.0 +#Fri Sep 22 10:36:51 CEST 2017 +\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000= +colormap=Grayscale +colormapAutomatic=false +colormapMax=400.0 +colormapMin=0.0 flipHorizontally=false flipVertically=false grayscale=false @@ -21,9 +22,9 @@ rotation=0.0 rotationCrop=false scale=1.0 serverURL=localhost\:10000 -spatialCalOffsetX=295.94701986754967 -spatialCalOffsetY=138.70408163265307 -spatialCalScaleX=-1.0 -spatialCalScaleY=-1.0 +spatialCalOffsetX=-212.32218865045797 +spatialCalOffsetY=-199.40365507891784 +spatialCalScaleX=-14.81873708800342 +spatialCalScaleY=-12.269938316113084 spatialCalUnits=mm transpose=false diff --git a/devices/cam1.properties b/devices/cam1.properties index 884604e..5304241 100644 --- a/devices/cam1.properties +++ b/devices/cam1.properties @@ -1,4 +1,4 @@ -#Fri Jun 30 08:55:58 CEST 2017 +#Wed Sep 20 16:11:40 CEST 2017 colormap=Temperature colormapAutomatic=true colormapMax=30000.0 diff --git a/devices/cam2.properties b/devices/cam2.properties index c56d42d..e4c055b 100644 --- a/devices/cam2.properties +++ b/devices/cam2.properties @@ -1,4 +1,4 @@ -#Tue Jun 27 15:04:39 CEST 2017 +#Wed Sep 20 10:01:09 CEST 2017 colormap=Flame colormapAutomatic=true colormapMax=255.0 diff --git a/devices/cam3.properties b/devices/cam3.properties index 33b139d..dbe34c7 100644 --- a/devices/cam3.properties +++ b/devices/cam3.properties @@ -1,4 +1,4 @@ -#Wed Aug 23 13:47:22 CEST 2017 +#Wed Sep 20 10:01:09 CEST 2017 colormap=Flame colormapAutomatic=true colormapMax=255.0 diff --git a/devices/cam_server.properties b/devices/cam_server.properties index 627fa8b..7a1dcb6 100644 --- a/devices/cam_server.properties +++ b/devices/cam_server.properties @@ -1,4 +1,4 @@ -#Tue Sep 05 14:13:35 CEST 2017 +#Tue Sep 05 18:51:43 CEST 2017 colormap=Flame colormapAutomatic=true colormapMax=NaN @@ -16,9 +16,9 @@ roiY=0 rotation=0.0 rotationCrop=false scale=1.0 -spatialCalOffsetX=-50.03909304143862 -spatialCalOffsetY=-50.048875855327466 -spatialCalScaleX=-1.0 -spatialCalScaleY=-1.0 +spatialCalOffsetX=0.0 +spatialCalOffsetY=0.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 spatialCalUnits=mm transpose=false diff --git a/devices/http:/sf-daqsync-01:8881.properties b/devices/http:/sf-daqsync-01:8881.properties new file mode 100644 index 0000000..c56b04d --- /dev/null +++ b/devices/http:/sf-daqsync-01:8881.properties @@ -0,0 +1,25 @@ +#Tue Sep 19 11:06:51 CEST 2017 +colormap=Grayscale +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +serverURL=localhost\:8888 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/http:/sf-daqsync-01:8888.properties b/devices/http:/sf-daqsync-01:8888.properties new file mode 100644 index 0000000..dd604af --- /dev/null +++ b/devices/http:/sf-daqsync-01:8888.properties @@ -0,0 +1,25 @@ +#Tue Sep 19 11:08:59 CEST 2017 +colormap=Grayscale +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +serverURL=localhost\:8888 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/positioner.properties b/devices/positioner.properties index 3124a2e..3d7d8c5 100644 --- a/devices/positioner.properties +++ b/devices/positioner.properties @@ -1,8 +1,9 @@ -#Wed Apr 05 09:03:47 CEST 2017 +#Tue Sep 05 14:28:32 CEST 2017 maxValue=NaN minValue=NaN offset=0.0 precision=-1 resolution=NaN +rotation=false scale=1.0 unit=null diff --git a/devices/sf-daqsync-01:8888.properties b/devices/sf-daqsync-01:8888.properties new file mode 100644 index 0000000..71881a0 --- /dev/null +++ b/devices/sf-daqsync-01:8888.properties @@ -0,0 +1,25 @@ +#Tue Sep 19 11:11:22 CEST 2017 +colormap=Grayscale +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +serverURL=localhost\:8888 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/plugins/GunSolenoidAlignment.form b/plugins/GunSolenoidAlignment.form index 316a2eb..61847c9 100644 --- a/plugins/GunSolenoidAlignment.form +++ b/plugins/GunSolenoidAlignment.form @@ -329,10 +329,11 @@ - - - - + + + + + diff --git a/plugins/GunSolenoidAlignment.java b/plugins/GunSolenoidAlignment.java index 3b38c57..d5a492b 100644 --- a/plugins/GunSolenoidAlignment.java +++ b/plugins/GunSolenoidAlignment.java @@ -165,7 +165,7 @@ public class GunSolenoidAlignment extends Panel { jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel7.setText("Settling time:"); - comboSource.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "camtool", "direct", "bpm" })); + comboSource.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "server", "camtool", "direct", "bpm" })); javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); panelParameters.setLayout(panelParametersLayout); diff --git a/plugins/LaserGunAlignment.form b/plugins/LaserGunAlignment.form index cd96b04..5e5b93f 100644 --- a/plugins/LaserGunAlignment.form +++ b/plugins/LaserGunAlignment.form @@ -315,10 +315,11 @@ - - - - + + + + + diff --git a/plugins/LaserGunAlignment.java b/plugins/LaserGunAlignment.java index e88c153..04bfb78 100644 --- a/plugins/LaserGunAlignment.java +++ b/plugins/LaserGunAlignment.java @@ -165,7 +165,7 @@ public class LaserGunAlignment extends Panel { jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel7.setText("Source:"); - comboSource.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "camtool", "direct", "bpm" })); + comboSource.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "server", "camtool", "direct", "bpm" })); javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); panelParameters.setLayout(panelParametersLayout); diff --git a/plugins/SchottkyScan.form b/plugins/SchottkyScan.form index 98749cd..9f47651 100644 --- a/plugins/SchottkyScan.form +++ b/plugins/SchottkyScan.form @@ -158,7 +158,7 @@ - + @@ -177,7 +177,7 @@ - + @@ -196,7 +196,7 @@ - + @@ -216,7 +216,7 @@ - + @@ -278,7 +278,7 @@ - + diff --git a/plugins/SchottkyScan.java b/plugins/SchottkyScan.java index be65b07..29bc326 100644 --- a/plugins/SchottkyScan.java +++ b/plugins/SchottkyScan.java @@ -102,7 +102,7 @@ public class SchottkyScan extends Panel { panelPars.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameters (beam phase)")); - spinnerStep.setModel(new javax.swing.SpinnerNumberModel(5.0d, 1.0d, 90.0d, 1.0d)); + spinnerStep.setModel(new javax.swing.SpinnerNumberModel(5.0d, 0.1d, 20.0d, 0.1d)); labelLatency.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelLatency.setText("Latency:"); @@ -110,7 +110,7 @@ public class SchottkyScan extends Panel { labelStart.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelStart.setText("Start:"); - spinnerStop.setModel(new javax.swing.SpinnerNumberModel(180.0d, -180.0d, 360.0d, 1.0d)); + spinnerStop.setModel(new javax.swing.SpinnerNumberModel(150.0d, -180.0d, 360.0d, 1.0d)); labelStep.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelStep.setText("Step size:"); @@ -118,14 +118,14 @@ public class SchottkyScan extends Panel { labelStop.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelStop.setText("Stop:"); - spinnerLatency.setModel(new javax.swing.SpinnerNumberModel(0.1d, 0.0d, 5.0d, 0.01d)); + spinnerLatency.setModel(new javax.swing.SpinnerNumberModel(0.15d, 0.0d, 5.0d, 0.01d)); spinnerSamples.setModel(new javax.swing.SpinnerNumberModel(1, 1, 50, 1)); labelSamples.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelSamples.setText("Nb Samples:"); - spinnerStart.setModel(new javax.swing.SpinnerNumberModel(0.0d, -180.0d, 360.0d, 1.0d)); + spinnerStart.setModel(new javax.swing.SpinnerNumberModel(-10.0d, -180.0d, 360.0d, 1.0d)); javax.swing.GroupLayout panelParsLayout = new javax.swing.GroupLayout(panelPars); panelPars.setLayout(panelParsLayout); @@ -194,7 +194,7 @@ public class SchottkyScan extends Panel { labelRefPhase.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); labelRefPhase.setText("Ref Phase:"); - spinnerPhaseRef.setModel(new javax.swing.SpinnerNumberModel(0.0d, -180.0d, 360.0d, 1.0d)); + spinnerPhaseRef.setModel(new javax.swing.SpinnerNumberModel(0.0d, -180.0d, 360.0d, 0.1d)); spinnerPhaseRef.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { spinnerPhaseRefStateChanged(evt); diff --git a/plugins/ScreenPanel.java b/plugins/ScreenPanel.java index 12f0a47..6c6b303 100644 --- a/plugins/ScreenPanel.java +++ b/plugins/ScreenPanel.java @@ -2,6 +2,7 @@ * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. */ +import ch.psi.pshell.bs.CameraServer; import ch.psi.pshell.core.Context; import java.io.IOException; import java.nio.file.Paths; @@ -14,6 +15,7 @@ import ch.psi.utils.swing.SwingUtils; import ch.psi.utils.swing.TextEditor; import ch.psi.pshell.bs.PipelineServer; import ch.psi.pshell.bs.StreamValue; +import ch.psi.pshell.core.JsonSerializer; import ch.psi.pshell.device.DescStatsDouble; import ch.psi.pshell.device.Device; import ch.psi.pshell.epics.ChannelInteger; @@ -104,8 +106,7 @@ public class ScreenPanel extends Panel { String userOverlaysConfigFile; ColormapSource camera; PipelineServer server; - String cameraName; - String cameraConfigJson; + String cameraName; int polling = 1000; Overlay marker = null; JDialog histogramDialog; @@ -450,16 +451,13 @@ public class ScreenPanel extends Panel { DefaultComboBoxModel getCameraList(boolean fromServer) throws Exception { DefaultComboBoxModel model = new DefaultComboBoxModel(); if (fromServer){ - PipelineServer server = newServer(); - try { - server.initialize(); - List cameras = server.getCameras(); + try (PipelineServer srv = newServer()){ + srv.initialize(); + List cameras = srv.getCameras(); Collections.sort(cameras); for (String camera : cameras) { model.addElement(camera); } - } finally { - server.close(); } } else { @@ -625,10 +623,6 @@ public class ScreenPanel extends Panel { try { - String configFolder = (String) getContext().getClassByName("SfCamera").getMethod("getConfigFolder", new Class[]{}).invoke(null); - Path configFile = Paths.get(configFolder, cameraName + ".json"); - cameraConfigJson = configFile.toFile().exists() ? new String(Files.readAllBytes(configFile)) : null; - if (buttonServer.isSelected()) { camera = newServer(); camera.getConfig().flipHorizontally = false; @@ -640,7 +634,7 @@ public class ScreenPanel extends Panel { camera.getConfig().roiHeight = -1; } else { //camera = new SfCamera(CAMERA_DEVICE_NAME, cameraName); - camera = (ColormapSource) getContext().getClassByName("SfCamera").getConstructor(new Class[]{String.class, String.class}).newInstance(new Object[]{CAMERA_DEVICE_NAME, cameraName}); + camera = (ColormapSource) getContext().getClassByName("SfCamera").getConstructor(new Class[]{String.class, String.class}).newInstance(new Object[]{CAMERA_DEVICE_NAME, cameraName}); } camera.initialize(); camera.assertInitialized(); @@ -2528,6 +2522,20 @@ public class ScreenPanel extends Panel { private void buttonArgsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonArgsActionPerformed try { if (camera != null) { + String cameraConfigJson = null; + if (usingServer){ + String cameraServerUrl = server.getUrl().substring(0, server.getUrl().length()-1) + "8"; + try (CameraServer srv = new CameraServer("CamServer", cameraServerUrl)){ + srv.initialize(); + //TODO: replace into encodeMultiline + cameraConfigJson = JsonSerializer.encode(srv.getConfig(cameraName), true); + } + + } else { + String configFolder = (String) getContext().getClassByName("SfCamera").getMethod("getConfigFolder", new Class[]{}).invoke(null); + Path configFile = Paths.get(configFolder, cameraName + ".json"); + cameraConfigJson = configFile.toFile().exists() ? new String(Files.readAllBytes(configFile)) : null; + } TextEditor editor = new TextEditor(); editor.setText(cameraConfigJson); editor.setReadOnly(true); @@ -2628,7 +2636,7 @@ public class ScreenPanel extends Panel { try { System.out.println("Grabbing background for: " + cameraName); if (server!=null){ - server.captureBackground(cameraName, 5); + server.captureBackground(5); } else { camera.captureBackground(5, 0); } diff --git a/script/Alignment/Gun_solenoid_alignment.py b/script/Alignment/Gun_solenoid_alignment.py index c590991..cec20c0 100755 --- a/script/Alignment/Gun_solenoid_alignment.py +++ b/script/Alignment/Gun_solenoid_alignment.py @@ -10,14 +10,14 @@ import datetime +do_elog = True +dry_run = False is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run" - camera_name = "SINEG01-DSCR190" use_good_region=False -do_elog = True if not is_panel: - source = "direct" # "camtool", "bpm" or "direct" + source = "server" # "server", "camtool", "bpm" or "direct" I1 = 100.0 I2 = 105.0 dI = 1.0 @@ -46,103 +46,39 @@ centroid_plot.addSeries(scan_series) scan_series.setLinesVisible(False) scan_series.setPointSize(4) -#Testing -""" -camera_name = "SLG-LCAM-C041" -def laser_on(): - print "Laser On" -def laser_off(): - print "Laser Off" -def switch_off_magnets(magnets = None): - pass -add_device(DummyPositioner("gun_solenoid"), True) -do_elog = False -""" -laser_was_on = is_laser_on() -original_gun_solenoid = gun_solenoid.read() +positioner = DummyPositioner("positioner") if dry_run else gun_solenoid + +original_gun_solenoid = positioner.read() multiple_background = multiple_background and use_background print "Parameters: ", I1, I2, dI, settling_time, plot_image, number_images, use_background, multiple_background, number_backgrounds -if source == "camtool": - check_camtool() - if use_background: - laser_off() - if not multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - camtool.start(camera_name, 0, use_background, None, 0.0, None) -else: - if source == "bpm": - run("Devices/BpmStats") - add_device(BpmStats("image_stats", camera_name), True) - multiple_background = False - use_background = False - else: - run("Devices/ImageStats") - add_device(ImageStats("image_stats", camera_name), True) - add_device(image_stats.source, True) - image_stats.enableBackground(use_background) - if use_background: - laser_off() - if not multiple_background: - image_stats.grabBackground(number_backgrounds) - image_stats.setNumberOfImages(max(number_images,1)) +setup_camera_scan() #switch_off_magnets() # add here gun phase setting see wiki page -def before_sample(position, scan): - if source == "camtool": - if multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - camtool.start(camera_name, 0, use_background, None, 0.0, None) - laser_on() - wait_camtool_message(number_images) #Wait filing the averager cache - else: - if multiple_background: - image_stats.grabBackground(number_backgrounds) - laser_on() - image_stats.update() def after_sample(record, scan): x = record.values[0] y = record.values[1] stdev_x = record.values[2] stdev_y = record.values[3] - if source == "camtool": + if source in ["camtool", "server"]: #x, y, stdev_x, stdev_y = x.mean, y.mean, stdev_x.mean, stdev_y.mean x, y, stdev_x, stdev_y = x.mean, y.mean, x.stdev, y.stdev scan_series.appendData(x, y, abs(stdev_x), abs(stdev_y)); - if multiple_background: - laser_off() + after_sample_camera_scan() r = None -if not multiple_background: - laser_on() try: - if source != "camtool": - sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] - if plot_image and (source == "direct"): - sensors.append(image_stats.source.getDataMatrix()) - else: - sensors = get_camtool_stats(number_images, good_region=use_good_region) - if plot_image: - sensors.append(camtool.getDataMatrix()) - r = lscan(gun_solenoid, sensors , I1, I2, dI, settling_time, before_read = before_sample, after_read = after_sample) + sensors = get_camera_scan_sensors() + r = lscan(positioner, sensors , I1, I2, dI, settling_time, before_read = before_sample_camera_scan, after_read = after_sample) finally: - if source == "camtool": - camtool.stop() - else: - image_stats.stop() - gun_solenoid.write(original_gun_solenoid) -if laser_was_on: - laser_on() -else: - laser_off() + end_camera_scan() + positioner.write(original_gun_solenoid) # take the result of the scan and generate convex hull plot (hx,hy)= convex_hull(x=to_array(r.getReadable(0), 'd'), y=to_array(r.getReadable(1),'d')) diff --git a/script/Alignment/Laser_gun_alignment.py b/script/Alignment/Laser_gun_alignment.py index 2c83127..b3bf26f 100755 --- a/script/Alignment/Laser_gun_alignment.py +++ b/script/Alignment/Laser_gun_alignment.py @@ -10,14 +10,15 @@ import datetime +do_elog = True +dry_run = False is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run" - camera_name = "SINEG01-DSCR190" use_good_region=False -do_elog = True + if not is_panel: - source = "camtool" # "camtool", "bpm" or "direct" + source = "server" # "server", "camtool", "bpm" or "direct" phi1= 95.0 phi2 = 100.0 dphi = 1.0 @@ -46,105 +47,40 @@ centroid_plot.addSeries(scan_series) scan_series.setLinesVisible(False) scan_series.setPointSize(4) -""" -#Testing -camera_name = "SLG-LCAM-C041" -def laser_on(): - print "Laser On" -def laser_off(): - print "Laser Off" -def switch_off_magnets(magnets = None): - pass -add_device(DummyPositioner("gun_phase"), True) -do_elog = False -""" +positioner = DummyPositioner("positioner") if dry_run else gun_phase -laser_was_on = is_laser_on() -original_phase = gun_phase.read() +original_phase = positioner.read() multiple_background = multiple_background and use_background print "Parameters: ", phi1, phi2, dphi, settling_time, plot_image, number_images, use_background, multiple_background, number_backgrounds -if source == "camtool": - #kill_camtool() - check_camtool() - if use_background: - laser_off() - if not multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - camtool.start(camera_name, 0, use_background, None, 0.0, None) -else: - if source == "bpm": - run("Devices/BpmStats") - add_device(BpmStats("image_stats", camera_name), True) - multiple_background = False - use_background = False - else: - run("Devices/ImageStats") - add_device(ImageStats("image_stats", camera_name), True) - add_device(image_stats.source, True) - image_stats.enableBackground(use_background) - if use_background: - laser_off() - if not multiple_background: - image_stats.grabBackground(number_backgrounds) - image_stats.setNumberOfImages(max(number_images,1)) +setup_camera_scan() #switch_off_magnets() # add here gun phase setting see wiki page -def before_sample(position, scan): - if source == "camtool": - if multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - camtool.start(camera_name, 0, use_background, None, 0.0, None) - laser_on() - wait_camtool_message(number_images) #Wait filing the averager cache - else: - if multiple_background: - image_stats.grabBackground(number_backgrounds) - laser_on() - image_stats.update() def after_sample(record, scan): x = record.values[0] y = record.values[1] stdev_x = record.values[2] stdev_y = record.values[3] - if source == "camtool": + if source in ["camtool", "server"]: #x, y, stdev_x, stdev_y = x.mean, y.mean, stdev_x.mean, stdev_y.mean x, y, stdev_x, stdev_y = x.mean, y.mean, x.stdev, y.stdev scan_series.appendData(x, y, abs(stdev_x), abs(stdev_y)); - if multiple_background: - laser_off() + after_sample_camera_scan() r = None -if not multiple_background: - laser_on() try: - if source != "camtool": - sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] - if plot_image and (source == "direct"): - sensors.append(image_stats.source.getDataMatrix()) - else: - sensors = get_camtool_stats(number_images, good_region=use_good_region) - if plot_image: - sensors.append(camtool.getDataMatrix()) - r = lscan(gun_phase, sensors , phi1, phi2, dphi, settling_time, before_read = before_sample, after_read = after_sample) + sensors = get_camera_scan_sensors() + r = lscan(positioner, sensors , phi1, phi2, dphi, settling_time, before_read = before_sample_camera_scan, after_read = after_sample) finally: - if source == "camtool": - camtool.stop() - else: - image_stats.stop() - gun_phase.write(original_phase) -if laser_was_on: - laser_on() -else: - laser_off() + end_camera_scan() + positioner.write(original_phase) + # take the result of the scan and generate convex hull plot (hx,hy)= convex_hull(x=to_array(r.getReadable(0), 'd'), y=to_array(r.getReadable(1),'d')) diff --git a/script/CPython/extremum.py b/script/CPython/extremum.py index 93b1171..006f295 100644 --- a/script/CPython/extremum.py +++ b/script/CPython/extremum.py @@ -1,13 +1,10 @@ import numpy as np - def extremum(x, y): """ Return extremum coordinates of quadratic fit """ - pf = np.polyfit(x, y, 2, full=True) - p = pf[0] - res = pf[1][0] + p = np.polyfit(x, y, 2) f = np.poly1d(p) if p[0] != 0: x_ext = -p[1] / (2 * p[0]) @@ -15,6 +12,11 @@ def extremum(x, y): else: x_ext = None y_ext = None + yhat = f(x) + ybar = np.sum(y)/len(y) + ssreg = np.sum((yhat - ybar)**2) + sstot = np.sum((y - ybar)**2) + R2 = ssreg / sstot x_fit = np.linspace(min(x), max(x), 100) y_fit = f(x_fit) - return (x_ext, y_ext, x_fit, y_fit, res) + return (x_ext, y_ext, x_fit, y_fit, R2) diff --git a/script/CPython/wrapper.py b/script/CPython/wrapper.py index 36edbf7..d9e1759 100644 --- a/script/CPython/wrapper.py +++ b/script/CPython/wrapper.py @@ -11,4 +11,13 @@ def extremum(x, y): def gfitoff(x, y, off=None, amp=None, com=None, sigma=None): ret = call_jep("CPython/gfitoff", "gfitoff", [to_npa(x), to_npa(y), off, amp, com, sigma]) return ret if ret is None or is_list(ret) else ret.data + + + + + + + + + \ No newline at end of file diff --git a/script/Devices/camtool.py b/script/Devices/camtool.py new file mode 100644 index 0000000..ee97c78 --- /dev/null +++ b/script/Devices/camtool.py @@ -0,0 +1,246 @@ +#Interface to CameraTool application + +import ch.psi.utils.Convert.toBidimensional as mono_to_bidi +import ch.psi.utils.Convert.toDouble as toDouble +import org.apache.commons.math3.linear.Array2DRowRealMatrix as Matrix + +class CamToolImage(ReadableMatrix): + def __init__(self, camtool): + self.camtool = camtool + shape = camtool.shape.read() + self._width = shape[1] #len(camtool.profile_x.read()) + self._height = shape[0] #len(camtool.(profile_y.read()) + + def read(self): + raw = self.camtool.data.read() + #return Matrix(toDouble(mono_to_bidi(raw, self.getHeight(), self.getWidth()))).transpose().getData() #data is transposed + return mono_to_bidi(raw, self.getWidth(), self.getHeight()) + + def getWidth(self): + return self._width + + def getHeight(self): + return self._height + + +class CamTool(DeviceBase): + def __init__(self, name, prefix = "cam:", latch = False, camera = "SINEG01-DSCR190", egu = True, gauss = True): + DeviceBase.__init__(self, name) + run_channel = prefix + "camera.run" + + caget(run_channel) + #try: + # caget(run_channel) + #except: + # cmd = "camtool --casprefix " + prefix + " --run -1 " + camera #--nogui + # print cmd + # fork( (exec_cmd,(cmd,)),) + # self.waitForChannel(run_channel, 20) + # time.sleep(5.0) + self.prefix = prefix + self.latch = latch + self.egu = egu + self.gauss=gauss + self.mode = "latch" if latch else "pipeline" + self.data_prefix = prefix + self.mode + "." + self.cam_run = create_channel_device(prefix + "camera.run", type='i', size=None, deviceName=name + " run") # Channel(prefix + "camera.run", alias = name + " run") + self.cam_latch = create_channel_device(prefix + "latch.capture", type='l', size=None, deviceName=name + " latch") # Channel(prefix + "latch.capture", 'l', alias = name + " latch") + + + if self.latch: + self.start() + time.sleep(3.0) + self.cam_latch.write(1) + self.waitForChannel(self.data_prefix + "timestamp",20) + else: + self.cam_run.write(1) + time.sleep(5.0) + self.waitForChannel(self.data_prefix + "timestamp",20) + self.waitForChannel(self.data_prefix + "image.shape",20) + self.stop() + self.timestamp = create_channel_device(self.data_prefix + "timestamp", type='d', size=None, deviceName=name + " timestamp") # Channel(self.data_prefix + "timestamp",type = 'd', alias = name + " timestamp") #[D1, D2, ...] + self.timestamp.setMonitored(True)#self.timestamp.set_monitored(True) + if egu: + if gauss: + self.com_x = create_channel_device(self.data_prefix + "x_stats.g_center_egu", type='d', size=None, deviceName=name + " gc_egu x") + self.com_y = create_channel_device(self.data_prefix + "y_stats.g_center_egu", type='d', size=None, deviceName=name + " gc_egu y") + caput(self.data_prefix + "x_stats.gauss_en", 1) + caput(self.data_prefix + "y_stats.gauss_en", 1) + else: + self.com_x = create_channel_device(self.data_prefix + "x_stats.com_egu", type='d', size=None, deviceName=name + " com_egu x") #Channel(self.data_prefix + "x_stats.com_egu", alias = name + " com_egu x") + self.com_y = create_channel_device(self.data_prefix + "y_stats.com_egu", type='d', size=None, deviceName=name + " com_egu y") #Channel(self.data_prefix + "y_stats.com_egu", alias = name + " com_egu y") + else: + self.com_x = create_channel_device(self.data_prefix + "x_stats.com", type='d', size=None, deviceName=name + " com x") #Channel(self.data_prefix + "x_stats.com", alias = name + " com x") + self.com_y = create_channel_device(self.data_prefix + "y_stats.com", type='d', size=None, deviceName=name + " com x") #Channel(self.data_prefix + "y_stats.com", alias = name + " com y") + self.profile_x = create_channel_device(self.data_prefix + "profile.x", type='d', size=None, deviceName=name + " profile x") #Channel(self.data_prefix + "profile.x", alias = name + " profile x") + self.profile_y = create_channel_device(self.data_prefix + "profile.y", type='d', size=None, deviceName=name + " profile y") #Channel(self.data_prefix + "profile.y", alias = name + " profile y") + self.data = Channel(self.data_prefix + "image", alias = name + " data") + self.shape = Channel(self.data_prefix + "image.shape", alias = name + " shape") #[D1, D2, ...] + self.bg_en = create_channel_device(prefix + "pipeline.bg.enabled", type='l', size=None, deviceName=name + " bg enabled") #self.bg_en = Channel(prefix + "pipeline.bg.enabled", type = 'l', alias = name + " bg enabled") + self.bg_capture = create_channel_device(prefix + "pipeline.bg.capture", type='l', size=None, deviceName=name + " bg capture") #self.bg_capture = Channel(prefix + "pipeline.bg.capture", type = 'l', alias = name + " bg capture") + self.bg_capture_remain = create_channel_device(prefix + "pipeline.bg.capture_remain", type='l', size=None, deviceName=name + " capture remain") #self.bg_capture_remain = Channel(prefix + "pipeline.bg.capture_remain", alias = name + " capture remain") + self.num_images = 1 + self.grab_timeout = 5.0 + self.image = CamToolImage(self) + set_device_alias(self.image, name + " image") + self.com_x_samples, self.com_y_samples = [], [] + class CamToolComX(Readable): + def read(self): + return mean(self.camtool.com_x_samples) + self.com_x_mean = CamToolComX(); self.com_x_mean.camtool = self + class CamToolComY(Readable): + def read(self): + return mean(self.camtool.com_y_samples) + self.com_y_mean = CamToolComY(); self.com_y_mean.camtool = self + class CamToolComXVar(Readable): + def read(self): + return stdev(self.camtool.com_x_samples) + self.com_x_stdev = CamToolComXVar(); self.com_x_stdev.camtool = self + class CamToolComXVar(Readable): + def read(self): + return stdev(self.camtool.com_y_samples) + self.com_y_stdev = CamToolComXVar(); self.com_y_stdev.camtool = self + set_device_alias(self.com_x_mean, name + " com x mean") + set_device_alias(self.com_y_mean, name + " com y mean") + set_device_alias(self.com_x_stdev, name + " com x stdev") + set_device_alias(self.com_y_stdev, name + " com y stdev") + + def waitForChannel(self, channel, timeout): + print "Waiting for:", channel + start = time.time() + while(True): + try: + caget(channel) + print "Found channel:", channel + break + #except Exception as e: + except: + if (time.time() - start) > timeout: + raise Exception("Timeout waiting for channel: " + channel) + time.sleep(0.5) + + + def doInitialize(self): + if self.latch: + self.start() + else: + self.stop() + + def start(self): + #print "Start" + self.cam_run.write(-1) + + def stop(self): + #print "Stop" + self.cam_run.write(0) + + def capture(self): + retries = 3 + while(True): + try: + timestamp = self.timestamp.read() + #print "Current timestamp: ", timestamp + if not self.latch: + self.cam_run.write(1) + else: + self.cam_latch.write(1) + start = time.time() + while(True): + val = self.timestamp.read() + if timestamp != val: + #print "New timestamp: ", val + self.setCache(val) + return + if (time.time()-start) > self.grab_timeout: + raise Exception("Frame timeout") + time.sleep(0.005) + except Exception, e: + retries = retries -1 + print "---------------- Exception ------------------------" + print e + if retries<=0: + print "Failure " + raise e + else: + print "Retrying ", retries + + def doUpdate(self): + self.com_x_samples, self.com_y_samples = [], [] + for i in range(self.num_images): + self.capture() + self.com_x_samples.append(self.com_x.read()) + self.com_y_samples.append(self.com_y.read()) + + def setNumberOfImages(self, value): + self.num_images = value + + def enableBackground(self, value): + self.bg_en.write(1 if value else 0) + + def captureBackground(self, images): + self.start() + self.bg_capture.write(images) + sleep(0.2) + while(True): + finished = True + for retry in range(10): + if self.bg_capture_remain.read() > 0: + finished = False + break + sleep(0.05) + if finished: + break + time.sleep(0.1) + #self.stop() + #self.bg_capture.write(images) + #while( self.bg_capture_remain.read() > 0): + # self.capture() + self.doInitialize() + + def doClose(self): + self.cam_run.close() + self.cam_latch.close() + self.timestamp.close() + self.com_x.close() + self.com_y.close() + self.profile_x.close() + self.profile_y.close() + self.data.close() + self.shape.close() + #self.bg_image.close() + self.bg_en.close() + self.bg_capture.close() + self.bg_capture_remain.close() + #self.image.close() + +""" +try: + if get_device("camtool") is None: + add_device(CamTool("camtool", prefix = "SINEG01-DSCR190:", latch = True, camera = "SINEG01-DSCR190"), True) + camtool.enableBackground(True) + for i in range (1000): + camtool.capture() + print i, camtool.take(), camtool.com_x.read(), camtool.com_y.read() + +finally: + print "" + +""" + +""" +if __name__ == "__builtin__": + #image_stats.enableBackground(False) + image_stats.enableBackground(False) + #image_stats.captureBackground(5) + for i in range (1000): + image_stats.capture() + print i, image_stats.take(), image_stats.com_x.read(), image_stats.com_y.read() + #from camtool import CamTool + #camera_tool = CamTool("camtool", latch = True) + #add_device(camera_tool, True) + #camera_tool.enableBackground(True) + #camera_tool.capture() + #print camera_tool.take(), camera_tool.com_x.read(), camera_tool.com_y.read() + + +""" \ No newline at end of file diff --git a/script/Diagnostics/CamtoolScan.py b/script/Diagnostics/CamtoolScan.py index c21d079..e93bbbd 100644 --- a/script/Diagnostics/CamtoolScan.py +++ b/script/Diagnostics/CamtoolScan.py @@ -1,7 +1,7 @@ import ch.psi.pshell.epics.ControlledVariable as ControlledVariable CAMERA = "S10DI01-DSCR020" -#CAMERA = "SINDI02-DLAC055" +#CAMERA = "SINDI02-DLAC055" QUADRUPOLE = "S10CB01-MQUA430" # quadrupole for the scan with S10DI01-DSCR020: S10CB02-MQUA230 CHARGE_BPM = "SINEG01-DBPM340:Q1" CHARGE_ICT = "SINEG01-DICT215:B1_CHARGE-OP" @@ -9,19 +9,13 @@ RANGE = (-0.485, 1.515) STEPS = 100 SETTLING_TIME = 0.1 -#kill_camtool() -check_camtool() -print camtool.getCameras() - -#camtool.start("SINBD01-DSCR010") -camtool.start(CAMERA) -camtool.stream.waitCacheChange(10000) -print camtool.value.identifiers - -#plot(camtool.getValue("y_fit_gauss_function")) -m=camtool.getDataMatrix() -x = camtool.stream.getChild("x_fit_mean") -y = camtool.stream.getChild("y_fit_mean") +print cam_server.cameras +cam_server.start(CAMERA) +wait_cam_server_message() +print cam_server.value.identifiers +m=cam_server.getDataMatrix() +x = cam_server.stream.getChild("x_fit_mean") +y = cam_server.stream.getChild("y_fit_mean") """ ax = create_averager(x, 5, -1, "X Fit") @@ -56,21 +50,21 @@ except: try: laser_off() #save_dataset("/Background", m.read()) - #mscan (camtool.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz + #mscan (cam_server.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz tscan(m, 10, 1.0) # 10 samples every 0.2 s -> For machine at 1Hz laser_on() #tscan((m, x, y), 10, 1.0) # 10 samples every 1.0 s - #mscan (camtool.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s - #mscan (camtool.stream,(m, x, y), 50) # Saves firs 50 frames + #mscan (cam_server.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s + #mscan (cam_server.stream,(m, x, y), 50) # Saves firs 50 frames #lscan(quad, (m, x, y), RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) - readables = camtool.stream.getReadables().clone() + [bpm, ict] - readables.remove(camtool.stream.getChild("image")) + readables = cam_server.stream.getReadables().clone() + [bpm, ict] + readables.remove(cam_server.stream.getChild("image")) readables.insert(0,m) lscan(quad, readables, RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) finally: quad.close() - camtool.stop() + cam_server.stop() diff --git a/script/Diagnostics/Camtoolreadout_for_WSC_comparison.py b/script/Diagnostics/Camtoolreadout_for_WSC_comparison.py index 790d916..6673f05 100644 --- a/script/Diagnostics/Camtoolreadout_for_WSC_comparison.py +++ b/script/Diagnostics/Camtoolreadout_for_WSC_comparison.py @@ -1,6 +1,6 @@ import ch.psi.pshell.epics.ControlledVariable as ControlledVariable -#Easy script to read the camtool camera data and save it +#Easy script to read the camera data and save it # #CAMERA = "S10DI01-DSCR020" #"simulation" @@ -16,23 +16,19 @@ WirePos = "SINDI01-DWSC090:MOTOR_1.RBV" #STEPS = 100 #SETTLING_TIME = 1 -#kill_camtool() -check_camtool() -print camtool.getCameras() +print cam_server.cameras +cam_server.start(CAMERA) +wait_cam_server_message() +print cam_server.value.identifiers -#camtool.start("SINBD01-DSCR010") -camtool.start(CAMERA) -camtool.stream.waitCacheChange(10000) -print camtool.value.identifiers - -#plot(camtool.getValue("y_fit_gauss_function")) -m=camtool.getDataMatrix() -x = camtool.stream.getChild("x_fit_mean") -y = camtool.stream.getChild("y_fit_mean") -x_profile = camtool.stream.getChild("x_profile") -y_profile = camtool.stream.getChild("y_profile") -x_axis = camtool.stream.getChild("x_axis") -y_axis = camtool.stream.getChild("y_axis") +#plot(cam_server.getValue("y_fit_gauss_function")) +m=cam_server.getDataMatrix() +x = cam_server.stream.getChild("x_fit_mean") +y = cam_server.stream.getChild("y_fit_mean") +x_profile = cam_server.stream.getChild("x_profile") +y_profile = cam_server.stream.getChild("y_profile") +x_axis = cam_server.stream.getChild("x_axis") +y_axis = cam_server.stream.getChild("y_axis") """ ax = create_averager(x, 5, -1, "X Fit") @@ -67,22 +63,22 @@ except: try: #laser_off() #save_dataset("/Background", m.read()) - #mscan (camtool.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz + #mscan (cam_server.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz #tscan(m, 10, 0.2) # 10 samples every 0.2 s -> For machine at 1Hz #laser_on() #tscan((m, x, y), 10, 1.0) # 10 samples every 1.0 s - #mscan (camtool.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s - #mscan (camtool.stream,(m, x, y), 50) # Saves firs 50 frames + #mscan (cam_server.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s + #mscan (cam_server.stream,(m, x, y), 50) # Saves firs 50 frames #lscan(quad, (m, x, y), RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) - #readables = camtool.stream.getReadables().clone() + [bpm, ict] - #readables.remove(camtool.stream.getChild("image")) + #readables = cam_server.stream.getReadables().clone() + [bpm, ict] + #readables.remove(cam_server.stream.getChild("image")) #readables.insert(0,m) # lscan(quad, readables, RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) #tscan((m, x_profile, y_profile, x_axis, y_axis, bpm, wcs), 10, 1.0) #Saves 10 samples waiting 1.0 s between them tscan((m, x_profile, y_profile, x_axis, y_axis, bpm, wcs), 10, 1) finally: # quad.close() - camtool.stop() + cam_server.stop() diff --git a/script/Diagnostics/Laser_position_scan.py b/script/Diagnostics/Laser_position_scan.py index 8ab22fd..65759ee 100644 --- a/script/Diagnostics/Laser_position_scan.py +++ b/script/Diagnostics/Laser_position_scan.py @@ -9,19 +9,16 @@ RANGE = (-3.0, 0.0) STEPS = 100 SETTLING_TIME = 1 -#kill_camtool() -check_camtool() -print camtool.getCameras() +print cam_server.cameras +cam_server.start(CAMERA) +wait_cam_server_message() +print cam_server.value.identifiers -#camtool.start("SINBD01-DSCR010") -camtool.start(CAMERA) -camtool.stream.waitCacheChange(10000) -print camtool.value.identifiers -#plot(camtool.getValue("y_fit_gauss_function")) -m=camtool.getDataMatrix() -x = camtool.stream.getChild("x_fit_mean") -y = camtool.stream.getChild("y_fit_mean") +#plot(cam_server.getValue("y_fit_gauss_function")) +m=cam_server.getDataMatrix() +x = cam_server.stream.getChild("x_fit_mean") +y = cam_server.stream.getChild("y_fit_mean") """ ax = create_averager(x, 5, -1, "X Fit") @@ -56,21 +53,21 @@ except: try: laser_off() #save_dataset("/Background", m.read()) - #mscan (camtool.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz + #mscan (cam_server.stream, m, 10) #Saves 10 next frames -> For machine at 10 -> 100Hz tscan(m, 10, 1.0) # 10 samples every 0.2 s -> For machine at 1Hz laser_on() #tscan((m, x, y), 10, 1.0) # 10 samples every 1.0 s - #mscan (camtool.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s - #mscan (camtool.stream,(m, x, y), 50) # Saves firs 50 frames + #mscan (cam_server.stream,(m, x, y), -1, 5.0) #Saves all frames received in 5s + #mscan (cam_server.stream,(m, x, y), 50) # Saves firs 50 frames #lscan(quad, (m, x, y), RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) - readables = camtool.stream.getReadables().clone() + [bpm, ict] - readables.remove(camtool.stream.getChild("image")) + readables = cam_server.stream.getReadables().clone() + [bpm, ict] + readables.remove(cam_server.stream.getChild("image")) readables.insert(0,m) lscan(quad, readables, RANGE[0], RANGE[1], STEPS, latency=SETTLING_TIME) finally: quad.close() - camtool.stop() + cam_server.stop() diff --git a/script/RFscan/GunEnergyScan.py b/script/RFscan/GunEnergyScan.py index e24210c..69ce802 100644 --- a/script/RFscan/GunEnergyScan.py +++ b/script/RFscan/GunEnergyScan.py @@ -1,8 +1,8 @@ import ch.psi.pshell.epics.Positioner as Positioner import ch.psi.pshell.epics.Camtool as Camtool -dry_run = True -do_elog = False +dry_run = False +do_elog = True is_panel = get_exec_pars().source != CommandSource.ui #must be check before run run("CPython/wrapper") @@ -57,13 +57,19 @@ phase.config.save() phase.initialize() phase0 = phase.read() -#Camtool setup -kill_camtool() -check_camtool() -camtool.start(camera_name) -wait_camtool_message() -x = camtool.stream.getChild("x_fit_mean") -dx = camtool.stream.getChild("x_fit_standard_deviation") +##Camtool setup +#kill_camtool() +#check_camtool() +#camtool.start(camera_name) +#wait_camtool_message() +#x = camtool.stream.getChild("x_fit_mean") +#dx = camtool.stream.getChild("x_fit_standard_deviation") + +#Camera setup +cam_server.start(camera_name) +wait_cam_server_message() +x = cam_server.stream.getChild("x_fit_mean") +dx = cam_server.stream.getChild("x_fit_standard_deviation") #Creating averagers x_averager = create_averager(x, nb, -1) # -1 event based, waits for the next value @@ -88,7 +94,8 @@ try: finally: phase.write(phase0) phase.close() - camtool.stop() # stops camtool but does not close it camtool is a global object + #camtool.stop() # stops camtool but does not close it camtool is a global object + cam_server.stop() # stops cam_server but does not close it cam_server is a global object ph = r.getPositions(0) p = [A * val.mean + B for val in r.getReadable(0)] @@ -99,13 +106,13 @@ try: i_max = p.index(max(p)) i_min = dp.index(min(dp)) min_i, max_i = max(i_max-5, 0), min(i_max+6, len(p)) - (ph_p_max, p_max, ph_p_fit, p_fit, p_res) = extremum(ph[min_i:max_i], p[min_i:max_i]) + (ph_p_max, p_max, ph_p_fit, p_fit, p_R2) = extremum(ph[min_i:max_i], p[min_i:max_i]) min_i, max_i = max(i_min-5, 0), min(i_min+6, len(dp)) - (ph_dp_min, dp_min, ph_dp_fit, dp_fit, dp_res) = extremum(ph[min_i:max_i], dp[min_i:max_i]) + (ph_dp_min, dp_min, ph_dp_fit, dp_fit, dp_R2) = extremum(ph[min_i:max_i], dp[min_i:max_i]) plt.addSeries(LinePlotErrorSeries("Momentum Fit", plt.getSeries(0).color)) plt.addSeries(LinePlotErrorSeries("Momentum Spread Fit", plt.getSeries(1).color, 2)) plt.getSeries(2).setData(ph_p_fit, p_fit) - plt.getSeries(3).setData(ph_dp_fit, dp_fit) + plt.getSeries(3).setData(ph_dp_fit, dp_fit) plt.getSeries(2).setPointsVisible(False) plt.getSeries(3).setPointsVisible(False) plt.addMarker(ph_p_max, plt.AxisId.X, "%3.2f" % ph_p_max, plt.getSeries(0).color) @@ -117,11 +124,11 @@ except: save_dataset(get_exec_pars().group + "/p", p) set_attribute(get_exec_pars().group + "/p", "p max", p_max) set_attribute(get_exec_pars().group + "/p", "p max phase", ph_p_max) -set_attribute(get_exec_pars().group + "/p", "p fit residuals", p_res) +set_attribute(get_exec_pars().group + "/p", "p fit R2", p_R2) save_dataset(get_exec_pars().group + "/dp", dp) set_attribute(get_exec_pars().group + "/dp", "dp min", dp_min) set_attribute(get_exec_pars().group + "/dp", "dp min phase", ph_dp_min) -set_attribute(get_exec_pars().group + "/dp", "dp fit residuals", dp_res) +set_attribute(get_exec_pars().group + "/dp", "dp fit R2", dp_R2) #Elog entry if do_elog: diff --git a/script/RFscan/SchottkyScan.py b/script/RFscan/SchottkyScan.py index 8527a66..1c0195b 100644 --- a/script/RFscan/SchottkyScan.py +++ b/script/RFscan/SchottkyScan.py @@ -3,27 +3,30 @@ import ch.psi.pshell.epics.ChannelDouble as ChannelDouble dry_run = False do_elog = True - -if get_exec_pars().source == CommandSource.ui: - start = -50.0 - stop = 150.0 - step = 2.0 - nb = 2 - lat = 0.120 - plt = None -else: +is_panel = get_exec_pars().source != CommandSource.ui #must be check before run +if is_panel: start = args[0] stop = args[1] step = args[2] nb = int(args[3]) lat = args[4] plt = args[5] - -if plt is not None: - plt.clear() - plt.addSeries(LinePlotErrorSeries("Values")) - plt.getAxis(plt.AxisId.X).setLabel("Gun Beam Phase (deg)") - plt.getAxis(plt.AxisId.Y).setLabel("SINEG01-DICT215:B1_CHARGE") +else: + start = -50.0 + stop = 150.0 + step = 1.0 + nb = 2 + lat = 0.010 + plt = plot(None, title="Output")[0] + +#Plot setup +plt.clear() +plt.removeMarker(None) +plt.setStyle(plt.Style.ErrorY) +plt.addSeries(LinePlotErrorSeries("Charge", Color.red)) +plt.getAxis(plt.AxisId.X).setLabel("Gun Beam Phase (deg)") +plt.getAxis(plt.AxisId.Y).setLabel("SINEG01-DICT215:B1_CHARGE (pC)") +plt.setLegendVisible(True) if dry_run: bph = Positioner("Beam phase", "SINEG01-RSYS:SET-BEAM-PHASE-SIM", "SINEG01-RSYS:SET-BEAM-PHASE-SIM") @@ -42,7 +45,6 @@ else: q = ChannelDouble("Charge", "SINEG01-DICT215:B1_CHARGE") q.initialize() q.monitored=True - bph.config.minValue = -360.0 bph.config.maxValue = 360.0 bph.config.precision = 3 @@ -52,31 +54,52 @@ bph.config.save() bph.initialize() rph.initialize() rph.monitored=True - bph0 = bph.read() rph0 = rph.read() +#Creating averagers +rph_averager = create_averager(rph, nb, 0.1) +q_averager = create_averager(q, nb, 0.1) +q_averager.monitored=True + #Record callback: uptate of output plot def after_sample(record, scan): - if plt is not None: - plt.getSeries(0).appendData(record.positions[0], record.values[1].mean, record.values[1].stdev) + plt.getSeries(0).appendData(record.positions[0], record.values[1].mean, record.values[1].stdev) +#The scan loop try: - rph_averager = create_averager(rph, nb, 0.1) # Set polling time to -1 for BS data to get all messages - q_averager = create_averager(q, nb, 0.1) - q_averager.monitored=True r = lscan(bph, (rph_averager, q_averager), start, stop, step, latency=lat, after_read = after_sample) - beamphase = r.getPositions(0) - rfphase = [val.mean for val in r.getReadable(0)] - rfphaserms = [val.stdev for val in r.getReadable(0)] - charge = [val.mean for val in r.getReadable(1)] - chargerms = [val.stdev for val in r.getReadable(1)] finally: rph.write(rph0) bph.close() rph.close() q.close() #st.close() +beamphase = r.getPositions(0) +rfphase = [val.mean for val in r.getReadable(0)] +rfphaserms = [val.stdev for val in r.getReadable(0)] +charge = [val.mean for val in r.getReadable(1)] +chargerms = [val.stdev for val in r.getReadable(1)] + +#Fitting and plotting +i, a, b = 0, 0, 0 +while charge[i] < (max(charge) * 0.20) : a = i; i = i + 1 +while charge[i] < (max(charge) * 0.80) : b = i; i = i + 1 +x = beamphase[a:b+1] +y = charge[a:b+1] +p = (a0, a1) = fit_polynomial(y, x, 1) +f = PolynomialFunction(p) +x1 = -a0 / a1 if a1 != 0 else 0.0 +x2 = beamphase[charge.index(max(charge))] +x_fit = frange(x1, x2, (x2-x1), True) +y_fit = [f.value(val) for val in x_fit] +plt.addSeries(LinePlotErrorSeries("Fit", Color.green)) +plt.getSeries(1).setData(to_array(x_fit, 'd'), y_fit, [0.0] * len(x_fit)) +plt.getSeries(1).setPointsVisible(False) + +#Setting the return value +bph_ref_guess = x1 +set_return([bph_ref_guess]) #Elog entry if do_elog: @@ -93,6 +116,7 @@ if do_elog: else: log_msg = log_msg + "Collimator: " + str(caget("SLGTV-LMTO-M053:MOT-ACT-POS")) + "\n" log_msg = log_msg + "Charge: %0.2f" % caget("SINEG01-DICT215:B1_CHARGE-OP") + " pC at %0.2f" % bph0 + " deg beam phase\n" + log_msg = log_msg + "Ref. phase: %0.2f" % x1 + " deg \n" attachments = [] if plt is not None: sleep(0.1) #Give some time to plot to be finished - it is not sync with acquisition @@ -100,7 +124,3 @@ if do_elog: plt.saveSnapshot(file_name , "png") attachments = [file_name] elog("Schottky scan", log_msg, attachments) - -#Setting the return value -bph_ref_guess = 0.0 -set_return([bph_ref_guess]) diff --git a/script/RFscan/phase_scan_caqtdm.py b/script/RFscan/phase_scan_caqtdm.py index e669c74..52730f7 100644 --- a/script/RFscan/phase_scan_caqtdm.py +++ b/script/RFscan/phase_scan_caqtdm.py @@ -3,14 +3,13 @@ import ch.psi.pshell.epics.ChannelDouble as ChannelDouble dry_run = False do_elog = True - -if get_exec_pars().source == CommandSource.ui: - station = "SINSB01" - bpm_ch = "S10BD01-DBPM020" -else: +is_panel = get_exec_pars().source != CommandSource.ui +if is_panel: station = args[0] bpm_ch = args[1] - +else: + station = "STEST01" + bpm_ch = "SINBC02-DBPM140" start = caget(station + "-RSYS:SET-SCAN-START") stop = caget(station + "-RSYS:SET-SCAN-STOP") step = caget(station + "-RSYS:SET-SCAN-STEP") @@ -18,10 +17,8 @@ lat = caget(station + "-RSYS:SET-SCAN-WAIT-TIME") nb = caget(station + "-RSYS:SET-NUM-AVERAGE") disp = caget(bpm_ch + ":DISPERSION") energy0 = caget(bpm_ch + ":ENERGY") - A = energy0 / disp / 1e3 B = energy0 - phase = Positioner("Phase", station + "-RSYS:SET-VSUM-PHASE", station + "-RSYS:GET-VSUM-PHASE") phase.config.minValue =-360.0 phase.config.maxValue = 360.0 @@ -30,17 +27,15 @@ phase.config.rotation = False phase.config.resolution = 0.1 phase.initialize() V = ChannelDouble("Amplitude Readback", station + "-RSYS:GET-VSUM-AMPLT") +V.initialize() P = ChannelDouble("Power Readback", station + "-RSYS:GET-KLY-POWER") +P.initialize() if dry_run: x = ChannelDouble("BPM-X", bpm_ch + ":X1-SIMU") else: x = ChannelDouble("BPM-X", bpm_ch + ":X1") -V.initialize() -P.initialize() x.initialize() - phase0 = phase.read() - caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", to_array([0.0],'d')) caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", to_array([0.0],'d')) caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", float('nan')) @@ -57,6 +52,7 @@ def after(rec): caput(station + "-RSYS:GET-PHASE-ARRAY", to_array(arr_phase, 'd')) caput(station + "-RSYS:GET-ENERGY-ARRAY", to_array(arr_energy,'d')) +#scan and plot try: phase.write(start) time.sleep(1.0) @@ -71,48 +67,44 @@ try: (fit_amplitude, fit_phase_deg, fit_offset, ph_crest, fit_x, fit_y) = hfitoff(energy , rf_phase) except: raise Exception("Fit failure") - # This only works when pshell is visible not in server mode to be fixed - plt = plot(None,name="data")[0] + plt = plot(None,name="phase scan")[0] plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d')) - plt.getSeries(0).setPointSize(8) + plt.getSeries(0).setPointSize(6) plt.getSeries(0).setLinesVisible(False) plt.addSeries(LinePlotSeries("fit")) plt.getSeries(1).setData(fit_x, fit_y) plt.getSeries(1).setPointsVisible(False) plt.setLegendVisible(True) - caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", ph_crest) - caput(station + "-RSYS:GET-ONCREST-E-GAIN", fit_amplitude) - caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", fit_x) - caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", fit_y) phase.write(ph_crest) time.sleep(lat) Ampl = V.read() Power = P.read() + caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", ph_crest) + caput(station + "-RSYS:GET-ONCREST-E-GAIN", fit_amplitude) caput(station + "-RSYS:GET-ONCREST-VSUM-AMPLT", Ampl) caput(station + "-RSYS:GET-ONCREST-KLY-POWER", Power) + caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", fit_x) + caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", fit_y) finally: phase.write(phase0) phase.close() V.close() P.close() x.close() - -phase_offset = 90.0 - ph_crest +phase_offset = 90.0 - ph_crest # should take into account chicane delays which will be stored in :GET-VSUM-PHASE-OFFSET-CORR amplitude_scale = fit_amplitude / Ampl -power_scale = Power / math.pow(fit_amplitude,2) - +power_scale = Power / fit_amplitude**2 if fit_amplitude != 0 else 0.0 caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC", phase_offset) caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC", amplitude_scale) caput(station + "-RSYS:SET-VOLT-POWER-SCALE-CALC", power_scale) - if do_elog: title = "Phase scan" + station log_msg = "Data file: " + get_exec_pars().path + "\n" log_msg = log_msg + "On-crest VS phase: %0.2f" % ph_crest + " deg \n" - log_msg = log_msg + "Energy Gain: %0.3f" % fit_amplitude + " MeV \n" - log_msg = log_msg + "VS -phase Offset: %0.2f" % phase_offset + " deg \n" - log_msg = log_msg + "Amplitude Scale: %0.3f" % amplitude_scale + " MV \n" - log_msg = log_msg + "Power Scale: %0.3f" % power_scale + " MW/MV^2" + log_msg = log_msg + "Energy gain: %0.3f" % fit_amplitude + " MeV \n" + log_msg = log_msg + "VS-phase offset: %0.2f" % phase_offset + " deg \n" + log_msg = log_msg + "Amplitude scale: %0.3f" % amplitude_scale + " MV \n" + log_msg = log_msg + "Power scale: %0.3f" % power_scale + " MW/MV^2" attachments = get_plot_snapshots() - elog(title, log_msg, attachments) + elog(title, log_msg, attachments) \ No newline at end of file diff --git a/script/RFscan/phase_scan_caqtdm_set.py b/script/RFscan/phase_scan_caqtdm_set.py index ca99403..21160e1 100644 --- a/script/RFscan/phase_scan_caqtdm_set.py +++ b/script/RFscan/phase_scan_caqtdm_set.py @@ -1,40 +1,35 @@ do_elog = True - -if get_exec_pars().source == CommandSource.ui: - station = "STEST01" -else: +is_panel = get_exec_pars().source != CommandSource.ui +if is_panel: station = args[0] - +else: + station = "STEST01" phase_set = caget(station + "-RSYS:PHASE-SET") ampli_set = caget(station + "-RSYS:AMPLT-SET") power_set = caget(station + "-RSYS:POWER-SET") - n = 0 if (phase_set == 'True'): phase_offset = caget(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC") phase_offset_old = caget(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE") caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", phase_offset) - print phase_set n = n + 1 if (ampli_set == 'True'): amplitude_scale = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC") amplitude_scale_old = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE") caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE", amplitude_scale) - print ampli_set n = n + 1 if (power_set == 'True'): power_scale = caget(station + "-RSYS:SET-VOLT-POWER-SCALE-CALC") power_scale_old = caget(station + "-RSYS:SET-VOLT-POWER-SCALE") caput(station + "-RSYS:SET-VOLT-POWER-SCALE", power_scale) - print power_set n = n + 1 -caput(station + "-RSYS:CMD-LOAD-CALIB-BEAM", 1) - -if do_elog == True and n > 0: - title = "Set RF calibration:" + station - log_msg = "" - if (phase_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE: %0.2f" % phase_offset + " deg (was %0.2f" % phase_offset_old + " deg)\n" - if (ampli_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-AMPLT-SCALE: %0.3f" % amplitude_scale + " MV (was %0.3f" % amplitude_scale_old + " MV)\n" - if (power_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VOLT-POWER-SCALE: %0.5f" % power_scale + " MW/MV^2 (was %0.5f" % power_scale_old + " MW/MV^2)" - attachments = [] - elog(title, log_msg, attachments) \ No newline at end of file +if n > 0: + caput(station + "-RSYS:CMD-LOAD-CALIB-BEAM", 1) + if do_elog == True: + title = "Set RF calibration:" + station + log_msg = "" + if (phase_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE: %0.2f" % phase_offset + " deg (was %0.2f" % phase_offset_old + " deg)\n" + if (ampli_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-AMPLT-SCALE: %0.3f" % amplitude_scale + " MV (was %0.3f" % amplitude_scale_old + " MV)\n" + if (power_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VOLT-POWER-SCALE: %0.5f" % power_scale + " MW/MV^2 (was %0.5f" % power_scale_old + " MW/MV^2)" + attachments = [] + elog(title, log_msg, attachments) diff --git a/script/local.py b/script/local.py index 10c1a9e..73b84b1 100755 --- a/script/local.py +++ b/script/local.py @@ -278,6 +278,36 @@ avy = create_averager(comy, 5, 0.001) ################################################################################################### # Camera server ################################################################################################### +def wait_cam_server_message(number_messages = 1, timeout = 10000): + for i in range (number_messages): + if not cam_server.stream.waitCacheChange(timeout): + raise Exception("Timeout receiving from camera server") + +def get_cam_server_stats(number_images=1, async = True, interval=-1, good_region = False): + ret = [] + wait_cam_server_message() + prefix = "gr_" if good_region else "" + for ident in [prefix+"x_center_of_mass", prefix+"y_center_of_mass", prefix+"x_rms", prefix+"y_rms"]: + child = cam_server.stream.getChild(ident) + av = create_averager(child, number_images, interval) + av.monitored = async + ret.append(av) + return ret + +def wait_cam_server_background(background, timeout = 10000): + start = time.time() + while True: + processing_parameters = cam_server.getProcessingParameters() + if (processing_parameters is not None) and (str(background) == processing_parameters["image_background"]): + return + if (time.time()-start) > timeout/1000: + raise Exception("Timeout waiting for camera server background: " + str(background)) + time.sleep(0.01) + +################################################################################################### +# Camtool +################################################################################################### + def wait_camtool_message(number_messages = 1, timeout = 10000): for i in range (number_messages): if not camtool.stream.waitCacheChange(timeout): @@ -340,7 +370,111 @@ def check_camtool(): raise Exception("Error starting camtool process") time.sleep(3.0) +################################################################################################### +# Camera scans +################################################################################################### +# mode = "server", "camtool", "bpm" or "direct" +def setup_camera_scan(): + global mode, camera_name, number_images, use_background, multiple_background, number_backgrounds, dry_run, laser_was_on + laser_was_on = is_laser_on() + multiple_background = multiple_background and use_background + if mode == "server": + cam_server.start(camera_name) + if use_background: + if not dry_run: + laser_off() + bg=cam_server.captureBackground(1 if multiple_background else number_backgrounds) + cam_server.setBackgroundSubtraction(True) + if not multiple_background: wait_cam_server_background(bg) + else: + cam_server.setBackgroundSubtraction(False) + + elif mode == "camtool": + #kill_camtool() + check_camtool() + if use_background: + if not dry_run: + laser_off() + if not multiple_background: + camtool.stop() + camtool.grabBackground(camera_name, number_backgrounds) + camtool.start(camera_name, 0, use_background, None, 0.0, None) + else: + if source == "bpm": + run("Devices/BpmStats") + add_device(BpmStats("image_stats", camera_name), True) + multiple_background = False + use_background = False + else: + run("Devices/ImageStats") + add_device(ImageStats("image_stats", camera_name), True) + add_device(image_stats.source, True) + image_stats.enableBackground(use_background) + if use_background: + laser_off() + if not multiple_background: + image_stats.grabBackground(number_backgrounds) + image_stats.setNumberOfImages(max(number_images,1)) + + if not multiple_background: + if not dry_run: + laser_on() + +def before_sample_camera_scan(): + global mode, camera_name, number_images, use_background, multiple_background, number_backgrounds, dry_run + if mode == "server": + if multiple_background: + bg = cam_server.captureBackground(number_backgrounds) + wait_cam_server_background(bg) + wait_cam_server_message(number_images) + elif mode == "camtool": + if multiple_background: + camtool.stop() + camtool.grabBackground(camera_name, number_backgrounds) + camtool.start(camera_name, 0, use_background, None, 0.0, None) + if not dry_run: + laser_on() + wait_camtool_message(number_images) #Wait filing the averager cache + else: + if multiple_background: + image_stats.grabBackground(number_backgrounds) + laser_on() + image_stats.update() + +def after_sample_camera_scan(): + if multiple_background: + if not dry_run: + laser_off() + +def get_camera_scan_sensors(): + global mode, camera_name, number_images, use_background, multiple_background, number_backgrounds, dry_run + if mode == "server": + sensors = get_cam_server_stats(number_images, good_region=use_good_region) + if plot_image: + sensors.append(cam_server.getDataMatrix()) + elif mode == "camtool": + sensors = get_camtool_stats(number_images, good_region=use_good_region) + if plot_image: + sensors.append(camtool.getDataMatrix()) + else: + sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] + if plot_image and (source == "direct"): + sensors.append(image_stats.source.getDataMatrix()) + return sensors + +def end_camera_scan(): + global mode, camera_name, number_images, use_background, multiple_background, number_backgrounds, dry_run, laser_was_on + #if mode == "server": cam_server.stop() + #elif mode == "camtool": camtool.stop() + #elif mode == "camtool": camtool.stop() + #else: image_stats.stop() + if not dry_run: + if laser_was_on: + laser_on() + else: + laser_off() + pass ################################################################################################### #CAS ################################################################################################### diff --git a/script/test/CamtoolBug.py b/script/test/CamtoolBug.py deleted file mode 100644 index 6498ddc..0000000 --- a/script/test/CamtoolBug.py +++ /dev/null @@ -1,7 +0,0 @@ - -class AnalogInput(ReadonlyRegisterBase): - def doRead(self): - return cam_server.getValue("x_rms") - -add_device(AnalogInput("tst"), True) -tst.setPolling(10) \ No newline at end of file diff --git a/script/test/CamtoolTest.py b/script/test/CamtoolTest.py deleted file mode 100644 index f186f1a..0000000 --- a/script/test/CamtoolTest.py +++ /dev/null @@ -1,13 +0,0 @@ -c = {"reference_marker":[0, 0, 100, 100]} -camtool.setCalibration("SLG-LCAM-C021", c) - - -camtool.getGeometry("SINEG01-DSCR350") - -for c in camtool.getCameras(): - if c not in ["example", "simulation"]: - try: - print c , " - ", camtool.getGeometry(c) - except: - print c - time.sleep(0.2) \ No newline at end of file diff --git a/script/test/GunEnergyScan_dv.py b/script/test/GunEnergyScan_dv.py index eeb3d31..ff2f01b 100644 --- a/script/test/GunEnergyScan_dv.py +++ b/script/test/GunEnergyScan_dv.py @@ -56,13 +56,12 @@ phase.config.save() phase.initialize() phase0 = phase.read() -#Camtool setup -kill_camtool() -check_camtool() -camtool.start(camera_name) -wait_camtool_message() -x = camtool.stream.getChild("x_fit_mean") -dx = camtool.stream.getChild("x_fit_standard_deviation") +#Camera setup +cam_server.start(camera_name) +wait_cam_server_message() +x = cam_server.stream.getChild("x_fit_mean") +dx = cam_server.stream.getChild("x_fit_standard_deviation") + #Creating averagers x_averager = create_averager(x, nb, -1) # -1 event based, waits for the next value @@ -87,7 +86,7 @@ try: finally: phase.write(phase0) phase.close() - camtool.stop() # stops camtool but does not close it camtool is a global object + cam_server.stop() # stops cam_server but does not close it cam_server is a global object ph = r.getPositions(0) p = [A * val.mean + B for val in r.getReadable(0)] diff --git a/script/test/SchottkyScan_dv.py b/script/test/SchottkyScan_dv.py index a83d012..5a3ceb3 100644 --- a/script/test/SchottkyScan_dv.py +++ b/script/test/SchottkyScan_dv.py @@ -2,9 +2,8 @@ import ch.psi.pshell.epics.Positioner as Positioner import ch.psi.pshell.epics.ChannelDouble as ChannelDouble dry_run = True -do_elog = False +do_elog = True is_panel = get_exec_pars().source != CommandSource.ui #must be check before run - if is_panel: start = args[0] stop = args[1] @@ -15,18 +14,18 @@ if is_panel: else: start = -50.0 stop = 150.0 - step = 10.0 + step = 1.0 nb = 2 - lat = 0.120 + lat = 0.010 plt = plot(None, title="Output")[0] - + #Plot setup plt.clear() plt.removeMarker(None) plt.setStyle(plt.Style.ErrorY) plt.addSeries(LinePlotErrorSeries("Charge", Color.red)) plt.getAxis(plt.AxisId.X).setLabel("Gun Beam Phase (deg)") -plt.getAxis(plt.AxisId.Y).setLabel("SINEG01-DICT215:B1_CHARGE") +plt.getAxis(plt.AxisId.Y).setLabel("SINEG01-DICT215:B1_CHARGE (pC)") plt.setLegendVisible(True) if dry_run: @@ -55,7 +54,6 @@ bph.config.save() bph.initialize() rph.initialize() rph.monitored=True - bph0 = bph.read() rph0 = rph.read() @@ -77,7 +75,6 @@ finally: rph.close() q.close() #st.close() - beamphase = r.getPositions(0) rfphase = [val.mean for val in r.getReadable(0)] rfphaserms = [val.stdev for val in r.getReadable(0)] @@ -85,22 +82,21 @@ charge = [val.mean for val in r.getReadable(1)] chargerms = [val.stdev for val in r.getReadable(1)] #Fitting and plotting -#try: -i, i_min, i_max = 0, 0, 0 -while charge[i] < max(charge) * 0.10 : i_min = i; i = i + 1 -while charge[i] < max(charge) * 0.60 : i_max = i; i = i + 1 -readable = charge[i_min:i_max] -positions = beamphase[i_min:i_max] -pars_polynomial = (a0, a1) = fit_polynomial(readable, positions, 1) -fitted_polynomial_function = PolynomialFunction(pars_polynomial) -charge_fit = [] -for x in beamphase: charge_fit.append(fitted_polynomial_function.value(x)) -plt.addSeries(LinePlotSeries("Fit", plt.getSeries(0).color)) -plt.getSeries(1).setData(beamphase, charge_fit) +i, a, b = 0, 0, 0 +while charge[i] < (max(charge) * 0.20) : a = i; i = i + 1 +while charge[i] < (max(charge) * 0.80) : b = i; i = i + 1 +x = beamphase[a:b+1] +y = charge[a:b+1] +p = (a0, a1) = fit_polynomial(y, x, 1) +f = PolynomialFunction(p) +x1 = -a0 / a1 if a1 != 0 else 0.0 +x2 = beamphase[charge.index(max(charge))] +x_fit = frange(x1, x2, (x2-x1), True) +y_fit = [f.value(val) for val in x_fit] +plt.addSeries(LinePlotErrorSeries("Fit", Color.blue)) +plt.getSeries(1).setData(to_array(x_fit, 'd'), y_fit, [0.0] * len(x_fit)) plt.getSeries(1).setPointsVisible(False) - #plt.addMarker(ph_p_max, plt.AxisId.X, "%3.2f" % ph_p_max, plt.getSeries(0).color) -#except: -# raise Exception("Fit failure") +plt.addMarker(x1, plt.AxisId.X, "%3.2f" % x1, plt.getSeries(1).color) #Elog entry if do_elog: @@ -126,5 +122,5 @@ if do_elog: elog("Schottky scan", log_msg, attachments) #Setting the return value -bph_ref_guess = 0.0 +bph_ref_guess = x1 set_return([bph_ref_guess]) diff --git a/script/test/TestAlignmentScan.py b/script/test/TestAlignmentScan.py index 0038269..40c1fbb 100644 --- a/script/test/TestAlignmentScan.py +++ b/script/test/TestAlignmentScan.py @@ -11,27 +11,27 @@ import datetime import ch.psi.utils.Chrono as Chrono -mode = "camtool" # "camtool", "bpm" or "direct" +mode = "server" # "server", "camtool", "bpm" or "direct" camera_name = "simulation" #camera_name = "SLG-LCAM-C041" use_good_region=False +dry_run = True if True: #get_exec_pars().source == CommandSource.ui: I1 = 95.0 I2 = 100.0 - dI = 2.5 + dI = 1.0 settling_time = 0.1 plot_image = False number_images = 3 - use_background = False - multiple_background = False + use_background = True + multiple_background = True number_backgrounds = 3 do_elog = False centroid_excursion_plot = True else: centroid_excursion_plot = False -check_camtool() #laser_was_on = is_laser_on() positioner = DummyPositioner("positioner") @@ -44,69 +44,20 @@ print "Parameters: ", I1, I2, dI, settling_time, plot_image, number_images, use_ plot_name = datetime.datetime.fromtimestamp(time.time()).strftime('%H%M%S') -if mode == "camtool": - if use_background: - #laser_off() - if not multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - #camtool.stop() - #camtool.startPipeline(camera_name, 0, use_background, None, 0.0, None) - #camtool.startReceiver(); - c = Chrono() - - print "t1 = " , c.ellapsed - camtool.start(camera_name, 0, use_background, None, 0.0, None) - print "t2 = " , c.ellapsed - if camtool.value is not None: print "Started " , camtool.value.getTimestamp() - wait_camtool_message() - print "t3 = " , c.ellapsed - print "OK" -else: - if mode == "bpm": - add_device(BpmStats("image_stats", camera_name), True) - else: - add_device(ImageStats(PsiCamera("image_stats", camera_name)), True) - multiple_background = False - use_background = False - image_stats.setNumberOfImages(max(number_images,1)) + +setup_camera_scan() #switch_off_magnets() -# add here gun phase setting see wiki page -def before_sample(): - if mode == "camtool": - if multiple_background: - camtool.stop() - camtool.grabBackground(camera_name, number_backgrounds) - camtool.start(camera_name, 0, use_background, None, 0.0, None) - #laser_on() - wait_camtool_message(number_images) #Wait filing the averager cache - else: - image_stats.update() - -def after_sample(): - if multiple_background: - #laser_off() - pass r = None -#if not multiple_background: -# laser_on() -try: - if mode == "camtool": - print "Getting sensors" - sensors = get_camtool_stats(number_images, good_region=use_good_region) - print "Sensors ok" - if plot_image: - sensors.append(camtool.getDataMatrix()) - else: - sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] - r = lscan(positioner, sensors , I1, I2, dI, settling_time, before_read = before_sample, after_read = after_sample) + +try: + sensors = get_camera_scan_sensors() + r = lscan(positioner, sensors , I1, I2, dI, settling_time, before_read = before_sample_camera_scan, after_read = after_sample_camera_scan) finally: - if mode == "camtool": camtool.stop() - #pass + end_camera_scan() positioner.write(original_gun_solenoid) #if laser_was_on: @@ -130,4 +81,5 @@ gsa_log_msg = gsa_log_msg + "\n\n" + r.print() if do_elog: elog("Gun solenoid current scan", gsa_log_msg , get_plot_snapshots()) +print gsa_log_msg set_return([r, hx, hy]) diff --git a/script/test/TestSeverity.py b/script/test/TestSeverity.py new file mode 100644 index 0000000..3efbddd --- /dev/null +++ b/script/test/TestSeverity.py @@ -0,0 +1,40 @@ +import ch.psi.pshell.epics.ChannelDouble as ChannelDouble +import ch.psi.pshell.epics.InvalidValueAction as InvalidValueAction +import java.lang.System as System + +invalid = ChannelDouble("invalid", "SARUN15-UIND030:INVALID-PV", -1, True, InvalidValueAction.Nullify) +avg = create_averager(invalid, 5, interval =2.0, name = "avg") + + +invalid.monitored = True +add_device(invalid, True) +add_device(avg, True) + + + + + + +""" +invalid.write(100.0) +#caput ("SARUN15-UIND030:INVALID-PV", 100) +print invalid.read() +print invalid.severity +""" + +""" +tspc = System.currentTimeMillis(); ts = invalid.timestamp; tsn = invalid.timestampNanos +print tspc +print ts +print tsn +print tspc - ts +#print invalid.takeTimestamped().severity +""" +""" +invalid.write(1000.0) +#caput ("SARUN15-UIND030:INVALID-PV", 1000) +print invalid.read() +print invalid.severity +""" + + diff --git a/script/test/phase_scan_caqtdm_dv.py b/script/test/phase_scan_caqtdm_dv.py new file mode 100644 index 0000000..8b8c316 --- /dev/null +++ b/script/test/phase_scan_caqtdm_dv.py @@ -0,0 +1,110 @@ +import ch.psi.pshell.epics.Positioner as Positioner +import ch.psi.pshell.epics.ChannelDouble as ChannelDouble + +dry_run = True +do_elog = False +is_panel = get_exec_pars().source != CommandSource.ui +if is_panel: + station = args[0] + bpm_ch = args[1] +else: + station = "STEST01" + bpm_ch = "SINBC02-DBPM140" +start = caget(station + "-RSYS:SET-SCAN-START") +stop = caget(station + "-RSYS:SET-SCAN-STOP") +step = caget(station + "-RSYS:SET-SCAN-STEP") +lat = caget(station + "-RSYS:SET-SCAN-WAIT-TIME") +nb = caget(station + "-RSYS:SET-NUM-AVERAGE") +disp = caget(bpm_ch + ":DISPERSION") +energy0 = caget(bpm_ch + ":ENERGY") +A = energy0 / disp / 1e3 +B = energy0 +phase = Positioner("Phase", station + "-RSYS:SET-VSUM-PHASE", station + "-RSYS:GET-VSUM-PHASE") +phase.config.minValue =-360.0 +phase.config.maxValue = 360.0 +phase.config.precision = 4 +phase.config.rotation = False +phase.config.resolution = 0.1 +phase.initialize() +V = ChannelDouble("Amplitude Readback", station + "-RSYS:GET-VSUM-AMPLT") +V.initialize() +P = ChannelDouble("Power Readback", station + "-RSYS:GET-KLY-POWER") +P.initialize() +if dry_run: + x = ChannelDouble("BPM-X", bpm_ch + ":X1-SIMU") +else: + x = ChannelDouble("BPM-X", bpm_ch + ":X1") +x.initialize() +phase0 = phase.read() +caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", to_array([0.0],'d')) +caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", to_array([0.0],'d')) +caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", float('nan')) +caput(station + "-RSYS:GET-ONCREST-VSUM-AMPLT", float('nan')) +caput(station + "-RSYS:GET-ONCREST-E-GAIN", float('nan')) +caput(station + "-RSYS:GET-ONCREST-KLY-POWER", float('nan')) + +#update the plot dynamically +arr_phase,arr_energy = [],[] +def after(rec): + global A, B + arr_phase.append(rec.positions[0]) + arr_energy.append(A * rec.values[0].mean + B) + caput(station + "-RSYS:GET-PHASE-ARRAY", to_array(arr_phase, 'd')) + caput(station + "-RSYS:GET-ENERGY-ARRAY", to_array(arr_energy,'d')) + +#scan and plot +try: + phase.write(start) + time.sleep(1.0) + x_averager = create_averager(x, nb, 0.100) + r = lscan(phase, x_averager, start, stop, step, latency=lat, after_read = after) + rf_phase = r.getPositions(0) + energy = [A * val.mean + B for val in r.getReadable(0)] + caput(station + "-RSYS:GET-ENERGY-ARRAY", to_array(energy, 'd')) + caput(station + "-RSYS:GET-PHASE-ARRAY", to_array(rf_phase,'d')) + try: + run("CPython/wrapper") + (fit_amplitude, fit_phase_deg, fit_offset, ph_crest, fit_x, fit_y) = hfitoff(energy , rf_phase) + except: + raise Exception("Fit failure") + # This only works when pshell is visible not in server mode to be fixed + plt = plot(None,name="phase scan")[0] + plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d')) + plt.getSeries(0).setPointSize(6) + plt.getSeries(0).setLinesVisible(False) + plt.addSeries(LinePlotSeries("fit")) + plt.getSeries(1).setData(fit_x, fit_y) + plt.getSeries(1).setPointsVisible(False) + plt.setLegendVisible(True) + phase.write(ph_crest) + time.sleep(lat) + Ampl = V.read() + Power = P.read() + caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", ph_crest) + caput(station + "-RSYS:GET-ONCREST-E-GAIN", fit_amplitude) + caput(station + "-RSYS:GET-ONCREST-VSUM-AMPLT", Ampl) + caput(station + "-RSYS:GET-ONCREST-KLY-POWER", Power) + caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", fit_x) + caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", fit_y) +finally: + phase.write(phase0) + phase.close() + V.close() + P.close() + x.close() +phase_offset = 90.0 - ph_crest +amplitude_scale = fit_amplitude / Ampl +power_scale = Power / math.pow(fit_amplitude,2) +caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC", phase_offset) +caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC", amplitude_scale) +caput(station + "-RSYS:SET-VOLT-POWER-SCALE-CALC", power_scale) +if do_elog: + title = "Phase scan" + station + log_msg = "Data file: " + get_exec_pars().path + "\n" + log_msg = log_msg + "On-crest VS phase: %0.2f" % ph_crest + " deg \n" + log_msg = log_msg + "Energy Gain: %0.3f" % fit_amplitude + " MeV \n" + log_msg = log_msg + "VS -phase Offset: %0.2f" % phase_offset + " deg \n" + log_msg = log_msg + "Amplitude Scale: %0.3f" % amplitude_scale + " MV \n" + log_msg = log_msg + "Power Scale: %0.3f" % power_scale + " MW/MV^2" + attachments = get_plot_snapshots() + elog(title, log_msg, attachments) \ No newline at end of file diff --git a/script/test/phase_scan_caqtdm_set_dv.py b/script/test/phase_scan_caqtdm_set_dv.py new file mode 100644 index 0000000..bc51f2a --- /dev/null +++ b/script/test/phase_scan_caqtdm_set_dv.py @@ -0,0 +1,40 @@ +do_elog = False + +if get_exec_pars().source == CommandSource.ui: + station = "STEST01" +else: + station = args[0] + +phase_set = caget(station + "-RSYS:PHASE-SET") +ampli_set = caget(station + "-RSYS:AMPLT-SET") +power_set = caget(station + "-RSYS:POWER-SET") + +n = 0 +if (phase_set == 'True'): + phase_offset = caget(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC") + phase_offset_old = caget(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE") + caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", phase_offset) + print phase_set + n = n + 1 +if (ampli_set == 'True'): + amplitude_scale = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC") + amplitude_scale_old = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE") + caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE", amplitude_scale) + print ampli_set + n = n + 1 +if (power_set == 'True'): + power_scale = caget(station + "-RSYS:SET-VOLT-POWER-SCALE-CALC") + power_scale_old = caget(station + "-RSYS:SET-VOLT-POWER-SCALE") + caput(station + "-RSYS:SET-VOLT-POWER-SCALE", power_scale) + print power_set + n = n + 1 +caput(station + "-RSYS:CMD-LOAD-CALIB-BEAM", 1) + +if do_elog == True and n > 0: + title = "Set RF calibration:" + station + log_msg = "" + if (phase_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE: %0.2f" % phase_offset + " deg (was %0.2f" % phase_offset_old + " deg)\n" + if (ampli_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-AMPLT-SCALE: %0.3f" % amplitude_scale + " MV (was %0.3f" % amplitude_scale_old + " MV)\n" + if (power_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VOLT-POWER-SCALE: %0.5f" % power_scale + " MW/MV^2 (was %0.5f" % power_scale_old + " MW/MV^2)" + attachments = [] + elog(title, log_msg, attachments) \ No newline at end of file