From bc833cb885796eaeaefd6718c3ff4bcd8219137c Mon Sep 17 00:00:00 2001 From: sfop Date: Thu, 3 Nov 2016 11:48:15 +0100 Subject: [PATCH] Startup --- devices/CurrentCamera.properties | 18 +- plugins/ScreenPanel.java | 625 ++++++++++++++++++++----------- 2 files changed, 411 insertions(+), 232 deletions(-) diff --git a/devices/CurrentCamera.properties b/devices/CurrentCamera.properties index df89124..7b9bd71 100644 --- a/devices/CurrentCamera.properties +++ b/devices/CurrentCamera.properties @@ -1,13 +1,13 @@ -#Wed Nov 02 09:25:00 CET 2016 -colormap=Temperature +#Thu Nov 03 11:37:50 CET 2016 +colormap=Grayscale colormapAutomatic=true colormapMax=0.0 colormapMin=0.0 flipHorizontally=false -flipVertically=true +flipVertically=false grayscale=false -imageHeight=1200 -imageWidth=1246 +imageHeight=500 +imageWidth=500 invert=false rescaleFactor=1.0 rescaleOffset=0.0 @@ -18,9 +18,9 @@ roiY=0 rotation=0.0 rotationCrop=true scale=1.0 -spatialCalOffsetX=-630.0 -spatialCalOffsetY=-612.0 -spatialCalScaleX=-26.761819803746654 -spatialCalScaleY=-26.595744680851062 +spatialCalOffsetX=-258.0 +spatialCalOffsetY=-250.0 +spatialCalScaleX=-0.2840909090909091 +spatialCalScaleY=-0.5649717514124294 spatialCalUnits=mm transpose=false diff --git a/plugins/ScreenPanel.java b/plugins/ScreenPanel.java index 3f9a828..bd30e24 100644 --- a/plugins/ScreenPanel.java +++ b/plugins/ScreenPanel.java @@ -18,8 +18,13 @@ import ch.psi.pshell.epics.PsiCamera; import ch.psi.pshell.epics.Camtool; import ch.psi.pshell.core.JsonSerializer; import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.DeviceAdapter; +import ch.psi.pshell.device.DeviceListener; import ch.psi.pshell.epics.ArraySource; +import ch.psi.pshell.epics.ChannelDouble; +import ch.psi.pshell.epics.ChannelDoubleArray; import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.epics.ChannelIntegerArray; import ch.psi.pshell.epics.DiscretePositioner; import ch.psi.pshell.epics.Epics; import ch.psi.pshell.imaging.Colormap; @@ -45,6 +50,7 @@ import ch.psi.pshell.swing.ValueSelection.ValueSelectionListener; import ch.psi.utils.Arr; import ch.psi.utils.ArrayProperties; import ch.psi.utils.Convert; +import ch.psi.utils.Str; import ch.psi.utils.swing.Editor.EditorDialog; import ch.psi.utils.swing.MainFrame; import ch.psi.utils.swing.SwingUtils.OptionResult; @@ -54,17 +60,24 @@ import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; +import java.lang.reflect.Array; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; +import javax.swing.JMenuItem; import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; import org.apache.commons.math3.analysis.function.Gaussian; import org.apache.commons.math3.fitting.GaussianCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; @@ -74,7 +87,7 @@ import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; * */ public class ScreenPanel extends Panel { - + final boolean USE_CAMTOOL_STATS = true; final String configFolder = "/afs/psi.ch/intranet/SF/Applications/config/camtool"; File[] cameraConfigFiles = new File[0]; ArraySource camera; @@ -87,11 +100,11 @@ public class ScreenPanel extends Panel { DiscretePositioner screen; DiscretePositioner filter; boolean showFit; - + final ArrayList imageBuffer = new ArrayList(); int imageBufferLenght = 0; Text imageBufferOverlay; - + public ScreenPanel() { initComponents(); renderer.setPersistenceFile(Paths.get(getController().getSetup().getContextPath(), "Renderer_Cameras.bin")); @@ -119,33 +132,95 @@ public class ScreenPanel extends Panel { ex.printStackTrace(); } } - - renderer.setProfileNormalized(true); + + renderer.setProfileNormalized(true); renderer.setShowProfileLimits(false); + JMenuItem menuSetROI = new JMenuItem("Set ROI..."); + menuSetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (camera instanceof Camtool) { + final Overlays.Rect selection = new Overlays.Rect(renderer.getPenMovingOverlay()); + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + try { + Rectangle roi = overlay.isFixed() ? renderer.toImageCoord(overlay.getBounds()) : overlay.getBounds(); + if (((Camtool)camera).roiEnabled.read() >0){ + int[] cur = ((Camtool)camera).roi.read(); + ((Camtool)camera).roi.writeAsync(new int[]{roi.x + cur[0] , roi.y + cur[1], roi.width, roi.height}); + } + else { + ((Camtool)camera).roi.writeAsync(new int[]{roi.x, roi.y, roi.width, roi.height}); + ((Camtool)camera).roiEnabled.writeAsync(1); + } + } catch (Exception ex) { + } finally { + renderer.removeListener(this); + } + } + + @Override + public void onSelectionAborted(Renderer renderer, Overlay overlay) { + renderer.removeListener(this); + } + }); + selection.setFixed(true); + renderer.startSelection(selection); + } + }); + + JMenuItem menuResetROI = new JMenuItem("Reset ROI"); + menuResetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (camera instanceof Camtool) { + ((Camtool)camera).roiEnabled.writeAsync(0); + } + }); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuSetROI); + renderer.getPopupMenu().add(menuResetROI); + renderer.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { + + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuResetROI.setEnabled (camera instanceof Camtool); + menuSetROI.setEnabled (camera instanceof Camtool); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + renderer.getPopupMenu().setVisible(false); + showFit = buttonFit.isSelected(); - - if (imageBufferLenght>1){ + + if (imageBufferLenght > 1) { renderer.addListener(new RendererListener() { @Override - public void onImage(Renderer renderer, Object origin, BufferedImage image, Data data) { - if (data!=null){ - synchronized(imageBuffer){ + public void onImage(Renderer renderer, Object origin, BufferedImage image, Data data) { + if (data != null) { + synchronized (imageBuffer) { imageBuffer.add(data); - if (imageBuffer.size() > imageBufferLenght){ + if (imageBuffer.size() > imageBufferLenght) { imageBuffer.remove(0); } } } - } + } }); } pauseSelection.setVisible(false); pauseSelection.setMinValue(1); pauseSelection.addListener(new ValueSelectionListener() { @Override - public void onValueChanged(ValueSelection origin, double value, boolean editing){ - if (editing && (value>=1) && (value<=imageBuffer.size())){ + public void onValueChanged(ValueSelection origin, double value, boolean editing) { + if (editing && (value >= 1) && (value <= imageBuffer.size())) { updatePause(); } } @@ -153,7 +228,7 @@ public class ScreenPanel extends Panel { imageBufferOverlay = new Text(renderer.getPenErrorText(), "", new Font("Verdana", Font.PLAIN, 12), new Point(-100, 20)); imageBufferOverlay.setFixed(true); imageBufferOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_RIGHT); - if (MainFrame.isDark()){ + if (MainFrame.isDark()) { textState.setEnabled(true); } } @@ -203,22 +278,22 @@ public class ScreenPanel extends Panel { if (model.getSize() > 0) { try { if (App.hasArgument("cam")) { - comboCameras.setSelectedItem(App.getArgumentValue("cam")); + comboCameras.setSelectedItem(App.getArgumentValue("cam")); } } catch (Exception ex) { ex.printStackTrace(); } } } - startTimer(1000); + startTimer(1000); } - void manageFit(BufferedImage bi, Data data){ + void manageFit(BufferedImage bi, Data data) { Overlay[] fo = ((bi == null) || (!showFit)) ? null : getFitOverlays(data); renderer.updateOverlays(fo, fitOv); fitOv = fo; } - + @Override public void onStateChange(State state, State former) { @@ -347,7 +422,7 @@ public class ScreenPanel extends Panel { try { Path configFile = Paths.get(configFolder, cameraName + ".json"); cameraConfigJson = new String(Files.readAllBytes(configFile)); - this.cameraName = cameraName; + this.cameraName = cameraName; try { if (buttonCamtool.isSelected()) { camera = new Camtool("CurrentCamera", cameraName, false); @@ -372,8 +447,8 @@ public class ScreenPanel extends Panel { try { camera.getConfig().spatialCalOffsetX = config.getCalOffsetX(); camera.getConfig().spatialCalOffsetY = config.getCalOffsetY(); - camera.getConfig().spatialCalScaleX = - config.getScaleX(); - camera.getConfig().spatialCalScaleY = - config.getScaleY(); + camera.getConfig().spatialCalScaleX = -config.getScaleX(); + camera.getConfig().spatialCalScaleY = -config.getScaleY(); } catch (Exception ex) { camera.getConfig().spatialCalOffsetX = Double.NaN; camera.getConfig().spatialCalOffsetY = Double.NaN; @@ -390,8 +465,8 @@ public class ScreenPanel extends Panel { try { camera.getConfig().spatialCalOffsetX = ((Camtool) camera).calOffX.read(); camera.getConfig().spatialCalOffsetY = ((Camtool) camera).calOffY.read(); - camera.getConfig().spatialCalScaleX = - ((Camtool) camera).calScaleX.read(); - camera.getConfig().spatialCalScaleY = - ((Camtool) camera).calScaleY.read(); + camera.getConfig().spatialCalScaleX = -((Camtool) camera).calScaleX.read(); + camera.getConfig().spatialCalScaleY = -((Camtool) camera).calScaleY.read(); } catch (Exception ex) { System.err.println(ex.getMessage()); camera.getConfig().spatialCalOffsetX = 0.0; @@ -399,6 +474,31 @@ public class ScreenPanel extends Panel { camera.getConfig().spatialCalScaleX = 1.0; camera.getConfig().spatialCalScaleY = 1.0; } + ((Camtool)camera).shape.addListener(new DeviceAdapter(){ + @Override + public void onValueChanged(Device device, Object value, Object former) { + if ((camera instanceof Camtool) &&(device==((Camtool)camera).shape) && (camera.getState().isInitialized())) { + try { + if ((value != null) && (value.getClass() == int[].class)) { + final int[] s = (int[]) value; + if ((s.length > 1) && (s[0] * s[1] > 0) && + ((s[0] != camera.getConfig().imageHeight) || (s[1] != camera.getConfig().imageWidth))) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + comboCamerasActionPerformed(null); + } + }); + } + } + } catch (Exception ex) { + System.err.println(ex); + } + } + } + + }); + ((Camtool)camera).shape.setMonitored(true); } buttonReticle.setEnabled(camera.getConfig().isCalibrated()); buttonGrabBackground.setEnabled(camera instanceof Camtool); @@ -413,20 +513,20 @@ public class ScreenPanel extends Panel { renderer.setAutoScroll(true); renderer.setMarker(marker); firstImage = true; - + camera.addListener(new ImageListener() { @Override - public void onImage(Object o, BufferedImage bi, Data data) { - if (bi!=null){ - if (firstImage){ - if ((renderer.getMode()==RendererMode.Zoom) || (renderer.getMode()==RendererMode.Fixed)){ + public void onImage(Object o, BufferedImage bi, Data data) { + if (bi != null) { + if (firstImage) { + if ((renderer.getMode() == RendererMode.Zoom) || (renderer.getMode() == RendererMode.Fixed)) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { centralizeRenderer(); } }); - } + } firstImage = false; } renderer.setProfileSize(Math.min(bi.getWidth(), bi.getHeight())); @@ -436,7 +536,7 @@ public class ScreenPanel extends Panel { fitOv = null; } else { if (!renderer.isPaused()) { - Overlay[] fo = getFitOverlays(data); + Overlay[] fo = getFitOverlays(data); renderer.updateOverlays(fo, fitOv); fitOv = fo; } @@ -462,7 +562,7 @@ public class ScreenPanel extends Panel { screen.initialize(); DefaultComboBoxModel model = new DefaultComboBoxModel(); for (String pos : screen.getPositions()) { - model.addElement(pos); + model.addElement(pos); } comboScreen.setModel(model); comboScreen.setSelectedItem(screen.read()); @@ -476,11 +576,11 @@ public class ScreenPanel extends Panel { valueScreen.setDevice(screen); try { - filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); + filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); filter.initialize(); DefaultComboBoxModel model = new DefaultComboBoxModel(); for (String pos : filter.getPositions()) { - model.addElement(pos); + model.addElement(pos); } comboFilter.setModel(model); comboFilter.setSelectedItem(filter.read()); @@ -493,7 +593,7 @@ public class ScreenPanel extends Panel { valueFilter.setDevice(filter); } - + volatile Boolean firstImage; void checkReticle() { @@ -511,7 +611,7 @@ public class ScreenPanel extends Panel { void checkMarker() { if (camera != null) { if (buttonMarker.isSelected()) { - Dimension d = renderer.getImageSize(); + Dimension d = renderer.getImageSize(); Point p = (d == null) ? new Point(renderer.getWidth() / 2, renderer.getHeight() / 2) : new Point(d.width / 2, d.height / 2); Overlay ov = null; marker = new Overlays.Crosshairs(renderer.getPenMarker(), p, new Dimension(100, 100)); @@ -523,7 +623,7 @@ public class ScreenPanel extends Panel { renderer.setMarker(marker); } } - + void updateZoom() { try { buttonZoomStretch.setSelected(renderer.getMode() == RendererMode.Stretch); @@ -603,14 +703,14 @@ public class ScreenPanel extends Panel { Logger.getLogger(ScreenPanel.class.getName()).log(Level.SEVERE, null, ex); } } - if (renderer.isPaused() != buttonPause.isSelected()){ + if (renderer.isPaused() != buttonPause.isSelected()) { buttonPause.setSelected(renderer.isPaused()); buttonPauseActionPerformed(null); } - if (renderer.getShowReticle()!= buttonReticle.isSelected()){ + if (renderer.getShowReticle() != buttonReticle.isSelected()) { buttonReticle.setSelected(renderer.getShowReticle()); } - if ((renderer.getMarker()==null) && buttonMarker.isSelected()){ + if ((renderer.getMarker() == null) && buttonMarker.isSelected()) { buttonMarker.setSelected(false); } updateZoom(); @@ -625,102 +725,153 @@ public class ScreenPanel extends Panel { Overlay[] getFitOverlays(Data data) { Overlays.Polyline hpoly = null; Overlays.Polyline vpoly = null; + Overlays.Polyline hprofile = null; + Overlays.Polyline vprofile = null; Double xMean = null, xSigma = null, xNorm = null; Double yMean = null, ySigma = null, yNorm = null; if (data != null) { - int profileSize = renderer.getProfileSize(); - ArrayProperties properties = data.getProperties(); - double maxPlot = properties.max; - double minPlot = properties.min; - double rangePlot = maxPlot - minPlot; + int profileSize = renderer.getProfileSize(); + if ((USE_CAMTOOL_STATS) &&(camera instanceof Camtool)){ + try{ + profileSize/=4; + double[] gX = ((Camtool)camera).gaussX.read(); + double[] pX = ((Camtool)camera).profileX.read(); + int[] x = Arr.indexesInt(gX.length); + int[] y = new int[gX.length]; + int[] p = new int[gX.length]; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pX)); + Double min = Collections.min(l); + Double max = Collections.max(l); + double minPlot = min; + double rangePlot = max- min; + + for (int i = 0; i < x.length; i++) { + y[i] = (int) (data.getHeight() - 1 - (((gX[i] - minPlot) / rangePlot) * profileSize)); + p[i] = (int) (data.getHeight() - 1 - (((pX[i] - minPlot) / rangePlot) * profileSize)); + } + vpoly = new Overlays.Polyline(fitPen, x, y); + vprofile = new Overlays.Polyline(fitPen, x, p); + + double[] gY = ((Camtool)camera).gaussY.read(); + double[] pY = ((Camtool)camera).profileY.read(); + y = Arr.indexesInt(gY.length); + x = new int[gY.length]; + p = new int[gY.length]; + l = Arrays.asList((Double[]) Convert.toWrapperArray(pY)); + min = Collections.min(l); + max = Collections.max(l); + minPlot = min; + rangePlot = max- min; + + for (int i = 0; i < x.length; i++) { + x[i] = (int) (((gY[i] - minPlot) / rangePlot) * profileSize); + p[i] = (int) (((pY[i] - minPlot) / rangePlot) * profileSize); + } + hpoly = new Overlays.Polyline(fitPen, x, y); + hprofile = new Overlays.Polyline(fitPen, p, y); + + xMean = ((Camtool)camera).gaussCenterX.read(); + yMean = ((Camtool)camera).gaussCenterY.read(); + xSigma = ((Camtool)camera).gaussStdDivX.read(); + ySigma = ((Camtool)camera).gaussStdDivY.read(); + } catch (Exception ex){ + System.err.println(ex.getMessage()); + return null; + } + }else { + ArrayProperties properties = data.getProperties(); + double maxPlot = properties.max; + double minPlot = properties.min; + double rangePlot = maxPlot - minPlot; + + if (rangePlot <= 0) { + return null; + } + try { + double[] sum = (double[]) Convert.toDouble(data.integrateVertically(true)); + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + sum[i] = sum[i] - min; + } + + double[] gaussian = fitGaussian(sum, x); + if (gaussian != null) { + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + //gaussian[0] += min; + + xNorm = gaussian[0]; + xMean = gaussian[1]; + xSigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) (data.getHeight() - 1 - ((((fit[i] + min) / data.getHeight() - minPlot) / rangePlot) * profileSize)); + } + vpoly = new Overlays.Polyline(fitPen, x, y); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + try { + double[] sum = (double[]) Convert.toDouble(data.integrateHorizontally(true)); + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + sum[i] = sum[i] - min; + } + + double[] gaussian = fitGaussian(sum, x); + if (gaussian != null) { + //Only aknowledge beam fully inside the image and peak over 3% of min + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + //gaussian[0] += min; + yNorm = gaussian[0]; + yMean = gaussian[1]; + ySigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) ((((fit[i] + min) / data.getWidth() - minPlot) / rangePlot) * profileSize); + } + hpoly = new Overlays.Polyline(fitPen, y, x); + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + } - if (rangePlot>0){ - try { - double[] sum = (double[]) Convert.toDouble(data.integrateVertically(true)); - int[] x = Arr.indexesInt(sum.length); - DescriptiveStatistics stats = new DescriptiveStatistics(sum); - double min = stats.getMin(); - for (int i = 0; i < sum.length; i++) { - sum[i] = sum[i] - min; - } - - double[] gaussian = fitGaussian(sum, x); - if (gaussian != null) { - if ((gaussian[2] < sum.length * 0.45) - && (gaussian[2] > 2) - && (gaussian[0] > min * 0.03) - ) { - //gaussian[0] += min; - - xNorm = gaussian[0]; - xMean = gaussian[1]; - xSigma = gaussian[2]; - double[] fit = getFitFunction(gaussian, x); - int[] y = new int[x.length]; - for (int i = 0; i < x.length; i++) { - y[i] = (int) (data.getHeight() - 1 - ((((fit[i]+min)/ data.getHeight()- minPlot) / rangePlot) * profileSize)); - } - vpoly = new Overlays.Polyline(fitPen, x, y); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - try { - double[] sum = (double[]) Convert.toDouble(data.integrateHorizontally(true)); - int[] x = Arr.indexesInt(sum.length); - DescriptiveStatistics stats = new DescriptiveStatistics(sum); - double min = stats.getMin(); - for (int i = 0; i < sum.length; i++) { - sum[i] = sum[i] - min; - } - - double[] gaussian = fitGaussian(sum, x); - if (gaussian != null) { - //Only aknowledge beam fully inside the image and peak over 3% of min - if ((gaussian[2] < sum.length * 0.45) - && (gaussian[2] > 2) - && (gaussian[0] > min * 0.03) - ) { - //gaussian[0] += min; - yNorm = gaussian[0]; - yMean = gaussian[1]; - ySigma = gaussian[2]; - double[] fit = getFitFunction(gaussian, x); - - int[] y = new int[x.length]; - for (int i = 0; i < x.length; i++) { - y[i] = (int) ((((fit[i]+min) / data.getWidth() - minPlot) / rangePlot) * profileSize); - } - hpoly = new Overlays.Polyline(fitPen, y, x); - } - } - - } catch (Exception ex) { - ex.printStackTrace(); - } - Overlays.Crosshairs cross = null; Overlays.Text text = null; if ((xMean != null) && (yMean != null)) { cross = new Overlays.Crosshairs(crossPen, new Point(xMean.intValue(), yMean.intValue()), new Dimension(2 * xSigma.intValue(), 2 * ySigma.intValue())); - if (renderer.getCalibration()!=null){ + if (renderer.getCalibration() != null) { xSigma *= renderer.getCalibration().getScaleX(); ySigma *= renderer.getCalibration().getScaleY(); } - text = new Overlays.Text(fitPen, - String.format("x = %1.3f " + "\u03C3 = %1.3f \ny = %1.3f " + "\u03C3 = %1.3f" , - data.getX((int) Math.round(xMean)), xSigma, data.getY((int) Math.round(yMean)), ySigma), - new Font(Font.MONOSPACED, 0, 14), new Point(20,20)); + text = new Overlays.Text(fitPen, + String.format("x = %1.3f " + "\u03C3 = %1.3f \ny = %1.3f " + "\u03C3 = %1.3f", + data.getX((int) Math.round(xMean)), xSigma, data.getY((int) Math.round(yMean)), ySigma), + new Font(Font.MONOSPACED, 0, 14), new Point(20, 20)); text.setFixed(true); text.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); } - return new Overlay[]{hpoly, vpoly, cross, text}; - } - } + return new Overlay[]{hpoly, vpoly, hprofile, vprofile, cross, text}; + } return null; } @@ -767,31 +918,35 @@ public class ScreenPanel extends Panel { } return fit; } -/* + public class Camtool extends ArraySource { final String prefix; final String dataPrefix; final boolean latch; + final Object lock = new Object(); final public ChannelInteger channelRun; final public ChannelInteger channelLatch; final public ChannelDouble channelTimestamp; - final public ChannelDoubleArray origin; + final public ChannelDoubleArray origin; final public ChannelDouble posX, posY; final public ChannelDoubleArray profileX, profileY; final public ChannelIntegerArray shape; - //final public ChannelInteger roiEnabled; - //final public ChannelIntegerArray roiShape; + final public ChannelInteger roiEnabled; + final public ChannelIntegerArray roi; final public ChannelInteger bgEnable, bgCapture, bgCaptureRemain; final public ChannelDouble calOffX, calOffY, calScaleX, calScaleY; + final public ChannelDoubleArray gaussX, gaussY; + final public ChannelDouble gaussCenterX, gaussCenterY; + final public ChannelDouble gaussStdDivX, gaussStdDivY; + public Camtool(String name, String prefix) { this(name, prefix, false); } public Camtool(String name, String prefix, boolean latch) { - //super(name, prefix + (latch ? ":latch" : ":pipeline") + (roi ? ".roi.output" : ".image")); super(name, prefix + (latch ? ":latch" : ":pipeline") + ".roi.output"); this.prefix = prefix + ":"; this.latch = latch; @@ -801,18 +956,13 @@ public class ScreenPanel extends Panel { channelLatch = new ChannelInteger(name + " latch", this.prefix + "latch.capture"); channelTimestamp = new ChannelDouble(name + " timestamp", dataPrefix + "timestamp"); channelTimestamp.setMonitored(true); - //posX = new ChannelDouble(name + " com x", dataPrefix + "x_stats.com"); - //posY = new ChannelDouble(name + " com y", dataPrefix + "y_stats.com"); posX = new ChannelDouble(name + " com x", dataPrefix + "x_stats.com_egu"); posY = new ChannelDouble(name + " com y", dataPrefix + "y_stats.com_egu"); profileX = new ChannelDoubleArray(name + " profile x", dataPrefix + "profile.x"); profileY = new ChannelDoubleArray(name + " profile y", dataPrefix + "profile.y"); - //shape = new ChannelIntegerArray(name + " shape", dataPrefix + (roi ? "roi.output.shape" : "image.shape")); - //shape = new ChannelIntegerArray(name + " shape", dataPrefix + ("image.shape")); - shape = new ChannelIntegerArray(name + " shape", dataPrefix + ("roi.output.shape")); - //roiShape = new ChannelIntegerArray(name + " roi shape", dataPrefix + "roi.roi"); - //roiEnabled = new ChannelInteger(name + " roi enabled", dataPrefix + "roi.enabled"); - //origin = new ChannelDoubleArray(name + " origin X", roi ? (dataPrefix + "roi.origin_out") : (prefix + "origin")); + shape = new ChannelIntegerArray(name + " shape", dataPrefix + ("roi.output.shape")); + roiEnabled = new ChannelInteger(name + " roi enable", dataPrefix + ("roi.enabled")); + roi = new ChannelIntegerArray(name + " roi", dataPrefix + ("roi.roi")); origin = new ChannelDoubleArray(name + " origin X", dataPrefix + "roi.origin_out"); bgEnable = new ChannelInteger(name + " bg enable", this.prefix + "pipeline.bg.enabled"); bgCapture = new ChannelInteger(name + " bg capture", this.prefix + "pipeline.bg.capture"); @@ -821,6 +971,13 @@ public class ScreenPanel extends Panel { calOffY = new ChannelDouble(name + " cal off y", this.prefix + "pipeline.egu.eoff_y"); calScaleX = new ChannelDouble(name + " cal scale x", this.prefix + "pipeline.egu.eslo_x"); calScaleY = new ChannelDouble(name + " cal scale y", this.prefix + "pipeline.egu.eslo_y"); + + gaussX = new ChannelDoubleArray(name + " gauss x", dataPrefix + ("x_stats.gauss")); + gaussY = new ChannelDoubleArray(name + " gauss y", dataPrefix + ("y_stats.gauss")); + gaussCenterX = new ChannelDouble(name + "gauss center x", dataPrefix + "x_stats.g_center"); + gaussCenterY = new ChannelDouble(name + "gauss center y", dataPrefix + "y_stats.g_center"); + gaussStdDivX = new ChannelDouble(name + "gauss stddiv x", dataPrefix + "x_stats.g_stddiv"); + gaussStdDivY = new ChannelDouble(name + "gauss stddiv t", dataPrefix + "y_stats.g_stddiv"); } @Override @@ -829,12 +986,6 @@ public class ScreenPanel extends Panel { getDevice().setMonitored(value); } - @Override - public void doUpdate() throws IOException, InterruptedException { - super.doUpdate(); - getDevice().update(); - } - void safeInitialize(Device dev, int timeout) throws IOException, InterruptedException { for (int retries = 0; retries < 10; retries++) { try { @@ -864,8 +1015,8 @@ public class ScreenPanel extends Panel { profileX.initialize(); profileY.initialize(); shape.initialize(); - //roiShape.initialize(); - //roiEnabled.initialize(); + roiEnabled.initialize(); + roi.initialize(); origin.initialize(); bgEnable.initialize(); bgCapture.initialize(); @@ -878,25 +1029,19 @@ public class ScreenPanel extends Panel { } catch (Exception ex) { ex.printStackTrace(); } + gaussX.initialize(); + gaussY.initialize(); + gaussCenterX.initialize(); + gaussCenterY.initialize(); + gaussStdDivX.initialize(); + gaussStdDivY.initialize(); - - //if (roiEnabled.read() > 0) { - // int[] s = roiShape.read(); - // //for (int x : s) System.out.println(x); - // getConfig().imageHeight = s[3]; - // getConfig().imageWidth = s[2]; - //} else { - // - int[] s = shape.read(); - //for (int x : s){ System.out.println(x);} - getConfig().imageHeight = s[0]; - getConfig().imageWidth = s[1]; - //} - + int[] s = shape.read(); + getConfig().imageHeight = s[0]; + getConfig().imageWidth = s[1]; getConfig().save(); - getDevice().setSize(getConfig().imageHeight * getConfig().imageWidth); + getDevice().setSize(getConfig().imageHeight * getConfig().imageWidth); super.doInitialize(); - //System.out.println(((int[])(getDevice().read())).length); } catch (InterruptedException ex) { throw ex; } catch (Exception ex) { @@ -904,6 +1049,41 @@ public class ScreenPanel extends Panel { throw new IOException(ex); } } + + @Override + public void doClose() throws IOException { + super.doClose(); + channelRun.close(); + channelLatch.close(); + channelTimestamp.close(); + posX.close(); + posY.close(); + profileX.close(); + profileY.close(); + shape.close(); + roiEnabled.close(); + roi.close(); + origin.close(); + bgEnable.close(); + bgCapture.close(); + bgCaptureRemain.close(); + calOffX.close(); + calOffY.close(); + calScaleX.close(); + calScaleY.close(); + gaussX.close(); + gaussY.close(); + gaussCenterX.close(); + gaussCenterY.close(); + gaussStdDivX.close(); + gaussStdDivY.close(); + gaussX.close(); + gaussY.close(); + gaussCenterX.close(); + gaussCenterY.close(); + gaussStdDivX.close(); + gaussStdDivY.close(); + } int numImages = 1; @@ -983,9 +1163,7 @@ public class ScreenPanel extends Panel { Thread.sleep(10); } } - } - */ void setHistogramVisible(boolean value) { if (value) { @@ -1002,24 +1180,23 @@ public class ScreenPanel extends Panel { } } } - - void setLaserState(boolean value) throws Exception{ - + + void setLaserState(boolean value) throws Exception { + Epics.putq("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", value ? 0 : 1); Epics.putq("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1); Thread.sleep(3000); } - - boolean getLaserState() throws Exception{ + + boolean getLaserState() throws Exception { return (Epics.get("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", Integer.class) == 0); } - - - void elog(String title, String message, String[] attachments) throws Exception{ + + void elog(String title, String message, String[] attachments) throws Exception { String domain = ""; String logbook = "SwissFEL commissioning data"; String category = "Info"; - String entry=""; + String entry = ""; StringBuffer cmd = new StringBuffer(); cmd.append("G_CS_ELOG_add -l \"").append(logbook).append("\" "); @@ -1029,58 +1206,60 @@ public class ScreenPanel extends Panel { cmd.append("-a \"Title=").append(title).append("\" "); cmd.append("-a \"Category=").append(category).append("\" "); cmd.append("-a \"Domain=").append(domain).append("\" "); - for (String attachment : attachments){ + for (String attachment : attachments) { cmd.append("-f \"").append(attachment).append("\" "); } cmd.append("-n 1 "); cmd.append("\"").append(message).append("\" "); - System.out.println(cmd.toString()); - - final Process process = Runtime.getRuntime().exec(new String[]{"bash","-c",cmd.toString()}); + System.out.println(cmd.toString()); + + final Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmd.toString()}); new Thread(() -> { - try{ + try { process.waitFor(); int bytes = process.getInputStream().available(); - byte[] arr = new byte[bytes];process.getInputStream().read(arr, 0, bytes); + byte[] arr = new byte[bytes]; + process.getInputStream().read(arr, 0, bytes); System.out.println(new String(arr)); bytes = process.getErrorStream().available(); - arr = new byte[bytes];process.getErrorStream().read(arr, 0, bytes); + arr = new byte[bytes]; + process.getErrorStream().read(arr, 0, bytes); System.err.println(new String(arr)); - } catch(Exception ex){ + } catch (Exception ex) { System.err.println(ex); } }).start(); } - - void centralizeRenderer(){ + + void centralizeRenderer() { Point center = null; Dimension size = renderer.getImageSize(); - double zoom = (renderer.getMode() == RendererMode.Fixed) ? 1.0: renderer.getZoom(); - if (renderer.getCalibration()!=null){ + double zoom = (renderer.getMode() == RendererMode.Fixed) ? 1.0 : renderer.getZoom(); + if (renderer.getCalibration() != null) { center = renderer.getCalibration().getCenter(); - } else if (size!=null){ - center = new Point(size.width/2, size.height/2); + } else if (size != null) { + center = new Point(size.width / 2, size.height / 2); } - if (center!=null){ - Point topleft = new Point(Math.max((int) (center.x - renderer.getWidth()/2/zoom), 0), - Math.max((int) (center.y - renderer.getHeight()/2/zoom) , 0)); + if (center != null) { + Point topleft = new Point(Math.max((int) (center.x - renderer.getWidth() / 2 / zoom), 0), + Math.max((int) (center.y - renderer.getHeight() / 2 / zoom), 0)); renderer.setViewPosition(topleft); - } + } } - - void updatePause(){ - int index = ((int)pauseSelection.getValue())-1; - synchronized(imageBuffer){ - if (index0)); - if (pauseSelection.isVisible()){ + pauseSelection.setVisible(buttonPause.isSelected() && (imageBuffer.size() > 0)); + if (pauseSelection.isVisible()) { renderer.addOverlay(imageBufferOverlay); pauseSelection.setMaxValue(imageBuffer.size()); - pauseSelection.setValue(imageBuffer.size());; - } + pauseSelection.setValue(imageBuffer.size());; + } } } } catch (Exception ex) { @@ -1794,22 +1973,22 @@ public class ScreenPanel extends Panel { private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed try { - String snapshotFile=getController().getSetup().expandPath("{images}/snapshot.png"); + String snapshotFile = getController().getSetup().expandPath("{images}/snapshot.png"); renderer.saveSnapshot(snapshotFile, "png", true); getController().setExecutionContext("snapshot", null, null, null, null, null, null, null); - getController().getDataManager().setDataset("/data", renderer.getData().getMatrix(), renderer.getData().isUnsigned()); + getController().getDataManager().setDataset("/data", renderer.getData().getMatrix(), renderer.getData().isUnsigned()); getController().getDataManager().closeOutput(); StringBuilder message = new StringBuilder(); message.append("Camera: ").append(cameraName).append(" ("). - append((camera instanceof Camtool) ? "camtool" : "direct").append(")").append("\n"); + append((camera instanceof Camtool) ? "camtool" : "direct").append(")").append("\n"); message.append("Data file: ").append(getController().getExecutionContext().getPath()).append("\n"); - if ((fitOv != null) && (fitOv.length>3)){ + if ((fitOv != null) && (fitOv.length > 3)) { Overlays.Text text = (Overlays.Text) fitOv[3]; message.append(text.getText()).append("\n"); } elog("ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); - SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getController().getExecutionContext().getPath(), 5000); - + SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getController().getExecutionContext().getPath(), 5000); + } catch (Exception ex) { ex.printStackTrace(); showException(ex); @@ -1819,19 +1998,19 @@ public class ScreenPanel extends Panel { private void buttonGrabBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGrabBackgroundActionPerformed try { if (camera instanceof Camtool) { - if (SwingUtils.showOption(getTopLevel(), "Background", "Do you want to capture background now?", OptionType.YesNo) == OptionResult.Yes){ + if (SwingUtils.showOption(getTopLevel(), "Background", "Do you want to capture background now?", OptionType.YesNo) == OptionResult.Yes) { boolean laserOn = getLaserState(); - if (laserOn){ + if (laserOn) { setLaserState(false); } - try{ - ((Camtool) camera).captureBackground(5); - } finally{ - if (laserOn){ + try { + ((Camtool) camera).captureBackground(5); + } finally { + if (laserOn) { setLaserState(true); } } - SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); + SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); } } } catch (Exception ex) { @@ -1868,21 +2047,21 @@ public class ScreenPanel extends Panel { try { if ((camera != null) && (camera instanceof ColormapSource)) { ColormapSource source = (ColormapSource) camera; - Color colorReticule = new Color(16,16,16); - Color colorMarker = new Color(128,128,128); + Color colorReticule = new Color(16, 16, 16); + Color colorMarker = new Color(128, 128, 128); if (buttonGrayscale.isSelected()) { colorReticule = new Color(0, 192, 0); colorMarker = new Color(64, 255, 64); source.getConfig().colormap = Colormap.Grayscale; } - if (buttonTemperature.isSelected()) { + if (buttonTemperature.isSelected()) { source.getConfig().colormap = Colormap.Temperature; } - if (buttonRainbow.isSelected()) { + if (buttonRainbow.isSelected()) { source.getConfig().colormap = Colormap.Rainbow; } - - renderer.setPenReticle(new Pen(colorReticule)); + + renderer.setPenReticle(new Pen(colorReticule)); renderer.setPenProfile(new Pen(colorReticule)); renderer.setPenMarker(new Pen(colorMarker, 2)); renderer.setShowReticle(false); @@ -1892,7 +2071,7 @@ public class ScreenPanel extends Panel { source.getConfig().colormapMax = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMax.getValue(); source.getConfig().save(); source.refresh(); - if (buttonPause.isSelected()){ + if (buttonPause.isSelected()) { updatePause(); } } @@ -1933,13 +2112,13 @@ public class ScreenPanel extends Panel { setpoint.initialize(); if (setpoint.read() != index) { boolean laserOn = getLaserState(); - if (laserOn){ + if (laserOn) { setLaserState(false); } - try{ + try { setpoint.write(index); - } finally{ - if (laserOn){ + } finally { + if (laserOn) { setLaserState(true); } } @@ -1974,7 +2153,7 @@ public class ScreenPanel extends Panel { private void buttonZoom2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom2ActionPerformed renderer.setZoom(2.0); - renderer.setMode(RendererMode.Zoom); + renderer.setMode(RendererMode.Zoom); centralizeRenderer(); }//GEN-LAST:event_buttonZoom2ActionPerformed