commit ae4d6216099b1fde43a25ddf2244ef9c4d1f7b71 Author: Alexandre Gobbo Date: Fri Jan 19 10:56:53 2018 +0100 New ScreenPanel diff --git a/config/.DS_Store b/config/.DS_Store new file mode 100644 index 0000000..05ca374 Binary files /dev/null and b/config/.DS_Store differ diff --git a/config/administrator.properties b/config/administrator.properties new file mode 100755 index 0000000..7dd97d0 --- /dev/null +++ b/config/administrator.properties @@ -0,0 +1,15 @@ +#Thu Feb 09 10:07:32 CET 2017 +denyConfig=false +denyConsole=false +denyDeviceConfig=false +denyDeviceWrite=false +denyEdit=false +denyPrefs=false +denyRun=false +denyVersioning=false +hideConsole=false +hideData=false +hideDevices=false +hideEditor=false +hideScripts=false +hideToolbar=false diff --git a/config/cgf2.properties b/config/cgf2.properties new file mode 100755 index 0000000..0454636 --- /dev/null +++ b/config/cgf2.properties @@ -0,0 +1,30 @@ +#Wed Jan 10 10:22:45 CET 2018 +autoSaveScanData=true +createSessionFiles=false +dataLayout=default +dataPath={data}/{year}_{month}/{date}/{date}_{time}_{name} +dataProvider=h5 +dataScanFlushRecords=false +dataScanPreserveTypes=false +dataScanReleaseRecords=false +dataServerPort=-1 +depthDimension=0 +hostName=null +instanceName= +logDaysToLive=-1 +logLevel=Info +logLevelConsole=Off +logPath={logs}/{date}_{time} +notificationLevel=Off +scanStreamerPort=-1 +serverEnabled=false +serverPort=8080 +simulation=false +terminalEnabled=false +terminalPort=3579 +userAuthenticator= +userManagement=false +versionTrackingEnabled=false +versionTrackingLogin= +versionTrackingManual=false +versionTrackingRemote= diff --git a/config/config.properties b/config/config.properties new file mode 100755 index 0000000..d74df4f --- /dev/null +++ b/config/config.properties @@ -0,0 +1,30 @@ +#Fri Jan 19 10:56:01 CET 2018 +autoSaveScanData=true +createSessionFiles=false +dataLayout=default +dataPath={data}/{year}_{month}/{date}/{date}_{time}_{name} +dataProvider=h5 +dataScanFlushRecords=false +dataScanPreserveTypes=false +dataScanReleaseRecords=false +dataServerPort=5573 +depthDimension=0 +hostName= +instanceName=Dev +logDaysToLive=8 +logLevel=Fine +logLevelConsole=Off +logPath={logs}/{date}_{time} +notificationLevel=Off +scanStreamerPort=5563 +serverEnabled=true +serverPort=8080 +simulation=false +terminalEnabled=false +terminalPort=3579 +userAuthenticator=ch.psi.pshell.security.LdapAuthenticator | ldap\://d.psi.ch | d.psi.ch | users.psi +userManagement=true +versionTrackingEnabled=true +versionTrackingLogin={context}/svcusr-hlapp_robot +versionTrackingManual=true +versionTrackingRemote=git@git.psi.ch\:pshell_config/dev.git diff --git a/config/devices.properties b/config/devices.properties new file mode 100755 index 0000000..42cb11a --- /dev/null +++ b/config/devices.properties @@ -0,0 +1,98 @@ +dispatcher=ch.psi.pshell.bs.Provider|tcp://localhost:9999||| +stream=ch.psi.pshell.bs.Stream| #false:boolean||| +scalar=ch.psi.pshell.bs.Scalar|stream Int8Scalar||| +cam=ch.psi.pshell.bs.StreamCamera|"tcp://gfa-lc6-64:10100" 1|||true +cam_server=ch.psi.pshell.bs.PipelineServer|gfa-lc6-64:8889||| +#prosilica=ch.psi.pshell.prosilica.Prosilica|119734 "PacketSize=1504;ExposureValue=300000"|||true +rr=RotationReadback|TESTIOC:TESTCALCOUT:Output|||true +rp=ch.psi.pshell.epics.Positioner|TESTIOC:TESTCALCOUT:Input null rr||| +#webcam=ch.psi.pshell.webcam.Webcam|:2|||true +det=ch.psi.pshell.epics.AreaDetector|13SIM1|||false +PiezoRoll1=ch.psi.pshell.epics.ControlledVariable|"TESTIOC:TESTCALCOUT:Input" TESTIOC:TESTCALCOUT:Output|||true +$ser=ch.psi.pshell.serial.TcpDevice|||| +$beam_ok=ch.psi.pshell.epics.ChannelString|CHANNEL||| +sc1=ch.psi.pshell.epics.Scaler|MTEST-HW3:JS|||true +#bragg=ch.psi.pshell.crlogic.CrlogicPositioner|MTEST-HW3:MOT1||| +#wago=ch.psi.pshell.modbus.ModbusTCP|SF-TEST-WAGO1:502||| +testd=ch.psi.pshell.device.DummyPositioner|||| +#ralays=ch.psi.pshell.modbus.DigitalOutputArray|wago 0 16||1000| +#relay1=ch.psi.pshell.modbus.DigitalOutput|wago 0||1000| +#relay2=ch.psi.pshell.modbus.DigitalOutput|wago 1||1000| +streamcam=ch.psi.pshell.bs.StreamCamera|tcp://gfa-lc6-64:9999||-1000| +#camtool_provider=ch.psi.pshell.bs.Provider|tcp://gfa-lc6-64:9999||| +#camtool_stream=ch.psi.pshell.bs.Stream|camtool_provider|||true +#camtool_min=ch.psi.pshell.bs.Scalar|camtool_stream min_value||| +#test\u00201=ch.psi.pshell.epics.ChannelDouble|"TESTIOC:TESTSINUS:SinCalc" 3 true|||true +#marco=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTSINUS:SinCalc 3||5000|false +#ts=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTSINUS:SinCalc 3 true|||true +#tsa=ch.psi.pshell.epics.ChannelDoubleArray|TESTIOC:TESTWF2:MyWF 2 -1 true||| +#m1=ch.psi.pshell.epics.Motor|MTEST-HW3:MOT1|||true +#ai1=ch.psi.pshell.epics.ChannelDouble|MTEST-HW3-AI1:AI_01|||true +#ai2=ch.psi.pshell.epics.ChannelDouble|MTEST-HW3-AI1:AI_05|||true +#mb=ch.psi.pshell.modbus.ModbusTCP|MTEST-CWAG-OFF:502||| +#mb_delay=ch.psi.pshell.modbus.Register|mb 0x1037||| +#mbdo=ch.psi.pshell.modbus.DigitalOutput|mb 4||50| +#mbdi=ch.psi.pshell.modbus.DigitalInput|mb 0||50|false +#mbdoa=ch.psi.pshell.modbus.DigitalOutputArray|mb 0 10||50| +#mbdia=ch.psi.pshell.modbus.DigitalInputArray|mb 0 10||50| +#mbao=ch.psi.pshell.modbus.AnalogOutput|mb 0||100| +#mbai=ch.psi.pshell.modbus.AnalogInput|mb 0||100| +#mbaoa=ch.psi.pshell.modbus.AnalogOutputArray|mb 0 10||100| +#mbaia=ch.psi.pshell.modbus.AnalogInputArray|mb 0 10||100| +#mot=ch.psi.pshell.epics.ChannelDouble|MTEST-GOBBO:MOT1 5|||true +dp=ch.psi.pshell.epics.DiscretePositioner|TESTIOC:CMD|||true +dev=ch.psi.pshell.device.DummyRegister|6||| +#dev2=ch.psi.pshell.device.MyDevice|||| +$vhq=ch.psi.pshell.epics.ChannelDouble|T-MMDV5:IST:2 6|Read|| +outc=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTCALCOUT:Output|||true +inpc=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTCALCOUT:Input|||true +out=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTCALCOUT:Output 6|||true +#outx=ch.psi.pshell.epics.ProcessVariable|TESTIOC:TESTCALCOUT:Output|||true +inp=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTCALCOUT:Input|||true +sin=ch.psi.pshell.epics.ChannelDouble|TESTIOC:TESTSINUS:SinCalc 3 true|||true +#sinx=ch.psi.pshell.epics.ProcessVariable|TESTIOC:TESTSINUS:SinCalc|||true +#average=ch.psi.pshell.device.Averager|sin||2000| +isin=ch.psi.pshell.epics.ChannelInteger|TESTIOC:TESTSINUS:SinCalc|||true +arr=ch.psi.pshell.epics.ChannelDoubleArray|TESTIOC:TESTWF2:MyWF 6 -1 true|||true +pv=ch.psi.pshell.epics.ProcessVariable|TESTIOC:TESTCALCOUT:Input|||true +shutter=ch.psi.pshell.epics.BinaryPositioner|TESTIOC:TESTBO:MyBO TESTIOC:TESTBO:MyBO|||true +$motor=ch.psi.pshell.epics.Motor|MTEST-GOBBO:MOT1|||true +$motor2=ch.psi.pshell.epics.Motor|MTEST-GOBBO:MOT2|||true +table=ch.psi.pshell.device.MotorGroupBase|motor motor2||| +$manip=ch.psi.pshell.epics.Manipulator|||| +tab=ch.psi.pshell.device.MotorGroupDiscretePositioner|table||| +#tab2=ch.psi.pshell.device.MotorGroupDiscretePositioner|table||| +#imgx=ch.psi.pshell.epics.ChannelByteArray|13SIM1:image1:ArrayData -1 1048576||| +$scienta=ch.psi.pshell.epics.Scienta|13SIM1:cam1 13SIM1:image1|||true +slit=ch.psi.pshell.device.Slit|motor motor2||| +#$vhq4=ch.psi.pshell.epics.Vhq4|T-MMDV5||| +#$ps=PowerSupply|T-MMDV5||| +pe=ch.psi.pshell.epics.Positioner|"TESTIOC:TESTCALCOUT:Input" TESTIOC:TESTCALCOUT:Output|||true +cv=ch.psi.pshell.epics.ControlledVariable|TESTIOC:TESTCALCOUT:Input TESTIOC:TESTCALCOUT:Output|||true +detector=ch.psi.pshell.detector.DetectorBase|http://127.0.0.1:8090/||| +#serial=ch.psi.pshell.serial.SerialPortDevice|||| +tcp=ch.psi.pshell.serial.TcpDevice|127.0.0.1:5554||| +beeper=Beeper|||| +img=ch.psi.pshell.imaging.CameraSource|det||-500| +imgbis=ch.psi.pshell.imaging.CameraSource|det||-500| +sc=ch.psi.pshell.imaging.CameraSource|scienta||-500| +tst=ch.psi.pshell.imaging.FileSource|C:\\Users\\gobbo_a\\Pictures\\beam.jpg||| +tst2=ch.psi.pshell.imaging.FileSource|C:\\Users\\gobbo_a\\Pictures\\tst.png||-500| +tst3=ch.psi.pshell.imaging.FileSource|C:\\Users\\gobbo_a\\Pictures\\tst.png||-500| +rec=ch.psi.pshell.detector.Receiver|tcp://127.0.0.1:5444|||true +#rec2=ch.psi.pshell.detector.Receiver|tcp://127.0.0.1:5555||-500|false +pvt=ch.psi.pshell.epics.ProcessVariable|TESTIOC:TESTCALCOUT:Input|Read|| +$master=ch.psi.pshell.modbus.ModbusTCP|127.0.0.1||| +ai=ch.psi.pshell.modbus.AnalogOutput|master 0||| +cache=ch.psi.pshell.device.RegisterCache|sin||| +$scaler=ch.psi.pshell.epics.Scaler|SCALER||| +testpos=ch.psi.pshell.device.DummyPositioner||||true +$test=ch.psi.pshell.epics.Motor|X|||true +arrsrc=ch.psi.pshell.epics.ArraySource|13SIM1:image1:ArrayData 125000||-500|true +#barrsrc=ch.psi.pshell.epics.ByteArraySource|13SIM1:image1:ArrayData 125000||-500| +#matrix=ch.psi.pshell.epics.GenericMatrix|13SIM1:image1:ArrayData 1024 640 Int8||| +#matrix_src=ch.psi.pshell.imaging.RegisterMatrixSource|matrix||-200| +ga=ch.psi.pshell.epics.GenericArray|13SIM1:image1:ArrayData 125000||| +#img2=ch.psi.pshell.imaging.FileSource|C:\\Users\\gobbo_a\\Pictures\\Chrysanthemum.jpg||| +#mxd=ch.psi.pshell.epics.AreaDetector|MX-SAMCAM||| +#mx=ch.psi.pshell.imaging.CameraSource|mxd||-1000| diff --git a/config/devices_2.properties b/config/devices_2.properties new file mode 100755 index 0000000..f261840 --- /dev/null +++ b/config/devices_2.properties @@ -0,0 +1,5 @@ +#wc=ch.psi.pshell.webcam.Webcam|"USB2.0 UVC PC Camera 0:2"|||true +cam=ch.psi.pshell.bs.StreamCamera|"tcp://gfa-lc6-64:10100" true|||true +pip=ch.psi.pshell.bs.StreamCamera|"tcp://gfa-lc6-64:11103"|||true +cs=ch.psi.pshell.bs.CameraServer|"http://gfa-lc6-64:8888"|||false +ps=ch.psi.pshell.bs.PipelineServer|"http://gfa-lc6-64:8889"||| diff --git a/config/energy_scan.properties b/config/energy_scan.properties new file mode 100755 index 0000000..82d5938 --- /dev/null +++ b/config/energy_scan.properties @@ -0,0 +1,4 @@ +Fe=690.0 755.0 2.0 10.0 0.0 2.0 2.0 2.0 +Ti=400.0 475.0 2.0 10.0 0.0 2.0 2.0 2.0 +Er=1380.0 1470.0 3.0 10.0 -11.0 -5.5 4.0 4.0 +Ta=1700.0 1820.0 3.0 10.0 -11.0 -5.5 4.0 4.0 diff --git a/config/jcae.properties b/config/jcae.properties new file mode 100755 index 0000000..6ce6441 --- /dev/null +++ b/config/jcae.properties @@ -0,0 +1,11 @@ +#Thu Jan 18 11:07:41 CET 2018 +ch.psi.jcae.ContextFactory.addressList=127.0.0.1\:54321 +ch.psi.jcae.ContextFactory.maxArrayBytes=10000000 +ch.psi.jcae.ChannelFactory.timeout=100 +ch.psi.jcae.ChannelFactory.retries=1 +ch.psi.jcae.ContextFactory.serverPort= +ch.psi.jcae.impl.DefaultChannelService.retries=4 +ch.psi.jcae.impl.DefaultChannelService.timeout=5000 +ch.psi.jcae.ContextFactory.autoAddressList=true +ch.psi.jcae.ContextFactory.useShellVariables=false +ch.psi.jcae.ContextFactory.addLocalBroadcastInterfaces=false diff --git a/config/mail.properties b/config/mail.properties new file mode 100755 index 0000000..060db28 --- /dev/null +++ b/config/mail.properties @@ -0,0 +1,10 @@ +#Wed Oct 18 15:31:18 CEST 2017 +auth=None +from=pshell.pearl@psi.ch +host=smtpint.psi.ch +port=0 +pwd= +smsSuffix=@sms.switch.ch +to=alexandre.gobbo@psi.ch +usr= + diff --git a/config/old_ca_ips.txt b/config/old_ca_ips.txt new file mode 100644 index 0000000..97f04a6 --- /dev/null +++ b/config/old_ca_ips.txt @@ -0,0 +1,15 @@ +129.129.144.79 +129.129.130.188 +129.129.130.255 +129.129.130.37 +129.129.130.77 +129.129.145.206:54321 +129.129.145.26:5064 +129.129.145.31:54321 +129.129.130.87 +129.129.130.142 +129.129.150.123 +129.129.130.123 +129.129.130.120 +172.20.3.50 +129.129.130.110 \ No newline at end of file diff --git a/config/plugins.properties b/config/plugins.properties new file mode 100755 index 0000000..760fdb1 --- /dev/null +++ b/config/plugins.properties @@ -0,0 +1,43 @@ +Nilson.java=disabled +CameraCalibrationDialog.java=enabled +ScalarPanel.java=enabled +CameraConfigDialog.java=disabled +Inventory.java=disabled +LayoutParallelScan.py=disabled +PhaseScan.java=disabled +PythonInteractive.java=disabled +RotationReadback.java=enabled +SfCamera.java=enabled +ScreenPanel.java=disabled +Didier.java=disabled +PersonalizedTheme.java=disabled +MXSC-1.5.0.jar=disabled +TestLdap.java=disabled +TestScan.java=disabled +MXSC-1.4.0.jar=disabled +TestPlot.java=disabled +MatlabTokenMaker.java=enabled +BandpassFilter.java=disabled +DataFile.java=disabled +Commands.java=disabled +CustomStopAll.java=disabled +importer.java=disabled +Beeper.java=enabled +DarkTheme.java=disabled +DefaultPlugin.java=disabled +EnergyScan.java=disabled +GroovyPlugin.groovy=disabled +HoloScan.java=disabled +Image.java=disabled +ManipulatorScan.java=disabled +Microscope.java=disabled +PanelPlugin.java=disabled +NetbeansPlugin.java=disabled +panel.py=disabled +Pearl.java=disabled +PhotonEnergy.java=disabled +plugin-1.0-SNAPSHOT.jar=disabled +PowerSupply.java=disabled +sb1.groovy=disabled +test.py=disabled +XPSSpectrum.java=disabled diff --git a/config/pool2.properties b/config/pool2.properties new file mode 100755 index 0000000..af87f8e --- /dev/null +++ b/config/pool2.properties @@ -0,0 +1 @@ +tst=ch.psi.pshell.epics.ChannelInteger|TST||1000| diff --git a/config/power.properties b/config/power.properties new file mode 100755 index 0000000..33b0dd9 --- /dev/null +++ b/config/power.properties @@ -0,0 +1,15 @@ +#Mon Aug 31 10:36:30 CEST 2015 +denyConfig=false +denyConsole=false +denyDeviceConfig=false +denyDeviceWrite=false +denyEdit=false +denyPrefs=false +denyRun=false +denyVersioning=false +hideConsole=false +hideData=false +hideDevices=false +hideEditor=false +hideScripts=false +hideToolbar=false diff --git a/config/remote.properties b/config/remote.properties new file mode 100755 index 0000000..d0bc75a --- /dev/null +++ b/config/remote.properties @@ -0,0 +1,15 @@ +#Mon Aug 31 17:26:04 CEST 2015 +denyConfig=false +denyConsole=false +denyDeviceConfig=false +denyDeviceWrite=false +denyEdit=false +denyPrefs=false +denyRun=false +denyVersioning=false +hideConsole=false +hideData=false +hideDevices=false +hideEditor=false +hideScripts=false +hideToolbar=false diff --git a/config/setup.properties b/config/setup.properties new file mode 100755 index 0000000..a40f43c --- /dev/null +++ b/config/setup.properties @@ -0,0 +1,20 @@ +#Wed Jan 10 09:07:30 CET 2018 +configFile={config}/config.properties +configFileDevices={config}/devices.properties +configFileImageSources={config}/imaging.properties +configFilePlugins={config}/plugins.properties +configFileTasks={config}/tasks.properties +configFileUpdateStrategy={config}/update.properties +configPath={home}/config +contextPath={outp}/context +dataPath={outp}/data +devicesPath={home}/devices +extensionsPath={home}/extensions +imagesPath={outp}/images +libraryPath={script}; {script}/Lib; src/main/assembly/script/tutorial +logPath={outp}/log +pluginsPath={home}/plugins +scriptPath={home}/script +scriptType=py +sessionsPath={outp}/sessions +wwwPath={home}/www diff --git a/config/standard.properties b/config/standard.properties new file mode 100755 index 0000000..ebfeb43 --- /dev/null +++ b/config/standard.properties @@ -0,0 +1,15 @@ +#Mon Aug 31 16:40:44 CEST 2015 +denyConfig=true +denyConsole=false +denyDeviceConfig=true +denyDeviceWrite=true +denyEdit=true +denyPrefs=true +denyRun=false +denyVersioning=true +hideConsole=false +hideData=false +hideDevices=false +hideEditor=false +hideScripts=false +hideToolbar=false diff --git a/config/tasks.properties b/config/tasks.properties new file mode 100755 index 0000000..93b9920 --- /dev/null +++ b/config/tasks.properties @@ -0,0 +1,4 @@ +#spectrum=1 +#back=1 +#task1=3 +#task2=-1 diff --git a/config/update.properties b/config/update.properties new file mode 100755 index 0000000..4df96a0 --- /dev/null +++ b/config/update.properties @@ -0,0 +1,34 @@ +mot= +dev=polled:500 +dev2= +vhq= +outc= +inpc= +out=monitored polled:1000 +inp=monitored +sin=monitored +arr= +pv= +motor=monitored +motor2=monitored +table= +manip=monitored +tab= +imgx= +det=monitored +scienta= +slit=monitored +vhq4=polled:1000 +ps= +pe=monitored +cv= +detector= +serial= +beeper= +img= +sc= +tst= +rec= +rec2= +det.data= +scienta.data=polled:1000 diff --git a/config/users b/config/users new file mode 100755 index 0000000..a735d71 Binary files /dev/null and b/config/users differ diff --git a/devices/BasePlate.properties b/devices/BasePlate.properties new file mode 100755 index 0000000..810d5ba --- /dev/null +++ b/devices/BasePlate.properties @@ -0,0 +1,3 @@ +#Wed Jan 18 13:18:39 CET 2017 +numberOfPucks=4 +numberOfSamples=9 diff --git a/devices/CamServer.properties b/devices/CamServer.properties new file mode 100755 index 0000000..fa47746 --- /dev/null +++ b/devices/CamServer.properties @@ -0,0 +1,24 @@ +#Wed Oct 25 11:29:41 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/Camera Server.properties b/devices/Camera Server.properties new file mode 100755 index 0000000..26ab0a1 --- /dev/null +++ b/devices/Camera Server.properties @@ -0,0 +1,25 @@ +#Mon Oct 23 11:55:12 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/Chrysanthemum.jpg.properties b/devices/Chrysanthemum.jpg.properties new file mode 100755 index 0000000..19ec717 --- /dev/null +++ b/devices/Chrysanthemum.jpg.properties @@ -0,0 +1,20 @@ +#Wed Mar 08 16:17:29 CET 2017 +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 new file mode 100755 index 0000000..b647e6b --- /dev/null +++ b/devices/CurrentCamera.properties @@ -0,0 +1,30 @@ +#Thu Jan 18 08:50:50 CET 2018 +colormap=Flame +colormapAutomatic=true +colormapMax=25300.0 +colormapMin=0.0 +custom=12345 +flipHorizontally=false +flipVertically=false +grayscale=false +imageHeight=0 +imageWidth=0 +invert=false +regionStartX=0 +regionStartY=0 +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +serverURL=http\://gfa-lc6-64\:8889 +spatialCalOffsetX=0.0 +spatialCalOffsetY=0.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=false diff --git a/devices/Eph.properties b/devices/Eph.properties new file mode 100755 index 0000000..e28ec03 --- /dev/null +++ b/devices/Eph.properties @@ -0,0 +1,8 @@ +#Thu Mar 31 17:22:56 CEST 2016 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +scale=1.0 +unit=null diff --git a/devices/Motor 1.properties b/devices/Motor 1.properties new file mode 100755 index 0000000..6025633 --- /dev/null +++ b/devices/Motor 1.properties @@ -0,0 +1,13 @@ +#Thu Jul 30 09:13:06 CEST 2015 +accessType=ReadWrite +defaultSpeed=NaN +estbilizationDelay=0 +maxSpeed=NaN +maxValue=NaN +minSpeed=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +scale=1.0 +unit=null diff --git a/devices/Phase.properties b/devices/Phase.properties new file mode 100755 index 0000000..af3fe11 --- /dev/null +++ b/devices/Phase.properties @@ -0,0 +1,9 @@ +#Thu Sep 07 17:56:13 CEST 2017 +maxValue=1000.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=0.5 +rotation=false +scale=1.0 +unit=mm diff --git a/devices/PiezoRoll1.properties b/devices/PiezoRoll1.properties new file mode 100755 index 0000000..0388355 --- /dev/null +++ b/devices/PiezoRoll1.properties @@ -0,0 +1,8 @@ +#Thu Feb 16 13:51:32 CET 2017 +maxValue=1000.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/Pulse ID.properties b/devices/Pulse ID.properties new file mode 100755 index 0000000..ae250ab --- /dev/null +++ b/devices/Pulse ID.properties @@ -0,0 +1,5 @@ +#Mon May 09 10:35:17 CEST 2016 +id=null +modulo=1 +offset=0 +precision=-1 diff --git a/devices/RotationPositioner.properties b/devices/RotationPositioner.properties new file mode 100755 index 0000000..b6666e7 --- /dev/null +++ b/devices/RotationPositioner.properties @@ -0,0 +1,9 @@ +#Tue Aug 15 18:13:34 CEST 2017 +maxValue=360.0 +minValue=-360.0 +offset=0.0 +precision=3 +resolution=0.01 +rotation=true +scale=1.0 +unit=mm diff --git a/devices/SimMotor.properties b/devices/SimMotor.properties new file mode 100755 index 0000000..0e25737 --- /dev/null +++ b/devices/SimMotor.properties @@ -0,0 +1,15 @@ +#Thu Jul 13 11:50:11 CEST 2017 +defaultSpeed=1.0 +estbilizationDelay=0 +hasEnable=false +homingType=null +maxSpeed=10.0 +maxValue=10.0 +minSpeed=0.1 +minValue=-10.0 +offset=0.0 +precision=2 +resolution=NaN +rotation=false +scale=1.0 +unit=mm diff --git a/devices/Time.properties b/devices/Time.properties new file mode 100755 index 0000000..a213619 --- /dev/null +++ b/devices/Time.properties @@ -0,0 +1,9 @@ +#Fri Jun 16 17:47:37 CEST 2017 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +rotation=false +scale=1.0 +unit=null diff --git a/devices/arrsrc.bkg b/devices/arrsrc.bkg new file mode 100755 index 0000000..fdbfecc Binary files /dev/null and b/devices/arrsrc.bkg differ diff --git a/devices/arrsrc.properties b/devices/arrsrc.properties new file mode 100755 index 0000000..8bee660 --- /dev/null +++ b/devices/arrsrc.properties @@ -0,0 +1,41 @@ +#Wed Jun 07 14:26:44 CEST 2017 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +calibrationOffsetX=0.0 +calibrationOffsetY=0.0 +calibrationScaleX=0.0 +calibrationScaleY=0.0 +colormap=Grayscale +colormapAutomatic=true +colormapMax=61.23 +colormapMin=0.0 +flipHorizontally=false +flipVertically=false +grayscale=false +height=250 +imageHeight=150 +imageWidth=800 +invert=false +offsetX=0.0 +offsetY=0.0 +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +scaleX=1.0 +scaleY=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false +width=500 diff --git a/devices/asd.properties b/devices/asd.properties new file mode 100755 index 0000000..f343bb3 --- /dev/null +++ b/devices/asd.properties @@ -0,0 +1,14 @@ +#Mon Apr 10 11:53:25 CEST 2017 +defaultSpeed=NaN +estbilizationDelay=0 +hasEnable=false +homingType=None +maxSpeed=NaN +maxValue=NaN +minSpeed=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +scale=1.0 +unit=null diff --git a/devices/average.properties b/devices/average.properties new file mode 100755 index 0000000..3ddbe81 --- /dev/null +++ b/devices/average.properties @@ -0,0 +1,4 @@ +#Mon Nov 21 14:07:24 CET 2016 +interval=1 +measures=50 +precision=3 diff --git a/devices/barrsrc.properties b/devices/barrsrc.properties new file mode 100755 index 0000000..31b2554 --- /dev/null +++ b/devices/barrsrc.properties @@ -0,0 +1,35 @@ +#Wed Sep 07 14:07:46 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Temperature +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +imageHeight=250 +imageWidth=500 +invert=false +offsetX=0.0 +offsetY=0.0 +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +scaleX=1.0 +scaleY=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/bs.properties b/devices/bs.properties new file mode 100755 index 0000000..913e32f --- /dev/null +++ b/devices/bs.properties @@ -0,0 +1,8 @@ +#Tue Dec 13 14:45:21 CET 2016 +alignmentRetries=21 +disableCompression=true +highWaterMark=100 +keepListeningOnStop=false +parallelHandlerProcessing=true +sendIncompleteMessages=true +socketType=PULL diff --git a/devices/cam.properties b/devices/cam.properties new file mode 100755 index 0000000..ac47fda --- /dev/null +++ b/devices/cam.properties @@ -0,0 +1,28 @@ +#Wed Aug 09 11:41:47 CEST 2017 +colormap=Flame +colormapAutomatic=true +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +imageHeight=0 +imageWidth=0 +invert=false +regionStartX=0 +regionStartY=0 +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/cam_server.properties b/devices/cam_server.properties new file mode 100755 index 0000000..5309886 --- /dev/null +++ b/devices/cam_server.properties @@ -0,0 +1,24 @@ +#Tue Nov 14 16:09:47 CET 2017 +colormap=Flame +colormapAutomatic=true +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=-661.516812111553 +spatialCalOffsetY=-490.5109552096732 +spatialCalScaleX=-25.06265652487295 +spatialCalScaleY=-32.822757470346716 +spatialCalUnits=mm +transpose=false diff --git a/devices/camtool.properties b/devices/camtool.properties new file mode 100755 index 0000000..6336d4b --- /dev/null +++ b/devices/camtool.properties @@ -0,0 +1,24 @@ +#Thu Jun 08 15:48:20 CEST 2017 +colormap=Flame +colormapAutomatic=true +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=0.0 +spatialCalOffsetY=0.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=false diff --git a/devices/camtool_bs.properties b/devices/camtool_bs.properties new file mode 100755 index 0000000..a012655 --- /dev/null +++ b/devices/camtool_bs.properties @@ -0,0 +1,24 @@ +#Fri Dec 09 11:28:15 CET 2016 +colormap=Temperature +colormapAutomatic=true +colormapMax=NaN +colormapMin=NaN +flipHorizontally=true +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=-0.0 +spatialCalOffsetY=-0.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=false diff --git a/devices/camtool_provider.properties b/devices/camtool_provider.properties new file mode 100755 index 0000000..d8b7686 --- /dev/null +++ b/devices/camtool_provider.properties @@ -0,0 +1,7 @@ +#Fri Dec 02 14:40:45 CET 2016 +alignmentRetries=200 +disableCompression=false +keepListeningOnStop=false +parallelHandlerProcessing=true +sendIncompleteMessages=false +socketType=DEFAULT diff --git a/devices/channel.properties b/devices/channel.properties new file mode 100755 index 0000000..85ce808 --- /dev/null +++ b/devices/channel.properties @@ -0,0 +1,5 @@ +#Mon May 02 13:22:44 CEST 2016 +id=null +modulo=1 +offset=0 +precision=-1 diff --git a/devices/counter.properties b/devices/counter.properties new file mode 100755 index 0000000..a5be2de --- /dev/null +++ b/devices/counter.properties @@ -0,0 +1,8 @@ +#Wed Aug 10 15:06:27 CEST 2016 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +scale=1.0 +unit=null diff --git a/devices/cs.properties b/devices/cs.properties new file mode 100755 index 0000000..46b78df --- /dev/null +++ b/devices/cs.properties @@ -0,0 +1,24 @@ +#Wed Aug 09 16:33:39 CEST 2017 +colormap=Flame +colormapAutomatic=true +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/cv.properties b/devices/cv.properties new file mode 100755 index 0000000..c70284c --- /dev/null +++ b/devices/cv.properties @@ -0,0 +1,9 @@ +#Fri Mar 24 15:08:15 CET 2017 +accessType=ReadWrite +maxValue=1000.0 +minValue=-1000.0 +offset=0.0 +precision=3 +resolution=1.0 +scale=1.0 +unit=C diff --git a/devices/data1d.properties b/devices/data1d.properties new file mode 100755 index 0000000..2342a55 --- /dev/null +++ b/devices/data1d.properties @@ -0,0 +1,8 @@ +#Mon Nov 30 15:00:37 CET 2015 +maxValue=1000.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/det - Copy.properties b/devices/det - Copy.properties new file mode 100755 index 0000000..50884d9 --- /dev/null +++ b/devices/det - Copy.properties @@ -0,0 +1,13 @@ +#Wed Mar 04 17:47:23 CET 2015 +grayscale=false +colormap=Grayscale +pollingBackground=false +scale=1.0 +colormapAutomatic=false +dataMonitoring=false +pollingInterval=0 +colormapMin=0.0 +dataPolling=0 +mirrored=false +colormapMax=255.0 +rotation=0.0 diff --git a/devices/det.properties b/devices/det.properties new file mode 100755 index 0000000..50884d9 --- /dev/null +++ b/devices/det.properties @@ -0,0 +1,13 @@ +#Wed Mar 04 17:47:23 CET 2015 +grayscale=false +colormap=Grayscale +pollingBackground=false +scale=1.0 +colormapAutomatic=false +dataMonitoring=false +pollingInterval=0 +colormapMin=0.0 +dataPolling=0 +mirrored=false +colormapMax=255.0 +rotation=0.0 diff --git a/devices/detector.properties b/devices/detector.properties new file mode 100755 index 0000000..167fb39 --- /dev/null +++ b/devices/detector.properties @@ -0,0 +1,5 @@ +#Fri Dec 02 16:38:36 CET 2016 +dtype=float +frame_rate=100 +n_frames=10000 +shape=400|200 diff --git a/devices/dispatcher.properties b/devices/dispatcher.properties new file mode 100755 index 0000000..c77149f --- /dev/null +++ b/devices/dispatcher.properties @@ -0,0 +1,8 @@ +#Tue Jul 04 16:16:39 CEST 2017 +alignmentRetries=20 +disableCompression=true +dropIncomplete=true +keepListeningOnStop=false +parallelHandlerProcessing=true +sendIncompleteMessages=true +socketType=PULL diff --git a/devices/dispatcher_.properties b/devices/dispatcher_.properties new file mode 100755 index 0000000..e7b4634 --- /dev/null +++ b/devices/dispatcher_.properties @@ -0,0 +1,6 @@ +#Tue Dec 20 14:29:42 CET 2016 +disableCompression=false +keepListeningOnStop=false +parallelHandlerProcessing=true +sendIncompleteMessages=false +socketType=DEFAULT diff --git a/devices/dispatchers.properties b/devices/dispatchers.properties new file mode 100755 index 0000000..c486d16 --- /dev/null +++ b/devices/dispatchers.properties @@ -0,0 +1,6 @@ +#Tue Nov 28 14:12:46 CET 2017 +disableCompression=false +dropIncomplete=false +keepListeningOnStop=false +parallelHandlerProcessing=true +socketType=DEFAULT diff --git a/devices/dp1.properties b/devices/dp1.properties new file mode 100755 index 0000000..6719cb3 --- /dev/null +++ b/devices/dp1.properties @@ -0,0 +1,11 @@ +#Tue Jan 17 10:47:10 CET 2017 +motor1=0.0|4.0|8.0|0.0 +motor2=0.0|5.0|3.0|NaN +motor3=null +motor4=null +motor5=null +motor6=null +motor7=null +motor8=null +positions=Park|Ready|Out|Clear +precision=-1 diff --git a/devices/good_region.properties b/devices/good_region.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/good_region.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_axis.properties b/devices/gr_x_axis.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_axis.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_fit_amplitude.properties b/devices/gr_x_fit_amplitude.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_fit_amplitude.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_fit_gauss_function.properties b/devices/gr_x_fit_gauss_function.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_fit_gauss_function.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_fit_mean.properties b/devices/gr_x_fit_mean.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_fit_mean.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_fit_offset.properties b/devices/gr_x_fit_offset.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_fit_offset.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_x_fit_standard_deviation.properties b/devices/gr_x_fit_standard_deviation.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_x_fit_standard_deviation.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_axis.properties b/devices/gr_y_axis.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_axis.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_fit_amplitude.properties b/devices/gr_y_fit_amplitude.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_fit_amplitude.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_fit_gauss_function.properties b/devices/gr_y_fit_gauss_function.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_fit_gauss_function.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_fit_mean.properties b/devices/gr_y_fit_mean.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_fit_mean.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_fit_offset.properties b/devices/gr_y_fit_offset.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_fit_offset.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/gr_y_fit_standard_deviation.properties b/devices/gr_y_fit_standard_deviation.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/gr_y_fit_standard_deviation.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/hyst.png.properties b/devices/hyst.png.properties new file mode 100755 index 0000000..38fc90e --- /dev/null +++ b/devices/hyst.png.properties @@ -0,0 +1,20 @@ +#Thu Mar 09 10:59:39 CET 2017 +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/image.properties b/devices/image.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/image.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/image1.properties b/devices/image1.properties new file mode 100755 index 0000000..c3cb7dc --- /dev/null +++ b/devices/image1.properties @@ -0,0 +1,24 @@ +#Thu Sep 07 17:54:46 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/img.properties b/devices/img.properties new file mode 100755 index 0000000..03a9327 --- /dev/null +++ b/devices/img.properties @@ -0,0 +1,39 @@ +#Tue Mar 28 16:27:45 CEST 2017 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Grayscale +colormapAutomatic=true +colormapMax=NaN +colormapMin=NaN +colormapRangeMax=NaN +colormapRangeMin=NaN +colormapTemperature=false +dataMonitoring=true +dataPolling=1000 +flipHorizontally=true +flipVertically=true +grayscale=false +invert=false +mirrored=false +monitored=false +polling=0 +pollingBackground=false +pollingInterval=0 +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=10.0 +rotationCrop=false +scale=1.0 +spatialCalOffsetX=-280.0 +spatialCalOffsetY=-230.0 +spatialCalScaleX=-0.1 +spatialCalScaleY=-0.1 +spatialCalUnits=mm +transpose=false diff --git a/devices/img2.properties b/devices/img2.properties new file mode 100755 index 0000000..a4394c3 --- /dev/null +++ b/devices/img2.properties @@ -0,0 +1,20 @@ +#Wed Sep 21 11:10:11 CEST 2016 +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/img4.png.properties b/devices/img4.png.properties new file mode 100755 index 0000000..56f6610 --- /dev/null +++ b/devices/img4.png.properties @@ -0,0 +1,20 @@ +#Thu Mar 02 13:37:24 CET 2017 +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/img_0000.png.properties b/devices/img_0000.png.properties new file mode 100755 index 0000000..8931c9e --- /dev/null +++ b/devices/img_0000.png.properties @@ -0,0 +1,20 @@ +#Thu Mar 02 13:35:39 CET 2017 +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/img_0020.png.properties b/devices/img_0020.png.properties new file mode 100755 index 0000000..22fc65a --- /dev/null +++ b/devices/img_0020.png.properties @@ -0,0 +1,20 @@ +#Thu Mar 02 16:12:07 CET 2017 +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/imgbis.properties b/devices/imgbis.properties new file mode 100755 index 0000000..5e2bce7 --- /dev/null +++ b/devices/imgbis.properties @@ -0,0 +1,24 @@ +#Mon Sep 26 17:24:05 CEST 2016 +colormap=Grayscale +colormapAutomatic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=true +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=true diff --git a/devices/inpc.properties b/devices/inpc.properties new file mode 100755 index 0000000..9ce7411 --- /dev/null +++ b/devices/inpc.properties @@ -0,0 +1,5 @@ +#Tue Mar 03 09:23:33 CET 2015 +precision=-1 +accessType=ReadWrite +channel=TESTIOC\:TESTCALCOUT\:Input +simulation=false diff --git a/devices/m1.properties b/devices/m1.properties new file mode 100755 index 0000000..1b5e6ac --- /dev/null +++ b/devices/m1.properties @@ -0,0 +1,14 @@ +#Wed Oct 18 16:49:39 CEST 2017 +defaultSpeed=1.0 +estbilizationDelay=0 +maxSpeed=10.0 +maxValue=10.0 +minSpeed=0.1 +minValue=-10.0 +offset=0.0 +precision=2 +resolution=NaN +rotation=false +scale=1.0 +startRetries=1 +unit=mm diff --git a/devices/m2.properties b/devices/m2.properties new file mode 100755 index 0000000..0b66b61 --- /dev/null +++ b/devices/m2.properties @@ -0,0 +1,15 @@ +#Wed Oct 18 16:49:39 CEST 2017 +accessType=ReadWrite +defaultSpeed=1.0 +estbilizationDelay=0 +maxSpeed=10.0 +maxValue=10.0 +minSpeed=0.1 +minValue=-10.0 +offset=0.0 +precision=4 +resolution=NaN +rotation=false +scale=1.0 +startRetries=1 +unit=mm diff --git a/devices/manip.properties b/devices/manip.properties new file mode 100755 index 0000000..195d6c5 --- /dev/null +++ b/devices/manip.properties @@ -0,0 +1,8 @@ +#Tue Mar 17 16:26:08 CET 2015 +accessType=ReadWrite +position_pvs=TESTIOC-MA\:RETRACTED|TESTIOC-MA\:YAG |TESTIOC-MA\:NE |TESTIOC-MA\:TRCL|TESTIOC-MA\:SHIELD|TESTIOC-MA\:CLAMP|TESTIOC-MA\:HEATER|TESTIOC-MA\:SAMPLE +positions=Retracted |YAG |Normal emission|Transfer \t | Shield |Clamping screw |Heater screw |Sample access +positions_pvs=asd|zxc +precision=-1 +readback_pv=TESTIOC-MA\:STS +stop_pv=TESTIOC-MA-STOP\:ALL diff --git a/devices/master.properties b/devices/master.properties new file mode 100755 index 0000000..42f7e5f --- /dev/null +++ b/devices/master.properties @@ -0,0 +1,8 @@ +#Thu Dec 24 09:57:56 CET 2015 +offsetReadAnalogInput=0 +offsetReadAnalogOutput=0 +offsetReadDigitalInput=0 +offsetReadDigitalOutput=0 +offsetWriteAnalogOutput=0 +offsetWriteDigitalOutput=0 +timeout=1000 diff --git a/devices/matrix.properties b/devices/matrix.properties new file mode 100755 index 0000000..0440c71 --- /dev/null +++ b/devices/matrix.properties @@ -0,0 +1,9 @@ +#Tue Aug 23 09:32:49 CEST 2016 +mirror_x=false +mirror_y=false +precision=-1 +roi_height=-1 +roi_width=-1 +roi_x=0 +roi_y=0 +transpose=false diff --git a/devices/matrix_src.properties b/devices/matrix_src.properties new file mode 100755 index 0000000..dce5348 --- /dev/null +++ b/devices/matrix_src.properties @@ -0,0 +1,29 @@ +#Wed Sep 07 16:18:54 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Grayscale +colormapAutomatic=false +colormapMax=266.704 +colormapMin=0.0 +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/max_value.properties b/devices/max_value.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/max_value.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/mb.properties b/devices/mb.properties new file mode 100755 index 0000000..38c014f --- /dev/null +++ b/devices/mb.properties @@ -0,0 +1,8 @@ +#Mon Apr 11 12:13:31 CEST 2016 +offsetReadAnalogInput=0 +offsetReadAnalogOutput=0x200 +offsetReadDigitalInput=0 +offsetReadDigitalOutput=0x200 +offsetWriteAnalogOutput=0 +offsetWriteDigitalOutput=0 +timeout=1000 diff --git a/devices/min_value.properties b/devices/min_value.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/min_value.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/motor.properties b/devices/motor.properties new file mode 100755 index 0000000..2484dac --- /dev/null +++ b/devices/motor.properties @@ -0,0 +1,20 @@ +#Fri Sep 22 09:54:50 CEST 2017 +accessType=ReadWrite +channel=MTEST-GOBBO\:MOT1 +defaultSpeed=1.0 +estbilizationDelay=0 +hasEnable=true +homingDirection=Backward +homingType=Backward +maxSpeed=20.0 +maxValue=75.0 +minSpeed=0.1 +minValue=-5.0 +offset=0.0 +precision=4 +resolution=0.00125 +rotation=false +scale=1.0 +simulation=false +startRetries=1 +unit=mm diff --git a/devices/motor2.properties b/devices/motor2.properties new file mode 100755 index 0000000..2376a1a --- /dev/null +++ b/devices/motor2.properties @@ -0,0 +1,20 @@ +#Fri Sep 22 09:54:50 CEST 2017 +accessType=ReadWrite +channel=MTEST-GOBBO\:MOT2 +defaultSpeed=0.2 +estbilizationDelay=0 +hasEnable=true +homingDirection=Backward +homingType=Backward +maxSpeed=100.0 +maxValue=2.0 +minSpeed=0.001 +minValue=-2.0 +offset=10.0 +precision=3 +resolution=NaN +rotation=false +scale=2.0 +simulation=false +startRetries=1 +unit=null diff --git a/devices/mx.properties b/devices/mx.properties new file mode 100755 index 0000000..650fe13 --- /dev/null +++ b/devices/mx.properties @@ -0,0 +1,24 @@ +#Wed Sep 21 16:49:15 CEST 2016 +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/outc.properties b/devices/outc.properties new file mode 100755 index 0000000..1cee739 --- /dev/null +++ b/devices/outc.properties @@ -0,0 +1,5 @@ +#Tue Mar 03 09:23:33 CET 2015 +precision=-1 +accessType=ReadWrite +channel=TESTIOC\:TESTCALCOUT\:Output +simulation=false diff --git a/devices/outx.properties b/devices/outx.properties new file mode 100755 index 0000000..8755443 --- /dev/null +++ b/devices/outx.properties @@ -0,0 +1,8 @@ +#Wed Apr 12 18:01:02 CEST 2017 +maxValue=1000.0 +minValue=0.0 +offset=0.1 +precision=6 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/p1.properties b/devices/p1.properties new file mode 100755 index 0000000..c518c22 --- /dev/null +++ b/devices/p1.properties @@ -0,0 +1,9 @@ +#Fri Jun 16 17:46:24 CEST 2017 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +rotation=false +scale=1.0 +unit=null diff --git a/devices/pe.properties b/devices/pe.properties new file mode 100755 index 0000000..e1e324c --- /dev/null +++ b/devices/pe.properties @@ -0,0 +1,10 @@ +#Mon Jun 12 18:25:49 CEST 2017 +accessType=ReadWrite +maxValue=1000.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=NaN +rotation=true +scale=1.0 +unit=mm diff --git a/devices/pip.properties b/devices/pip.properties new file mode 100755 index 0000000..422a4ec --- /dev/null +++ b/devices/pip.properties @@ -0,0 +1,24 @@ +#Wed Nov 08 08:37:09 CET 2017 +colormap=Flame +colormapAutomatic=true +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=-661.516812111553 +spatialCalOffsetY=-490.5109552096732 +spatialCalScaleX=-25.06265652487295 +spatialCalScaleY=-32.822757470346716 +spatialCalUnits=mm +transpose=false diff --git a/devices/positioner.properties b/devices/positioner.properties new file mode 100755 index 0000000..47ec462 --- /dev/null +++ b/devices/positioner.properties @@ -0,0 +1,8 @@ +#Wed Nov 08 12:33:55 CET 2017 +maxValue=1000.0 +minValue=-1000.0 +offset=0.0 +precision=5 +resolution=Infinity +scale=1.0 +unit=mm diff --git a/devices/prosilica.properties b/devices/prosilica.properties new file mode 100755 index 0000000..49c82f8 --- /dev/null +++ b/devices/prosilica.properties @@ -0,0 +1,20 @@ +#Tue Jul 11 10:54:59 CEST 2017 +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=-300.0 +spatialCalOffsetY=-200.0 +spatialCalScaleX=0.1 +spatialCalScaleY=0.1 +spatialCalUnits=mm +transpose=false diff --git a/devices/ps.properties b/devices/ps.properties new file mode 100755 index 0000000..a2de389 --- /dev/null +++ b/devices/ps.properties @@ -0,0 +1,24 @@ +#Tue Aug 15 12:50:13 CEST 2017 +colormap=Flame +colormapAutomatic=true +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=502.00803212851406 +spatialCalOffsetY=402.6845637583893 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=false diff --git a/devices/pv.properties b/devices/pv.properties new file mode 100755 index 0000000..598b23e --- /dev/null +++ b/devices/pv.properties @@ -0,0 +1,11 @@ +#Mon Jun 12 18:07:43 CEST 2017 +accessType=ReadWrite +channel=TESTIOC\:TESTCALCOUT\:Input +maxValue=180.0 +minValue=-180.0 +offset=1.0 +precision=5 +resolution=-1.0 +scale=2.0 +simulation=false +unit=mm diff --git a/devices/pvt.properties b/devices/pvt.properties new file mode 100755 index 0000000..afdce92 --- /dev/null +++ b/devices/pvt.properties @@ -0,0 +1,8 @@ +#Thu Dec 17 09:45:43 CET 2015 +maxValue=100.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/rec.properties b/devices/rec.properties new file mode 100755 index 0000000..ac9bae0 --- /dev/null +++ b/devices/rec.properties @@ -0,0 +1,31 @@ +#Thu Aug 25 16:31:33 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Temperature +colormapAutomatic=false +colormapMax=255.0 +colormapMin=0.0 +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +pollingBackground=false +pollingInterval=100 +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/rec2.properties b/devices/rec2.properties new file mode 100755 index 0000000..cc0f8dc --- /dev/null +++ b/devices/rec2.properties @@ -0,0 +1,31 @@ +#Wed Sep 07 10:24:42 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Grayscale +colormapAutomatic=false +colormapMax=255.0 +colormapMin=0.0 +flipHorizontally=false +flipVertically=false +grayscale=true +invert=false +pollingBackground=false +pollingInterval=100 +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/resized.tiff.properties b/devices/resized.tiff.properties new file mode 100755 index 0000000..f1eca97 --- /dev/null +++ b/devices/resized.tiff.properties @@ -0,0 +1,20 @@ +#Thu Mar 02 16:11:55 CET 2017 +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/rot.properties b/devices/rot.properties new file mode 100755 index 0000000..0ff906a --- /dev/null +++ b/devices/rot.properties @@ -0,0 +1,9 @@ +#Wed Aug 16 09:19:17 CEST 2017 +maxValue=360.0 +minValue=-360.0 +offset=0.0 +precision=3 +resolution=0.01 +rotation=false +scale=1.0 +unit=mm diff --git a/devices/rp.properties b/devices/rp.properties new file mode 100755 index 0000000..43a680e --- /dev/null +++ b/devices/rp.properties @@ -0,0 +1,9 @@ +#Tue Jun 13 10:33:58 CEST 2017 +maxValue=1000.0 +minValue=0.0 +offset=0.0 +precision=5 +resolution=NaN +rotation=true +scale=1.0 +unit=mm diff --git a/devices/sc.properties b/devices/sc.properties new file mode 100755 index 0000000..2f33b5d --- /dev/null +++ b/devices/sc.properties @@ -0,0 +1,33 @@ +#Wed Sep 21 16:35:18 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Grayscale +colormapAutomatic=true +colormapMax=NaN +colormapMin=NaN +dataMonitoring=true +dataPolling=1000 +flipHorizontally=true +flipVertically=true +grayscale=false +invert=false +pollingBackground=false +pollingInterval=0 +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/scienta.properties b/devices/scienta.properties new file mode 100755 index 0000000..ef238aa --- /dev/null +++ b/devices/scienta.properties @@ -0,0 +1,13 @@ +#Thu Mar 05 10:21:14 CET 2015 +grayscale=false +colormap=Grayscale +pollingBackground=false +scale=1.0 +colormapAutomatic=false +dataMonitoring=false +pollingInterval=0 +colormapMin=0.0 +dataPolling=0 +colormapMax=255.0 +mirrored=false +rotation=0.0 diff --git a/devices/ser.properties b/devices/ser.properties new file mode 100755 index 0000000..f75ebab --- /dev/null +++ b/devices/ser.properties @@ -0,0 +1,8 @@ +#Wed Mar 01 09:28:17 CET 2017 +address=localhost +baudRate=9600 +dataBits=DB_8 +parity=None +port=0 +stopBits=SB_1 +timeout=3000 diff --git a/devices/serial.properties b/devices/serial.properties new file mode 100755 index 0000000..fbaba15 --- /dev/null +++ b/devices/serial.properties @@ -0,0 +1,6 @@ +#Wed Nov 04 15:26:01 CET 2015 +baudRate=9600 +dataBits=DB_8 +parity=None +port=COM1 +stopBits=SB_1 diff --git a/devices/sim.properties b/devices/sim.properties new file mode 100755 index 0000000..eccd255 --- /dev/null +++ b/devices/sim.properties @@ -0,0 +1,24 @@ +#Thu Sep 21 17:13:36 CEST 2017 +colormap=Flame +colormapAutomatic=true +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/simudisp.properties b/devices/simudisp.properties new file mode 100755 index 0000000..0ecadb8 --- /dev/null +++ b/devices/simudisp.properties @@ -0,0 +1,7 @@ +#Mon Oct 17 15:38:13 CEST 2016 +alignmentRetries=20 +disableCompression=true +keepListeningOnStop=false +parallelHandlerProcessing=true +sendIncompleteMessages=true +socketType=DEFAULT diff --git a/devices/sinx.properties b/devices/sinx.properties new file mode 100755 index 0000000..32b8730 --- /dev/null +++ b/devices/sinx.properties @@ -0,0 +1,8 @@ +#Wed Apr 12 17:44:45 CEST 2017 +maxValue=100.0 +minValue=100.0 +offset=0.1 +precision=3 +resolution=NaN +scale=1.0 +unit= diff --git a/devices/slit neg blade.properties b/devices/slit neg blade.properties new file mode 100755 index 0000000..6f15482 --- /dev/null +++ b/devices/slit neg blade.properties @@ -0,0 +1,15 @@ +#Fri May 22 17:00:57 CEST 2015 +accessType=ReadWrite +defaultSpeed=1.0 +estbilizationDelay=0 +hasEnable=false +homingType=None +maxSpeed=1.0 +maxValue=20.0 +minSpeed=0.001 +minValue=-10.0 +offset=0.0 +precision=2 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/slit pos blade.properties b/devices/slit pos blade.properties new file mode 100755 index 0000000..6f15482 --- /dev/null +++ b/devices/slit pos blade.properties @@ -0,0 +1,15 @@ +#Fri May 22 17:00:57 CEST 2015 +accessType=ReadWrite +defaultSpeed=1.0 +estbilizationDelay=0 +hasEnable=false +homingType=None +maxSpeed=1.0 +maxValue=20.0 +minSpeed=0.001 +minValue=-10.0 +offset=0.0 +precision=2 +resolution=NaN +scale=1.0 +unit=mm diff --git a/devices/src1.properties b/devices/src1.properties new file mode 100755 index 0000000..1074f5c --- /dev/null +++ b/devices/src1.properties @@ -0,0 +1,32 @@ +#Wed Mar 22 10:57:46 CET 2017 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Temperature +colormapAutomatic=true +colormapMax=255.0 +colormapMin=0.0 +dataMonitoring=false +dataPolling=100 +flipHorizontally=true +flipVertically=false +grayscale=false +invert=false +pollingBackground=false +pollingInterval=0 +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/src2.properties b/devices/src2.properties new file mode 100755 index 0000000..f022812 --- /dev/null +++ b/devices/src2.properties @@ -0,0 +1,32 @@ +#Tue Jan 17 11:08:33 CET 2017 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +colormap=Grayscale +colormapAutomatic=true +colormapMax=255.0 +colormapMin=0.0 +dataMonitoring=false +dataPolling=100 +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +pollingBackground=false +pollingInterval=0 +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/stream.properties b/devices/stream.properties new file mode 100755 index 0000000..b13d471 --- /dev/null +++ b/devices/stream.properties @@ -0,0 +1,52 @@ +#Wed Dec 06 14:34:04 CET 2017 +channel01=null +channel02=null +channel03=null +channel04=null +channel05=null +channel06=null +channel07=null +channel08=null +channel09=null +channel10=null +channel11=null +channel12=null +channel13=null +channel14=null +channel15=null +channel16=null +channel17=null +channel18=null +channel19=null +channel20=null +channel21=null +channel22=null +channel23=null +channel24=null +channel25=null +channel26=null +channel27=null +channel28=null +channel29=null +channel30=null +channel31=null +channel32=null +channel33=null +channel34=null +channel35=null +channel36=null +channel37=null +channel38=null +channel39=null +channel40=null +channel41=null +channel42=null +channel43=null +channel44=null +channel45=null +channel46=null +channel47=null +channel48=null +channel49=null +channel50=null +filter=null diff --git a/devices/stream_per.properties b/devices/stream_per.properties new file mode 100755 index 0000000..e4a73d2 --- /dev/null +++ b/devices/stream_per.properties @@ -0,0 +1,60 @@ +#Mon Oct 03 10:52:07 CEST 2016 +channel01=SINXB01-RWVG100-DCP10\:FOR-PHASE 10 +channel02=SINXB01-RWVG100-DCP10\:FOR-AMPLT 10 +channel03=null +channel04=null +channel05=null +channel06=null +channel07=null +channel08=null +channel09=null +channel1=null +channel10=null +channel11=null +channel12=null +channel13=null +channel14=null +channel15=null +channel16=null +channel17=null +channel18=null +channel19=null +channel2=null +channel20=null +channel21=null +channel22=null +channel23=null +channel24=null +channel25=null +channel26=null +channel27=null +channel28=null +channel29=null +channel3=null +channel30=null +channel31=null +channel32=null +channel33=null +channel34=null +channel35=null +channel36=null +channel37=null +channel38=null +channel39=null +channel4=null +channel40=null +channel41=null +channel42=null +channel43=null +channel44=null +channel45=null +channel46=null +channel47=null +channel48=null +channel49=null +channel5=null +channel50=null +channel6=null +channel7=null +channel8=null +channel9=null diff --git a/devices/streamcam.properties b/devices/streamcam.properties new file mode 100755 index 0000000..a0f7630 --- /dev/null +++ b/devices/streamcam.properties @@ -0,0 +1,24 @@ +#Thu Jan 12 16:24:34 CET 2017 +colormap=Temperature +colormapAutomatic=true +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=380.0 +spatialCalOffsetY=555.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=false diff --git a/devices/tab.properties b/devices/tab.properties new file mode 100755 index 0000000..4065134 --- /dev/null +++ b/devices/tab.properties @@ -0,0 +1,14 @@ +#Thu Dec 17 09:44:30 CET 2015 +accessType=ReadWrite +motor1=0.0 | 1.0 | 2.0 | 0.1 +motor10=null +motor2=0.0 | 1.0 |2.0 | NaN +motor3= +motor4= +motor5= +motor6= +motor7= +motor8= +motor9=null +positions=Park | Ready | Out | Clear +precision=-1 diff --git a/devices/tab2.properties b/devices/tab2.properties new file mode 100755 index 0000000..f6225f2 --- /dev/null +++ b/devices/tab2.properties @@ -0,0 +1,11 @@ +#Thu Dec 17 09:31:50 CET 2015 +motor1=null +motor2=null +motor3=null +motor4=null +motor5=null +motor6=null +motor7=null +motor8=null +positions=null +precision=-1 diff --git a/devices/td.properties b/devices/td.properties new file mode 100755 index 0000000..625d88b --- /dev/null +++ b/devices/td.properties @@ -0,0 +1,5 @@ +#Fri Sep 30 13:50:12 CEST 2016 +alignmentRetries=20 +keepListeningOnStop=false +parallelHandlerProcessing=true +socketType=SUB diff --git a/devices/test.properties b/devices/test.properties new file mode 100755 index 0000000..49f8305 --- /dev/null +++ b/devices/test.properties @@ -0,0 +1,16 @@ +#Fri Sep 22 09:54:51 CEST 2017 +defaultSpeed=NaN +estbilizationDelay=0 +hasEnable=false +homingType=None +maxSpeed=NaN +maxValue=2000.0 +minSpeed=NaN +minValue=0.0 +offset=0.0 +precision=3 +resolution=0.1 +rotation=false +scale=1.0 +startRetries=1 +unit=eV diff --git a/devices/testd.properties b/devices/testd.properties new file mode 100755 index 0000000..1cfac83 --- /dev/null +++ b/devices/testd.properties @@ -0,0 +1,9 @@ +#Mon Jun 12 17:34:43 CEST 2017 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +rotation=false +scale=1.0 +unit=null diff --git a/devices/testpos.properties b/devices/testpos.properties new file mode 100755 index 0000000..29114a8 --- /dev/null +++ b/devices/testpos.properties @@ -0,0 +1,9 @@ +#Mon Jun 12 17:34:44 CEST 2017 +maxValue=NaN +minValue=NaN +offset=0.0 +precision=-1 +resolution=NaN +rotation=false +scale=1.0 +unit=null diff --git a/devices/tst.properties b/devices/tst.properties new file mode 100755 index 0000000..54f3fc0 --- /dev/null +++ b/devices/tst.properties @@ -0,0 +1,28 @@ +#Mon Sep 26 15:19:46 CEST 2016 +binning=1 +calOffsetX=NaN +calOffsetY=NaN +calScaleX=NaN +calScaleY=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +mirrored=false +pollingBackground=false +pollingInterval=0 +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=45.0 +rotationCrop=false +scale=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/tst2.properties b/devices/tst2.properties new file mode 100755 index 0000000..4711a2d --- /dev/null +++ b/devices/tst2.properties @@ -0,0 +1,20 @@ +#Mon Sep 26 16:22:14 CEST 2016 +flipHorizontally=true +flipVertically=true +grayscale=true +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=0.0 +spatialCalOffsetY=0.0 +spatialCalScaleX=1.0 +spatialCalScaleY=1.0 +spatialCalUnits=mm +transpose=true diff --git a/devices/tst3.properties b/devices/tst3.properties new file mode 100755 index 0000000..865200d --- /dev/null +++ b/devices/tst3.properties @@ -0,0 +1,20 @@ +#Mon Sep 26 16:20:10 CEST 2016 +flipHorizontally=true +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/undulator.properties b/devices/undulator.properties new file mode 100755 index 0000000..77605d7 --- /dev/null +++ b/devices/undulator.properties @@ -0,0 +1,9 @@ +#Wed Nov 08 15:03:48 CET 2017 +maxValue=1000.0 +minValue=-1000.0 +offset=0.0 +precision=5 +resolution=NaN +rotation=false +scale=1.0 +unit=mm diff --git a/devices/wago.properties b/devices/wago.properties new file mode 100755 index 0000000..4099481 --- /dev/null +++ b/devices/wago.properties @@ -0,0 +1,8 @@ +#Thu Jan 05 09:54:57 CET 2017 +offsetReadAnalogInput=0 +offsetReadAnalogOutput=0x200 +offsetReadDigitalInput=0 +offsetReadDigitalOutput=0x200 +offsetWriteAnalogOutput=0 +offsetWriteDigitalOutput=0 +timeout=1000 diff --git a/devices/wc.properties b/devices/wc.properties new file mode 100755 index 0000000..6a4a7b7 --- /dev/null +++ b/devices/wc.properties @@ -0,0 +1,20 @@ +#Thu Aug 17 08:55:38 CEST 2017 +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/webcam.properties b/devices/webcam.properties new file mode 100755 index 0000000..4ac8be4 --- /dev/null +++ b/devices/webcam.properties @@ -0,0 +1,20 @@ +#Wed Sep 13 13:20:55 CEST 2017 +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/x_axis.properties b/devices/x_axis.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_axis.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_fit_amplitude.properties b/devices/x_fit_amplitude.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_fit_amplitude.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_fit_gauss_function.properties b/devices/x_fit_gauss_function.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_fit_gauss_function.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_fit_mean.properties b/devices/x_fit_mean.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_fit_mean.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_fit_offset.properties b/devices/x_fit_offset.properties new file mode 100755 index 0000000..0bcc8af --- /dev/null +++ b/devices/x_fit_offset.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:09:25 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_fit_standard_deviation.properties b/devices/x_fit_standard_deviation.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_fit_standard_deviation.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/x_profile.properties b/devices/x_profile.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/x_profile.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_axis.properties b/devices/y_axis.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_axis.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_fit_amplitude.properties b/devices/y_fit_amplitude.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_fit_amplitude.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_fit_gauss_function.properties b/devices/y_fit_gauss_function.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_fit_gauss_function.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_fit_mean.properties b/devices/y_fit_mean.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_fit_mean.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_fit_offset.properties b/devices/y_fit_offset.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_fit_offset.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_fit_standard_deviation.properties b/devices/y_fit_standard_deviation.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_fit_standard_deviation.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/devices/y_profile.properties b/devices/y_profile.properties new file mode 100755 index 0000000..0a35a8a --- /dev/null +++ b/devices/y_profile.properties @@ -0,0 +1,5 @@ +#Thu Mar 30 15:12:31 CEST 2017 +id=null +modulo=10 +offset=0 +precision=-1 diff --git a/plugins/BandpassFilter.java b/plugins/BandpassFilter.java new file mode 100755 index 0000000..ebbf4c4 --- /dev/null +++ b/plugins/BandpassFilter.java @@ -0,0 +1,442 @@ + +import ij.*; +import ij.process.*; +import ij.gui.*; +import ij.measure.*; +import ij.plugin.ContrastEnhancer; +import java.awt.*; +import java.util.*; +import ij.plugin.filter.PlugInFilter; + + +/** +This class implements the Process/FFT/bandpass Filter command. It started out as +Joachim Walter's FFT Filter plugin at "http://rsb.info.nih.gov/ij/plugins/fft-filter.html". +2001/10/29: First Version (JW) +2003/02/06: 1st bugfix (works in macros/plugins, works on stacks, overwrites image(=>filter)) (JW) +2003/07/03: integrated into ImageJ, added "Display Filter" option (WSR) +2007/03/26: 2nd bugfix (Fixed incorrect calculation of filter from structure sizes, which caused + the real structure sizes to be wrong by a factor of 0.75 to 1.5 depending on the image size.) +*/ +public class BandpassFilter implements PlugInFilter, Measurements { + + private ImagePlus imp; + private String arg; + private static int filterIndex = 1; + private FHT fht; + private int slice; + private int stackSize = 1; + + public static double filterLargeDia = 40.0; + public static double filterSmallDia = 3.0; + public static int choiceIndex = 0; + public static String[] choices = {"None","Horizontal","Vertical"}; + public static String choiceDia = choices[0]; + public static double toleranceDia = 5.0; + public static boolean doScalingDia = true; + public static boolean saturateDia = true; + public static boolean displayFilter; + public static boolean processStack; + + public int setup(String arg, ImagePlus imp) { + this.arg = arg; + this.imp = imp; + if (imp==null) + {IJ.noImage(); return DONE;} + stackSize = imp.getStackSize(); + fht = (FHT)imp.getProperty("FHT"); + if (fht!=null) { + IJ.error("FFT Filter", "Spatial domain image required"); + return DONE; + } + //if (!showBandpassDialog(imp)) + // return DONE; + //else + return processStack?DOES_ALL+DOES_STACKS:DOES_ALL; + } + + public void run(ImageProcessor ip) { + slice++; + filter(ip); + } + + void filter(ImageProcessor ip) { + ImageProcessor ip2 = ip; + if (ip2 instanceof ColorProcessor) { + showStatus("Extracting brightness"); + ip2 = ((ColorProcessor)ip2).getBrightness(); + } + Rectangle roiRect = ip2.getRoi(); + int maxN = Math.max(roiRect.width, roiRect.height); + double sharpness = (100.0 - toleranceDia) / 100.0; + boolean doScaling = doScalingDia; + boolean saturate = saturateDia; + + IJ.showProgress(1,20); + + /* tile mirrored image to power of 2 size + first determine smallest power 2 >= 1.5 * image width/height + factor of 1.5 to avoid wrap-around effects of Fourier Trafo */ + + int i=2; + while(i<1.5 * maxN) i *= 2; + + // Calculate the inverse of the 1/e frequencies for large and small structures. + double filterLarge = 2.0*filterLargeDia / (double)i; + double filterSmall = 2.0*filterSmallDia / (double)i; + + // fit image into power of 2 size + Rectangle fitRect = new Rectangle(); + fitRect.x = (int) Math.round( (i - roiRect.width) / 2.0 ); + fitRect.y = (int) Math.round( (i - roiRect.height) / 2.0 ); + fitRect.width = roiRect.width; + fitRect.height = roiRect.height; + + // put image (ROI) into power 2 size image + // mirroring to avoid wrap around effects + showStatus("Pad to "+i+"x"+i); + ip2 = tileMirror(ip2, i, i, fitRect.x, fitRect.y); + IJ.showProgress(2,20); + + // transform forward + showStatus(i+"x"+i+" forward transform"); + FHT fht = new FHT(ip2); + fht.setShowProgress(false); + fht.transform(); + System.gc(); + IJ.showProgress(9,20); + //new ImagePlus("after fht",ip2.crop()).show(); + + // filter out large and small structures + showStatus("Filter in frequency domain"); + filterLargeSmall(fht, filterLarge, filterSmall, choiceIndex, sharpness); + //new ImagePlus("filter",ip2.crop()).show(); + IJ.showProgress(11,20); + + // transform backward + showStatus("Inverse transform"); + fht.inverseTransform(); + IJ.showProgress(19,20); + //new ImagePlus("after inverse",ip2).show(); + + // crop to original size and do scaling if selected + showStatus("Crop and convert to original type"); + fht.setRoi(fitRect); + ip2 = fht.crop(); + if (doScaling) { + ImagePlus imp2 = new ImagePlus(imp.getTitle()+"-filtered", ip2); + new ContrastEnhancer().stretchHistogram(imp2, saturate?1.0:0.0); + ip2 = imp2.getProcessor(); + } + + // convert back to original data type + int bitDepth = imp.getBitDepth(); + switch (bitDepth) { + case 8: ip2 = ip2.convertToByte(doScaling); break; + case 16: ip2 = ip2.convertToShort(doScaling); break; + case 24: + ip.snapshot(); + showStatus("Setting brightness"); + ((ColorProcessor)ip).setBrightness((FloatProcessor)ip2); + break; + case 32: break; + } + + // copy filtered image back into original image + if (bitDepth!=24) { + ip.snapshot(); + ip.copyBits(ip2, roiRect.x, roiRect.y, Blitter.COPY); + } + ip.resetMinAndMax(); + System.gc(); + IJ.showProgress(20,20); + } + + void showStatus(String msg) { + if (stackSize>1 && processStack) + IJ.showStatus("FFT Filter: "+slice+"/"+stackSize); + else + IJ.showStatus(msg); + } + + /** Puts imageprocessor (ROI) into a new imageprocessor of size width x height y at position (x,y). + The image is mirrored around its edges to avoid wrap around effects of the FFT. */ + ImageProcessor tileMirror(ImageProcessor ip, int width, int height, int x, int y) { + + if (x < 0 || x > (width -1) || y < 0 || y > (height -1)) { + IJ.error("Image to be tiled is out of bounds."); + return null; + } + + ImageProcessor ipout = ip.createProcessor(width, height); + + ImageProcessor ip2 = ip.crop(); + int w2 = ip2.getWidth(); + int h2 = ip2.getHeight(); + + //how many times does ip2 fit into ipout? + int i1 = (int) Math.ceil(x / (double) w2); + int i2 = (int) Math.ceil( (width - x) / (double) w2); + int j1 = (int) Math.ceil(y / (double) h2); + int j2 = (int) Math.ceil( (height - y) / (double) h2); + + //tile + if ( (i1%2) > 0.5) + ip2.flipHorizontal(); + if ( (j1%2) > 0.5) + ip2.flipVertical(); + + for (int i=-i1; i1) + gd.addCheckbox("Process Entire Stack", processStack); + gd.showDialog(); + if(gd.wasCanceled()) + return false; + if(gd.invalidNumber()) { + IJ.error("Error", "Invalid input number"); + return false; + } + filterLargeDia = gd.getNextNumber(); + filterSmallDia = gd.getNextNumber(); + choiceIndex = gd.getNextChoiceIndex(); + choiceDia = choices[choiceIndex]; + toleranceDia = gd.getNextNumber(); + doScalingDia = gd.getNextBoolean(); + saturateDia = gd.getNextBoolean(); + displayFilter = gd.getNextBoolean(); + if (stackSize>1) + processStack = gd.getNextBoolean(); + return true; + } + +} diff --git a/plugins/Beeper.java b/plugins/Beeper.java new file mode 100755 index 0000000..90d9a83 --- /dev/null +++ b/plugins/Beeper.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.device.*; +import com.sun.jna.Function; +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.Structure; +import com.sun.jna.ptr.IntByReference; +import com.sun.jna.win32.StdCallLibrary; +import com.sun.jna.win32.W32APIFunctionMapper; +import com.sun.jna.win32.W32APITypeMapper; +import java.util.HashMap; +import java.util.Map; + +/** + */ +public class Beeper extends DeviceBase { + + public Beeper(String name) { + super(name); + } + + // JNA Mapping + static Map UNICODE_OPTIONS = new HashMap() { + + { + put("type-mapper", W32APITypeMapper.UNICODE); + put("function-mapper", W32APIFunctionMapper.UNICODE); + } + }; + + interface Kernel32 extends StdCallLibrary { + + public static final String LIBRARY_NAME = "kernel32"; + Kernel32 INSTANCE = (Kernel32) Native.loadLibrary(LIBRARY_NAME, Kernel32.class, UNICODE_OPTIONS); + Kernel32 SYNC_INSTANCE = (Kernel32) Native.synchronizedLibrary(INSTANCE); + + boolean Beep(int FREQUENCY, int DURATION); + + void Sleep(int DURATION); + + int CreateEventW(Pointer securityAttributes, boolean manualReset, boolean initialState, String name); + + int CreateThread(/*Pointer*/int lpThreadAttributes, IntByReference dwStackSize, Function lpStartAddress, Structure lpParameter, int dwCreationFlags, IntByReference lpThreadId); + public static final int STILL_ACTIVE = 259; + + int GetExitCodeThread(int hThread, IntByReference lpExitCode); + + int GetLastError(); + + boolean CloseHandle(int handle); + + } + private final int mEventHandle = Kernel32.INSTANCE.CreateEventW(Pointer.NULL, true, false, null); + + + //Public interface + public int getLastError(){ + return Kernel32.SYNC_INSTANCE.GetLastError(); + } + + public void sleep(int duration){ + Kernel32.SYNC_INSTANCE.Sleep(duration); + } + + public void beep(int frequency, int duration){ + Kernel32.SYNC_INSTANCE.Beep(frequency, duration); + } + +} diff --git a/plugins/CameraCalibrationDialog.form b/plugins/CameraCalibrationDialog.form new file mode 100755 index 0000000..4ac7ff9 --- /dev/null +++ b/plugins/CameraCalibrationDialog.form @@ -0,0 +1,545 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/CameraCalibrationDialog.java b/plugins/CameraCalibrationDialog.java new file mode 100755 index 0000000..2a93151 --- /dev/null +++ b/plugins/CameraCalibrationDialog.java @@ -0,0 +1,726 @@ + + +import ch.psi.utils.swing.StandardDialog; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.pshell.bs.CameraServer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.ui.App; +import ch.psi.utils.Convert; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.swing.JDialog; + + +/* + */ + +/** + * + */ +public class CameraCalibrationDialog extends StandardDialog { + + CameraServer server; + Renderer renderer; + String cameraName; + Overlay[] calibrationOverlays; + Pen pen = new Pen(new Color(128, 0, 128), 1, Pen.LineStyle.solid); + Overlays.Crosshairs ovTop = new Overlays.Crosshairs(pen, new Dimension(-1, 1)); + Overlays.Crosshairs ovBottom = new Overlays.Crosshairs(pen, new Dimension(-1, 1)); + Overlays.Crosshairs ovLeft = new Overlays.Crosshairs(pen, new Dimension(1, -1)); + Overlays.Crosshairs ovRight = new Overlays.Crosshairs(pen, new Dimension(1, -1)); + + /** + * + * { + * name=SINEG01-DSCR350, + * prefix=SINEG01-DSCR350, + * mirror_x=true, + * mirror_y=true, + * rotate=0, + * calibration={ + * horizontal_camera_angle=0, + * vertical_camera_angle=0 + * reference_marker_width=16000.0, + * reference_marker_height=16000.0, + * reference_marker=[120, 245, 1251, 1504], + * }, + * } + */ + public CameraCalibrationDialog(Frame parent, String cameraName, Renderer renderer) throws IOException { + super(parent, cameraName, false); + + initComponents(); + + if (App.hasArgument("cam_srv_url")) { + this.server = new CameraServer("Camera Server", App.getArgumentValue("cam_srv_url")); + } else { + this.server = new CameraServer("Camera Server"); + } + + + this.cameraName = cameraName; + this.renderer = renderer; + + Map config = server.getConfig(cameraName); + Map calibration = (Map) config.get("camera_calibration"); + List refMarker = null; + System.out.println("Current config: " + config); + checkMirrorX.setSelected((config.get("mirror_x") ==null) ? Boolean.FALSE: (Boolean)config.get("mirror_x")); + checkMirrorY.setSelected((config.get("mirror_y") ==null) ? Boolean.FALSE: (Boolean)config.get("mirror_y")); + comboRotation.setSelectedIndex((config.get("rotate") == null) ? 0 :(Integer) (config.get("rotate"))); + ckCalibrationEnabled.setSelected(calibration!=null); + if (calibration!=null){ + spinnerRefWidth.setValue(((Number)calibration.get("reference_marker_width")).doubleValue()); + spinnerRefHeight.setValue(((Number)calibration.get("reference_marker_height")).doubleValue()); + spinnerAngleHor.setValue(((Number)calibration.get("angle_horizontal")).doubleValue()); + spinnerAngleVer.setValue(((Number)calibration.get("angle_vertical")).doubleValue()); + refMarker = ((List)calibration.get("reference_marker")); + if (refMarker.size()==4){ + spinnerLeft.setValue(refMarker.get(0)); + spinnerTop.setValue(refMarker.get(1)); + spinnerRight.setValue(refMarker.get(2)); + spinnerBottom.setValue(refMarker.get(3)); + } + } + updateResults(); + + + renderer.setMode(RendererMode.Fit); + calibrationOverlays = new Overlay[]{ovTop, ovBottom, ovLeft, ovRight}; + for (Overlay ov : calibrationOverlays){ + ov.setMovable(true); + } + renderer.addOverlays(calibrationOverlays); + + try{ + Rectangle r = new Rectangle(); + ovLeft.update(new Point(Math.max(refMarker.get(0), 0), 0)); + ovTop.update(new Point(0, Math.max(refMarker.get(1), 0))); + ovRight.update(new Point(Math.max(refMarker.get(2), 0), 0)); + ovBottom.update(new Point(0, Math.max(refMarker.get(3),0))); + } catch (Exception ex){ + SwingUtils.invokeDelayed(() -> { + Dimension size = renderer.getImageSize(); + ovTop.update(new Point(0, size.height/8)); + ovBottom.update(new Point(0, 7*size.height/8)); + ovLeft.update(new Point(size.width/8, 0)); + ovRight.update(new Point(7*size.width/8, 0)); + }, 500); + } + renderer.addListener(new RendererListener(){ + @Override + public void onMoveFinished(Renderer renderer, Overlay overlay) { + if (overlay==ovTop){ + spinnerTop.setValue(ovTop.getPosition().y); + } else if (overlay==ovBottom){ + spinnerBottom.setValue(ovBottom.getPosition().y); + } else if (overlay==ovLeft){ + spinnerLeft.setValue(ovLeft.getPosition().x); + } else if (overlay==ovRight){ + spinnerRight.setValue(ovRight.getPosition().x); + } + } + }); + setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + pack(); + } + + @Override + protected void onClosed() { + renderer.removeOverlays(calibrationOverlays); + calibrationOverlays = null; + server.close(); + } + + + void updateResults(){ + try{ + int left = (Integer)spinnerLeft.getValue(); + int right = (Integer)spinnerRight.getValue(); + int top = (Integer)spinnerTop.getValue(); + int bottom = (Integer)spinnerBottom.getValue(); + double width = (Double)spinnerRefWidth.getValue(); + double height = (Double)spinnerRefHeight.getValue(); + double angleHor = (Double)spinnerAngleHor.getValue(); + double angleVer = (Double)spinnerAngleVer.getValue(); + double pixelHor = width * Math.cos(Math.toRadians(angleHor)) /Math.abs(right-left); + double pixelVer = height * Math.cos(Math.toRadians(angleVer)) /Math.abs(bottom-top); + textOriginX.setText(String.valueOf((left+right)/2)); + textOriginY.setText(String.valueOf((top+bottom)/2)); + textPixelSizeX.setText(String.valueOf(Convert.roundDouble(pixelHor, 2))); + textPixelSizeY.setText(String.valueOf(Convert.roundDouble(pixelVer, 2))); + ovLeft.update(new Point(Math.max(left, 0), 0)); + ovTop.update(new Point(0, Math.max(top, 0))); + ovRight.update(new Point(Math.max(right, 0), 0)); + ovBottom.update(new Point(0, Math.max(bottom,0))); + renderer.refresh(); + + } catch (Exception ex){ + SwingUtils.showException(this, ex); + } + } + + + public static void main(String args[]) throws Exception { + //String cameraName = "SINEG01-DSCR190"; + String cameraName = "SATSY02-DSCR220" ; + //java.awt.EventQueue.invokeLater(() -> { + Renderer renderer = new Renderer(); + JDialog dlgRenderer = SwingUtils.showDialog(null, cameraName, new Dimension(600,400), renderer); + CameraCalibrationDialog dialog = new CameraCalibrationDialog(null, cameraName, renderer); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + dlgRenderer.setVisible(false); + System.exit(0); + } + }); + SwingUtils.centerComponent(null, dialog); + dialog.setVisible(true); + // }); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + jPanel1 = new javax.swing.JPanel(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + jLabel6 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + jLabel2 = new javax.swing.JLabel(); + jLabel8 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + jLabel10 = new javax.swing.JLabel(); + spinnerAngleHor = new javax.swing.JSpinner(); + spinnerAngleVer = new javax.swing.JSpinner(); + spinnerRefWidth = new javax.swing.JSpinner(); + spinnerRefHeight = new javax.swing.JSpinner(); + spinnerTop = new javax.swing.JSpinner(); + spinnerBottom = new javax.swing.JSpinner(); + spinnerLeft = new javax.swing.JSpinner(); + spinnerRight = new javax.swing.JSpinner(); + buttonFetch = new javax.swing.JButton(); + ckCalibrationEnabled = new javax.swing.JCheckBox(); + jPanel2 = new javax.swing.JPanel(); + checkMirrorX = new javax.swing.JCheckBox(); + checkMirrorY = new javax.swing.JCheckBox(); + comboRotation = new javax.swing.JComboBox(); + jLabel7 = new javax.swing.JLabel(); + jPanel3 = new javax.swing.JPanel(); + jLabel11 = new javax.swing.JLabel(); + textOriginX = new javax.swing.JTextField(); + jLabel12 = new javax.swing.JLabel(); + textOriginY = new javax.swing.JTextField(); + jLabel13 = new javax.swing.JLabel(); + jLabel14 = new javax.swing.JLabel(); + textPixelSizeX = new javax.swing.JTextField(); + textPixelSizeY = new javax.swing.JTextField(); + buttonOk = new javax.swing.JButton(); + buttonCancel = new javax.swing.JButton(); + buttonApply = new javax.swing.JButton(); + + jLabel1.setText("Calibrate the camera moving the line overlays to the reference marks."); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Calibration")); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Reference marker height (um):"); + + jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel5.setText("Horizontal camera angle (deg):"); + + jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel6.setText("Vertical camera angle (deg):"); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Reference marker width (um):"); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("Top (px):"); + + jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel8.setText("Botton (px):"); + + jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel9.setText("Left (px):"); + + jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel10.setText("Right (px):"); + + spinnerAngleHor.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerAngleHor.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerAngleVer.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerAngleVer.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRefWidth.setModel(new javax.swing.SpinnerNumberModel(30000.0d, 1.0d, 500000.0d, 1.0d)); + spinnerRefWidth.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRefHeight.setModel(new javax.swing.SpinnerNumberModel(30000.0d, 1.0d, 500000.0d, 1.0d)); + spinnerRefHeight.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerTop.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerTop.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerBottom.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerBottom.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerLeft.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerLeft.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRight.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerRight.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + buttonFetch.setText("Fetch from Inventory"); + buttonFetch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFetchActionPerformed(evt); + } + }); + + ckCalibrationEnabled.setText("Enabled"); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerTop, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRefWidth, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel8) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerBottom, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRefHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel10) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRight, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel6) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerAngleVer, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel9) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerAngleHor, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGap(9, 9, 9) + .addComponent(ckCalibrationEnabled) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonFetch))) + .addContainerGap()) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel2, jLabel8, jLabel9}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(jLabel2) + .addComponent(spinnerRefWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel4) + .addComponent(jLabel8) + .addComponent(spinnerRefHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(jLabel9) + .addComponent(spinnerAngleHor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerLeft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(jLabel10) + .addComponent(spinnerAngleVer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerRight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonFetch) + .addComponent(ckCalibrationEnabled)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Transformations")); + + checkMirrorX.setText("Mirror X"); + + checkMirrorY.setText("Mirror Y"); + + comboRotation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "270", "180", "90" })); + + jLabel7.setText("Rotation: "); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(checkMirrorX) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel7) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(comboRotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(checkMirrorY) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboRotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel7)) + .addComponent(checkMirrorX)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(checkMirrorY) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Results")); + + jLabel11.setText("Origin X (px):"); + + textOriginX.setEditable(false); + textOriginX.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + jLabel12.setText("Origin Y (px):"); + + textOriginY.setEditable(false); + textOriginY.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + jLabel13.setText("Y pixel size (um/px):"); + + jLabel14.setText("X pixel size (um/px):"); + + textPixelSizeX.setEditable(false); + textPixelSizeX.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + textPixelSizeY.setEditable(false); + textPixelSizeY.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(21, 21, 21) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel12) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textOriginY, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textOriginX, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel13) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textPixelSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel14) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textPixelSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel11, jLabel12}); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel13, jLabel14}); + + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel14) + .addComponent(textPixelSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel13) + .addComponent(textPixelSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel11) + .addComponent(textOriginX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel12) + .addComponent(textOriginY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + + buttonOk.setText("Ok"); + buttonOk.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonOkActionPerformed(evt); + } + }); + + buttonCancel.setText("Cancel"); + buttonCancel.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonCancelActionPerformed(evt); + } + }); + + buttonApply.setText("Apply"); + buttonApply.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonApplyActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(buttonCancel) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(buttonApply) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(buttonOk) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonApply, buttonCancel, buttonOk}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonOk) + .addComponent(buttonCancel) + .addComponent(buttonApply)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed + + buttonApplyActionPerformed(evt); + accept(); + }//GEN-LAST:event_buttonOkActionPerformed + + private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed + cancel(); + }//GEN-LAST:event_buttonCancelActionPerformed + + private void buttonFetchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFetchActionPerformed + try{ + //List calib = Inventory.getCalibFromInventory(null, cameraName); + List calib = (List) Class.forName("Inventory"). + getMethod("getCalibFromInventory", + new Class[]{String.class,String.class}). + invoke(null, new Object[]{(String)null, cameraName}); + spinnerRefWidth.setValue(calib.get(0)*1000.0); + spinnerRefHeight.setValue(calib.get(1)*1000.0); + spinnerAngleHor.setValue(calib.get(2).doubleValue()); + spinnerAngleVer.setValue(calib.get(3).doubleValue()); + } catch (Exception ex){ + if (ex instanceof InvocationTargetException){ + ex = (Exception) ((InvocationTargetException)ex).getCause(); + } + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonFetchActionPerformed + + private void calibrationSpinnerChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_calibrationSpinnerChanged + updateResults(); + }//GEN-LAST:event_calibrationSpinnerChanged + + private void buttonApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonApplyActionPerformed + try { + int left = (Integer)spinnerLeft.getValue(); //left.getPosition().x + int right = (Integer)spinnerRight.getValue(); //right.getPosition().x + int top = (Integer)spinnerTop.getValue(); //top.getPosition().y + int bottom = (Integer)spinnerBottom.getValue(); //bottom.getPosition().y + double width = (Double)spinnerRefWidth.getValue(); + double height = (Double)spinnerRefHeight.getValue(); + double angleHor = (Double)spinnerAngleHor.getValue(); + double angleVer = (Double)spinnerAngleVer.getValue(); + + int x1 = Math.min(left, right); + int x2 = Math.max(left, right); + int y1 = Math.min(top, bottom); + int y2 = Math.max(top, bottom); + System.out.println("Updating " + cameraName + " configuration"); + HashMap calibration = null; + if (ckCalibrationEnabled.isSelected()){ + calibration = new HashMap(); + calibration.put("reference_marker", Arrays.asList(new Integer[]{x1, y1, x2, y2})); + calibration.put("reference_marker_width", width); + calibration.put("reference_marker_height", height); + calibration.put("angle_horizontal", angleHor); + calibration.put("angle_vertical", angleVer); + } + + Map config = server.getConfig(cameraName); + config.put("camera_calibration", calibration); + config.put("mirror_x", checkMirrorX.isSelected()); + config.put("mirror_y", checkMirrorY.isSelected()); + config.put("rotate", comboRotation.getSelectedIndex()); + server.setConfig(cameraName, config); + + System.out.println("New config: " + config); + boolean reticle = renderer.getShowReticle(); + if (reticle){ + renderer.setShowReticle(false); + } + SwingUtils.showMessage(this, "Success", "Updated " + cameraName + " configuration"); + + if (reticle){ + renderer.setShowReticle(true); + } + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonApplyActionPerformed + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonApply; + private javax.swing.JButton buttonCancel; + private javax.swing.JButton buttonFetch; + private javax.swing.JButton buttonOk; + private javax.swing.JCheckBox checkMirrorX; + private javax.swing.JCheckBox checkMirrorY; + private javax.swing.JCheckBox ckCalibrationEnabled; + private javax.swing.JComboBox comboRotation; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel12; + private javax.swing.JLabel jLabel13; + private javax.swing.JLabel jLabel14; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JSpinner spinnerAngleHor; + private javax.swing.JSpinner spinnerAngleVer; + private javax.swing.JSpinner spinnerBottom; + private javax.swing.JSpinner spinnerLeft; + private javax.swing.JSpinner spinnerRefHeight; + private javax.swing.JSpinner spinnerRefWidth; + private javax.swing.JSpinner spinnerRight; + private javax.swing.JSpinner spinnerTop; + private javax.swing.JTextField textOriginX; + private javax.swing.JTextField textOriginY; + private javax.swing.JTextField textPixelSizeX; + private javax.swing.JTextField textPixelSizeY; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/CameraConfigDialog.form b/plugins/CameraConfigDialog.form new file mode 100755 index 0000000..73ac4fd --- /dev/null +++ b/plugins/CameraConfigDialog.form @@ -0,0 +1,524 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/CameraConfigDialog.java b/plugins/CameraConfigDialog.java new file mode 100755 index 0000000..1d742ea --- /dev/null +++ b/plugins/CameraConfigDialog.java @@ -0,0 +1,693 @@ + + +import ch.psi.utils.swing.StandardDialog; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.pshell.bs.Camtool; +import ch.psi.pshell.bs.PipelineServer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.utils.Convert; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.swing.JDialog; + + +/* + */ + +/** + * + */ +public class CameraConfigDialog extends StandardDialog { + + PipelineServer camera; + Renderer renderer; + String cameraName; + Overlay[] calibrationOverlays; + Pen pen = new Pen(new Color(128, 0, 128), 1, Pen.LineStyle.solid); + Overlays.Crosshairs ovTop = new Overlays.Crosshairs(pen, new Dimension(-1, 1)); + Overlays.Crosshairs ovBottom = new Overlays.Crosshairs(pen, new Dimension(-1, 1)); + Overlays.Crosshairs ovLeft = new Overlays.Crosshairs(pen, new Dimension(1, -1)); + Overlays.Crosshairs ovRight = new Overlays.Crosshairs(pen, new Dimension(1, -1)); + + /** + * + * { + * name=SINEG01-DSCR350, + * prefix=SINEG01-DSCR350, + * mirror_x=true, + * mirror_y=true, + * rotate=0, + * calibration={ + * horizontal_camera_angle=0, + * vertical_camera_angle=0 + * reference_marker_width=16000.0, + * reference_marker_height=16000.0, + * reference_marker=[120, 245, 1251, 1504], + * }, + * } + */ + public CameraConfigDialog(Frame parent, PipelineServer camera, Renderer renderer) throws IOException { + super(parent, camera.getCurrentCamera(), false); + + initComponents(); + + this.camera = camera; + this.cameraName = camera.getCurrentCamera(); + this.renderer = renderer; + + Map config = camera.getConfig(cameraName); + Map calibration = (Map) config.get("calibration"); + List refMarker = null; + System.out.println("Current config: " + config); + checkMirrorX.setSelected((config.get("mirror_x") ==null) ? Boolean.FALSE: (Boolean)config.get("mirror_x")); + checkMirrorY.setSelected((config.get("mirror_y") ==null) ? Boolean.FALSE: (Boolean)config.get("mirror_y")); + comboRotation.setSelectedIndex((config.get("rotate") == null) ? 0 :(Integer) (config.get("rotate"))); + if (calibration!=null){ + spinnerRefWidth.setValue(((Number)calibration.get("reference_marker_width")).doubleValue()); + spinnerRefHeight.setValue(((Number)calibration.get("reference_marker_height")).doubleValue()); + spinnerAngleHor.setValue(((Number)calibration.get("horizontal_camera_angle")).doubleValue()); + spinnerAngleVer.setValue(((Number)calibration.get("vertical_camera_angle")).doubleValue()); + refMarker = ((List)calibration.get("reference_marker")); + if (refMarker.size()==4){ + spinnerLeft.setValue(refMarker.get(0)); + spinnerTop.setValue(refMarker.get(1)); + spinnerRight.setValue(refMarker.get(2)); + spinnerBottom.setValue(refMarker.get(3)); + } + } + updateResults(); + + camera.resetRoi(); + + + renderer.setMode(RendererMode.Fit); + calibrationOverlays = new Overlay[]{ovTop, ovBottom, ovLeft, ovRight}; + for (Overlay ov : calibrationOverlays){ + ov.setMovable(true); + } + renderer.addOverlays(calibrationOverlays); + + try{ + Rectangle r = new Rectangle(); + ovLeft.update(new Point(Math.max(refMarker.get(0), 0), 0)); + ovTop.update(new Point(0, Math.max(refMarker.get(1), 0))); + ovRight.update(new Point(Math.max(refMarker.get(2), 0), 0)); + ovBottom.update(new Point(0, Math.max(refMarker.get(3),0))); + } catch (Exception ex){ + SwingUtils.invokeDelayed(() -> { + Dimension size = renderer.getImageSize(); + ovTop.update(new Point(0, size.height/8)); + ovBottom.update(new Point(0, 7*size.height/8)); + ovLeft.update(new Point(size.width/8, 0)); + ovRight.update(new Point(7*size.width/8, 0)); + }, 500); + } + renderer.addListener(new RendererListener(){ + @Override + public void onMoveFinished(Renderer renderer, Overlay overlay) { + if (overlay==ovTop){ + spinnerTop.setValue(ovTop.getPosition().y); + } else if (overlay==ovBottom){ + spinnerBottom.setValue(ovBottom.getPosition().y); + } else if (overlay==ovLeft){ + spinnerLeft.setValue(ovLeft.getPosition().x); + } else if (overlay==ovRight){ + spinnerRight.setValue(ovRight.getPosition().x); + } + } + }); + setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + pack(); + } + + @Override + protected void onClosed() { + renderer.removeOverlays(calibrationOverlays); + calibrationOverlays = null; + } + + + void updateResults(){ + try{ + int left = (Integer)spinnerLeft.getValue(); + int right = (Integer)spinnerRight.getValue(); + int top = (Integer)spinnerTop.getValue(); + int bottom = (Integer)spinnerBottom.getValue(); + double width = (Double)spinnerRefWidth.getValue(); + double height = (Double)spinnerRefHeight.getValue(); + textOriginX.setText(String.valueOf((left+right)/2)); + textOriginY.setText(String.valueOf((top+bottom)/2)); + textPixelSizeX.setText(String.valueOf(Convert.roundDouble(width/Math.abs(right-left),2))); + textPixelSizeY.setText(String.valueOf(Convert.roundDouble(height/Math.abs(bottom-top),2))); + ovLeft.update(new Point(Math.max(left, 0), 0)); + ovTop.update(new Point(0, Math.max(top, 0))); + ovRight.update(new Point(Math.max(right, 0), 0)); + ovBottom.update(new Point(0, Math.max(bottom,0))); + renderer.refresh(); + + } catch (Exception ex){ + SwingUtils.showException(this, ex); + } + } + + + public static void main(String args[]) throws Exception { + //String cameraName = "SINEG01-DSCR190"; + //String cameraName = "SATSY02-DSCR220" ; + String cameraName = "simulation" ; + PipelineServer server = new PipelineServer("Camera", "gfa-lc6-64:8889"); + server.start(cameraName); + //java.awt.EventQueue.invokeLater(() -> { + Renderer renderer = new Renderer(); + server.addListener(renderer); + JDialog dlgRenderer = SwingUtils.showDialog(null, cameraName, new Dimension(600,400), renderer); + CameraConfigDialog dialog = new CameraConfigDialog(null, server, renderer); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + dlgRenderer.setVisible(false); + server.close(); + System.exit(0); + } + }); + SwingUtils.centerComponent(null, dialog); + dialog.setVisible(true); + // }); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + jPanel1 = new javax.swing.JPanel(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + jLabel6 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + jLabel2 = new javax.swing.JLabel(); + jLabel8 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + jLabel10 = new javax.swing.JLabel(); + spinnerAngleHor = new javax.swing.JSpinner(); + spinnerAngleVer = new javax.swing.JSpinner(); + spinnerRefWidth = new javax.swing.JSpinner(); + spinnerRefHeight = new javax.swing.JSpinner(); + spinnerTop = new javax.swing.JSpinner(); + spinnerBottom = new javax.swing.JSpinner(); + spinnerLeft = new javax.swing.JSpinner(); + spinnerRight = new javax.swing.JSpinner(); + buttonFetch = new javax.swing.JButton(); + jPanel2 = new javax.swing.JPanel(); + checkMirrorX = new javax.swing.JCheckBox(); + checkMirrorY = new javax.swing.JCheckBox(); + comboRotation = new javax.swing.JComboBox(); + jLabel7 = new javax.swing.JLabel(); + jPanel3 = new javax.swing.JPanel(); + jLabel11 = new javax.swing.JLabel(); + textOriginX = new javax.swing.JTextField(); + jLabel12 = new javax.swing.JLabel(); + textOriginY = new javax.swing.JTextField(); + jLabel13 = new javax.swing.JLabel(); + jLabel14 = new javax.swing.JLabel(); + textPixelSizeX = new javax.swing.JTextField(); + textPixelSizeY = new javax.swing.JTextField(); + buttonOk = new javax.swing.JButton(); + buttonCancel = new javax.swing.JButton(); + + jLabel1.setText("Calibrate the camera moving the line overlays to the reference marks."); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Calibration")); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Reference marker height (um):"); + + jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel5.setText("Horizontal camera angle (deg):"); + + jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel6.setText("Vertical camera angle (deg):"); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Reference marker width (um):"); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("Top (px):"); + + jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel8.setText("Botton (px):"); + + jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel9.setText("Left (px):"); + + jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel10.setText("Right (px):"); + + spinnerAngleHor.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerAngleHor.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerAngleVer.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerAngleVer.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRefWidth.setModel(new javax.swing.SpinnerNumberModel(30000.0d, 1.0d, 500000.0d, 1.0d)); + spinnerRefWidth.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRefHeight.setModel(new javax.swing.SpinnerNumberModel(30000.0d, 1.0d, 500000.0d, 1.0d)); + spinnerRefHeight.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerTop.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerTop.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerBottom.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerBottom.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerLeft.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerLeft.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + spinnerRight.setModel(new javax.swing.SpinnerNumberModel(0, -10000, 10000, 1)); + spinnerRight.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + calibrationSpinnerChanged(evt); + } + }); + + buttonFetch.setText("Fetch from Inventory"); + buttonFetch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFetchActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerTop, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRefWidth, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel8) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerBottom, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRefHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel10) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerRight, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel6) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerAngleVer, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jLabel9) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerAngleHor, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(buttonFetch))) + .addContainerGap()) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel2, jLabel8, jLabel9}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(jLabel2) + .addComponent(spinnerRefWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel4) + .addComponent(jLabel8) + .addComponent(spinnerRefHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(jLabel9) + .addComponent(spinnerAngleHor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerLeft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(jLabel10) + .addComponent(spinnerAngleVer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerRight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) + .addComponent(buttonFetch) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Transformations")); + + checkMirrorX.setText("Mirror X"); + + checkMirrorY.setText("Mirror Y"); + + comboRotation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "270", "180", "90" })); + + jLabel7.setText("Rotation: "); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(checkMirrorX) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel7) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(comboRotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(checkMirrorY) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboRotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel7)) + .addComponent(checkMirrorX)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(checkMirrorY) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Results")); + + jLabel11.setText("Origin X (px):"); + + textOriginX.setEditable(false); + textOriginX.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + jLabel12.setText("Origin Y (px):"); + + textOriginY.setEditable(false); + textOriginY.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + jLabel13.setText("Y pixel size (um/px):"); + + jLabel14.setText("X pixel size (um/px):"); + + textPixelSizeX.setEditable(false); + textPixelSizeX.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + textPixelSizeY.setEditable(false); + textPixelSizeY.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(21, 21, 21) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel12) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textOriginY, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textOriginX, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel13) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textPixelSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jLabel14) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textPixelSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel11, jLabel12}); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel13, jLabel14}); + + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel14) + .addComponent(textPixelSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel13) + .addComponent(textPixelSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel11) + .addComponent(textOriginX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel12) + .addComponent(textOriginY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + + buttonOk.setText("Ok"); + buttonOk.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonOkActionPerformed(evt); + } + }); + + buttonCancel.setText("Cancel"); + buttonCancel.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonCancelActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(buttonOk) + .addGap(18, 18, 18) + .addComponent(buttonCancel) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonCancel, buttonOk}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonOk) + .addComponent(buttonCancel)) + .addContainerGap(16, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed + + try { + //renderer.removeOverlays(calibrationOverlays); + //calibrationOverlays = null; + //calibrationDialolg = null; + + int left = (Integer)spinnerLeft.getValue(); //left.getPosition().x + int right = (Integer)spinnerRight.getValue(); //right.getPosition().x + int top = (Integer)spinnerTop.getValue(); //top.getPosition().y + int bottom = (Integer)spinnerBottom.getValue(); //bottom.getPosition().y + double width = (Double)spinnerRefWidth.getValue(); + double height = (Double)spinnerRefHeight.getValue(); + double angleHor = (Double)spinnerAngleHor.getValue(); + double angleVer = (Double)spinnerAngleVer.getValue(); + + int x1 = Math.min(left, right); + int x2 = Math.max(left, right); + int y1 = Math.min(top, bottom); + int y2 = Math.max(top, bottom); + if ((x1!=-1) && (x2!=-1) && (y1!=-1) && (y2!=-1)){ + System.out.println("Updating " + cameraName + " configuration"); + HashMap calibration = new HashMap(); + calibration.put("reference_marker", Arrays.asList(new Integer[]{x1, y1, x2, y2})); + calibration.put("reference_marker_width", width); + calibration.put("reference_marker_height", height); + calibration.put("horizontal_camera_angle", angleHor); + calibration.put("vertical_camera_angle", angleVer); + //((Camtool) camera).setCalibration(cameraName, calibration); + + Map config = camera.getConfig(cameraName); + config.put("calibration", calibration); + config.put("mirror_x", checkMirrorX.isSelected()); + config.put("mirror_y", checkMirrorY.isSelected()); + config.put("rotate", comboRotation.getSelectedIndex()); + camera.setConfig(cameraName, config); + System.out.println("New config: " + config); + SwingUtils.showMessage(this, "Success", "Updated " + cameraName + " configuration"); + } + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + + accept(); + }//GEN-LAST:event_buttonOkActionPerformed + + private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed + cancel(); + }//GEN-LAST:event_buttonCancelActionPerformed + + private void buttonFetchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFetchActionPerformed + try{ + //List calib = Inventory.getCalibFromInventory(null, cameraName); + List calib = (List) Class.forName("Inventory"). + getMethod("getCalibFromInventory", + new Class[]{String.class,String.class}). + invoke(null, new Object[]{(String)null, cameraName}); + spinnerRefWidth.setValue(calib.get(0)*1000.0); + spinnerRefHeight.setValue(calib.get(1)*1000.0); + spinnerAngleHor.setValue(calib.get(2).intValue()); + spinnerAngleVer.setValue(calib.get(3).intValue()); + } catch (Exception ex){ + if (ex instanceof InvocationTargetException){ + ex = (Exception) ((InvocationTargetException)ex).getCause(); + } + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonFetchActionPerformed + + private void calibrationSpinnerChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_calibrationSpinnerChanged + updateResults(); + }//GEN-LAST:event_calibrationSpinnerChanged + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonCancel; + private javax.swing.JButton buttonFetch; + private javax.swing.JButton buttonOk; + private javax.swing.JCheckBox checkMirrorX; + private javax.swing.JCheckBox checkMirrorY; + private javax.swing.JComboBox comboRotation; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel12; + private javax.swing.JLabel jLabel13; + private javax.swing.JLabel jLabel14; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JSpinner spinnerAngleHor; + private javax.swing.JSpinner spinnerAngleVer; + private javax.swing.JSpinner spinnerBottom; + private javax.swing.JSpinner spinnerLeft; + private javax.swing.JSpinner spinnerRefHeight; + private javax.swing.JSpinner spinnerRefWidth; + private javax.swing.JSpinner spinnerRight; + private javax.swing.JSpinner spinnerTop; + private javax.swing.JTextField textOriginX; + private javax.swing.JTextField textOriginY; + private javax.swing.JTextField textPixelSizeX; + private javax.swing.JTextField textPixelSizeY; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Commands.java b/plugins/Commands.java new file mode 100755 index 0000000..e29ab24 --- /dev/null +++ b/plugins/Commands.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.utils.State; +import java.awt.Component; + +/** + * + */ +public class Commands extends Panel { + + public Commands() { + initComponents(); + } + + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + for (Component c : SwingUtils.getComponentsByType(this, Component.class)){ + c.setEnabled(state == State.Ready); + } + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + btRock = new javax.swing.JButton(); + btFbm = new javax.swing.JButton(); + btSete = new javax.swing.JButton(); + spEnergy = new javax.swing.JSpinner(); + jLabel1 = new javax.swing.JLabel(); + deviceValuePanel1 = new ch.psi.pshell.swing.DeviceValuePanel(); + + btRock.setText("Rock"); + btRock.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btRockActionPerformed(evt); + } + }); + + btFbm.setText("FBM"); + btFbm.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btFbmActionPerformed(evt); + } + }); + + btSete.setText("Set Energy"); + btSete.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btSeteActionPerformed(evt); + } + }); + + spEnergy.setModel(new javax.swing.SpinnerNumberModel(6.0d, 4.7d, 17.5d, 0.1d)); + + jLabel1.setText("kev"); + + deviceValuePanel1.setDeviceName("energy"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(96, 96, 96) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btFbm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btRock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btSete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGap(18, 18, 18) + .addComponent(spEnergy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(deviceValuePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel1) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btFbm, btRock, btSete}); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deviceValuePanel1, spEnergy}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(56, 56, 56) + .addComponent(btRock) + .addGap(18, 18, 18) + .addComponent(btFbm) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel1) + .addComponent(deviceValuePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spEnergy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(btSete)) + .addContainerGap(210, Short.MAX_VALUE)) + ); + + layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btFbm, btRock, btSete, deviceValuePanel1, jLabel1, spEnergy}); + + }// //GEN-END:initComponents + + private void btRockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRockActionPerformed + try { + getContext().evalLineAsync("rock()"); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_btRockActionPerformed + + private void btFbmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFbmActionPerformed + try { + getContext().evalLineAsync("fbm()"); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_btFbmActionPerformed + + private void btSeteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSeteActionPerformed + try { + getContext().evalLineAsync("sete(" + String.valueOf(spEnergy.getValue()) + ")"); + } catch (Exception ex) { + showException(ex); + } + + + }//GEN-LAST:event_btSeteActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btFbm; + private javax.swing.JButton btRock; + private javax.swing.JButton btSete; + private ch.psi.pshell.swing.DeviceValuePanel deviceValuePanel1; + private javax.swing.JLabel jLabel1; + private javax.swing.JSpinner spEnergy; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Commands.txt b/plugins/Commands.txt new file mode 100755 index 0000000..5cb69a5 --- /dev/null +++ b/plugins/Commands.txt @@ -0,0 +1,98 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/CustomStopAll.java b/plugins/CustomStopAll.java new file mode 100755 index 0000000..b5329cd --- /dev/null +++ b/plugins/CustomStopAll.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Plugin; +import ch.psi.pshell.epics.Scienta; +import java.util.logging.Level; + +/** + * + */ +public class CustomStopAll implements Plugin { + + //Overridable callbacks + @Override + public void onStoppedDevices() { + try{ + ((Scienta)getDevice("scienta")).zeroSupplies(); + } catch (Exception ex){ + getLogger().log(Level.WARNING, null, ex); + } + } + +} diff --git a/plugins/DarkTheme.java b/plugins/DarkTheme.java new file mode 100755 index 0000000..9803998 --- /dev/null +++ b/plugins/DarkTheme.java @@ -0,0 +1,62 @@ + +import ch.psi.pshell.ui.Plugin; +import java.awt.Color; +import java.util.logging.Level; +import javax.swing.UIManager; + +public class DarkTheme implements Plugin{ + + @Override + public void onStart() { + try { + + /* + //set Nimbus Look And Feel + UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); + //to nod display tabs + UIManager.put("EditorTabDisplayerUI", "icare.ui.tweak.tab.NoTabsTabDisplayerUI"); + //because Nimbus LAF do not use opaque option, force it to allow painting of custom tab. + //UIManager.put("TabbedPane.tabsOpaque", true); + + //set Nimbus LAF primary colors + UIManager.put("control", new Color(114,114,114)); + UIManager.put("nimbusBase", new Color(64,64,64)); + UIManager.put("nimbusFocus", new Color(191,191,191)); + UIManager.put("nimbusLightBackground", new Color(176,176,176)); + UIManager.put("nimbusSelectionBackground", new Color(90,130,195)); + UIManager.put("text", new Color(0,0,0)); + */ +UIManager.put( "control", new Color( 128, 128, 128) ); +UIManager.put( "info", new Color(128,128,128) ); +UIManager.put( "nimbusBase", new Color( 18, 30, 49) ); +UIManager.put( "nimbusAlertYellow", new Color( 248, 187, 0) ); +UIManager.put( "nimbusDisabledText", new Color( 128, 128, 128) ); +UIManager.put( "nimbusFocus", new Color(115,164,209) ); +UIManager.put( "nimbusGreen", new Color(176,179,50) ); +UIManager.put( "nimbusInfoBlue", new Color( 66, 139, 221) ); +UIManager.put( "nimbusLightBackground", new Color( 18, 30, 49) ); +UIManager.put( "nimbusOrange", new Color(191,98,4) ); +UIManager.put( "nimbusRed", new Color(169,46,34) ); +UIManager.put( "nimbusSelectedText", new Color( 255, 255, 255) ); +UIManager.put( "nimbusSelectionBackground", new Color( 104, 93, 156) ); + + +//nager.put( "TabbedPane:TabbedPaneTab[Enabled+MouseOver].backgroundPainter", new Color( 230, 0, 0) ); + + + + + + + } + catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } + + } + + @Override + public void onStop() { + } + +} diff --git a/plugins/DataFile.java b/plugins/DataFile.java new file mode 100755 index 0000000..5f4eaa2 --- /dev/null +++ b/plugins/DataFile.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Plugin; +import javax.swing.Timer; +import java.awt.event.ActionEvent; +import java.util.logging.Level; + +/** + * + */ +public class DataFile implements Plugin { + Timer timer; + + @Override + public void onInitialize(int runCount) { + if (timer != null) { + timer.stop(); + } + getView().getStatusBar().getAuxLabel().setForeground(new java.awt.Color(100, 100, 100)); + timer = new Timer(2000, (ActionEvent e) -> { + try { + onTimer(); + } catch (Exception ex) { + getLogger().log(Level.FINE, null, ex); + } + }); + timer.start(); + + } + + + void onTimer(){ + String file = getContext().getDataManager().getLastOutput(); + if (getState().isNormal() && (file !=null)){ + getView().getStatusBar().setAuxMessage(file); + } else { + getView().getStatusBar().setAuxMessage(""); + } + } +} diff --git a/plugins/DefaultPlugin.java b/plugins/DefaultPlugin.java new file mode 100755 index 0000000..81ca7c2 --- /dev/null +++ b/plugins/DefaultPlugin.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Plugin; +import ch.psi.utils.State; + +/** + * + */ +public class DefaultPlugin implements Plugin { + //Abstracts + @Override + public void onStart() { + } + + @Override + public void onStop() { + } + + //Overridables + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + +} diff --git a/plugins/Didier.form b/plugins/Didier.form new file mode 100755 index 0000000..da0acaf --- /dev/null +++ b/plugins/Didier.form @@ -0,0 +1,39 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Didier.java b/plugins/Didier.java new file mode 100755 index 0000000..5769904 --- /dev/null +++ b/plugins/Didier.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2014-2017 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.plot.LinePlotErrorSeries; +import ch.psi.pshell.plot.LinePlotJFree; +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.Plot; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; + +/** + * + */ +public class Didier extends Panel { + //LinePlotErrorSeries seriesEnergy = new LinePlotErrorSeries("Energy"); + //LinePlotErrorSeries seriesEnergySpread = new LinePlotErrorSeries("Energy Spread", null, 2); + LinePlotSeries seriesEnergy = new LinePlotSeries("Energy"); + LinePlotSeries seriesEnergySpread = new LinePlotSeries("Energy Spread", null, 2); + + public Didier() { + initComponents(); + //plot.setStyle(LinePlotJFree.Style.ErrorY); + plot.addSeries(seriesEnergy); + plot.addSeries(seriesEnergySpread); + plot.getAxis(Plot.AxisId.X).setLabel("Gun Phase"); + plot.getAxis(Plot.AxisId.Y).setLabel("Energy (MeV)"); + plot.getAxis(Plot.AxisId.Y2).setLabel("Energy Spread (MeV)"); + plot.setLegendVisible(true); + + + double[] x = new double[]{0,1,2,3,4}; + double[] y1 = new double[]{0,1,2,3,4}; + double[] y2 = new double[]{10,11,12,13,14}; + double[] e = new double[]{1,1,1,1,1}; + //seriesEnergy.setData(x, y1,e); + //seriesEnergySpread.setData(x, y2, e); + seriesEnergy.setData(x, y1); + seriesEnergySpread.setData(x, y2); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + plot = new ch.psi.pshell.plot.LinePlotJFree(); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(2, 2, 2)) + ); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private ch.psi.pshell.plot.LinePlotJFree plot; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/EnergyScan.form b/plugins/EnergyScan.form new file mode 100755 index 0000000..c98bea0 --- /dev/null +++ b/plugins/EnergyScan.form @@ -0,0 +1,588 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/EnergyScan.java b/plugins/EnergyScan.java new file mode 100755 index 0000000..d879632 --- /dev/null +++ b/plugins/EnergyScan.java @@ -0,0 +1,918 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.core.Context.ContextStateException; +import ch.psi.pshell.data.PlotDescriptor; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.DeviceAdapter; +import ch.psi.pshell.device.DeviceListener; +import ch.psi.pshell.epics.ChannelDoubleArray; +import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.plot.LinePlot; +import ch.psi.pshell.plot.LinePlotBase; +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.Plot; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.Chrono; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.psaf.DsvEditor; +import ch.psi.psaf.Editor.EditorDialog; +import java.awt.Component; +import java.io.FileInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; +import java.util.logging.Level; +import javax.swing.DefaultComboBoxModel; +import javax.swing.JLabel; + +/** + * + */ +public class EnergyScan extends Panel { + + ChannelDoubleArray data; + ChannelDoubleArray edata; + ChannelDoubleArray idata; + ChannelDoubleArray fdata; + ChannelInteger count; + + double[] offsets = new double[4]; + + public EnergyScan() { + initComponents(); + buttonDefaultsActionPerformed(null); + } + + @Override + public void onInitialize(int runCount) { + super.onInitialize(runCount); + + count = (ChannelInteger) getContext().getDevicePool().getByName("count"); + data = (ChannelDoubleArray) getContext().getDevicePool().getByName("data"); + edata = (ChannelDoubleArray) getContext().getDevicePool().getByName("edata"); + idata = (ChannelDoubleArray) getContext().getDevicePool().getByName("idata"); + fdata = (ChannelDoubleArray) getContext().getDevicePool().getByName("fdata"); + + getContext().getDevicePool().getByName("count").addListener(new DeviceAdapter() { + @Override + public void onValueChanged(Device device, Object value, Object former) { + update(); + } + }); + update(); + //loadConfig(); + } + + @Override + public void onStart() { + super.onStart(); + loadConfig(); + } + + @Override + public void onStateChange(State state, State former) { + setEnabled(state == State.Ready); + } + + void stopScan() throws Exception { + evalAsync("caput('START', 'STOP')"); + } + + long scanStartTimestamp; + + @Override + public void onExecutedFile(String fileName, Object result) { + try { + switch (fileName) { + case "EnergyScan": + if (result instanceof Exception) { + batchIndex = 0; + batch = null; + stopScan(); + throw ((Exception) result); + } + if (batch != null) { + batchIndex++; + if (batchIndex >= batch.length) { + batchIndex = 0; + batch = null; + } else { + setMode(batch[batchIndex]); + run(); + } + } + break; + } + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + SwingUtils.showException(this, ex); + } + } + + @Override + protected void doUpdate() { + plot(); + } + + Path getConfigFile() { + return Paths.get(getContext().getSetup().getConfigPath(), "energy_scan.properties"); + } + + enum Mode { + + plus, + minus, + lh, + lv + } + + Mode[] batch; + int batchIndex; + + LinePlotBase scanPlot; + LinePlotSeries scanSeries; + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + buttonExecute.setEnabled(value); + comboSetup.setEnabled(value); + comboRunType.setEnabled(value); + buttonConfigure.setEnabled(value); + textFile.setEnabled(value); + textFolder.setEnabled(value); + buttonDefaults.setEnabled(value); + buttonPlot.setEnabled(value); + checkParameterControls(); + } + + void checkParameterControls() { + boolean enabled = isEnabled() && (comboRunType.getSelectedIndex() == 0); + for (Component c : panelParameters.getComponents()) { + if (!(c instanceof JLabel)) { + c.setEnabled(enabled); + } + } + spinnerAlpha.setEnabled(enabled && comboMode.getSelectedItem().equals("LINEAR")); + } + + void plot() { + try { + if ((scanPlot != null) && (scanSeries != null) && scanPlot.isShowing() && (count != null)) { + //buttonGroupPlot.getSelection(). + Integer c = count.take(); + if (c == null) { + scanSeries.clear(); + } else { + double[] ydata = null; + if (radioE.isSelected()) { + data.setSize(c); + ydata = data.read(); + } else if (radioF.isSelected()) { + fdata.setSize(c); + ydata = fdata.read(); + } else if (radioI0.isSelected()) { + idata.setSize(c); + ydata = idata.read(); + } else if (radioTEY.isSelected()) { + data.setSize(c); + idata.setSize(c); + ydata = data.read(); + double[] i0 = idata.read(); + for (int i = 0; i < c; i++) { + ydata[i] = (i0[i] == 0.0) ? Double.NaN : ydata[i] / i0[i]; + } + } else if (radioTFY.isSelected()) { + fdata.setSize(c); + idata.setSize(c); + ydata = fdata.read(); + double[] i0 = idata.read(); + for (int i = 0; i < c; i++) { + ydata[i] = (i0[i] == 0.0) ? Double.NaN : ydata[i] / i0[i]; + } + } + if (ydata == null) { + scanSeries.clear(); + } else { + edata.setSize(c); + double[] xdata = edata.read(); + scanSeries.setData(xdata, ydata); + } + } + } + } catch (Exception ex) { + SwingUtils.showException(this, ex); + ex.printStackTrace(); + } + } + + void loadConfig() { + DefaultComboBoxModel model = (DefaultComboBoxModel) comboSetup.getModel(); + model.removeAllElements(); + try { + for (String line : Files.readAllLines(getConfigFile())) { + if ((line != null) && (!line.trim().isEmpty())) { + String[] tokens = line.split("="); + if (tokens.length > 0) { + model.addElement(tokens[0].trim()); + } + } + } + } catch (Exception ex) { + } + } + + String expandPath(String path) { + long time = System.currentTimeMillis(); + String mode; + if (comboMode.getSelectedIndex() == 0) { + mode = "plus"; + } else if (comboMode.getSelectedIndex() == 1) { + mode = "minus"; + } else { + mode = "lin_" + String.format("%1.0f", (Double) spinnerAlpha.getValue()); + } + + path = path.replaceAll("\\{date\\}", Chrono.getTimeStr(time, "YYYYMMdd")); + path = path.replaceAll("\\{time\\}", Chrono.getTimeStr(time, "HHmmss")); + path = path.replaceAll("\\{year\\}", Chrono.getTimeStr(time, "YYYY")); + path = path.replaceAll("\\{month\\}", Chrono.getTimeStr(time, "MM")); + path = path.replaceAll("\\{day\\}", Chrono.getTimeStr(time, "dd")); + path = path.replaceAll("\\{el\\}", String.valueOf(comboSetup.getSelectedItem())); + path = path.replaceAll("\\{mode\\}", mode); + return path; + } + + void setMode(Mode mode) { + switch (mode) { + case plus: + comboMode.setSelectedIndex(0); + spinnerOffset.setValue(offsets[0]); + return; + case minus: + comboMode.setSelectedIndex(1); + spinnerOffset.setValue(offsets[1]); + return; + case lh: + comboMode.setSelectedIndex(2); + spinnerOffset.setValue(offsets[2]); + spinnerAlpha.setValue(0.0); + return; + case lv: + comboMode.setSelectedIndex(2); + spinnerOffset.setValue(offsets[3]); + spinnerAlpha.setValue(90.0); + return; + } + } + + boolean isManualRun() { + return (comboRunType.getSelectedIndex() == 0); + } + + void setElement() throws Exception { + Properties prop = new Properties(); + prop.load(new FileInputStream(getConfigFile().toFile())); + String selection = comboSetup.getSelectedItem().toString(); + String val = prop.getProperty(selection); + String[] tokens = val.split(" "); + if (tokens.length != 8) { + throw new Exception("Invalid file format"); + } + spinnerE1.setValue(Double.valueOf(tokens[0].trim())); + spinnerE2.setValue(Double.valueOf(tokens[1].trim())); + spinnerTime.setValue(Double.valueOf(tokens[2].trim())); + spinnerDelay.setValue(Double.valueOf(tokens[3].trim())); + + offsets[0] = Double.valueOf(tokens[4].trim()); + offsets[1] = Double.valueOf(tokens[5].trim()); + offsets[2] = Double.valueOf(tokens[6].trim()); + offsets[3] = Double.valueOf(tokens[7].trim()); + } + + void setRunType() throws Exception { + switch (comboRunType.getSelectedIndex()) { + case 0: //Manual + break; + case 1: //+ + setMode(Mode.plus); + break; + case 2: //- + setMode(Mode.minus); + break; + case 3: //LH + setMode(Mode.lh); + break; + case 4: //LV + setMode(Mode.lv); + break; + case 5: //+/- + setMode(Mode.plus); + break; + case 6: //+/-/-/+ + setMode(Mode.plus); + break; + case 7: //LH/LV + setMode(Mode.lh); + break; + case 8: //LH/LV/LV/LH + setMode(Mode.lh); + break; + } + checkParameterControls(); + } + + void run() throws ContextStateException { + HashMap args = new HashMap(); + Double e1 = (Double) spinnerE1.getValue(); + Double e2 = (Double) spinnerE2.getValue(); + args.put("E1", e1); + args.put("E2", e2); + args.put("TIME", (Double) spinnerTime.getValue()); + args.put("DELAY", (Double) spinnerDelay.getValue()); + args.put("MODE", comboMode.getSelectedItem().toString()); + args.put("OFFSET", (Double) spinnerOffset.getValue()); + args.put("ALPHA", (Double) spinnerAlpha.getValue()); + + String file = expandPath(textFile.getText()); + args.put("FILE", file); + + String folder = expandPath(textFolder.getText()); + args.put("FOLDER", folder); + scanStartTimestamp = System.currentTimeMillis(); + runAsync("EnergyScan", args); + if (scanPlot != null) { + scanPlot.getAxis(Plot.AxisId.X).setRange(Math.min(e1, e2), Math.max(e1, e2)); + } + + } + + void startPlot() throws Exception { + PlotDescriptor descriptors = new PlotDescriptor("Energy Scan"); + ArrayList plots = getContext().plot(new PlotDescriptor[]{descriptors}, null); + scanPlot = (LinePlotBase) plots.get(0); + scanSeries = scanPlot.getSeries(0); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroupPlot = new javax.swing.ButtonGroup(); + panelParameters = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + spinnerE1 = new javax.swing.JSpinner(); + jLabel2 = new javax.swing.JLabel(); + spinnerE2 = new javax.swing.JSpinner(); + jLabel3 = new javax.swing.JLabel(); + spinnerTime = new javax.swing.JSpinner(); + jLabel4 = new javax.swing.JLabel(); + spinnerDelay = new javax.swing.JSpinner(); + jLabel5 = new javax.swing.JLabel(); + comboMode = new javax.swing.JComboBox(); + jLabel8 = new javax.swing.JLabel(); + spinnerOffset = new javax.swing.JSpinner(); + jLabel9 = new javax.swing.JLabel(); + spinnerAlpha = new javax.swing.JSpinner(); + jPanel1 = new javax.swing.JPanel(); + comboSetup = new javax.swing.JComboBox(); + buttonConfigure = new javax.swing.JButton(); + jLabel10 = new javax.swing.JLabel(); + jLabel11 = new javax.swing.JLabel(); + comboRunType = new javax.swing.JComboBox(); + jPanel2 = new javax.swing.JPanel(); + radioTEY = new javax.swing.JRadioButton(); + radioTFY = new javax.swing.JRadioButton(); + radioE = new javax.swing.JRadioButton(); + radioF = new javax.swing.JRadioButton(); + radioI0 = new javax.swing.JRadioButton(); + buttonPlot = new javax.swing.JButton(); + panelData = new javax.swing.JPanel(); + buttonDefaults = new javax.swing.JButton(); + jLabel6 = new javax.swing.JLabel(); + textFile = new javax.swing.JTextField(); + jLabel7 = new javax.swing.JLabel(); + textFolder = new javax.swing.JTextField(); + jPanel3 = new javax.swing.JPanel(); + buttonExecute = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + + panelParameters.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameters")); + + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel1.setText("E1:"); + + spinnerE1.setModel(new javax.swing.SpinnerNumberModel(690.0d, 0.0d, 9999.0d, 1.0d)); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("E2:"); + + spinnerE2.setModel(new javax.swing.SpinnerNumberModel(755.0d, 0.0d, 9999.0d, 1.0d)); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Time(min):"); + + spinnerTime.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.0d, 60.0d, 1.0d)); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Delay(s):"); + + spinnerDelay.setModel(new javax.swing.SpinnerNumberModel(10.0d, 0.0d, 600.0d, 1.0d)); + + jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel5.setText("Mode:"); + + comboMode.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CIRC +", "CIRC -", "LINEAR" })); + comboMode.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboModeActionPerformed(evt); + } + }); + + jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel8.setText("Offset:"); + + spinnerOffset.setModel(new javax.swing.SpinnerNumberModel(0.0d, -20.0d, 20.0d, 1.0d)); + + jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel9.setText("Alpha:"); + + spinnerAlpha.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 90.0d, 1.0d)); + + javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); + panelParameters.setLayout(panelParametersLayout); + panelParametersLayout.setHorizontalGroup( + panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelParametersLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(spinnerE1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerTime, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(comboMode, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, Short.MAX_VALUE) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(spinnerE2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerDelay, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerOffset, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerAlpha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelParametersLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboMode, spinnerE1, spinnerTime}); + + panelParametersLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel4, jLabel8, jLabel9}); + + panelParametersLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerAlpha, spinnerDelay, spinnerE2, spinnerOffset}); + + panelParametersLayout.setVerticalGroup( + panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelParametersLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(spinnerE1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel2) + .addComponent(spinnerE2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(spinnerTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel4) + .addComponent(spinnerDelay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(comboMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel8) + .addComponent(spinnerOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(5, 5, 5) + .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerAlpha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel9)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Setup")); + + comboSetup.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboSetupActionPerformed(evt); + } + }); + + buttonConfigure.setText("Configure"); + buttonConfigure.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonConfigureActionPerformed(evt); + } + }); + + jLabel10.setText("Element:"); + + jLabel11.setText("Run Type:"); + + comboRunType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Manual", "+", "-", "LH", "LV", "+/-", "+/-/-/+", "LH/LV", "LH/LV/LV/LH" })); + comboRunType.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboRunTypeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(comboSetup, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonConfigure, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(comboRunType, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonConfigure, comboRunType, comboSetup}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboSetup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel10)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonConfigure) + .addGap(18, 18, 18) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel11) + .addComponent(comboRunType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(15, Short.MAX_VALUE)) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Plot Options")); + + buttonGroupPlot.add(radioTEY); + radioTEY.setSelected(true); + radioTEY.setText("TEY"); + radioTEY.setMinimumSize(new java.awt.Dimension(100, 22)); + radioTEY.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioPlotActionPerformed(evt); + } + }); + + buttonGroupPlot.add(radioTFY); + radioTFY.setText("TFY"); + radioTFY.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioPlotActionPerformed(evt); + } + }); + + buttonGroupPlot.add(radioE); + radioE.setText("TEY raw"); + radioE.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioPlotActionPerformed(evt); + } + }); + + buttonGroupPlot.add(radioF); + radioF.setText("TFY raw"); + radioF.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioPlotActionPerformed(evt); + } + }); + + buttonGroupPlot.add(radioI0); + radioI0.setText("I0"); + radioI0.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioPlotActionPerformed(evt); + } + }); + + buttonPlot.setText("Plot"); + buttonPlot.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonPlotActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(radioTEY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(radioTFY) + .addComponent(radioE) + .addComponent(radioF) + .addComponent(radioI0) + .addComponent(buttonPlot)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonPlot, radioE, radioF, radioI0, radioTEY, radioTFY}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(radioTEY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioTFY) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioF) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioI0) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonPlot) + .addContainerGap()) + ); + + panelData.setBorder(javax.swing.BorderFactory.createTitledBorder("Data")); + + buttonDefaults.setText("Defaults"); + buttonDefaults.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDefaultsActionPerformed(evt); + } + }); + + jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel6.setText("File:"); + + jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel7.setText("Folder:"); + + javax.swing.GroupLayout panelDataLayout = new javax.swing.GroupLayout(panelData); + panelData.setLayout(panelDataLayout); + panelDataLayout.setHorizontalGroup( + panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelDataLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)) + .addGroup(panelDataLayout.createSequentialGroup() + .addGap(55, 55, 55) + .addGroup(panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(textFolder) + .addComponent(textFile)))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonDefaults) + .addContainerGap()) + ); + + panelDataLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel6, jLabel7}); + + panelDataLayout.setVerticalGroup( + panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelDataLayout.createSequentialGroup() + .addGroup(panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(textFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel7) + .addComponent(textFolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonDefaults, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Scan Control")); + + buttonExecute.setText("Start"); + buttonExecute.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonExecuteActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonAbort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonExecute, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(buttonExecute) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonAbort) + .addContainerGap()) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addComponent(panelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(16, 16, 16) + .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteActionPerformed + try { + startPlot(); + batchIndex = 0; + switch (comboRunType.getSelectedIndex()) { + case 5: + batch = new Mode[]{Mode.plus, Mode.minus}; + break; + case 6: + batch = new Mode[]{Mode.plus, Mode.minus, Mode.minus, Mode.plus}; + break; + case 7: + batch = new Mode[]{Mode.lh, Mode.lv}; + break; + case 8: + batch = new Mode[]{Mode.lh, Mode.lv, Mode.lv, Mode.lh}; + break; + default: + batch = null; + } + run(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonExecuteActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + batch = null; + abort(); + }//GEN-LAST:event_buttonAbortActionPerformed + + private void comboSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboSetupActionPerformed + try { + setElement(); + if (!isManualRun()) { + setRunType(); + } + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_comboSetupActionPerformed + + EditorDialog dlgConfig; + private void buttonConfigureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConfigureActionPerformed + try { + //Desktop.getDesktop().open(getConfigFile().toFile()); + if ((dlgConfig==null) || (!dlgConfig.isShowing())){ + String[] columns = new String[]{"Element", "E1", "E2", "Time", "Delay", "OffPlus", "OffMinus", "OffLH", "OffLV"}; + Class[] types = new Class[]{String.class, Double.class, Double.class, Double.class, Double.class, Double.class, Double.class, Double.class, Double.class}; + DsvEditor editor = new DsvEditor(columns , types, " "); + dlgConfig = editor.getDialog(getView(),false); + editor.load(getConfigFile().toString()); + editor.setTitle("Energy Scan Configuration"); + } + dlgConfig.setSize(640, 320); + showWindow(dlgConfig); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonConfigureActionPerformed + + private void comboModeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboModeActionPerformed + checkParameterControls(); + }//GEN-LAST:event_comboModeActionPerformed + + private void radioPlotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioPlotActionPerformed + plot(); + }//GEN-LAST:event_radioPlotActionPerformed + + private void comboRunTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboRunTypeActionPerformed + try { + if (!isManualRun()) { + setElement(); + } + setRunType(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_comboRunTypeActionPerformed + + private void buttonDefaultsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDefaultsActionPerformed + textFile.setText("{el}_{mode}"); + textFolder.setText("{year}_{month}/{date}"); + }//GEN-LAST:event_buttonDefaultsActionPerformed + + private void buttonPlotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPlotActionPerformed + try { + startPlot(); + plot(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + + }//GEN-LAST:event_buttonPlotActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonConfigure; + private javax.swing.JButton buttonDefaults; + private javax.swing.JButton buttonExecute; + private javax.swing.ButtonGroup buttonGroupPlot; + private javax.swing.JButton buttonPlot; + private javax.swing.JComboBox comboMode; + private javax.swing.JComboBox comboRunType; + private javax.swing.JComboBox comboSetup; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel panelData; + private javax.swing.JPanel panelParameters; + private javax.swing.JRadioButton radioE; + private javax.swing.JRadioButton radioF; + private javax.swing.JRadioButton radioI0; + private javax.swing.JRadioButton radioTEY; + private javax.swing.JRadioButton radioTFY; + private javax.swing.JSpinner spinnerAlpha; + private javax.swing.JSpinner spinnerDelay; + private javax.swing.JSpinner spinnerE1; + private javax.swing.JSpinner spinnerE2; + private javax.swing.JSpinner spinnerOffset; + private javax.swing.JSpinner spinnerTime; + private javax.swing.JTextField textFile; + private javax.swing.JTextField textFolder; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/GroovyPlugin.groovy b/plugins/GroovyPlugin.groovy new file mode 100755 index 0000000..1454157 --- /dev/null +++ b/plugins/GroovyPlugin.groovy @@ -0,0 +1,10 @@ +import ch.psi.pshell.ui.Panel; +import javax.swing.JLabel; +import javax.swing.JPanel; + +class GroovyPlugin extends Panel{ + public JPanel onStart() { + super.onStart(); + add(new JLabel("Hello!")); + } +} \ No newline at end of file diff --git a/plugins/HoloScan.form b/plugins/HoloScan.form new file mode 100755 index 0000000..7fbd058 --- /dev/null +++ b/plugins/HoloScan.form @@ -0,0 +1,626 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/HoloScan.java b/plugins/HoloScan.java new file mode 100755 index 0000000..4daa10e --- /dev/null +++ b/plugins/HoloScan.java @@ -0,0 +1,630 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.device.Motor; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import java.awt.Component; +import java.util.ArrayList; +import java.util.HashMap; +import javax.swing.JCheckBox; +import javax.swing.SpinnerNumberModel; + +/** + * + */ +public class HoloScan extends Panel { + + public HoloScan() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + Motor phi = (Motor) getDevice("motor"); + Motor theta = (Motor) getDevice("motor2"); + motorPanelPhi.setDevice(phi); + motorPanelTheta.setDevice(theta); + spinnerFromPhi.setModel(new SpinnerNumberModel(phi.getMinValue(), phi.getMinValue(), phi.getMaxValue(), 1.0)); + spinnerToPhi.setModel(new SpinnerNumberModel(phi.getMaxValue(), phi.getMinValue(), phi.getMaxValue(), 1.0)); + spinnerFromTheta.setModel(new SpinnerNumberModel(theta.getMinValue(), theta.getMinValue(), theta.getMaxValue(), 1.0)); + spinnerToTheta.setModel(new SpinnerNumberModel(theta.getMaxValue(), theta.getMinValue(), theta.getMaxValue(), 1.0)); + } + + @Override + public void onStateChange(State state, State former) { + setEnabled(isEnabled()); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + buttonAbort.setEnabled(value && getState().isInitialized()); + + boolean enableControls = (value && (getState()==State.Ready)); + for (Component c : panelSensors.getComponents()) { + c.setEnabled(enableControls); + } + for (Component c : panelPhi.getComponents()) { + c.setEnabled(enableControls); + } + buttonStart.setEnabled(enableControls); + + spinnerStepSizePhi.setEnabled(enableControls && radioStepSize.isSelected()); + spinnerStepsPhi.setEnabled(enableControls && radioSteps.isSelected()); + spinnerFromPhi.setEnabled(enableControls && radioAbsolute.isSelected()); + spinnerToPhi.setEnabled(enableControls && radioAbsolute.isSelected()); + spinnerRangePhi.setEnabled(enableControls && !radioAbsolute.isSelected()); + + spinnerStepSizeTheta.setEnabled(spinnerStepSizePhi.isEnabled()); + spinnerStepsTheta.setEnabled(spinnerStepsPhi.isEnabled()); + spinnerFromTheta.setEnabled(spinnerFromPhi.isEnabled()); + spinnerToTheta.setEnabled(spinnerToPhi.isEnabled()); + spinnerRangeTheta.setEnabled(spinnerRangePhi.isEnabled()); + } + + void startScan() throws Exception{ + HashMap args = new HashMap<>(); + ArrayList sensors = new ArrayList(); + for (Component c : panelSensors.getComponents()) { + if ((c instanceof JCheckBox) && ((JCheckBox) c).isSelected()) { + sensors.add(c.getName()); + } + } + args.put("SENSORS", sensors); + if (radioRelative.isSelected()) { + args.put("PHI_RANGE", new Double[]{-(Double) spinnerRangePhi.getValue() / 2, (Double) spinnerRangePhi.getValue() / 2}); + args.put("THETA_RANGE", new Double[]{-(Double) spinnerRangeTheta.getValue() / 2, (Double) spinnerRangeTheta.getValue() / 2}); + } else { + args.put("PHI_RANGE", new Double[]{(Double) spinnerFromPhi.getValue(), (Double) spinnerToPhi.getValue()}); + args.put("THETA_RANGE", new Double[]{(Double) spinnerFromTheta.getValue(), (Double) spinnerToTheta.getValue()}); + } + ArrayList steps = new ArrayList(); + if (radioStepSize.isSelected()) { + steps.add((Double) spinnerStepSizePhi.getValue()); + steps.add((Double) spinnerStepSizeTheta.getValue()); + } else { + steps.add((Integer) spinnerStepsPhi.getValue()); + steps.add((Integer) spinnerStepsTheta.getValue()); + } + args.put("STEPS", steps); + args.put("LATENCY", (Double) 0.0); + args.put("RELATIVE", radioRelative.isSelected()); + + runAsync("HoloScan", args); + } + + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + panelPhi = new javax.swing.JPanel(); + motorPanelPhi = new ch.psi.pshell.swing.MotorReadoutPanel(); + jLabel2 = new javax.swing.JLabel(); + spinnerRangePhi = new javax.swing.JSpinner(); + radioStepSize = new javax.swing.JRadioButton(); + radioSteps = new javax.swing.JRadioButton(); + spinnerStepSizePhi = new javax.swing.JSpinner(); + spinnerStepsPhi = new javax.swing.JSpinner(); + radioAbsolute = new javax.swing.JRadioButton(); + spinnerFromPhi = new javax.swing.JSpinner(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + spinnerToPhi = new javax.swing.JSpinner(); + radioRelative = new javax.swing.JRadioButton(); + jLabel6 = new javax.swing.JLabel(); + jLabel7 = new javax.swing.JLabel(); + motorPanelTheta = new ch.psi.pshell.swing.MotorReadoutPanel(); + jLabel8 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + spinnerFromTheta = new javax.swing.JSpinner(); + spinnerToTheta = new javax.swing.JSpinner(); + jLabel10 = new javax.swing.JLabel(); + spinnerRangeTheta = new javax.swing.JSpinner(); + jLabel11 = new javax.swing.JLabel(); + jLabel12 = new javax.swing.JLabel(); + spinnerStepSizeTheta = new javax.swing.JSpinner(); + jLabel13 = new javax.swing.JLabel(); + jLabel14 = new javax.swing.JLabel(); + spinnerStepsTheta = new javax.swing.JSpinner(); + panelSensors = new javax.swing.JPanel(); + checkImage = new javax.swing.JCheckBox(); + checkImageIntegration = new javax.swing.JCheckBox(); + checkSpectrum = new javax.swing.JCheckBox(); + checkCounts1 = new javax.swing.JCheckBox(); + checkTotalCount = new javax.swing.JCheckBox(); + checkCounts2 = new javax.swing.JCheckBox(); + checkCounts3 = new javax.swing.JCheckBox(); + checkCounts4 = new javax.swing.JCheckBox(); + checkCurrent = new javax.swing.JCheckBox(); + checkCur1 = new javax.swing.JCheckBox(); + checkCur2 = new javax.swing.JCheckBox(); + checkCur3 = new javax.swing.JCheckBox(); + buttonScientaSetup = new javax.swing.JButton(); + jPanel3 = new javax.swing.JPanel(); + buttonStart = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + + panelPhi.setBorder(javax.swing.BorderFactory.createTitledBorder("Positioners")); + panelPhi.setPreferredSize(new java.awt.Dimension(239, 538)); + + jLabel2.setText("Range Phi:"); + + spinnerRangePhi.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.001d, 100.0d, 1.0d)); + spinnerRangePhi.setEnabled(false); + + buttonGroup1.add(radioStepSize); + radioStepSize.setSelected(true); + radioStepSize.setText("Step Size"); + radioStepSize.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioStepSizeActionPerformed(evt); + } + }); + + buttonGroup1.add(radioSteps); + radioSteps.setText("Number of Steps"); + radioSteps.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioStepSizeActionPerformed(evt); + } + }); + + spinnerStepSizePhi.setModel(new javax.swing.SpinnerNumberModel(0.1d, 0.001d, 10.0d, 0.1d)); + + spinnerStepsPhi.setModel(new javax.swing.SpinnerNumberModel(10, 1, 1000, 1)); + spinnerStepsPhi.setEnabled(false); + + buttonGroup2.add(radioAbsolute); + radioAbsolute.setSelected(true); + radioAbsolute.setText("Absolute Scan"); + radioAbsolute.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioAbsoluteActionPerformed(evt); + } + }); + + spinnerFromPhi.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + jLabel4.setText("Phi From:"); + + jLabel5.setText("Phi To:"); + + spinnerToPhi.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + buttonGroup2.add(radioRelative); + radioRelative.setText("Relative Scan"); + radioRelative.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioAbsoluteActionPerformed(evt); + } + }); + + jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel6.setText("Phi:"); + + jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel7.setText("Theta:"); + + jLabel8.setText("Theta To:"); + + jLabel9.setText("Theta From:"); + + spinnerFromTheta.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + spinnerToTheta.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + jLabel10.setText("Range Theta:"); + + spinnerRangeTheta.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.001d, 100.0d, 1.0d)); + spinnerRangeTheta.setEnabled(false); + + jLabel11.setText("Phi:"); + + jLabel12.setText("Theta:"); + + spinnerStepSizeTheta.setModel(new javax.swing.SpinnerNumberModel(0.1d, 0.001d, 10.0d, 0.1d)); + + jLabel13.setText("Phi:"); + + jLabel14.setText("Theta:"); + + spinnerStepsTheta.setModel(new javax.swing.SpinnerNumberModel(10, 1, 1000, 1)); + spinnerStepsTheta.setEnabled(false); + + javax.swing.GroupLayout panelPhiLayout = new javax.swing.GroupLayout(panelPhi); + panelPhi.setLayout(panelPhiLayout); + panelPhiLayout.setHorizontalGroup( + panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPhiLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPhiLayout.createSequentialGroup() + .addComponent(jLabel6) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(motorPanelPhi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(panelPhiLayout.createSequentialGroup() + .addComponent(jLabel7) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(motorPanelTheta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(panelPhiLayout.createSequentialGroup() + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(radioSteps) + .addComponent(radioStepSize) + .addComponent(radioAbsolute) + .addComponent(radioRelative)) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPhiLayout.createSequentialGroup() + .addGap(0, 74, Short.MAX_VALUE) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPhiLayout.createSequentialGroup() + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(spinnerFromPhi, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerRangePhi, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerToPhi, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerFromTheta, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerToTheta, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerRangeTheta, javax.swing.GroupLayout.Alignment.TRAILING))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPhiLayout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerStepSizePhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPhiLayout.createSequentialGroup() + .addComponent(jLabel12) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerStepSizeTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPhiLayout.createSequentialGroup() + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel14) + .addComponent(jLabel13)) + .addGap(6, 6, 6) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(spinnerStepsPhi, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerStepsTheta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))) + .addContainerGap()) + ); + + panelPhiLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {radioStepSize, radioSteps}); + + panelPhiLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerRangePhi, spinnerStepSizePhi, spinnerStepsPhi}); + + panelPhiLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel6, jLabel7}); + + panelPhiLayout.setVerticalGroup( + panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPhiLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel6) + .addComponent(motorPanelPhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel7) + .addComponent(motorPanelTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addComponent(radioAbsolute) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerFromPhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel4)) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerToPhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel5)) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerFromTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel9)) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerToTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel8)) + .addGap(18, 18, 18) + .addComponent(radioRelative) + .addGap(1, 1, 1) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(spinnerRangePhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(1, 1, 1) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel10) + .addComponent(spinnerRangeTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addComponent(radioStepSize) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStepSizePhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel11)) + .addGap(3, 3, 3) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStepSizeTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel12)) + .addGap(1, 1, 1) + .addComponent(radioSteps) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStepsPhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel13)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPhiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStepsTheta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel14)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelSensors.setBorder(javax.swing.BorderFactory.createTitledBorder("Sensors")); + panelSensors.setPreferredSize(new java.awt.Dimension(239, 422)); + + checkImage.setSelected(true); + checkImage.setText("Scienta Image"); + checkImage.setToolTipText(""); + checkImage.setContentAreaFilled(false); + checkImage.setName("det.dataMatrix"); // NOI18N + + checkImageIntegration.setSelected(true); + checkImageIntegration.setText("Scienta Image Integration"); + checkImageIntegration.setToolTipText(""); + checkImageIntegration.setContentAreaFilled(false); + checkImageIntegration.setName("integration"); // NOI18N + + checkSpectrum.setSelected(true); + checkSpectrum.setText("Scienta Spectrum"); + checkSpectrum.setName("scienta.spectrum"); // NOI18N + + checkCounts1.setText("Counts Region 1"); + checkCounts1.setName("countsr1"); // NOI18N + + checkTotalCount.setSelected(true); + checkTotalCount.setText("Total Counts"); + checkTotalCount.setName("sinp"); // NOI18N + + checkCounts2.setText("Counts Region 2"); + checkCounts2.setName("countsr2"); // NOI18N + + checkCounts3.setText("Counts Region 3"); + checkCounts3.setName("countsr3"); // NOI18N + + checkCounts4.setText("Counts Region 4"); + checkCounts4.setName("countsr4"); // NOI18N + + checkCurrent.setText("Current"); + checkCurrent.setName("current"); // NOI18N + + checkCur1.setText("Cur 1"); + checkCur1.setName("cur1"); // NOI18N + + checkCur2.setText("Cur 2"); + checkCur2.setName("cur2"); // NOI18N + + checkCur3.setText("Cur 3"); + checkCur3.setName("cur3"); // NOI18N + + buttonScientaSetup.setText("Scienta Setup"); + buttonScientaSetup.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScientaSetupActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelSensorsLayout = new javax.swing.GroupLayout(panelSensors); + panelSensors.setLayout(panelSensorsLayout); + panelSensorsLayout.setHorizontalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonScientaSetup, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addGroup(panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkImage) + .addComponent(checkImageIntegration) + .addComponent(checkSpectrum) + .addComponent(checkCounts1) + .addComponent(checkTotalCount) + .addComponent(checkCounts2) + .addComponent(checkCounts3) + .addComponent(checkCounts4) + .addComponent(checkCurrent) + .addComponent(checkCur1) + .addComponent(checkCur2) + .addComponent(checkCur3)) + .addGap(0, 56, Short.MAX_VALUE))) + .addContainerGap()) + ); + panelSensorsLayout.setVerticalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addComponent(checkImage) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkImageIntegration) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkSpectrum) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkTotalCount) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCurrent) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur3) + .addGap(18, 18, Short.MAX_VALUE) + .addComponent(buttonScientaSetup) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Scan Control")); + jPanel3.setPreferredSize(new java.awt.Dimension(239, 119)); + + buttonStart.setText("Start"); + buttonStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStartActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)) + .addContainerGap()) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonStart) + .addGap(18, 18, 18) + .addComponent(buttonAbort) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(panelSensors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(panelPhi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanel3, panelPhi, panelSensors}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(panelPhi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelSensors, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonScientaSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScientaSetupActionPerformed + try{ + showDevicePanel("scienta"); + } catch (Exception ex){ + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonScientaSetupActionPerformed + + private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed + try{ + startScan(); + } catch (Exception ex){ + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonStartActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + abort(); + }//GEN-LAST:event_buttonAbortActionPerformed + + private void radioStepSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioStepSizeActionPerformed + setEnabled(isEnabled()); + }//GEN-LAST:event_radioStepSizeActionPerformed + + private void radioAbsoluteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioAbsoluteActionPerformed + setEnabled(isEnabled()); + }//GEN-LAST:event_radioAbsoluteActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.JButton buttonScientaSetup; + private javax.swing.JButton buttonStart; + private javax.swing.JCheckBox checkCounts1; + private javax.swing.JCheckBox checkCounts2; + private javax.swing.JCheckBox checkCounts3; + private javax.swing.JCheckBox checkCounts4; + private javax.swing.JCheckBox checkCur1; + private javax.swing.JCheckBox checkCur2; + private javax.swing.JCheckBox checkCur3; + private javax.swing.JCheckBox checkCurrent; + private javax.swing.JCheckBox checkImage; + private javax.swing.JCheckBox checkImageIntegration; + private javax.swing.JCheckBox checkSpectrum; + private javax.swing.JCheckBox checkTotalCount; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel12; + private javax.swing.JLabel jLabel13; + private javax.swing.JLabel jLabel14; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel3; + private ch.psi.pshell.swing.MotorReadoutPanel motorPanelPhi; + private ch.psi.pshell.swing.MotorReadoutPanel motorPanelTheta; + private javax.swing.JPanel panelPhi; + private javax.swing.JPanel panelSensors; + private javax.swing.JRadioButton radioAbsolute; + private javax.swing.JRadioButton radioRelative; + private javax.swing.JRadioButton radioStepSize; + private javax.swing.JRadioButton radioSteps; + private javax.swing.JSpinner spinnerFromPhi; + private javax.swing.JSpinner spinnerFromTheta; + private javax.swing.JSpinner spinnerRangePhi; + private javax.swing.JSpinner spinnerRangeTheta; + private javax.swing.JSpinner spinnerStepSizePhi; + private javax.swing.JSpinner spinnerStepSizeTheta; + private javax.swing.JSpinner spinnerStepsPhi; + private javax.swing.JSpinner spinnerStepsTheta; + private javax.swing.JSpinner spinnerToPhi; + private javax.swing.JSpinner spinnerToTheta; + // End of variables declaration//GEN-END:variables +} + diff --git a/plugins/Image.form b/plugins/Image.form new file mode 100755 index 0000000..12acb0e --- /dev/null +++ b/plugins/Image.form @@ -0,0 +1,58 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Image.java b/plugins/Image.java new file mode 100755 index 0000000..60f408e --- /dev/null +++ b/plugins/Image.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.Source; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.awt.Color; +import java.awt.Point; + +/** + * + */ +public class Image extends Panel { + public Image() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + final Overlay overlay = new Overlays.Rect(new Pen(Color.RED), new Point(10,10), new Point(50,50)); + renderer.addOverlay(overlay); + overlay.setMovable(true); + overlay.setSolid(true); + + renderer.addListener(new RendererListener() { + public void onMouseDragged(Renderer renderer, Point p) { + //sendOutput(p.toString()); + System.out.println((p.x - renderer.getImageSize().width/2) + " - " + (p.y - renderer.getImageSize().height/2)); + } + + public void onMoveFinished(Renderer renderer, Overlay ov) { + if (ov == overlay){ + System.out.println(ov.getPosition().toString()); + } + } + } ); + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + renderer = new ch.psi.pshell.imaging.Renderer(); + jButton1 = new javax.swing.JButton(); + + renderer.setAutoscrolls(true); + renderer.setDeviceName("src1"); + renderer.setMode(ch.psi.pshell.imaging.RendererMode.Fit); + renderer.setShowStatus(false); + + jButton1.setText("Wait click"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jButton1) + .addContainerGap(430, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(renderer, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE) + .addComponent(jButton1) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + try{ + new Thread(()->{ + try { + Point p = renderer.waitClick(10000); + System.out.println(p); + } catch (Exception ex) { + } + jButton1.setEnabled(true); + + }).start(); + jButton1.setEnabled(false); + } catch (Exception ex){ + showException(ex); + } + }//GEN-LAST:event_jButton1ActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private ch.psi.pshell.imaging.Renderer renderer; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Inventory.java b/plugins/Inventory.java new file mode 100755 index 0000000..2a18f1c --- /dev/null +++ b/plugins/Inventory.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + + +import ch.psi.pshell.core.JsonSerializer; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.JacksonFeature; + +/** + * + */ +public class Inventory { + + public static T inventoryRequest(String url, Map attributes, Class type) throws IOException { + String json = JsonSerializer.encode(attributes); + Client client = ClientBuilder.newClient(new ClientConfig().register(JacksonFeature.class)); + try { + WebTarget resource = client.target(url); + Response r = resource.request().accept(MediaType.TEXT_HTML).post(Entity.json(json)); + json = r.readEntity(String.class); + if (r.getStatus() != Response.Status.OK.getStatusCode()) { + throw new IOException("Inventory returned error: " + json); + } + Map ret = (Map) JsonSerializer.decode(json, Map.class); + return (T) ret.get("d"); + } finally { + client.close(); + } + } + + public static String findPartidByHoly(String holy_name, String type) throws IOException { + if (type == null) { + type = "DSCR"; + } + Map query = new HashMap(); + Map qn = new HashMap(); + Map qt = new HashMap(); + qn.put("Field", "Holy List Name"); + qn.put("Operator", "Is"); + qn.put("Value", holy_name); + qt.put("Field", "Type"); + qt.put("Operator", "Is"); + qt.put("Value", type); + query.put("query", Arrays.asList(new Map[]{qn, qt})); + query.put("columns", Arrays.asList(new String[]{"Label"})); + + Map attr = new HashMap(); + attr.put("search", query); + Map ret = (Map) inventoryRequest("https://inventory.psi.ch/DataAccess.asmx/FindObjects", attr, Map.class); + try { + return (String) ((List) (((List) ret.get("Rows")).get(0))).get(0); + } catch (Exception ex) { + return null; + } + } + + public static List findAllByType(String type, String column) throws IOException { + if (type == null) { + type = "DSCR"; + } + if (column == null) { + column = "Holy List Name"; + } + + Map query = new HashMap(); + Map q = new HashMap(); + q.put("Field", "Type"); + q.put("Operator", "Is"); + q.put("Value", type); + query.put("query", Arrays.asList(new Map[]{q})); + query.put("columns", Arrays.asList(new String[]{"Label"})); + + Map attr = new HashMap(); + attr.put("search", query); + Map r = (Map) inventoryRequest("https://inventory.psi.ch/DataAccess.asmx/FindObjects", attr, Map.class); + List rows = (List) (r.get("Rows")); + List ret = new ArrayList(); + for (Object list : rows) { + ret.add(((List) list).get(0)); + } + return ret; + } + + public static List getPartAttributesFromInventory(String part_label, String holy_name) throws IOException { + if ((holy_name != null) && !holy_name.isEmpty()) { + part_label = findPartidByHoly(holy_name, "DSCR"); + if ((part_label == null) || part_label.isEmpty()) { + throw new IOException("Could not find inventory part for: " + holy_name); + } + } + Map map = new HashMap(); + map.put("psiLabel", part_label); + return (List) inventoryRequest("https://inventory.psi.ch/DataAccess.asmx/GetPartAttributes", map, List.class); + } + + public static List getCalibFromInvetory(String part_label, String holy_name) throws IOException { + double horizontal_dist = 0.0; + double vertical_dist = 0.0; + double horizontal_tilt = 0.0; + double vertical_tilt = 0.0; + + List attributes = getPartAttributesFromInventory(part_label, holy_name); + + for (Map a : attributes) { + String name = (String) a.get("Name"); + Double val = 0.0; + try { + val = Double.valueOf(a.get("Value").toString()); + } catch (Exception ex) { + } + + switch (name) { + case "Crystal angle in x (e-beam system) [deg]": + horizontal_tilt = val; + break; + case "Crystal angle in y (e-beam system) [deg]": + vertical_tilt = val; + break; + case "Mark distance in x (e-beam system) [mm]": + horizontal_dist = val; + break; + case "Mark distance in y (e-beam system) [mm]": + vertical_dist = val; + break; + } + } + + return Arrays.asList(new Double[]{horizontal_dist, vertical_dist, horizontal_tilt, vertical_tilt}); + } + + public static void main(String[] args) throws IOException { + System.out.println(getCalibFromInvetory("SINEG01-DSCR190", "SINEG01-DSCR190")); + System.out.println(findAllByType(null, null)); + } +} diff --git a/plugins/LayoutParallelScan.py b/plugins/LayoutParallelScan.py new file mode 100755 index 0000000..982ae52 --- /dev/null +++ b/plugins/LayoutParallelScan.py @@ -0,0 +1,5 @@ +import ch.psi.pshell.data.LayoutDefault + +class LayoutParallelScan(ch.psi.pshell.data.LayoutDefault): + def getDefaultGroup(self, scan): + return scan.readables[0].name \ No newline at end of file diff --git a/plugins/MXSC-1.4.0.jar b/plugins/MXSC-1.4.0.jar new file mode 100755 index 0000000..60c3451 Binary files /dev/null and b/plugins/MXSC-1.4.0.jar differ diff --git a/plugins/MXSC-1.5.0.jar b/plugins/MXSC-1.5.0.jar new file mode 100755 index 0000000..a9ee014 Binary files /dev/null and b/plugins/MXSC-1.5.0.jar differ diff --git a/plugins/MXSC-1.9.0.jar b/plugins/MXSC-1.9.0.jar new file mode 100755 index 0000000..f63e408 Binary files /dev/null and b/plugins/MXSC-1.9.0.jar differ diff --git a/plugins/ManipulatorScan.form b/plugins/ManipulatorScan.form new file mode 100755 index 0000000..3043641 --- /dev/null +++ b/plugins/ManipulatorScan.form @@ -0,0 +1,550 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/ManipulatorScan.java b/plugins/ManipulatorScan.java new file mode 100755 index 0000000..948e2e3 --- /dev/null +++ b/plugins/ManipulatorScan.java @@ -0,0 +1,604 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.device.Motor; +import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.ui.Plugin; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import java.awt.Component; +import java.util.ArrayList; +import java.util.HashMap; +import javax.swing.JCheckBox; +import javax.swing.SpinnerNumberModel; + +/** + * + */ +public class ManipulatorScan extends Panel { + + public ManipulatorScan() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + comboMotorActionPerformed(null); + } + + @Override + public void onStateChange(State state, State former) { + setEnabled(isEnabled()); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + buttonAbort.setEnabled(value && getState().isInitialized()); + + boolean enableControls = (value && (getState() == State.Ready)); + for (Component c : panelSensors.getComponents()) { + c.setEnabled(enableControls); + } + for (Component c : panelPositioner.getComponents()) { + c.setEnabled(enableControls); + } + buttonStart.setEnabled(enableControls); + spinnerStepSize.setEnabled(enableControls && radioStepSize.isSelected()); + spinnerSteps.setEnabled(enableControls && radioSteps.isSelected()); + + spinnerFrom.setEnabled(enableControls && radioAbsolute.isSelected()); + spinnerTo.setEnabled(enableControls && radioAbsolute.isSelected()); + spinnerRange.setEnabled(enableControls && !radioAbsolute.isSelected()); + + } + + void updateTable(){ + + } + + void startScan() throws Exception { + HashMap args = new HashMap<>(); + args.put("MOTOR", comboMotor.getSelectedItem().toString()); + ArrayList sensors = new ArrayList(); + for (Component c : panelSensors.getComponents()) { + if ((c instanceof JCheckBox) && ((JCheckBox) c).isSelected()) { + sensors.add(c.getName()); + } + } + args.put("SENSORS", sensors); + if (radioRelative.isSelected()) { + args.put("RANGE", new Double[]{-(Double) spinnerRange.getValue() / 2, (Double) spinnerRange.getValue() / 2}); + } else { + args.put("RANGE", new Double[]{(Double) spinnerFrom.getValue(), (Double) spinnerTo.getValue()}); + } + if (radioStepSize.isSelected()) { + ArrayList steps = new ArrayList(); + steps.add((Double) spinnerStepSize.getValue()); + args.put("STEPS", steps); + } else { + args.put("STEPS", (Integer) spinnerSteps.getValue()); + } + args.put("LATENCY", (Double) spinnerLatency.getValue()); + args.put("RELATIVE", radioRelative.isSelected()); + + runAsync("ManipulatorScan", args); + + /* + getContext().setExecutingContext("manip_scan"); + String scan ="lscan(" + comboMotor.getSelectedItem().toString() + ", ( " ; + for (Component c : panelSensors.getComponents()) { + if ((c instanceof JCheckBox) && ((JCheckBox)c).isSelected()) + scan += c.getName() + ", "; + } + scan+="), "; + if (radioRelative.isSelected()){ + double halfRange = (Double)spinnerRange.getValue()/2; + scan+= (-halfRange) + ", " + (halfRange)+ ", "; + } else { + Double from = (Double)spinnerFrom.getValue(); + Double to = (Double)spinnerTo.getValue(); + + if (to <= from){ + throw new Exception ("Invalid range"); + } + scan+= from + ", " + to + ", "; + } + + scan+= (radioStepSize.isSelected()) ? "(" +((Double)spinnerStepSize.getValue())+",)" :((Integer)spinnerSteps.getValue()); + scan+=", " + (Double)spinnerLatency.getValue() + ", "; + if (radioRelative.isSelected()){ + scan+="True, "; //Relative + } + scan+="before_read=trig_scienta)"; //Relative + + if (checkImageIntegration.isSelected()){ + scan = "set_preference(Preference.PLOT_TYPES,{'integration':1}); " + scan; + } + + evalAsync(scan); + */ + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + panelPositioner = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + comboMotor = new javax.swing.JComboBox(); + motorPanel = new ch.psi.pshell.swing.MotorReadoutPanel(); + txtSize = new javax.swing.JLabel(); + spinnerRange = new javax.swing.JSpinner(); + radioStepSize = new javax.swing.JRadioButton(); + radioSteps = new javax.swing.JRadioButton(); + spinnerStepSize = new javax.swing.JSpinner(); + spinnerSteps = new javax.swing.JSpinner(); + jLabel3 = new javax.swing.JLabel(); + spinnerLatency = new javax.swing.JSpinner(); + radioAbsolute = new javax.swing.JRadioButton(); + spinnerFrom = new javax.swing.JSpinner(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + spinnerTo = new javax.swing.JSpinner(); + radioRelative = new javax.swing.JRadioButton(); + jLabel6 = new javax.swing.JLabel(); + jLabel7 = new javax.swing.JLabel(); + jLabel8 = new javax.swing.JLabel(); + panelSensors = new javax.swing.JPanel(); + checkImage = new javax.swing.JCheckBox(); + checkImageIntegration = new javax.swing.JCheckBox(); + checkSpectrum = new javax.swing.JCheckBox(); + checkCounts1 = new javax.swing.JCheckBox(); + checkTotalCount = new javax.swing.JCheckBox(); + checkCounts2 = new javax.swing.JCheckBox(); + checkCounts3 = new javax.swing.JCheckBox(); + checkCounts4 = new javax.swing.JCheckBox(); + checkCurrent = new javax.swing.JCheckBox(); + checkCur1 = new javax.swing.JCheckBox(); + checkCur2 = new javax.swing.JCheckBox(); + checkCur3 = new javax.swing.JCheckBox(); + buttonScientaSetup = new javax.swing.JButton(); + jPanel3 = new javax.swing.JPanel(); + buttonStart = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + + panelPositioner.setBorder(javax.swing.BorderFactory.createTitledBorder("Positioner")); + + jLabel1.setText("Motor:"); + + comboMotor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "motor", "x", "y", "z", "theta", "tilt", "phi" })); + comboMotor.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboMotorActionPerformed(evt); + } + }); + + txtSize.setText("Size:"); + + spinnerRange.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.001d, 100.0d, 1.0d)); + spinnerRange.setEnabled(false); + + buttonGroup1.add(radioStepSize); + radioStepSize.setSelected(true); + radioStepSize.setText("Step Size"); + radioStepSize.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioStepSizeActionPerformed(evt); + } + }); + + buttonGroup1.add(radioSteps); + radioSteps.setText("Number of Steps"); + radioSteps.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioStepSizeActionPerformed(evt); + } + }); + + spinnerStepSize.setModel(new javax.swing.SpinnerNumberModel(0.1d, 0.001d, 10.0d, 0.1d)); + + spinnerSteps.setModel(new javax.swing.SpinnerNumberModel(10, 1, 1000, 1)); + spinnerSteps.setEnabled(false); + + jLabel3.setText("Latency(s):"); + + spinnerLatency.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 10.0d, 0.1d)); + + buttonGroup2.add(radioAbsolute); + radioAbsolute.setSelected(true); + radioAbsolute.setText("Absolute Scan"); + radioAbsolute.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioAbsoluteActionPerformed(evt); + } + }); + + spinnerFrom.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + jLabel4.setText("From:"); + + jLabel5.setText("To:"); + + spinnerTo.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 1.0d, 1.0d)); + + buttonGroup2.add(radioRelative); + radioRelative.setText("Relative Scan"); + radioRelative.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioAbsoluteActionPerformed(evt); + } + }); + + jLabel6.setText("Position:"); + + jLabel7.setText("Range:"); + + jLabel8.setText("Steps:"); + + javax.swing.GroupLayout panelPositionerLayout = new javax.swing.GroupLayout(panelPositioner); + panelPositioner.setLayout(panelPositionerLayout); + panelPositionerLayout.setHorizontalGroup( + panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(radioSteps, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel6) + .addComponent(jLabel1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(motorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboMotor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 85, Short.MAX_VALUE) + .addComponent(spinnerLatency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(radioStepSize) + .addComponent(radioAbsolute) + .addComponent(radioRelative)) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel4) + .addComponent(jLabel5) + .addComponent(jLabel7)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(spinnerFrom, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerRange, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerTo, javax.swing.GroupLayout.Alignment.TRAILING))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addComponent(jLabel8) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerSteps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addComponent(txtSize) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerStepSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) + .addContainerGap()) + ); + + panelPositionerLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerLatency, spinnerRange, spinnerStepSize, spinnerSteps}); + + panelPositionerLayout.setVerticalGroup( + panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(comboMotor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel6) + .addComponent(motorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addComponent(radioAbsolute) + .addGap(3, 3, 3) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel4)) + .addGap(3, 3, 3) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel5)) + .addGap(18, 18, 18) + .addComponent(radioRelative) + .addGap(1, 1, 1) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel7)) + .addGap(18, 18, 18) + .addComponent(radioStepSize) + .addGap(0, 0, 0) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStepSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(txtSize)) + .addGap(12, 12, 12) + .addComponent(radioSteps) + .addGap(0, 0, 0) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSteps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel8)) + .addGap(18, 18, 18) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(spinnerLatency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelSensors.setBorder(javax.swing.BorderFactory.createTitledBorder("Sensors")); + + checkImage.setSelected(true); + checkImage.setText("Scienta Image"); + checkImage.setToolTipText(""); + checkImage.setContentAreaFilled(false); + checkImage.setName("det.dataMatrix"); // NOI18N + + checkImageIntegration.setSelected(true); + checkImageIntegration.setText("Scienta Image Integration"); + checkImageIntegration.setToolTipText(""); + checkImageIntegration.setContentAreaFilled(false); + checkImageIntegration.setName("integration"); // NOI18N + + checkSpectrum.setSelected(true); + checkSpectrum.setText("Scienta Spectrum"); + checkSpectrum.setName("scienta.spectrum"); // NOI18N + + checkCounts1.setText("Counts Region 1"); + checkCounts1.setName("countsr1"); // NOI18N + + checkTotalCount.setSelected(true); + checkTotalCount.setText("Total Counts"); + checkTotalCount.setName("scienta.stats[0]"); // NOI18N + + checkCounts2.setText("Counts Region 2"); + checkCounts2.setName("countsr2"); // NOI18N + + checkCounts3.setText("Counts Region 3"); + checkCounts3.setName("countsr3"); // NOI18N + + checkCounts4.setText("Counts Region 4"); + checkCounts4.setName("countsr4"); // NOI18N + + checkCurrent.setText("Current"); + checkCurrent.setName("current"); // NOI18N + + checkCur1.setText("Cur 1"); + checkCur1.setName("cur1"); // NOI18N + + checkCur2.setText("Cur 2"); + checkCur2.setName("cur2"); // NOI18N + + checkCur3.setText("Cur 3"); + checkCur3.setName("cur3"); // NOI18N + + buttonScientaSetup.setText("Scienta Setup"); + buttonScientaSetup.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScientaSetupActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelSensorsLayout = new javax.swing.GroupLayout(panelSensors); + panelSensors.setLayout(panelSensorsLayout); + panelSensorsLayout.setHorizontalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonScientaSetup, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addGroup(panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkImage) + .addComponent(checkImageIntegration) + .addComponent(checkSpectrum) + .addComponent(checkCounts1) + .addComponent(checkTotalCount) + .addComponent(checkCounts2) + .addComponent(checkCounts3) + .addComponent(checkCurrent) + .addComponent(checkCur1) + .addComponent(checkCur2) + .addComponent(checkCur3) + .addComponent(checkCounts4)) + .addGap(0, 52, Short.MAX_VALUE))) + .addContainerGap()) + ); + panelSensorsLayout.setVerticalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addComponent(checkImage) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkImageIntegration) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkSpectrum) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkTotalCount) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCurrent) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur3) + .addGap(18, 18, Short.MAX_VALUE) + .addComponent(buttonScientaSetup) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Scan Control")); + + buttonStart.setText("Start"); + buttonStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStartActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)) + .addContainerGap()) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonStart) + .addGap(18, 18, 18) + .addComponent(buttonAbort) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(panelSensors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(panelPositioner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanel3, panelPositioner, panelSensors}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(panelPositioner, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelSensors, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonScientaSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScientaSetupActionPerformed + try { + showDevicePanel("scienta"); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonScientaSetupActionPerformed + + private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed + try { + startScan(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonStartActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + abort(); + }//GEN-LAST:event_buttonAbortActionPerformed + + private void radioStepSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioStepSizeActionPerformed + setEnabled(isEnabled()); + }//GEN-LAST:event_radioStepSizeActionPerformed + + private void comboMotorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboMotorActionPerformed + try { + Motor motor = (Motor) getDevice(comboMotor.getSelectedItem().toString()); + motorPanel.setDevice(motor); + spinnerFrom.setModel(new SpinnerNumberModel(motor.getMinValue(), motor.getMinValue(), motor.getMaxValue(), 1.0)); + spinnerTo.setModel(new SpinnerNumberModel(motor.getMaxValue(), motor.getMinValue(), motor.getMaxValue(), 1.0)); + txtSize.setText("Size (" + motor.getUnit() +")"); + //spinnerFrom.setModel(new javax.swing.SpinnerNumberModel(3.0, 0.001, 100.0, 1.0)); + //spinnerTo.setModel(new javax.swing.SpinnerNumberModel(2.0, 0.001, 100.0, 1.0)); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_comboMotorActionPerformed + + private void radioAbsoluteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioAbsoluteActionPerformed + setEnabled(isEnabled()); + }//GEN-LAST:event_radioAbsoluteActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.JButton buttonScientaSetup; + private javax.swing.JButton buttonStart; + private javax.swing.JCheckBox checkCounts1; + private javax.swing.JCheckBox checkCounts2; + private javax.swing.JCheckBox checkCounts3; + private javax.swing.JCheckBox checkCounts4; + private javax.swing.JCheckBox checkCur1; + private javax.swing.JCheckBox checkCur2; + private javax.swing.JCheckBox checkCur3; + private javax.swing.JCheckBox checkCurrent; + private javax.swing.JCheckBox checkImage; + private javax.swing.JCheckBox checkImageIntegration; + private javax.swing.JCheckBox checkSpectrum; + private javax.swing.JCheckBox checkTotalCount; + private javax.swing.JComboBox comboMotor; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JPanel jPanel3; + private ch.psi.pshell.swing.MotorReadoutPanel motorPanel; + private javax.swing.JPanel panelPositioner; + private javax.swing.JPanel panelSensors; + private javax.swing.JRadioButton radioAbsolute; + private javax.swing.JRadioButton radioRelative; + private javax.swing.JRadioButton radioStepSize; + private javax.swing.JRadioButton radioSteps; + private javax.swing.JSpinner spinnerFrom; + private javax.swing.JSpinner spinnerLatency; + private javax.swing.JSpinner spinnerRange; + private javax.swing.JSpinner spinnerStepSize; + private javax.swing.JSpinner spinnerSteps; + private javax.swing.JSpinner spinnerTo; + private javax.swing.JLabel txtSize; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/MatlabTokenMaker.java b/plugins/MatlabTokenMaker.java new file mode 100755 index 0000000..aae6a42 --- /dev/null +++ b/plugins/MatlabTokenMaker.java @@ -0,0 +1,978 @@ +/* + * #%L + * ImageJ software for multidimensional image processing and analysis. + * %% + * Copyright (C) 2009 - 2016 Board of Regents of the University of + * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck + * Institute of Molecular Cell Biology and Genetics. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +//package net.imagej.ui.swing.script.highliters; + + +import java.io.IOException; + +import javax.swing.text.Segment; + +import org.fife.ui.rsyntaxtextarea.AbstractJFlexTokenMaker; +import org.fife.ui.rsyntaxtextarea.Token; +import org.fife.ui.rsyntaxtextarea.TokenImpl; +import org.fife.ui.rsyntaxtextarea.TokenTypes; +import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory; +import org.fife.ui.rsyntaxtextarea.TokenMakerFactory; + +/** + * Scanner for the Matlab programming language. + *

+ * Copyright (C) 2009 Sumit Dubey Licensed as per LGPLv3, or any other license + * at the discretion of Robert Futrell. This implementation was created using JFlex 1.4.1; however, the generated file was + * modified for performance. Memory allocation needs to be almost completely + * removed to be competitive with the handwritten lexers (subclasses of + * AbstractTokenMaker, so this class has been modified so that + * Strings are never allocated (via yytext()), and the scanner never has to + * worry about refilling its buffer (needlessly copying chars around). We can + * achieve this because RText always scans exactly 1 line of tokens at a time, + * and hands the scanner this line as an array of characters (a Segment really). + * Since tokens contain pointers to char arrays instead of Strings holding their + * contents, there is no need for allocating new memory for Strings. + *

+ * The actual algorithm generated for scanning has, of course, not been + * modified. + *

+ * If you wish to regenerate this file yourself, keep in mind the following: + *

    + *
  • The generated JavaTokenMaker.java file will contain two + * definitions of both zzRefill and yyreset. You + * should hand-delete the second of each definition (the ones generated by the + * lexer), as these generated methods modify the input buffer, which we'll never + * have to do.
  • + *
  • You should also change the declaration/definition of zzBuffer to NOT be + * initialized. This is a needless memory allocation for us since we will be + * pointing the array somewhere else anyway.
  • + *
  • You should NOT call yylex() on the generated scanner + * directly; rather, you should use getTokenList as you would with + * any other TokenMaker instance.
  • + *
+ * + * @author Sumit Dubey + */ +public class MatlabTokenMaker extends AbstractJFlexTokenMaker { + + static{ + AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance(); + atmf.putMapping("text/matlab",MatlabTokenMaker.class.getName(), MatlabTokenMaker.class.getClassLoader()); + } + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int EOL_COMMENT = 6; + public static final int STRING = 2; + public static final int YYINITIAL = 0; + public static final int MLC = 4; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l at the + * beginning of a line l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1, 2, 2, 3, 3 }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\32\1\15\1\0\1\32\1\16\22\0\1\32\1\40\1\16" + + "\2\0\1\1\1\42\1\12\2\20\1\42\1\37\1\16\1\37\1\17" + + "\1\42\1\5\3\10\4\10\2\4\1\42\1\16\1\40\1\41\1\43" + + "\1\42\1\0\3\7\1\35\1\36\1\35\5\6\1\34\13\6\1\33" + + "\2\6\1\21\1\6\1\21\1\22\1\6\1\6\1\27\1\14\1\45" + + "\1\51\1\25\1\26\1\52\1\46\1\50\1\6\1\44\1\30\1\6" + + "\1\13\1\47\1\54\1\6\1\24\1\31\1\23\1\11\1\6\1\53" + + "\1\33\1\55\1\6\1\2\1\16\1\3\1\42\uff81\0"; + + /** + * Translates characters to character classes + */ + private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int[] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\4\0\1\1\1\2\1\3\2\4\1\5\1\6\1\5" + "\1\7\1\1\1\3\1\10\5\5\1\11\3\10\6\5" + + "\1\12\1\13\1\14\2\12\1\15\2\12\1\16\1\17" + + "\1\20\1\21\1\20\1\21\1\4\1\20\1\22\1\20" + + "\11\5\1\10\3\5\1\23\3\5\1\24\1\21\1\0" + + "\2\22\17\5\1\25\1\5\1\23\24\5"; + + private static int[] zzUnpackAction() { + final int[] result = new int[109]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(final String packed, final int offset, + final int[] result) + { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + final int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + final int value = packed.charAt(i++); + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /** + * Translates a state to a row index in the transition table + */ + private static final int[] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\56\0\134\0\212\0\270\0\346\0\270\0\u0114" + + "\0\u0142\0\u0170\0\270\0\u019e\0\270\0\u01cc\0\u0170\0\u0170" + + "\0\u01fa\0\u0228\0\u0256\0\u0284\0\u02b2\0\u02e0\0\270\0\u030e" + + "\0\u033c\0\u036a\0\u0398\0\u03c6\0\u03f4\0\u0422\0\u0450\0\u047e" + + "\0\u04ac\0\270\0\u04da\0\u0508\0\270\0\270\0\u0536\0\270" + + "\0\270\0\u0564\0\u0592\0\u05c0\0\u0564\0\u0564\0\u05ee\0\u061c" + + "\0\u064a\0\u0678\0\u06a6\0\u06d4\0\u0702\0\u0730\0\u075e\0\u078c" + + "\0\u07ba\0\u07e8\0\u0816\0\u0844\0\u0872\0\u08a0\0\u0170\0\u08ce" + + "\0\u08fc\0\u092a\0\270\0\u0958\0\u0986\0\u0564\0\u09b4\0\u09e2" + + "\0\u0a10\0\u0a3e\0\u0a6c\0\u0a9a\0\u0ac8\0\u0af6\0\u0b24\0\u0b52" + + "\0\u0b80\0\u0bae\0\u0bdc\0\u0c0a\0\u0c38\0\u0c66\0\u0170\0\u0c94" + + "\0\u0cc2\0\u0cf0\0\u0d1e\0\u0d4c\0\u0d7a\0\u0da8\0\u0dd6\0\u0e04" + + "\0\u0e32\0\u0e60\0\u0e8e\0\u0ebc\0\u0eea\0\u0f18\0\u0f46\0\u0f74" + + "\0\u0fa2\0\u0fd0\0\u0ffe\0\u102c\0\u105a"; + + private static int[] zzUnpackRowMap() { + final int[] result = new int[109]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(final String packed, final int offset, + final int[] result) + { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + final int l = packed.length(); + while (i < l) { + final int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int[] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\5\1\6\2\7\1\10\1\11\2\12\1\10\1\12" + + "\1\13\1\12\1\14\1\15\1\5\1\16\1\7\1\17" + + "\1\20\1\21\1\22\1\23\1\24\2\12\1\25\1\26" + + "\4\12\1\27\2\30\1\27\1\31\1\12\1\32\1\12" + + "\1\33\1\34\1\12\1\35\1\36\1\37\1\12\12\40" + + "\1\41\2\40\1\42\40\40\1\43\1\44\13\43\1\45" + + "\10\43\1\46\17\43\1\46\4\43\1\46\2\43\15\47" + + "\1\50\10\47\1\46\17\47\1\46\4\47\1\46\2\47" + + "\60\0\1\51\53\0\1\52\3\0\2\10\2\52\1\10" + + "\1\52\1\0\2\52\2\0\1\53\3\0\2\52\1\54" + + "\1\55\1\52\1\56\1\52\1\0\1\52\1\56\1\55" + + "\1\54\5\0\5\52\1\55\5\52\3\0\1\57\1\60" + + "\2\52\1\60\1\52\1\0\2\52\2\0\1\53\3\0" + + "\2\52\1\54\1\55\1\52\1\56\1\52\1\0\1\61" + + "\1\56\1\55\1\54\5\0\5\52\1\55\4\52\4\0" + + "\6\12\1\0\2\12\4\0\11\12\1\0\4\12\5\0" + + "\12\12\4\0\6\12\1\0\2\12\4\0\3\12\1\62" + + "\5\12\1\0\4\12\5\0\12\12\4\0\2\53\2\0" + + "\1\53\51\0\6\12\1\0\2\12\4\0\3\12\1\63" + + "\5\12\1\0\4\12\5\0\12\12\4\0\6\12\1\0" + + "\2\12\4\0\4\12\1\64\4\12\1\0\4\12\5\0" + + "\12\12\4\0\6\12\1\0\1\65\1\12\4\0\7\12" + + "\1\66\1\12\1\0\4\12\5\0\12\12\4\0\5\12" + + "\1\67\1\0\2\12\4\0\6\12\1\70\2\12\1\0" + + "\4\12\5\0\3\12\1\71\6\12\4\0\6\12\1\0" + + "\2\12\4\0\11\12\1\0\4\12\5\0\7\12\1\72" + + "\2\12\32\0\1\26\64\0\1\27\55\0\1\27\1\0" + + "\1\73\16\0\6\12\1\0\2\12\4\0\6\12\1\74" + + "\2\12\1\0\4\12\5\0\3\12\1\75\6\12\4\0" + + "\6\12\1\0\2\12\4\0\2\12\1\76\6\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\2\12\4\0" + + "\5\12\1\77\3\12\1\0\4\12\5\0\12\12\4\0" + + "\6\12\1\0\2\12\4\0\7\12\1\100\1\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\2\12\4\0" + + "\11\12\1\0\4\12\5\0\2\12\1\101\7\12\4\0" + + "\6\12\1\0\2\12\4\0\4\12\1\102\4\12\1\0" + + "\4\12\5\0\12\12\12\40\1\0\2\40\1\0\40\40" + + "\12\0\1\46\43\0\1\43\1\0\13\43\1\0\10\43" + + "\1\0\17\43\1\0\4\43\1\0\2\43\3\0\1\103" + + "\52\0\15\47\1\0\10\47\1\0\17\47\1\0\4\47" + + "\1\0\2\47\1\52\3\0\6\52\1\0\2\52\6\0" + + "\7\52\1\0\4\52\5\0\13\52\3\0\2\53\2\52" + + "\1\53\1\52\1\0\2\52\6\0\2\52\1\54\1\55" + + "\3\52\1\0\2\52\1\55\1\54\5\0\5\52\1\55" + + "\5\52\3\0\2\104\2\52\1\104\1\52\1\0\2\52" + + "\6\0\7\52\1\0\4\52\1\105\4\0\13\52\3\0" + + "\2\57\2\52\1\57\1\52\1\0\2\52\2\0\1\53" + + "\3\0\2\52\1\54\1\55\3\52\1\0\2\52\1\55" + + "\1\54\5\0\5\52\1\55\5\52\3\0\1\57\1\60" + + "\2\52\1\60\1\52\1\0\2\52\2\0\1\53\3\0" + + "\2\52\1\54\1\55\1\52\1\106\1\52\1\0\1\52" + + "\1\106\1\55\1\54\5\0\5\52\1\55\5\52\3\0" + + "\2\107\1\52\2\107\1\52\1\0\1\52\1\107\6\0" + + "\2\52\3\107\2\52\1\0\2\52\2\107\5\0\1\52" + + "\1\107\3\52\1\107\4\52\4\0\6\12\1\0\2\12" + + "\4\0\4\12\1\110\4\12\1\0\4\12\5\0\12\12" + + "\4\0\5\12\1\111\1\0\2\12\4\0\11\12\1\0" + + "\4\12\5\0\11\12\1\77\4\0\6\12\1\0\2\12" + + "\4\0\2\12\1\112\6\12\1\0\4\12\5\0\12\12" + + "\4\0\6\12\1\0\2\12\4\0\11\12\1\0\4\12" + + "\5\0\5\12\1\77\4\12\4\0\6\12\1\0\2\12" + + "\4\0\10\12\1\113\1\0\4\12\5\0\12\12\4\0" + + "\6\12\1\0\1\114\1\12\4\0\11\12\1\0\4\12" + + "\5\0\12\12\4\0\6\12\1\0\2\12\4\0\7\12" + + "\1\115\1\12\1\0\4\12\5\0\12\12\4\0\6\12" + + "\1\0\2\12\4\0\3\12\1\77\5\12\1\0\4\12" + + "\5\0\12\12\4\0\6\12\1\0\2\12\4\0\11\12" + + "\1\0\4\12\5\0\4\12\1\116\5\12\43\0\1\27" + + "\16\0\6\12\1\0\2\12\4\0\2\12\1\117\5\12" + + "\1\120\1\0\4\12\5\0\12\12\4\0\6\12\1\0" + + "\1\121\1\12\4\0\11\12\1\0\4\12\5\0\12\12" + + "\4\0\6\12\1\0\2\12\4\0\11\12\1\0\4\12" + + "\5\0\2\12\1\122\7\12\4\0\6\12\1\0\2\12" + + "\4\0\11\12\1\0\4\12\5\0\3\12\1\123\6\12" + + "\4\0\6\12\1\0\2\12\4\0\11\12\1\0\4\12" + + "\5\0\4\12\1\124\5\12\4\0\6\12\1\0\2\12" + + "\4\0\3\12\1\125\5\12\1\0\4\12\5\0\12\12" + + "\1\52\3\0\2\104\2\52\1\104\1\52\1\0\2\52" + + "\6\0\3\52\1\55\3\52\1\0\2\52\1\55\1\52" + + "\5\0\5\52\1\55\4\52\4\0\2\104\2\0\1\104" + + "\45\0\1\52\3\0\2\107\1\52\2\107\1\52\1\0" + + "\1\52\1\107\6\0\2\52\3\107\1\106\1\52\1\0" + + "\1\52\1\106\2\107\5\0\1\52\1\107\3\52\1\107" + + "\4\52\4\0\6\12\1\0\2\12\4\0\6\12\1\126" + + "\2\12\1\0\4\12\5\0\12\12\4\0\6\12\1\0" + + "\2\12\4\0\4\12\1\127\4\12\1\0\4\12\5\0" + + "\12\12\4\0\5\12\1\130\1\0\2\12\4\0\11\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\4\12\1\131\4\12\1\0\4\12\5\0\12\12" + + "\4\0\6\12\1\0\2\12\4\0\11\12\1\0\4\12" + + "\5\0\1\12\1\132\10\12\4\0\6\12\1\0\2\12" + + "\4\0\10\12\1\111\1\0\4\12\5\0\12\12\4\0" + + "\6\12\1\0\2\12\4\0\2\12\1\117\6\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\2\12\4\0" + + "\11\12\1\0\4\12\5\0\1\12\1\133\10\12\4\0" + + "\6\12\1\0\2\12\4\0\4\12\1\77\4\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\2\12\4\0" + + "\2\12\1\134\6\12\1\0\4\12\5\0\12\12\4\0" + + "\6\12\1\0\2\12\4\0\4\12\1\135\4\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\1\12\1\136" + + "\4\0\11\12\1\0\4\12\5\0\12\12\4\0\6\12" + + "\1\0\2\12\4\0\7\12\1\120\1\12\1\0\4\12" + + "\5\0\12\12\4\0\6\12\1\0\2\12\4\0\10\12" + + "\1\137\1\0\4\12\5\0\12\12\4\0\6\12\1\0" + + "\2\12\4\0\11\12\1\0\4\12\5\0\1\77\11\12" + + "\4\0\6\12\1\0\2\12\4\0\3\12\1\140\5\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\11\12\1\0\4\12\5\0\4\12\1\34\5\12" + + "\4\0\6\12\1\0\2\12\4\0\2\12\1\141\6\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\11\12\1\0\4\12\5\0\2\12\1\77\7\12" + + "\4\0\6\12\1\0\2\12\4\0\11\12\1\0\4\12" + + "\5\0\4\12\1\142\5\12\4\0\6\12\1\0\2\12" + + "\4\0\3\12\1\143\5\12\1\0\4\12\5\0\12\12" + + "\4\0\6\12\1\0\2\12\4\0\6\12\1\144\2\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\11\12\1\0\4\12\5\0\4\12\1\145\5\12" + + "\4\0\6\12\1\0\1\77\1\12\4\0\11\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\2\12\4\0" + + "\11\12\1\0\4\12\5\0\4\12\1\146\5\12\4\0" + + "\6\12\1\0\1\147\1\12\4\0\11\12\1\0\4\12" + + "\5\0\12\12\4\0\6\12\1\0\2\12\4\0\11\12" + + "\1\0\4\12\5\0\7\12\1\150\2\12\4\0\6\12" + + "\1\0\2\12\4\0\7\12\1\77\1\12\1\0\4\12" + + "\5\0\12\12\4\0\6\12\1\0\2\12\4\0\10\12" + + "\1\151\1\0\4\12\5\0\12\12\4\0\6\12\1\0" + + "\2\12\4\0\11\12\1\0\4\12\5\0\3\12\1\140" + + "\6\12\4\0\5\12\1\120\1\0\2\12\4\0\11\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\11\12\1\0\4\12\5\0\4\12\1\152\5\12" + + "\4\0\6\12\1\0\2\12\4\0\2\12\1\153\6\12" + + "\1\0\4\12\5\0\12\12\4\0\6\12\1\0\2\12" + + "\4\0\10\12\1\120\1\0\4\12\5\0\12\12\4\0" + + "\6\12\1\0\2\12\4\0\4\12\1\154\4\12\1\0" + + "\4\12\5\0\12\12\4\0\6\12\1\0\1\155\1\12" + + "\4\0\11\12\1\0\4\12\5\0\12\12\4\0\6\12" + + "\1\0\2\12\4\0\2\12\1\77\6\12\1\0\4\12" + "\5\0\12\12"; + + private static int[] zzUnpackTrans() { + final int[] result = new int[4232]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(final String packed, final int offset, + final int[] result) + { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + final int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", "Error: could not match input", + "Error: pushback value was too large" }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\4\0\1\11\1\1\1\11\3\1\1\11\1\1\1\11" + + "\11\1\1\11\12\1\1\11\2\1\2\11\1\1\2\11" + "\31\1\1\11\1\1\1\0\50\1"; + + private static int[] zzUnpackAttribute() { + final int[] result = new int[109]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(final String packed, final int offset, + final int[] result) + { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + final int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + final int value = packed.charAt(i++); + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** + * this buffer contains the current text to be matched and is the source of + * the yytext() string + */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** + * endRead marks the last character in the buffer, that has been read from + * input + */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + /** + * Constructor. This must be here because JFlex does not generate a + * no-parameter constructor. + */ + public MatlabTokenMaker() {} + + /** + * Adds the token specified to the current linked list of tokens. + * + * @param tokenType The token's type. + * @see #addToken(int, int, int) + */ + private void addHyperlinkToken(final int start, final int end, + final int tokenType) + { + final int so = start + offsetShift; + addToken(zzBuffer, start, end, tokenType, so, true); + } + + /** + * Adds the token specified to the current linked list of tokens. + * + * @param tokenType The token's type. + */ + private void addToken(final int tokenType) { + addToken(zzStartRead, zzMarkedPos - 1, tokenType); + } + + /** + * Adds the token specified to the current linked list of tokens. + * + * @param tokenType The token's type. + * @see #addHyperlinkToken(int, int, int) + */ + private void addToken(final int start, final int end, final int tokenType) { + final int so = start + offsetShift; + addToken(zzBuffer, start, end, tokenType, so, false); + } + + /** + * Adds the token specified to the current linked list of tokens. + * + * @param array The character array. + * @param start The starting offset in the array. + * @param end The ending offset in the array. + * @param tokenType The token's type. + * @param startOffset The offset in the document at which this token occurs. + * @param hyperlink Whether this token is a hyperlink. + */ + @Override + public void addToken(final char[] array, final int start, final int end, + final int tokenType, final int startOffset, final boolean hyperlink) + { + super.addToken(array, start, end, tokenType, startOffset, hyperlink); + zzStartRead = zzMarkedPos; + } + + /** + * Returns the first token in the linked list of tokens generated from + * text. This method must be implemented by subclasses so they + * can correctly implement syntax highlighting. + * + * @param text The text from which to get tokens. + * @param initialTokenType The token type we should start with. + * @param startOffset The offset into the document at which text + * starts. + * @return The first Token in a linked list representing the + * syntax highlighted text. + */ + @Override + public Token getTokenList(final Segment text, final int initialTokenType, + final int startOffset) + { + + resetTokenList(); + this.offsetShift = -text.offset + startOffset; + + // Start off in the proper state. + int state = TokenTypes.NULL; + switch (initialTokenType) { + case TokenTypes.COMMENT_MULTILINE: + state = MLC; + start = text.offset; + break; + /*case Token.COMMENT_DOCUMENTATION: + state = DOCCOMMENT; + start = text.offset; + break;*/ + case TokenTypes.LITERAL_STRING_DOUBLE_QUOTE: + state = STRING; + start = text.offset; + break; + default: + state = TokenTypes.NULL; + } + + s = text; + try { + yyreset(zzReader); + yybegin(state); + return yylex(); + } + catch (final IOException ioe) { + ioe.printStackTrace(); + return new TokenImpl(); + } + + } + + /** + * Refills the input buffer. + * + * @return true if EOF was reached, otherwise false. + * @exception IOException if any I/O-Error occurs. + */ + private boolean zzRefill() throws java.io.IOException { + return zzCurrentPos >= s.offset + s.count; + } + + /** + * Resets the scanner to read from a new input stream. Does not close the old + * reader. All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). Lexical + * state is set to YY_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(final java.io.Reader reader) + throws java.io.IOException + { + // 's' has been updated. + zzBuffer = s.array; + /* + * We replaced the line below with the two below it because zzRefill + * no longer "refills" the buffer (since the way we do it, it's always + * "full" the first time through, since it points to the segment's + * array). So, we assign zzEndRead here. + */ + // zzStartRead = zzEndRead = s.offset; + zzStartRead = s.offset; + zzEndRead = zzStartRead + s.count - 1; + zzCurrentPos = zzMarkedPos = s.offset; + zzLexicalState = YYINITIAL; + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + } + + /** + * Creates a new scanner There is also a java.io.InputStream version of this + * constructor. + * + * @param in the java.io.Reader to read input from. + */ + public MatlabTokenMaker(final java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. There is also java.io.Reader version of this + * constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + public MatlabTokenMaker(final java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char[] zzUnpackCMap(final String packed) { + final char[] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 156) { + int count = packed.charAt(i++); + final char value = packed.charAt(i++); + do + map[j++] = value; + while (--count > 0); + } + return map; + } + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * @exception java.io.IOException if any I/O-Error occurs + */ + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) zzReader.close(); + } + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + @Override + public final void yybegin(final int newState) { + zzLexicalState = newState; + } + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); + } + + /** + * Returns the character at position pos from the matched text. It is + * equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. A value from 0 to + * yylength()-1. + * @return the character at position pos + */ + public final char yycharat(final int pos) { + return zzBuffer[zzStartRead + pos]; + } + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos - zzStartRead; + } + + /** + * Reports an error that occured while scanning. In a wellformed scanner (no + * or only correct usage of yypushback(int) and a match-all fallback rule) + * this method will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong (e.g. a JFlex bug + * producing a faulty scanner etc.). Usual syntax/scanner level error handling + * should be done in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(final int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (final ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + /** + * Pushes the specified amount of characters back into the input stream. They + * will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. This number must + * not be greater than yylength()! + */ + public void yypushback(final int number) { + if (number > yylength()) zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + /** + * Resumes scanning until the next regular expression is matched, the end of + * input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public org.fife.ui.rsyntaxtextarea.Token yylex() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char[] zzBufferL = zzBuffer; + final char[] zzCMapL = ZZ_CMAP; + + final int[] zzTransL = ZZ_TRANS; + final int[] zzRowMapL = ZZ_ROWMAP; + final int[] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + zzForAction: + { + while (true) { + + if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + final boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + zzInput = zzBufferL[zzCurrentPosL++]; + } + final int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + final int zzAttributes = zzAttrL[zzState]; + if ((zzAttributes & 1) == 1) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ((zzAttributes & 8) == 8) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 7: { + addNullToken(); + return firstToken; + } + case 22: + break; + case 20: { + yybegin(YYINITIAL); + addToken(start, zzStartRead + 1, TokenTypes.COMMENT_MULTILINE); + } + case 23: + break; + case 15: { + start = zzMarkedPos - 2; + yybegin(MLC); + } + case 24: + break; + case 9: { + addToken(TokenTypes.WHITESPACE); + } + case 25: + break; + case 18: { + addToken(TokenTypes.LITERAL_NUMBER_HEXADECIMAL); + } + case 26: + break; + case 17: { + addToken(TokenTypes.LITERAL_NUMBER_FLOAT); + } + case 27: + break; + case 19: { + addToken(TokenTypes.RESERVED_WORD); + } + case 28: + break; + case 3: { + addToken(TokenTypes.SEPARATOR); + } + case 29: + break; + case 5: { + addToken(TokenTypes.IDENTIFIER); + } + case 30: + break; + case 14: { + addToken(start, zzStartRead - 1, TokenTypes.COMMENT_EOL); + addNullToken(); + return firstToken; + } + case 31: + break; + case 1: { + addToken(TokenTypes.ERROR_IDENTIFIER); + } + case 32: + break; + case 21: { + addToken(TokenTypes.LITERAL_BOOLEAN); + } + case 33: + break; + case 12: { + addToken(start, zzStartRead - 1, + TokenTypes.LITERAL_STRING_DOUBLE_QUOTE); + return firstToken; + } + case 34: + break; + case 16: { + addToken(TokenTypes.ERROR_NUMBER_FORMAT); + } + case 35: + break; + case 6: { + start = zzMarkedPos - 1; + yybegin(STRING); + } + case 36: + break; + case 2: { + start = zzMarkedPos - 1; + yybegin(EOL_COMMENT); + } + case 37: + break; + case 4: { + addToken(TokenTypes.LITERAL_NUMBER_DECIMAL_INT); + } + case 38: + break; + case 8: { + addToken(TokenTypes.OPERATOR); + } + case 39: + break; + case 11: { + yybegin(YYINITIAL); + addToken(start, zzStartRead, TokenTypes.LITERAL_STRING_DOUBLE_QUOTE); + } + case 40: + break; + case 10: {} + case 41: + break; + case 13: { + addToken(start, zzStartRead - 1, TokenTypes.COMMENT_MULTILINE); + return firstToken; + } + case 42: + break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + switch (zzLexicalState) { + case EOL_COMMENT: { + addToken(start, zzStartRead - 1, TokenTypes.COMMENT_EOL); + addNullToken(); + return firstToken; + } + case 110: + break; + case STRING: { + addToken(start, zzStartRead - 1, + TokenTypes.LITERAL_STRING_DOUBLE_QUOTE); + return firstToken; + } + case 111: + break; + case YYINITIAL: { + addNullToken(); + return firstToken; + } + case 112: + break; + case MLC: { + addToken(start, zzStartRead - 1, TokenTypes.COMMENT_MULTILINE); + return firstToken; + } + case 113: + break; + default: + return null; + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + +} diff --git a/plugins/Microscope.form b/plugins/Microscope.form new file mode 100755 index 0000000..4386f60 --- /dev/null +++ b/plugins/Microscope.form @@ -0,0 +1,142 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Microscope.java b/plugins/Microscope.java new file mode 100755 index 0000000..02bd11a --- /dev/null +++ b/plugins/Microscope.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.epics.Epics; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.awt.Color; +import java.awt.Point; +import java.util.logging.Level; + +/** + * + */ +public class Microscope extends Panel { + public Microscope() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + final Overlay overlay = new Overlays.Ellipse(new Pen(Color.RED), new Point(10,10), new Point(50,50)); + renderer.addOverlay(overlay); + overlay.setMovable(true); + overlay.setSolid(false); + + renderer.addListener(new RendererListener() { + public void onMouseDragged(Renderer renderer, Point p) { + //sendOutput(p.toString()); + System.out.println((p.x - renderer.getImageSize().width/2) + " - " + (p.y - renderer.getImageSize().height/2)); + } + + public void onMoveFinished(Renderer renderer, Overlay ov) { + if (ov == overlay){ + System.out.println(ov.getPosition().toString()); + } + } + } ); + + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + renderer = new ch.psi.pshell.imaging.Renderer(); + jButton1 = new javax.swing.JButton(); + motorPanel1 = new ch.psi.pshell.swing.MotorPanel(); + processVariablePanel1 = new ch.psi.pshell.swing.ProcessVariablePanel(); + buttonDefineBeam = new javax.swing.JButton(); + processVariablePanel2 = new ch.psi.pshell.swing.ProcessVariablePanel(); + processVariablePanel3 = new ch.psi.pshell.swing.ProcessVariablePanel(); + + renderer.setAutoscrolls(true); + renderer.setDeviceName("src1"); + renderer.setMode(ch.psi.pshell.imaging.RendererMode.Fixed); + renderer.setShowStatus(false); + + jButton1.setText("Wait click"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + motorPanel1.setDecimals(2); + motorPanel1.setDeviceName("motor"); + motorPanel1.setDoubleBuffered(false); + motorPanel1.setShowTitle(true); + + processVariablePanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("pe")); + processVariablePanel1.setDeviceName("pe"); + processVariablePanel1.setName(""); // NOI18N + processVariablePanel1.setShowSlider(false); + processVariablePanel1.setShowTitle(true); + + buttonDefineBeam.setText("Define Beam"); + buttonDefineBeam.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDefineBeamActionPerformed(evt); + } + }); + + processVariablePanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("pv")); + processVariablePanel2.setDecimals(2); + processVariablePanel2.setDeviceName("pv"); + processVariablePanel2.setName(""); // NOI18N + processVariablePanel2.setShowSlider(false); + processVariablePanel2.setShowTitle(true); + + processVariablePanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("cv")); + processVariablePanel3.setDecimals(2); + processVariablePanel3.setDeviceName("cv"); + processVariablePanel3.setName(""); // NOI18N + processVariablePanel3.setShowSlider(false); + processVariablePanel3.setShowTitle(true); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(processVariablePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(processVariablePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(processVariablePanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(motorPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGroup(layout.createSequentialGroup() + .addGap(123, 123, 123) + .addComponent(buttonDefineBeam))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(5, 5, 5)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jButton1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(motorPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(processVariablePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(processVariablePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(processVariablePanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE) + .addComponent(buttonDefineBeam) + .addGap(26, 26, 26)) + ); + }// //GEN-END:initComponents + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + try{ + new Thread(()->{ + try { + Point p = renderer.waitClick(10000); + System.out.println(p); + } catch (Exception ex) { + } + jButton1.setEnabled(true); + + }).start(); + jButton1.setEnabled(false); + } catch (Exception ex){ + showException(ex); + } + }//GEN-LAST:event_jButton1ActionPerformed + + Overlay beam; + + private void buttonDefineBeamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDefineBeamActionPerformed + try{ + Pen pen = new Pen(Color.RED); + final Overlay selection = new Overlays.Rect(pen); + + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + if (overlay == selection){ + try { + if (overlay.getLength() > 0) { + beam = overlay.copy(); + beam.setPen(pen); + beam.setSolid(false); + beam.setMovable(true); + //renderer.addOverlay(beam); + } + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } finally { + renderer.removeListener(this); + } + } + } + @Override + public void onSelectionAborted(Renderer renderer, Overlay overlay) { + if (overlay == selection){ + renderer.removeListener(this); + } + } + }); + renderer.removeOverlay(beam); + renderer.startSelection(selection); + renderer.requestFocus(); + + } catch (Exception ex){ + showException(ex); + } + + }//GEN-LAST:event_buttonDefineBeamActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonDefineBeam; + private javax.swing.JButton jButton1; + private ch.psi.pshell.swing.MotorPanel motorPanel1; + private ch.psi.pshell.swing.ProcessVariablePanel processVariablePanel1; + private ch.psi.pshell.swing.ProcessVariablePanel processVariablePanel2; + private ch.psi.pshell.swing.ProcessVariablePanel processVariablePanel3; + private ch.psi.pshell.imaging.Renderer renderer; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/NetbeansPlugin.form b/plugins/NetbeansPlugin.form new file mode 100755 index 0000000..bc5103d --- /dev/null +++ b/plugins/NetbeansPlugin.form @@ -0,0 +1,87 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/NetbeansPlugin.java b/plugins/NetbeansPlugin.java new file mode 100755 index 0000000..29fd073 --- /dev/null +++ b/plugins/NetbeansPlugin.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.psaf.Task; +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; +import ch.psi.utils.IO; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.pshell.data.PlotDescriptor; +import ch.psi.pshell.plot.LinePlot; +import ch.psi.pshell.plot.LinePlotBase; +import ch.psi.pshell.plot.LinePlotJFree; +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.Plot; +import ch.psi.pshell.ui.Panel; + +/** + * + */ +public class NetbeansPlugin extends Panel { + + public NetbeansPlugin() { + initComponents(); + plot = new LinePlotJFree(); + plot.setTitle(""); + series1 = new LinePlotSeries("data", Color.RED); + plot.addSeries(series1); + series2 = new LinePlotSeries("data2", Color.BLUE, 2); + plot.addSeries(series2); + plot.getAxis(Plot.AxisId.X).setRange(0, 1000); + plot.getAxis(Plot.AxisId.Y).setRange(-1.5, 1.5); + plot.getAxis(Plot.AxisId.Y2).setRange(-1000.0, 2000.0); + plot.getAxis(Plot.AxisId.Y2).setLabel("TEST"); + panelPlot.add(plot); + getApp().addTask(task); + } + + Task task = new Task() { + @Override + protected Object execute() throws Exception { + series1.clear(); + series2.clear(); + + extSeries1.clear(); + extSeries2.clear(); + for (int i = 0; i <= 1000; i++) { + double v1 = Math.sin(i); + double v2 = i + v1 * 100; + series1.appendData(i, v1); + series2.appendData(i, v2); + + extSeries1.appendData(i, v1); + extSeries2.appendData(i, v2); + + Thread.sleep(5); + } + return true; + } + }; + + LinePlotBase plot; + LinePlotSeries series1; + LinePlotSeries series2; + + LinePlotSeries extSeries1; + LinePlotSeries extSeries2; + + @Override + public void onStateChange(State state, State former) { + setEnabled(state == State.Ready); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + if (IO.getPrefix(fileName).equals("test11")) { + if (result instanceof Exception) { + getLogger().log(Level.SEVERE, "Script execution failed: " + ((Exception) result).getMessage()); + } else { + try { + runAsync("test10"); + } catch (Exception ex) { + SwingUtils.showException(null, ex); + } + } + } + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + buttonExecute.setEnabled(value); + buttonJava.setEnabled(value); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonExecute = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + panelPlot = new javax.swing.JPanel(); + buttonJava = new javax.swing.JButton(); + + buttonExecute.setText("Execute Script"); + buttonExecute.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonExecuteActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + panelPlot.setLayout(new java.awt.BorderLayout()); + + buttonJava.setText("Execute Java Code"); + buttonJava.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonJavaActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(layout.createSequentialGroup() + .addGap(45, 45, 45) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonJava) + .addComponent(buttonExecute)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE) + .addComponent(buttonAbort, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(44, 44, 44))) + .addContainerGap()) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonAbort, buttonExecute, buttonJava}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonExecute) + .addComponent(buttonAbort)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonJava, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteActionPerformed + try { + //Run script + //run("test1"); + + //Alternatives to run script with arguments + /* + eval("start = 22.0"); + eval("end = 32.0"); + eval("step = 10"); + runAsync("test11"); + */ + HashMap args = new HashMap(); + args.put("start", 20.0); + args.put("end", 52.0); + args.put("step", 20); + runAsync("test11", args); + + //eval("run('test11', locals = {'start':10.0, 'end':50.0, 'step':40})"); + //evalAsync("run('test11', locals = {'start':10.0, 'end':50.0, 'step':40})"); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonExecuteActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + abort(); + }//GEN-LAST:event_buttonAbortActionPerformed + + private void buttonJavaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonJavaActionPerformed + try { + PlotDescriptor plots1 = new PlotDescriptor("Plot 1"); + PlotDescriptor plots2 = new PlotDescriptor("Plot 2"); + ArrayList externalPlots = getContext().plot(new PlotDescriptor[]{plots1, plots2}, null); + externalPlots.get(0).getAxis(Plot.AxisId.X).setRange(0, 1000); + externalPlots.get(1).getAxis(Plot.AxisId.X).setRange(0, 1000); + externalPlots.get(0).getAxis(Plot.AxisId.Y).setRange(-1.5, 1.5); + externalPlots.get(1).getAxis(Plot.AxisId.Y).setRange(-1000.0, 2000.0); + extSeries1 = externalPlots.get(0).getSeries(0); + extSeries2 = externalPlots.get(1).getSeries(0); + getApp().startTask(task); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + + }//GEN-LAST:event_buttonJavaActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonExecute; + private javax.swing.JButton buttonJava; + private javax.swing.JPanel panelPlot; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Nilson.form b/plugins/Nilson.form new file mode 100755 index 0000000..5a85b75 --- /dev/null +++ b/plugins/Nilson.form @@ -0,0 +1,59 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Nilson.java b/plugins/Nilson.java new file mode 100755 index 0000000..b66783b --- /dev/null +++ b/plugins/Nilson.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2014-2017 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + */ +public class Nilson extends Panel { + + public Nilson() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { +buttonAbort.setEnabled(state == State.Busy); +buttonRun.setEnabled(state==State.Ready); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonRun = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + + buttonRun.setText("Run"); + buttonRun.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonRunActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(52, 52, 52) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(buttonAbort, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonRun, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(467, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(60, 60, 60) + .addComponent(buttonRun) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonAbort) + .addContainerGap(151, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + try { + this.abort(); + } catch (Exception ex) { + this.showException(ex); + } + }//GEN-LAST:event_buttonAbortActionPerformed + + private void buttonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunActionPerformed + try { + this.runAsync("test1"); + } catch (Exception ex) { + this.showException(ex); + } + }//GEN-LAST:event_buttonRunActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonRun; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/PanelPlugin.form b/plugins/PanelPlugin.form new file mode 100755 index 0000000..64507fd --- /dev/null +++ b/plugins/PanelPlugin.form @@ -0,0 +1,145 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/PanelPlugin.java b/plugins/PanelPlugin.java new file mode 100755 index 0000000..ee126cf --- /dev/null +++ b/plugins/PanelPlugin.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.awt.Component; + +/** + * + */ +public class PanelPlugin extends Panel { + + public PanelPlugin() { + initComponents(); + this.setPersistedComponents(new Component[]{jRadioButton1, jRadioButton2}); + } + + //Overridables + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + motorPanel2 = new ch.psi.pshell.swing.MotorPanel(); + scriptButton1 = new ch.psi.pshell.swing.ScriptButton(); + scriptButton2 = new ch.psi.pshell.swing.ScriptButton(); + jSpinner1 = new javax.swing.JSpinner(); + jSpinner2 = new javax.swing.JSpinner(); + jSpinner3 = new javax.swing.JSpinner(); + jRadioButton1 = new javax.swing.JRadioButton(); + jRadioButton2 = new javax.swing.JRadioButton(); + + motorPanel2.setDeviceName("m1"); + + scriptButton1.setScript("Test1"); + + scriptButton2.setArguments(new String[] {"start", "end", "step"}); + scriptButton2.setScript("Test11"); + scriptButton2.setText("Start Args"); + + jSpinner1.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 10.0d, 1.0d)); + jSpinner1.setName("start"); // NOI18N + + jSpinner2.setModel(new javax.swing.SpinnerNumberModel(10.0d, 0.0d, 10.0d, 1.0d)); + jSpinner2.setName("end"); // NOI18N + + jSpinner3.setModel(new javax.swing.SpinnerNumberModel(1.0d, 0.0d, 10.0d, 1.0d)); + jSpinner3.setName("step"); // NOI18N + + buttonGroup1.add(jRadioButton1); + jRadioButton1.setSelected(true); + jRadioButton1.setText("jRadioButton1"); + + buttonGroup1.add(jRadioButton2); + jRadioButton2.setText("jRadioButton2"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(scriptButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(motorPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jSpinner3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(scriptButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addGroup(layout.createSequentialGroup() + .addGap(36, 36, 36) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jRadioButton2) + .addComponent(jRadioButton1)))) + .addContainerGap(12, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(scriptButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(motorPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(scriptButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jSpinner3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(jRadioButton1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jRadioButton2) + .addContainerGap(62, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.JRadioButton jRadioButton1; + private javax.swing.JRadioButton jRadioButton2; + private javax.swing.JSpinner jSpinner1; + private javax.swing.JSpinner jSpinner2; + private javax.swing.JSpinner jSpinner3; + private ch.psi.pshell.swing.MotorPanel motorPanel2; + private ch.psi.pshell.swing.ScriptButton scriptButton1; + private ch.psi.pshell.swing.ScriptButton scriptButton2; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Pearl.form b/plugins/Pearl.form new file mode 100755 index 0000000..0d63924 --- /dev/null +++ b/plugins/Pearl.form @@ -0,0 +1,84 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Pearl.java b/plugins/Pearl.java new file mode 100755 index 0000000..6aba34b --- /dev/null +++ b/plugins/Pearl.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.RangeSelectionPlot.RangeSelection; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.Convert; +import ch.psi.utils.IO; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.psaf.Task; +import java.util.ArrayList; +import java.util.HashMap; + +/** + * + */ +public class Pearl extends Panel { + + public Pearl() { + initComponents(); + getApp().addTask(scan1); + getApp().addTask(scan2); + } + + Task scan1 = new Task() { + @Override + protected Object execute() throws Exception { + return true; + } + }; + + Task scan2 = new Task() { + @Override + protected Object execute() throws Exception { + return true; + } + }; + + @Override + public void onStateChange(State state, State former) { + setEnabled(state == State.Ready); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + String script = IO.getPrefix(fileName); + switch (script) { + case "InitialScan": + if (result instanceof Exception) { + //SwingUtils.showMessage(getComponent(), "Error in " + fileName, exception.getMessage()); + } else { + double[] data = (double[]) Convert.toDouble(result); + //double[] data = new double[]{1.0,1.0,1.0,1.0,1.0}; + LinePlotSeries series = new LinePlotSeries("Data"); + rangeSelectionPanel.setSeries(series); + series.setData(data); + } + break; + case "DetailedScan": + break; + } + updateButtons(); + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + rangeSelectionPanel.setEnabled(value); + updateButtons(); + } + + void updateButtons() { + buttonScan1.setEnabled(isEnabled()); + buttonScan2.setEnabled(isEnabled() && rangeSelectionPanel.getPlot().getSelectedRanges().length > 0); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonAbort = new javax.swing.JButton(); + buttonScan1 = new javax.swing.JButton(); + rangeSelectionPanel = new ch.psi.pshell.swing.RangeSelectionPanel() { + protected void onSeriesChanged() { + updateButtons(); + } + protected void onSelectionChanged() { + updateButtons(); + } + } + ; + buttonScan2 = new javax.swing.JButton(); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + buttonScan1.setText("Initial Scan"); + buttonScan1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScan1ActionPerformed(evt); + } + }); + + buttonScan2.setText("Detailed Scan"); + buttonScan2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScan2ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(rangeSelectionPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE) + .addContainerGap()) + .addGroup(layout.createSequentialGroup() + .addGap(44, 44, 44) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(buttonScan2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonScan1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort) + .addGap(54, 54, 54)) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonAbort, buttonScan1, buttonScan2}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonScan1) + .addComponent(buttonAbort)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonScan2) + .addGap(18, 18, 18) + .addComponent(rangeSelectionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + abort(); + }//GEN-LAST:event_buttonAbortActionPerformed + + private void buttonScan1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScan1ActionPerformed + try { + //getApp().startTask(task); + rangeSelectionPanel.clear(); + runAsync("InitialScan"); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + + }//GEN-LAST:event_buttonScan1ActionPerformed + + private void buttonScan2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScan2ActionPerformed + try { + RangeSelection[] ranges = rangeSelectionPanel.getRangesOrdered(); + HashMap args = new HashMap(); + args.put("ranges", ranges); + runAsync("DetailedScan", args); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonScan2ActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonScan1; + private javax.swing.JButton buttonScan2; + private ch.psi.pshell.swing.RangeSelectionPanel rangeSelectionPanel; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/PersonalizedTheme.java b/plugins/PersonalizedTheme.java new file mode 100755 index 0000000..bcd08b8 --- /dev/null +++ b/plugins/PersonalizedTheme.java @@ -0,0 +1,53 @@ + +import ch.psi.pshell.core.Plugin; +import ch.psi.utils.swing.SwingUtils; +import java.awt.Font; +import java.util.logging.Level; +import javax.swing.UIManager; + +public class PersonalizedTheme implements Plugin { + + @Override + public void onStart() { + try { + Font font = new Font("Verdana", Font.PLAIN, 16); + UIManager.put("Button.font", font); + UIManager.put("ToggleButton.font", font); + UIManager.put("RadioButton.font", font); + UIManager.put("CheckBox.font", font); + UIManager.put("ColorChooser.font", font); + UIManager.put("ComboBox.font", font); + UIManager.put("Label.font", font); + UIManager.put("List.font", font); + UIManager.put("MenuBar.font", font); + UIManager.put("MenuItem.font", font); + UIManager.put("RadioButtonMenuItem.font", font); + UIManager.put("CheckBoxMenuItem.font", font); + UIManager.put("Menu.font", font); + UIManager.put("PopupMenu.font", font); + UIManager.put("OptionPane.font", font); + UIManager.put("Panel.font", font); + UIManager.put("ProgressBar.font", font); + UIManager.put("ScrollPane.font", font); + UIManager.put("Viewport.font", font); + UIManager.put("TabbedPane.font", font); + UIManager.put("Table.font", font); + UIManager.put("TableHeader.font", font); + UIManager.put("TextField.font", font); + UIManager.put("PasswordField.font", font); + UIManager.put("TextArea.font", font); + UIManager.put("TextPane.font", font); + UIManager.put("EditorPane.font", font); + UIManager.put("TitledBorder.font", font); + UIManager.put("ToolBar.font", font); + UIManager.put("ToolTip.font", font); + UIManager.put("Tree.font", font); + SwingUtils.updateAllFrames(); + + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } + + } + +} diff --git a/plugins/PhaseScan.form b/plugins/PhaseScan.form new file mode 100755 index 0000000..b6fe433 --- /dev/null +++ b/plugins/PhaseScan.form @@ -0,0 +1,215 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/PhaseScan.java b/plugins/PhaseScan.java new file mode 100755 index 0000000..d43bb4a --- /dev/null +++ b/plugins/PhaseScan.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2014-2017 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.util.HashMap; +import java.util.List; + +/** + * + */ +public class PhaseScan extends Panel { + + public PhaseScan() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + buttonStart.setEnabled(state==State.Ready); + buttonAbort.setEnabled(state==State.Busy); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + plot = new ch.psi.pshell.plot.LinePlotJFree(); + buttonStart = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + jPanel1 = new javax.swing.JPanel(); + spinnerStart = new javax.swing.JSpinner(); + jLabel1 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + spinnerStep = new javax.swing.JSpinner(); + jLabel2 = new javax.swing.JLabel(); + spinnerEnd = new javax.swing.JSpinner(); + jPanel2 = new javax.swing.JPanel(); + jLabel4 = new javax.swing.JLabel(); + textOffset = new javax.swing.JTextField(); + + plot.setTitle(""); + + buttonStart.setText("Start"); + buttonStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStartActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameters")); + + spinnerStart.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel1.setText("Start"); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Step:"); + + spinnerStep.setModel(new javax.swing.SpinnerNumberModel(10.0d, 0.0d, 180.0d, 1.0d)); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("End:"); + + spinnerEnd.setModel(new javax.swing.SpinnerNumberModel(360.0d, -360.0d, 360.0d, 1.0d)); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(jLabel2) + .addComponent(jLabel3)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(spinnerEnd) + .addComponent(spinnerStep) + .addComponent(spinnerStart)) + .addContainerGap()) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel2)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerStep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Return")); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Offset:"); + + textOffset.setEditable(false); + textOffset.setHorizontalAlignment(javax.swing.JTextField.CENTER); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textOffset) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(textOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel4)) + .addContainerGap()) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(12, 12, 12) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(64, 64, 64) + .addComponent(buttonStart) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonAbort) + .addGap(91, 91, 91) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(113, 113, 113)) + .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + }// //GEN-END:initComponents + + private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed + try { + textOffset.setText(""); + HashMap args = new HashMap(); + args.put("start", spinnerStart.getValue()); + args.put("end", spinnerEnd.getValue()); + args.put("step", spinnerStep.getValue()); + args.put("plt", plot); + this.runAsync("scans/PhaseScan", args).handle((ret, ex) -> { + if (ex!=null){ + this.showException((Exception)ex); + } else{ + Double offset = (Double) ((List)ret).get(0); + textOffset.setText(String.valueOf(offset)); + } + return ret; + }); + } catch (Exception ex) { + this.showException(ex); + } + }//GEN-LAST:event_buttonStartActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + // TODO add your handling code here: + try { + this.abort(); + } catch (Exception ex) { + this.showException(ex); + } + }//GEN-LAST:event_buttonAbortActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonStart; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private ch.psi.pshell.plot.LinePlotJFree plot; + private javax.swing.JSpinner spinnerEnd; + private javax.swing.JSpinner spinnerStart; + private javax.swing.JSpinner spinnerStep; + private javax.swing.JTextField textOffset; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/PhotonEnergy.form b/plugins/PhotonEnergy.form new file mode 100755 index 0000000..e3c4a54 --- /dev/null +++ b/plugins/PhotonEnergy.form @@ -0,0 +1,622 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/PhotonEnergy.java b/plugins/PhotonEnergy.java new file mode 100755 index 0000000..833b9eb --- /dev/null +++ b/plugins/PhotonEnergy.java @@ -0,0 +1,750 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.epics.Scienta; +import ch.psi.pshell.scan.Scan; +import ch.psi.pshell.scan.ScanListener; +import ch.psi.pshell.scan.ScanRecord; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.Convert; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import java.awt.Component; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import javax.swing.JCheckBox; +import javax.swing.JSpinner; +import javax.swing.JToggleButton; + +/** + * + */ +public class PhotonEnergy extends Panel { + + public PhotonEnergy() { + initComponents(); + + //Component persistence + ArrayList persistedComponents = new ArrayList<>(); + persistedComponents.addAll(Arrays.asList(SwingUtils.getComponentsByType(this, JToggleButton.class))); + persistedComponents.addAll(Arrays.asList(SwingUtils.getComponentsByType(this, JSpinner.class))); + setPersistedComponents(persistedComponents.toArray(new Component[0])); + startTimer(1000); + } + boolean running; + + //Overridable callbacks + @Override + public void onStart() { + super.onStart(); + getContext().addScanListener(scanListener); + } + + @Override + public void onStop() { + super.onStop(); + getContext().removeScanListener(scanListener); + } + + @Override + public void onInitialize(int runCount) { + Scienta scienta = (Scienta) getDevice("scienta"); + dvpAcqTime.setDevice(scienta.getAcquisitionTime()); + updateTable(); + } + + protected void onTimer(){ + try{ + int seconds = (int) (Double.valueOf(dvpAcqTime.getLabel().getText()) * table.getRowCount()); + textTotalTime.setText(LocalTime.ofSecondOfDay(seconds).toString()); + } catch (Exception ex){ + textTotalTime.setText(""); + } + } + + ScanListener scanListener = new ScanListener() { + @Override + public void onScanStarted(Scan scan, String string) { + if (running) { + table.setRowSelectionInterval(0, 0); + SwingUtils.scrollToVisible(table, 0, 0); + } + } + + @Override + public void onNewRecord(Scan scan, ScanRecord rec) { + if (running) { + int index = rec.getIndex() + 1; + if (index < table.getRowCount()) { + table.setRowSelectionInterval(index, index); + SwingUtils.scrollToVisible(table, index, 0); + } + } + } + + @Override + public void onScanEnded(Scan scan, Exception ex) { + if (running) { + table.clearSelection(); + } + } + }; + + @Override + public void onStateChange(State state, State former) { + setEnabled(isEnabled()); + if (!state.isProcessing()) { + running = false; + } + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + buttonAbort.setEnabled(value && getState().isInitialized()); + + boolean enableControls = (value && (getState() == State.Ready)); + for (Component c : panelSensors.getComponents()) { + c.setEnabled(enableControls); + } + for (Component c : panelPositioner.getComponents()) { + c.setEnabled(enableControls); + } + + table.setEnabled(enableControls); + buttonStart.setEnabled(enableControls); + checkEndScan.setEnabled(enableControls); + spinnerLow.setEnabled(enableControls && radioSwept.isSelected()); + spinnerHigh.setEnabled(enableControls && radioSwept.isSelected()); + spinnerCenter.setEnabled(enableControls && radioFixed.isSelected()); + + buttonScientaSetup.setEnabled(value); + } + + Double[][] getVector() { + ArrayList ret = new ArrayList<>(); + Double start = (Double) spinnerStart.getValue(); + Double end = (Double) spinnerEnd.getValue(); + Double stepSize = (Double) spinnerStep.getValue(); + Double low = (Double) spinnerLow.getValue(); + Double center = (Double) spinnerCenter.getValue(); + Double high = (Double) spinnerHigh.getValue(); + + if (end > start) { + int step = 0; + Double energy = start; + do { + if (energy > end) { + energy = end; + } + + if (radioSwept.isSelected()) { + if (radioCfs.isSelected()) { + ret.add(new Double[]{energy, low, high}); + } else { + ret.add(new Double[]{energy, low + (stepSize * step), high + (stepSize * step)}); + } + } else { + if (radioCfs.isSelected()) { + ret.add(new Double[]{energy, center}); + } else { + ret.add(new Double[]{energy, center + (stepSize * step)}); + } + } + + step++; + energy += stepSize; + energy = Convert.roundDouble(energy, 3); + } while (energy <= end); + } + return ret.toArray(new Double[0][0]); + } + + void updateTable() { + String[] titles = radioSwept.isSelected() ? new String[]{"Eph", "Elow", "Ehigh"} : new String[]{"Eph", "Ecenter"}; + table.setModel(new javax.swing.table.DefaultTableModel(getVector(), titles) { + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + }); + } + + void startScan() throws Exception { + HashMap args = new HashMap<>(); + ArrayList sensors = new ArrayList(); + for (Component c : panelSensors.getComponents()) { + if ((c instanceof JCheckBox) && ((JCheckBox) c).isSelected()) { + sensors.add(c.getName()); + } + } + args.put("SENSORS", sensors); + args.put("VECTOR", getVector()); + args.put("LATENCY", (Double) spinnerLatency.getValue()); + args.put("MODE", radioSwept.isSelected() ? "swept" :"fixed"); + args.put("TYPE", radioCis.isSelected() ? "CIS" :"CFS"); + args.put("STEP", (Double) spinnerStep.getValue()); + args.put("ENDSCAN", checkEndScan.isSelected()); + + runAsync("PhotonEnergy", args); + running = true; + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + panelPositioner = new javax.swing.JPanel(); + radioCis = new javax.swing.JRadioButton(); + radioCfs = new javax.swing.JRadioButton(); + jLabel3 = new javax.swing.JLabel(); + spinnerLatency = new javax.swing.JSpinner(); + radioSwept = new javax.swing.JRadioButton(); + radioFixed = new javax.swing.JRadioButton(); + jLabel4 = new javax.swing.JLabel(); + spinnerStart = new javax.swing.JSpinner(); + jLabel5 = new javax.swing.JLabel(); + spinnerEnd = new javax.swing.JSpinner(); + spinnerStep = new javax.swing.JSpinner(); + jLabel6 = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + table = new javax.swing.JTable(); + jLabel7 = new javax.swing.JLabel(); + spinnerCenter = new javax.swing.JSpinner(); + spinnerLow = new javax.swing.JSpinner(); + jLabel8 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + spinnerHigh = new javax.swing.JSpinner(); + panelSensors = new javax.swing.JPanel(); + checkImage = new javax.swing.JCheckBox(); + checkImageIntegration = new javax.swing.JCheckBox(); + checkAngleDistribution = new javax.swing.JCheckBox(); + checkSpectrum = new javax.swing.JCheckBox(); + checkTotalCount = new javax.swing.JCheckBox(); + checkCounts1 = new javax.swing.JCheckBox(); + checkCounts2 = new javax.swing.JCheckBox(); + checkCounts3 = new javax.swing.JCheckBox(); + checkCounts4 = new javax.swing.JCheckBox(); + checkCurrent = new javax.swing.JCheckBox(); + checkCur1 = new javax.swing.JCheckBox(); + checkCur2 = new javax.swing.JCheckBox(); + checkCur3 = new javax.swing.JCheckBox(); + buttonScientaSetup = new javax.swing.JButton(); + jPanel3 = new javax.swing.JPanel(); + buttonStart = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + checkEndScan = new javax.swing.JCheckBox(); + labelAcqTime = new javax.swing.JLabel(); + dvpAcqTime = new ch.psi.pshell.swing.DeviceValuePanel(); + textTotalTime = new javax.swing.JLabel(); + labelTotalTime = new javax.swing.JLabel(); + + panelPositioner.setBorder(javax.swing.BorderFactory.createTitledBorder("Acquisition")); + + buttonGroup1.add(radioCis); + radioCis.setSelected(true); + radioCis.setText("Constant Initial State"); + radioCis.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioCisActionPerformed(evt); + } + }); + + buttonGroup1.add(radioCfs); + radioCfs.setText("Constant Final State"); + radioCfs.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioCisActionPerformed(evt); + } + }); + + jLabel3.setText("Latency(s):"); + + spinnerLatency.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 10.0d, 0.1d)); + + buttonGroup2.add(radioSwept); + radioSwept.setSelected(true); + radioSwept.setText("Swept"); + radioSwept.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioSweptActionPerformed(evt); + } + }); + + buttonGroup2.add(radioFixed); + radioFixed.setText("Fixed"); + radioFixed.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioSweptActionPerformed(evt); + } + }); + + jLabel4.setText("Eph Start"); + + spinnerStart.setModel(new javax.swing.SpinnerNumberModel(100.0d, 0.0d, 2000.0d, 50.0d)); + spinnerStart.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + jLabel5.setText("Eph End"); + + spinnerEnd.setModel(new javax.swing.SpinnerNumberModel(200.0d, 0.0d, 2000.0d, 50.0d)); + spinnerEnd.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + spinnerStep.setModel(new javax.swing.SpinnerNumberModel(50.0d, 0.001d, 1000.0d, 10.0d)); + spinnerStep.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + jLabel6.setText("Eph Step"); + + table.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + + }, + new String [] { + + } + )); + table.getTableHeader().setReorderingAllowed(false); + jScrollPane1.setViewportView(table); + + jLabel7.setText("E center:"); + + spinnerCenter.setModel(new javax.swing.SpinnerNumberModel(50.0d, 0.0d, 2000.0d, 10.0d)); + spinnerCenter.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + spinnerLow.setModel(new javax.swing.SpinnerNumberModel(50.0d, 0.0d, 2000.0d, 10.0d)); + spinnerLow.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + jLabel8.setText("E low:"); + + jLabel9.setText("E high:"); + + spinnerHigh.setModel(new javax.swing.SpinnerNumberModel(100.0d, 0.0d, 2000.0d, 10.0d)); + spinnerHigh.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerEnergyChanged(evt); + } + }); + + javax.swing.GroupLayout panelPositionerLayout = new javax.swing.GroupLayout(panelPositioner); + panelPositioner.setLayout(panelPositionerLayout); + panelPositionerLayout.setHorizontalGroup( + panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) + .addComponent(radioCfs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinnerLatency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addComponent(radioFixed) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(spinnerLow, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE) + .addComponent(spinnerHigh) + .addComponent(spinnerCenter))) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(radioCis) + .addComponent(radioSwept)) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPositionerLayout.createSequentialGroup() + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel4) + .addComponent(jLabel5) + .addComponent(jLabel6)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(spinnerStep, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE) + .addComponent(spinnerEnd) + .addComponent(spinnerStart)))) + .addContainerGap()) + ); + panelPositionerLayout.setVerticalGroup( + panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelPositionerLayout.createSequentialGroup() + .addContainerGap() + .addComponent(radioSwept) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerLow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel8)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerHigh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel9)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioFixed) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerCenter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel7)) + .addGap(18, 18, 18) + .addComponent(radioCis) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(radioCfs) + .addGap(18, 18, 18) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel4) + .addComponent(spinnerStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(spinnerEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(spinnerStep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE) + .addGap(18, 18, 18) + .addGroup(panelPositionerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(spinnerLatency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + panelSensors.setBorder(javax.swing.BorderFactory.createTitledBorder("Sensors")); + + checkImage.setSelected(true); + checkImage.setText("Scienta Image"); + checkImage.setToolTipText(""); + checkImage.setContentAreaFilled(false); + checkImage.setName("Scienta.dataMatrix"); // NOI18N + + checkImageIntegration.setSelected(true); + checkImageIntegration.setText("Scienta Energy Distribution"); + checkImageIntegration.setToolTipText(""); + checkImageIntegration.setContentAreaFilled(false); + checkImageIntegration.setName("EnergyDistribution"); // NOI18N + + checkAngleDistribution.setSelected(true); + checkAngleDistribution.setText("Scienta Angle Distribution"); + checkAngleDistribution.setToolTipText(""); + checkAngleDistribution.setContentAreaFilled(false); + checkAngleDistribution.setName("AngleDistribution"); // NOI18N + + checkSpectrum.setText("Scienta Spectrum"); + checkSpectrum.setName("Scienta.spectrum"); // NOI18N + + checkTotalCount.setSelected(true); + checkTotalCount.setText("Total Counts"); + checkTotalCount.setName("Counts"); // NOI18N + + checkCounts1.setText("Counts Region 1"); + checkCounts1.setName("CountsR1"); // NOI18N + + checkCounts2.setText("Counts Region 2"); + checkCounts2.setName("CountsR2"); // NOI18N + + checkCounts3.setText("Counts Region 3"); + checkCounts3.setName("CountsR3"); // NOI18N + + checkCounts4.setText("Counts Region 4"); + checkCounts4.setName("CountsR4"); // NOI18N + + checkCurrent.setText("Machine Current"); + checkCurrent.setName("MachineCurrent"); // NOI18N + + checkCur1.setText("Sample Current"); + checkCur1.setName("SampleCurrent"); // NOI18N + + checkCur2.setText("Ref Current"); + checkCur2.setName("RefCurrent"); // NOI18N + + checkCur3.setText("Aux Current"); + checkCur3.setName("AuxCurrent"); // NOI18N + + buttonScientaSetup.setText("Scienta Setup"); + buttonScientaSetup.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScientaSetupActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelSensorsLayout = new javax.swing.GroupLayout(panelSensors); + panelSensors.setLayout(panelSensorsLayout); + panelSensorsLayout.setHorizontalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonScientaSetup, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE) + .addComponent(checkImage) + .addComponent(checkImageIntegration) + .addComponent(checkSpectrum) + .addComponent(checkCounts1) + .addComponent(checkTotalCount) + .addComponent(checkCounts2) + .addComponent(checkCounts3) + .addComponent(checkCounts4) + .addComponent(checkCurrent) + .addComponent(checkCur1) + .addComponent(checkCur2) + .addComponent(checkCur3) + .addComponent(checkAngleDistribution)) + .addContainerGap()) + ); + panelSensorsLayout.setVerticalGroup( + panelSensorsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSensorsLayout.createSequentialGroup() + .addContainerGap() + .addComponent(checkImage) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkImageIntegration) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkAngleDistribution) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkSpectrum) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkTotalCount) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCounts4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCurrent) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(checkCur3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonScientaSetup) + .addGap(26, 26, 26)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Scan Control")); + + buttonStart.setText("Start"); + buttonStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStartActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + checkEndScan.setText("Turn off beam at end"); + + labelAcqTime.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelAcqTime.setText("Acquisition time(s):"); + + textTotalTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); + textTotalTime.setBorder(javax.swing.BorderFactory.createTitledBorder("")); + + labelTotalTime.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelTotalTime.setText("Total time:"); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(checkEndScan) + .addGap(0, 0, Short.MAX_VALUE)) + .addComponent(buttonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addGap(0, 1, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelAcqTime) + .addComponent(labelTotalTime)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(textTotalTime, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(dvpAcqTime, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {dvpAcqTime, textTotalTime}); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {labelAcqTime, labelTotalTime}); + + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonStart) + .addGap(18, 18, 18) + .addComponent(buttonAbort) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(dvpAcqTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelAcqTime)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(labelTotalTime) + .addComponent(textTotalTime)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(checkEndScan) + .addGap(26, 26, 26)) + ); + + jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {dvpAcqTime, textTotalTime}); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(panelSensors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(panelPositioner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(60, Short.MAX_VALUE)) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanel3, panelPositioner, panelSensors}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(panelPositioner, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelSensors, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonScientaSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScientaSetupActionPerformed + try { + showDevicePanel("Scienta"); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonScientaSetupActionPerformed + + private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed + try { + startScan(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonStartActionPerformed + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + try { + abort(); + } catch (Exception ex) { + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonAbortActionPerformed + + private void radioCisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioCisActionPerformed + setEnabled(isEnabled()); + updateTable(); + }//GEN-LAST:event_radioCisActionPerformed + + private void radioSweptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioSweptActionPerformed + setEnabled(isEnabled()); + updateTable(); + }//GEN-LAST:event_radioSweptActionPerformed + + private void spinnerEnergyChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerEnergyChanged + updateTable(); + }//GEN-LAST:event_spinnerEnergyChanged + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.JButton buttonScientaSetup; + private javax.swing.JButton buttonStart; + private javax.swing.JCheckBox checkAngleDistribution; + private javax.swing.JCheckBox checkCounts1; + private javax.swing.JCheckBox checkCounts2; + private javax.swing.JCheckBox checkCounts3; + private javax.swing.JCheckBox checkCounts4; + private javax.swing.JCheckBox checkCur1; + private javax.swing.JCheckBox checkCur2; + private javax.swing.JCheckBox checkCur3; + private javax.swing.JCheckBox checkCurrent; + private javax.swing.JCheckBox checkEndScan; + private javax.swing.JCheckBox checkImage; + private javax.swing.JCheckBox checkImageIntegration; + private javax.swing.JCheckBox checkSpectrum; + private javax.swing.JCheckBox checkTotalCount; + private ch.psi.pshell.swing.DeviceValuePanel dvpAcqTime; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel3; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JLabel labelAcqTime; + private javax.swing.JLabel labelTotalTime; + private javax.swing.JPanel panelPositioner; + private javax.swing.JPanel panelSensors; + private javax.swing.JRadioButton radioCfs; + private javax.swing.JRadioButton radioCis; + private javax.swing.JRadioButton radioFixed; + private javax.swing.JRadioButton radioSwept; + private javax.swing.JSpinner spinnerCenter; + private javax.swing.JSpinner spinnerEnd; + private javax.swing.JSpinner spinnerHigh; + private javax.swing.JSpinner spinnerLatency; + private javax.swing.JSpinner spinnerLow; + private javax.swing.JSpinner spinnerStart; + private javax.swing.JSpinner spinnerStep; + private javax.swing.JTable table; + private javax.swing.JLabel textTotalTime; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/PowerSupply.java b/plugins/PowerSupply.java new file mode 100755 index 0000000..50aed25 --- /dev/null +++ b/plugins/PowerSupply.java @@ -0,0 +1,634 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ +import ch.psi.pshell.device.*; +import ch.psi.pshell.epics.*; +import ch.psi.utils.BitMask; +import java.io.IOException; + +/** + */ +public class PowerSupply extends DeviceBase implements BitMask { + + public final ChannelDouble moduleVoltageRamp, moduleCurrentRamp, + + moduleTemperature, modulePower5, modulePower12, modulePower12N, moduleVoltageRampRb, + moduleCurrentRampRb, moduleVoltageMax, moduleCurrentMax,channelActualVoltage,channelActualCurrent; + + public final ChannelInteger moduleRestartDelay, moduleAdcSamples, moduleDigFilter, moduleIlkCommand, + moduleEvMaskSet, moduleEvMaskClr, moduleChMaskSet, moduleChMaskClr, + + moduleFirmware, moduleSerial, modulePlacedChannels, moduleNoChannels,moduleRestartDelayRb, + moduleCommandRb, moduleEvMaskRb, moduleChMaskRb, moduleIlkCommandRb,moduleStatus, + moduleIlkStatus, moduleEvStatus, moduleChStatus, moduleAdcSamplesRb, moduleDigFilterRb; + public final ChannelString moduleCommand; + + public final ChannelDouble channelVoltageNominalSetpoint, channelCurrentNominalSetpoint, channelDesiredVoltageSetpoint, + channelVoltageIlkMax, channelVoltageIlkMin, channelDesiredCurrentSetpoint, + channelCurrentIlkMax, channelCurrentIlkMin, + + channelVoltageMax, channelCurrentMax, channelVoltageNominalReadback,channelCurrentNominalReadback, + channelDesiredVoltageReadback,channelDesiredCurrentReadback,channelVoltageIlkMaxReadback, + channelVoltageIlkMinReadback, channelCurrentIlkMaxReadback,channelCurrentIlkMinReadback; + + public final ChannelInteger channelEvMaskSet, channelEvMaskClr, + + channelCommandReadback, channelEventMaskReadback, channelStatus, channelEvents; + public final ChannelString channelCommand; + + + public final String prefix; + + + public PowerSupply(String name, String prefix) { + super(name); + this.prefix=prefix; + + moduleVoltageRamp = new ChannelDouble(name + " moduleVoltageRamp", prefix + ":RAMP:2"); + moduleCurrentRamp = new ChannelDouble(name + " moduleCurrentRamp", prefix + ":IRAMP:2"); + + moduleTemperature = new ChannelDouble(name + " moduleTemperature", prefix + ":TMPE:2", RegisterAccessType.Read); + modulePower5 = new ChannelDouble(name + " modulePower5", prefix + ":VP5:2", RegisterAccessType.Read); + modulePower12 = new ChannelDouble(name + " modulePower12", prefix + ":VP12:2", RegisterAccessType.Read); + modulePower12N = new ChannelDouble(name + " modulePower12N", prefix + ":VN12:2", RegisterAccessType.Read); + moduleVoltageRampRb = new ChannelDouble(name + " moduleVoltageRampRb", prefix + ":RAMPRB:2", RegisterAccessType.Read); + moduleCurrentRampRb = new ChannelDouble(name + " moduleCurrentRampRb", prefix + ":IRAMPRB:2", RegisterAccessType.Read); + moduleVoltageMax = new ChannelDouble(name + " moduleVoltageMax", prefix + ":VMAX:2", RegisterAccessType.Read); + moduleCurrentMax = new ChannelDouble(name + " moduleCurrentMax", prefix + ":IMAX:2", RegisterAccessType.Read); + channelActualVoltage = new ChannelDouble(name + " channelActualVoltage", prefix + ":IST:2", RegisterAccessType.Read); + channelActualCurrent = new ChannelDouble(name + " channelActualCurrent", prefix + ":STR:1", RegisterAccessType.Read); + + moduleRestartDelay = new ChannelInteger(name + " moduleRestartDelay", prefix + ":RTAR:2"); + moduleAdcSamples = new ChannelInteger(name + " moduleAdcSamples", prefix + ":NADC:2"); + moduleDigFilter = new ChannelInteger(name + " moduleDigFilter", prefix + ":NDF:2"); + moduleIlkCommand = new ChannelInteger(name + " moduleIlkCommand", prefix + ":ICOM:2"); + moduleEvMaskSet = new ChannelInteger(name + " moduleEvMaskSet", prefix + ":MMEMSKSET:2"); + moduleEvMaskClr = new ChannelInteger(name + " moduleEvMaskClr", prefix + ":MMEMSKCLR:2"); + moduleChMaskSet = new ChannelInteger(name + " moduleChMaskSet", prefix + ":MCEMSKSET:2"); + moduleChMaskClr = new ChannelInteger(name + " moduleChMaskClr", prefix + ":MCEMSKCLR:2"); + + moduleFirmware = new ChannelInteger(name + " moduleFirmware", prefix + ":FWNR:1", RegisterAccessType.Read); + moduleSerial = new ChannelInteger(name + " moduleSerial", prefix + ":SRNR:1", RegisterAccessType.Read); + modulePlacedChannels = new ChannelInteger(name + " modulePlacedChannels", prefix + ":PLCH:1", RegisterAccessType.Read); + moduleNoChannels = new ChannelInteger(name + " moduleNoChannels", prefix + ":NRCH:2", RegisterAccessType.Read); + moduleRestartDelayRb = new ChannelInteger(name + " moduleRestartDelayRb", prefix + ":RTARRB:2", RegisterAccessType.Read); + moduleCommandRb = new ChannelInteger(name + " moduleCommandRb", prefix + ":COMXRB:1", RegisterAccessType.Read); + moduleEvMaskRb = new ChannelInteger(name + " moduleEvMaskRb", prefix + ":MMEMSKRB:1", RegisterAccessType.Read); + moduleChMaskRb = new ChannelInteger(name + " moduleChMaskRb", prefix + ":MCEMSKRB:1", RegisterAccessType.Read); + moduleIlkCommandRb = new ChannelInteger(name + " moduleIlkCommandRb", prefix + ":ICOMRB:1", RegisterAccessType.Read); + moduleStatus = new ChannelInteger(name + " moduleStatus", prefix + ":STAX:1", RegisterAccessType.Read); + moduleIlkStatus = new ChannelInteger(name + " moduleIlkStatus", prefix + ":STA1:1", RegisterAccessType.Read); + moduleEvStatus = new ChannelInteger(name + " moduleEvStatus", prefix + ":MMESTA:1", RegisterAccessType.Read); + moduleChStatus = new ChannelInteger(name + " moduleChStatus", prefix + ":MCESTA:1", RegisterAccessType.Read); + moduleAdcSamplesRb = new ChannelInteger(name + " moduleAdcSamplesRb", prefix + ":NADCRB:1", RegisterAccessType.Read); + moduleDigFilterRb= new ChannelInteger(name + " moduleDigFilterRb", prefix + ":NDFRB:2", RegisterAccessType.Read); + + moduleCommand = new ChannelString(name + " moduleCommand", prefix + ":COMX:2"); + + channelVoltageNominalSetpoint = new ChannelDouble(name + " channelVoltageNominalSetpoint", prefix + ":VNOM:2"); + channelCurrentNominalSetpoint = new ChannelDouble(name + " channelCurrentNominalSetpoint", prefix + ":INOM:2"); + channelDesiredVoltageSetpoint = new ChannelDouble(name + " channelDesiredVoltageSetpoint", prefix + ":SOL:2"); + channelVoltageIlkMax = new ChannelDouble(name + " channelVoltageIlkMax", prefix + ":VIMX:2"); + channelVoltageIlkMin = new ChannelDouble(name + " channelVoltageIlkMin", prefix + ":VIMN:2"); + channelDesiredCurrentSetpoint = new ChannelDouble(name + " channelDesiredCurrentSetpoint", prefix + ":STRR:2"); + channelCurrentIlkMax = new ChannelDouble(name + " channelCurrentIlkMax", prefix + ":IIMX:2"); + channelCurrentIlkMin = new ChannelDouble(name + " channelCurrentIlkMin", prefix + ":IIMN:2"); + + channelVoltageMax = new ChannelDouble(name + " channelVoltageMax", prefix + ":VSMX:2", RegisterAccessType.Read); + channelCurrentMax = new ChannelDouble(name + " channelCurrentMax", prefix + ":ISMX:2", RegisterAccessType.Read); + channelVoltageNominalReadback = new ChannelDouble(name + " channelVoltageNominalReadback", prefix + ":VNOMRB:2", RegisterAccessType.Read); + channelCurrentNominalReadback = new ChannelDouble(name + " channelCurrentNominalReadback", prefix + ":INOMRB:2", RegisterAccessType.Read); + channelDesiredVoltageReadback = new ChannelDouble(name + " channelDesiredVoltageReadback", prefix + ":SOLRB:2", RegisterAccessType.Read); + channelDesiredCurrentReadback = new ChannelDouble(name + " channelDesiredCurrentReadback", prefix + ":STRRRB:2", RegisterAccessType.Read); + channelVoltageIlkMaxReadback = new ChannelDouble(name + " channelVoltageIlkMaxReadback", prefix + ":VIMXRB:2", RegisterAccessType.Read); + channelVoltageIlkMinReadback = new ChannelDouble(name + " channelVoltageIlkMinReadback", prefix + ":VIMNRB:2", RegisterAccessType.Read); + channelCurrentIlkMaxReadback = new ChannelDouble(name + " channelCurrentIlkMaxReadback", prefix + ":IIMXRB:2", RegisterAccessType.Read); + channelCurrentIlkMinReadback = new ChannelDouble(name + " channelCurrentIlkMinReadback", prefix + ":IIMNRB:2", RegisterAccessType.Read); + + channelEvMaskSet = new ChannelInteger(name + " channelEvMaskSet", prefix + ":CEMSKSET:2"); + channelEvMaskClr = new ChannelInteger(name + " channelEvMaskClr", prefix + ":CEMSKCLR:2"); + + channelCommandReadback = new ChannelInteger(name + " channelCommandReadback", prefix + ":COMRB:1", RegisterAccessType.Read); + channelEventMaskReadback = new ChannelInteger(name + " channelEventMaskReadback", prefix + ":CEMSKRB:1", RegisterAccessType.Read); + channelStatus = new ChannelInteger(name + " channelStatus", prefix + ":STA:1", RegisterAccessType.Read); + channelEvents = new ChannelInteger(name + " channelEvents", prefix + ":CESTA:1", RegisterAccessType.Read); + + + channelCommand = new ChannelString(name + " channelCommand", prefix + ":COM:2"); + + + setChildren(new Device[]{moduleVoltageRamp, moduleCurrentRamp, + moduleTemperature, modulePower5, modulePower12, modulePower12N, moduleVoltageRampRb, + moduleCurrentRampRb, moduleVoltageMax, moduleCurrentMax,channelActualVoltage,channelActualCurrent, + moduleRestartDelay, moduleAdcSamples, moduleDigFilter, moduleIlkCommand, + moduleEvMaskSet, moduleEvMaskClr, moduleChMaskSet, moduleChMaskClr, + moduleFirmware, moduleSerial, modulePlacedChannels, moduleNoChannels,moduleRestartDelayRb, + moduleCommandRb, moduleEvMaskRb, moduleChMaskRb, moduleIlkCommandRb,moduleStatus, + moduleIlkStatus, moduleEvStatus, moduleChStatus, moduleAdcSamplesRb, moduleDigFilterRb, + moduleCommand, + channelVoltageNominalSetpoint, channelCurrentNominalSetpoint, channelDesiredVoltageSetpoint, + channelVoltageIlkMax, channelVoltageIlkMin, channelDesiredCurrentSetpoint, + channelCurrentIlkMax, channelCurrentIlkMin, + channelVoltageMax, channelCurrentMax, channelVoltageNominalReadback,channelCurrentNominalReadback, + channelDesiredVoltageReadback,channelDesiredCurrentReadback,channelVoltageIlkMaxReadback, + channelVoltageIlkMinReadback, channelCurrentIlkMaxReadback,channelCurrentIlkMinReadback, + channelEvMaskSet, channelEvMaskClr, + channelCommandReadback, channelEventMaskReadback, channelStatus, channelEvents, + channelCommand } + ); + + } + + @Override + protected void doUpdate() throws InterruptedException, IOException { + super.doUpdate(); + try { + + channelActualVoltage.update(); + channelActualCurrent.update(); + setCache(new double[]{channelActualVoltage.getValue(), channelActualCurrent.getValue()}); + } catch (Exception ex) { + throw new DeviceException(ex); + } + } + + @Override + protected void doSetMonitored(boolean value) { + super.doSetMonitored(value); + for (Device dev: getChildren()){ + dev.setMonitored(value); + } + } + + + + String toHexString(Integer value){ + return String.format("0x%04X",value); + } + + public String getFirmware() throws InterruptedException, IOException { + //return toHexString(moduleFirmware.getValue()); + int value = moduleFirmware.getValue(); + return String.valueOf((value&0xFF0000)>>16) + "." + String.valueOf((value&0xFF00)>>8) + String.valueOf((value&0xFF)); + } + + public String getSerial() throws InterruptedException, IOException { + //return toHexString(moduleSerial.getValue()); + return String.valueOf(moduleSerial.getValue()); + } + + public Integer getNumberOfChannels() throws InterruptedException, IOException { + return moduleNoChannels.getValue(); + } + + public Integer getPlacedChannels() throws InterruptedException, IOException { + return modulePlacedChannels.getValue(); + } + + public Double getTemperature() throws InterruptedException, IOException { + return moduleTemperature.getValue(); + } + + public Double getPower5() throws InterruptedException, IOException { + return modulePower5.getValue(); + } + + public Double getPower12() throws InterruptedException, IOException { + return modulePower12.getValue(); + } + + public Double getPower12N() throws InterruptedException, IOException { + return modulePower12N.getValue(); + } + + public Double getVoltageRampReadback() throws InterruptedException, IOException { + return moduleVoltageRampRb.getValue(); + } + + public Double getCurrentRampReadback() throws InterruptedException, IOException { + return moduleCurrentRampRb.getValue(); + } + + public Double getCurrentMax() throws InterruptedException, IOException { + return moduleCurrentMax.getValue(); + } + + public Double getVoltageMax() throws InterruptedException, IOException { + return moduleVoltageMax.getValue(); + } + + public Integer getRestartDelayReadback() throws InterruptedException, IOException { + return moduleRestartDelayRb.getValue(); + } + + public Integer getAdcSamplesReadback() throws InterruptedException, IOException { + return moduleAdcSamplesRb.getValue(); + } + + public Integer getDigFilterReadback() throws InterruptedException, IOException { + return moduleDigFilterRb.getValue(); + } + + public int getModuleControl() throws InterruptedException, IOException { + return moduleCommandRb.getValue(); + } + + public String getModuleControlStr() throws InterruptedException, IOException { + return toHexString(getModuleControl()); + } + + public int getEventMask() throws InterruptedException, IOException { + return moduleEvMaskRb.getValue(); + } + + public String getEventMaskStr() throws InterruptedException, IOException { + return toHexString(getEventMask()); + } + + public int getEventChannelMask() throws InterruptedException, IOException { + return moduleChMaskRb.getValue(); + } + + public String getEventChannelMaskStr() throws InterruptedException, IOException { + return toHexString(getEventChannelMask()); + } + + public int getChannelIlkCommand() throws InterruptedException, IOException { + return moduleIlkCommandRb.getValue(); + } + + public String getChannelIlkCommandStr() throws InterruptedException, IOException { + return toHexString(getChannelIlkCommand()); + } + + public static class ModuleStatus { + + int mask; + boolean fineAdjAct; + boolean ilkOutActive; + boolean moduleIsOff; + boolean needService; + boolean inputError; + boolean inSpecialMode; + boolean commandComplete; + boolean noModuleErr; + boolean noChanRamping; + boolean saftyLoopOk; + boolean eventActive; + boolean moduleStateOk; + boolean powerSupplyOk; + boolean temperatureOk; + boolean killEnabled; + } + + public ModuleStatus getStatus(int mask) throws InterruptedException, IOException { + ModuleStatus ret = new ModuleStatus(); + ret.mask = mask; + ret.fineAdjAct = ((mask & BIT0) != 0); + ret.ilkOutActive = ((mask & BIT1) != 0); + ret.moduleIsOff = ((mask & BIT2) != 0); + ret.needService = ((mask & BIT4) != 0); + ret.inputError = ((mask & BIT5) != 0); + ret.inSpecialMode = ((mask & BIT6) != 0); + ret.commandComplete = ((mask & BIT7) != 0); + ret.noModuleErr = ((mask & BIT8) != 0); + ret.noChanRamping = ((mask & BIT9) != 0); + ret.saftyLoopOk = ((mask & BIT10) != 0); + ret.eventActive = ((mask & BIT11) != 0); + ret.moduleStateOk = ((mask & BIT12) != 0); + ret.powerSupplyOk = ((mask & BIT13) != 0); + ret.temperatureOk = ((mask & BIT14) != 0); + ret.killEnabled = ((mask & BIT15) != 0); + return ret; + } + + public ModuleStatus getStatus() throws InterruptedException, IOException { + Integer mask = moduleStatus.getValue(); + return getStatus(mask); + } + public static class ModuleEventStatus { + + int mask; + boolean restarted; + boolean needService; + boolean inputError; + boolean saftyLoopOpen; + boolean noGood; + boolean tGreater55C; + + } + + public ModuleEventStatus getEventStatus() throws InterruptedException, IOException { + Integer mask = moduleEvStatus.getValue(); + ModuleEventStatus ret = new ModuleEventStatus(); + ret.mask = mask; + ret.restarted = ((mask & BIT1) != 0); + ret.needService = ((mask & BIT4) != 0); + ret.inputError = ((mask & BIT5) != 0); + ret.saftyLoopOpen = ((mask & BIT10) != 0); + ret.noGood = ((mask & BIT13) != 0); + ret.tGreater55C = ((mask & BIT14) != 0); + return ret; + } + + //////////////////////////////////////////////////////////////////////////// + //Public Interface - Module config + //////////////////////////////////////////////////////////////////////////// + public Double getVoltageRampSetpoint() throws InterruptedException, IOException { + return moduleVoltageRamp.getValue(); + } + + public Double getCurrentRampSetpoint() throws InterruptedException, IOException { + return moduleCurrentRamp.getValue(); + } + + public Integer getAdcSamplesSetpoint() throws InterruptedException, IOException { + return moduleAdcSamples.getValue(); + } + + public void setAdcSamplesSetpoint(Integer value) throws InterruptedException, IOException { + moduleAdcSamples.write(value); + } + + public Integer getDigFilterSetpoint() throws InterruptedException, IOException { + return moduleDigFilter.getValue(); + } + + public void setDigFilterSetpoint(Integer value) throws InterruptedException, IOException { + moduleDigFilter.write(value); + } + + public Integer getRestartDelaySetpoint() throws InterruptedException, IOException { + return moduleRestartDelay.getValue(); + } + + public void setRestartDelaySetpoint(Integer value) throws InterruptedException, IOException { + moduleRestartDelay.write(value); + } + + public void setVoltageRampSetpoint(Double value) throws InterruptedException, IOException { + moduleVoltageRamp.write(value); + } + + public void setCurrentRampSetpoint(Double value) throws InterruptedException, IOException { + moduleCurrentRamp.write(value); + } + + public enum ModuleCommand { + + SAVE, + RECALL, + STP_ON, + STP_OFF, + AON_ON, + AON_OFF, + ADJ_ON, + ADJ_OFF, + KIL_ON, + KIL_OFF, + CLEAR + } + + public void setModuleCommand(ModuleCommand cmd) throws InterruptedException, IOException { + moduleCommand.write(cmd.toString().replaceAll("_", " ")); + } + + //////////////////////////////////////////////////////////////////////////// + //Public Interface - Channel Readback + //////////////////////////////////////////////////////////////////////////// + public static class ChannelStatus { + + int mask; + boolean inputDataErr; + boolean isOn; + boolean isRamping; + boolean isEmergencyOff; + boolean isIControlled; + boolean isVControlled; + boolean iOutOfBounds; + boolean vOutOfBounds; + boolean isExtInhibit; + boolean isTripSet; + boolean hwILimExc; + boolean hwVLimExc; + + String getMessageStatus() { + if (!isOn) { + return "Off"; + } + if (isRamping) { + return "Ramping"; + } + if (isEmergencyOff) { + return "Emergency"; + } + if (vOutOfBounds || iOutOfBounds) { + return "Out of Bounds"; + } + if (hwILimExc || hwILimExc) { + return "Lim Exc"; + } + if (isExtInhibit) { + return "Ext Inhibit"; + } + if (isRamping) { + return "Ramping"; + } + if (isVControlled) { + return "Voltage Control"; + } + if (isIControlled) { + return "Current Control"; + } + if (inputDataErr) { + return "Input Data Error"; + } + return "Unknown"; + } + } + + public static ChannelStatus getChannelStatus(int mask) throws InterruptedException, IOException { + ChannelStatus ret = new ChannelStatus(); + ret.mask = mask; + ret.inputDataErr = ((mask & BIT2) != 0); + ret.isOn = ((mask & BIT3) != 0); + ret.isRamping = ((mask & BIT4) != 0); + ret.isEmergencyOff = ((mask & BIT5) != 0); + ret.isIControlled = ((mask & BIT6) != 0); + ret.isVControlled = ((mask & BIT7) != 0); + ret.iOutOfBounds = ((mask & BIT10) != 0); + ret.vOutOfBounds = ((mask & BIT11) != 0); + ret.isExtInhibit = ((mask & BIT12) != 0); + ret.isTripSet = ((mask & BIT13) != 0); + ret.hwILimExc = ((mask & BIT14) != 0); + ret.hwVLimExc = ((mask & BIT15) != 0); + return ret; + } + + + public ChannelStatus getChannelStatus() throws InterruptedException, IOException { + Integer mask = channelStatus.getValue(); + return getChannelStatus(mask); + } + + public ChannelStatus getChannelEventStatus() throws InterruptedException, IOException { + Integer mask = channelEvents.getValue(); + ChannelStatus ret = new ChannelStatus(); + ret.mask = mask; + ret.inputDataErr = ((mask & BIT2) != 0); + ret.isOn = ((mask & BIT3) != 0); + ret.isRamping = ((mask & BIT4) != 0); + ret.isEmergencyOff = ((mask & BIT5) != 0); + ret.isIControlled = ((mask & BIT6) != 0); + ret.isVControlled = ((mask & BIT7) != 0); + ret.iOutOfBounds = ((mask & BIT10) != 0); + ret.vOutOfBounds = ((mask & BIT11) != 0); + ret.isExtInhibit = ((mask & BIT12) != 0); + ret.isTripSet = ((mask & BIT13) != 0); + ret.hwILimExc = ((mask & BIT14) != 0); + ret.hwVLimExc = ((mask & BIT15) != 0); + return ret; + } + + public int getChannelEventMask() throws InterruptedException, IOException { + return channelEventMaskReadback.getValue(); + } + + public Double getChannelVoltageMax() throws InterruptedException, IOException { + return channelVoltageMax.getValue(); + } + + public Double getChannelVoltageNominalReadback() throws InterruptedException, IOException { + return channelVoltageNominalReadback.getValue(); + } + + public Double getChannelActualVoltage() throws InterruptedException, IOException { + return channelActualVoltage.getValue(); + } + + public Double getChannelCurrentMax() throws InterruptedException, IOException { + return channelCurrentMax.getValue(); + } + + public Double getChannelActualCurrent() throws InterruptedException, IOException { + return channelActualCurrent.getValue(); + } + + public Double getChannelCurrentNominalReadback() throws InterruptedException, IOException { + return channelCurrentNominalReadback.getValue(); + } + + public Double getChannelDesiredVoltageReadback() throws InterruptedException, IOException { + return channelDesiredVoltageReadback.getValue(); + } + + public Double getChannelDesiredCurrentReadback() throws InterruptedException, IOException { + return channelDesiredCurrentReadback.getValue(); + } + + public Double getChannelVoltageIlkMaxReadback() throws InterruptedException, IOException { + return channelVoltageIlkMaxReadback.getValue(); + } + + public Double getChannelVoltageIlkMinReadback() throws InterruptedException, IOException { + return channelVoltageIlkMinReadback.getValue(); + } + + public Double getChannelCurrentIlkMaxReadback() throws InterruptedException, IOException { + return channelCurrentIlkMaxReadback.getValue(); + } + + public Double getChannelCurrentIlkMinReadback() throws InterruptedException, IOException { + return channelCurrentIlkMinReadback.getValue(); + } + + public int getChannelControlReadback() throws InterruptedException, IOException { + return channelCommandReadback.getValue(); + } + + public String getChannelControlReadbackStr() throws InterruptedException, IOException { + return toHexString(getModuleControl()); + } + + //////////////////////////////////////////////////////////////////////////// + //Public Interface - Channel Config + //////////////////////////////////////////////////////////////////////////// + public Double getChannelDesiredVoltage() throws InterruptedException, IOException { + return channelDesiredVoltageSetpoint.getValue(); + } + + public Double getChannelDesiredCurrent() throws InterruptedException, IOException { + return channelDesiredCurrentSetpoint.getValue(); + } + + public void setChannelDesiredVoltage(Double value) throws InterruptedException, IOException { + channelDesiredVoltageSetpoint.write(value); + } + + public void setChannelDesiredCurrent(Double value) throws InterruptedException, IOException { + channelDesiredCurrentSetpoint.write(value); + } + + public Double getChannelVoltageIlkMax() throws InterruptedException, IOException { + return channelVoltageIlkMax.getValue(); + } + + public Double getChannelVoltageIlkMin() throws InterruptedException, IOException { + return channelVoltageIlkMin.getValue(); + } + + public Double getChannelCurrentIlkMax() throws InterruptedException, IOException { + return channelCurrentIlkMax.getValue(); + } + + public Double getChannelCurrentIlkMin() throws InterruptedException, IOException { + return channelCurrentIlkMin.getValue(); + } + + public void setChannelVoltageIlkMax(Double value) throws InterruptedException, IOException { + channelVoltageIlkMax.write(value); + } + + public void setChannelVoltageIlkMin(Double value) throws InterruptedException, IOException { + channelVoltageIlkMin.write(value); + } + + public void setChannelCurrentIlkMax(Double value) throws InterruptedException, IOException { + channelCurrentIlkMax.write(value); + } + + public void setChannelCurrentIlkMin(Double value) throws InterruptedException, IOException { + channelCurrentIlkMin.write(value); + } + + public Double getChannelVoltageNominal() throws InterruptedException, IOException { + return channelVoltageNominalSetpoint.getValue(); + } + + public Double getChannelCurrentNominal() throws InterruptedException, IOException { + return channelCurrentNominalSetpoint.getValue(); + } + + public void setChannelVoltageNominal(Double value) throws InterruptedException, IOException { + channelVoltageNominalSetpoint.write(value); + } + + public void setChannelCurrentNominal(Double value) throws InterruptedException, IOException { + channelCurrentNominalSetpoint.write(value); + } + + public enum ChannelCommand { + ON, + OFF, + EMCY_ON, + EMCY_OFF, + AVBND_ON, + AVBND_OFF, + AIBND_ON, + AIBND_OFF + } + + public void setChannelCommand(ChannelCommand cmd) throws InterruptedException, IOException { + channelCommand.write(cmd.toString().replaceAll("_", " ")); + } +} diff --git a/plugins/PythonInteractive.java b/plugins/PythonInteractive.java new file mode 100755 index 0000000..137e3c9 --- /dev/null +++ b/plugins/PythonInteractive.java @@ -0,0 +1,39 @@ + +import java.io.PrintStream; + +/** + * + */ +public class PythonInteractive { + + public static void main(String[] args) throws Exception { + ProcessBuilder builder = new ProcessBuilder("python", "-i"); + builder.redirectErrorStream(true); + Process p = builder.start(); + + PrintStream printStream = new PrintStream(p.getOutputStream(), true); + new Thread(() -> { + int r; + try { + while (p.isAlive()) { + + while (p.getInputStream().available() > 0) { + r = p.getInputStream().read(); + System.out.print(Character.toString((char) r)); + } + Thread.sleep(10); + } + } catch (Exception ex) { + System.err.println(ex); + } + }).start(); + + Thread.sleep(200); + String cmd = "print (1+2)"; + System.out.println(cmd); + printStream.println(cmd); + Thread.sleep(200); + p.destroy(); + + } +} diff --git a/plugins/RotationReadback.java b/plugins/RotationReadback.java new file mode 100755 index 0000000..1d00edb --- /dev/null +++ b/plugins/RotationReadback.java @@ -0,0 +1,24 @@ + +import ch.psi.pshell.device.AccessType; +import ch.psi.pshell.epics.ChannelDouble; +import ch.psi.utils.Convert; + +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +/** + * + */ +public class RotationReadback extends ChannelDouble { + + public RotationReadback(String name, String channelName) { + super(name, channelName); + setAccessType(AccessType.Read); + } + + @Override + protected Double convertFromRead(Double value) { + return Convert.toDegrees0To360(value); + } +} diff --git a/plugins/ScalarPanel.form b/plugins/ScalarPanel.form new file mode 100755 index 0000000..39807b2 --- /dev/null +++ b/plugins/ScalarPanel.form @@ -0,0 +1,43 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ScalarPanel.java b/plugins/ScalarPanel.java new file mode 100755 index 0000000..6c2c502 --- /dev/null +++ b/plugins/ScalarPanel.java @@ -0,0 +1,55 @@ + +import ch.psi.pshell.swing.DevicePanel; + +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +/** + * + * @author gobbo_a + */ +public class ScalarPanel extends DevicePanel { + + /** + * Creates new form ScalarPanel + */ + public ScalarPanel() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT + * modify this code. The content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jButton1 = new javax.swing.JButton(); + + jButton1.setText("jButton1"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(58, 58, 58) + .addComponent(jButton1) + .addContainerGap(265, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(62, 62, 62) + .addComponent(jButton1) + .addContainerGap(206, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/ScreenPanel.form b/plugins/ScreenPanel.form new file mode 100755 index 0000000..3974d55 --- /dev/null +++ b/plugins/ScreenPanel.form @@ -0,0 +1,960 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ScreenPanel.java b/plugins/ScreenPanel.java new file mode 100755 index 0000000..275395a --- /dev/null +++ b/plugins/ScreenPanel.java @@ -0,0 +1,3223 @@ +/* + * 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; +import javax.swing.DefaultComboBoxModel; +import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.imaging.ImageListener; +import ch.psi.utils.State; +import ch.psi.utils.Chrono; +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.data.DataManager; +import ch.psi.pshell.device.DescStatsDouble; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.epics.DiscretePositioner; +import ch.psi.pshell.epics.Epics; +import ch.psi.pshell.imaging.Calibration; +import ch.psi.pshell.imaging.Colormap; +import ch.psi.pshell.imaging.ColormapSource; +import ch.psi.pshell.imaging.ColormapSource.ColormapSourceConfig; +import ch.psi.pshell.ui.App; +import ch.psi.pshell.imaging.Data; +import ch.psi.pshell.imaging.DimensionDouble; +import ch.psi.pshell.imaging.Histogram; +import ch.psi.pshell.imaging.ImageBuffer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Overlays.Text; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.PointDouble; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.imaging.Source; +import ch.psi.pshell.imaging.SourceBase; +import ch.psi.pshell.imaging.Utils; +import ch.psi.pshell.scripting.InterpreterResult; +import ch.psi.pshell.scripting.ScriptManager; +import ch.psi.pshell.swing.ValueSelection; +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.swing.Editor.EditorDialog; +import ch.psi.utils.swing.MainFrame; +import ch.psi.utils.swing.StandardDialog; +import ch.psi.utils.swing.StandardDialog.StandardDialogListener; +import ch.psi.utils.swing.SwingUtils.OptionResult; +import ch.psi.utils.swing.SwingUtils.OptionType; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.FileInputStream; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +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.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.DefaultTableModel; +import org.apache.commons.math3.analysis.function.Gaussian; +import org.apache.commons.math3.fitting.GaussianCurveFitter; +import org.apache.commons.math3.fitting.WeightedObservedPoint; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; + +/** + * + */ +public class ScreenPanel extends Panel { + + final String CAMERA_DEVICE_NAME = "CurrentCamera"; + boolean useServerStats = true; + String userOverlaysConfigFile; + ColormapSource camera; + PipelineServer server; + String cameraName; + int polling = 1000; + Overlay marker = null; + JDialog histogramDialog; + DiscretePositioner screen; + DiscretePositioner filter; + boolean showFit; + boolean showProfile; + Overlay[] userOv; + Overlay[] fitOv; + Overlay[] profileOv; + Overlay errorOverlay; + boolean requestCameraListUpdate; + boolean goodRegion; + String serverUrl; + String instanceName; + + boolean averaging = false; + + Double getServerDouble(String name) { + return (Double) Convert.toDouble(server.getValue(name)); + } + + double[] getServerDoubleArray(String name) { + return (double[]) Convert.toDouble(server.getValue(name)); + } + + Double getServerDouble(String name, StreamValue cache) { + return (Double) Convert.toDouble(cache.__getitem__(name)); + } + + double[] getServerDoubleArray(String name, StreamValue cache) { + return (double[]) Convert.toDouble(cache.__getitem__(name)); + } + + class ImageData { + + ImageData() { + if (server != null) { + cache = server.getStream().take(); + String prefix = goodRegion ? "gr_" : ""; + x_fit_mean = getServerDouble(prefix + "x_fit_mean", cache); + y_fit_mean = getServerDouble(prefix + "y_fit_mean", cache); + x_fit_standard_deviation = getServerDouble(prefix + "x_fit_standard_deviation", cache); + y_fit_standard_deviation = getServerDouble(prefix + "y_fit_standard_deviation", cache); + x_fit_gauss_function = getServerDoubleArray(prefix + "x_fit_gauss_function", cache); + y_fit_gauss_function = getServerDoubleArray(prefix + "y_fit_gauss_function", cache); + x_profile = getServerDoubleArray("x_profile", cache); + y_profile = getServerDoubleArray("y_profile", cache); + x_center_of_mass = getServerDouble("x_center_of_mass", cache); + y_center_of_mass = getServerDouble("y_center_of_mass", cache); + x_rms = getServerDouble("x_rms", cache); + y_rms = getServerDouble("y_rms", cache); + if (goodRegion) { + double[] gX2 = new double[x_profile.length]; + Arrays.fill(gX2, Double.NaN); + try { + double x = getServerDoubleArray("gr_x_axis", cache)[0]; + System.arraycopy(x_fit_gauss_function, 0, gX2, (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageX(x) : x), x_fit_gauss_function.length); + } catch (Exception ex) { + } + x_fit_gauss_function = gX2; + double[] gY2 = new double[y_profile.length]; + Arrays.fill(gY2, Double.NaN); + try { + double y = getServerDoubleArray("gr_y_axis", cache)[0]; + System.arraycopy(y_fit_gauss_function, 0, gY2, (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageY(y) : y), y_fit_gauss_function.length); + } catch (Exception ex) { + } + y_fit_gauss_function = gY2; + } + } + } + public Double x_fit_mean; + public Double y_fit_mean; + public Double x_center_of_mass; + public Double x_rms; + public Double x_fit_standard_deviation; + public Double y_fit_standard_deviation; + public Double y_center_of_mass; + public Double y_rms; + public double[] x_profile; + public double[] x_fit_gauss_function; + public double[] y_profile; + public double[] y_fit_gauss_function; + public StreamValue cache; + + } + + class Frame extends ImageData { + + Frame(Data data) { + this.data = data; + } + Data data; + + } + + final ArrayList imageBuffer = new ArrayList(); + Frame currentFrame; + int imageBufferLenght = 1; + Text imageBufferOverlay; + + public ScreenPanel() { + initComponents(); + spinnerThreshold.setVisible(false); + btFixColormapRange.setVisible(false); + spinnerGrThreshold.setVisible(false); + labelGrThreshold.setVisible(false); + spinnerGrScale.setVisible(false); + labelGrScale.setVisible(false); + //spinnerMin.setVisible(false); labelMin.setVisible(false); + //spinnerMax.setVisible(false); labelMax.setVisible(false); + renderer.setPersistenceFile(Paths.get(getContext().getSetup().getContextPath(), "Renderer_Cameras.bin")); + setPersistedComponents(new Component[]{buttonServer, buttonDirect}); + comboCameras.setEnabled(false); + SwingUtils.setEnumCombo(comboColormap, Colormap.class); + if (App.hasArgument("poll")) { + try { + polling = Integer.valueOf(App.getArgumentValue("poll")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("zoom")) { + try { + renderer.setDefaultZoom(Double.valueOf(App.getArgumentValue("zoom"))); + renderer.resetZoom(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("buf")) { + try { + imageBufferLenght = Integer.valueOf(App.getArgumentValue("buf")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("usr_ov")) { + try { + userOverlaysConfigFile = App.getArgumentValue("usr_ov"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("srv_url")) { + serverUrl = App.getArgumentValue("srv_url"); + } + + if (App.hasArgument("calc")) { + useServerStats = false; + } + + renderer.setProfileNormalized(true); + renderer.setShowProfileLimits(false); + + JMenuItem menuCalibrate = new JMenuItem("Calibrate..."); + menuCalibrate.addActionListener((ActionEvent e) -> { + try { + calibrate(); + } catch (Exception ex) { + ex.printStackTrace(); + showException(ex); + } + }); + + JMenuItem menuShowStreamData = new JMenuItem("Show Stream Data"); + menuShowStreamData.addActionListener((ActionEvent e) -> { + try { + showStreamData(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSaveStack = new JMenuItem("Save Stack"); + menuSaveStack.addActionListener((ActionEvent e) -> { + try { + saveStack(); + } catch (Exception ex) { + showException(ex); + } + }); + menuSaveStack.setEnabled(imageBufferLenght > 0); + + JMenuItem menuSetROI = new JMenuItem("Set ROI..."); + menuSetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + final Overlays.Rect selection = new Overlays.Rect(renderer.getPenMovingOverlay()); + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + try { + renderer.setShowReticle(false); + Rectangle roi = overlay.isFixed() ? renderer.toImageCoord(overlay.getBounds()) : overlay.getBounds(); + if (server.isRoiEnabled()) { + int[] cur = server.getRoi(); + server.setRoi(new int[]{roi.x + cur[0], roi.y + cur[1], roi.width, roi.height}); + } else { + server.setRoi(new int[]{roi.x, roi.y, roi.width, roi.height}); + } + } 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 (server != null) { + try { + renderer.setShowReticle(false); + server.resetRoi(); + } catch (IOException ex) { + showException(ex); + } + } + }); + + renderer.getPopupMenu().add(menuShowStreamData); + renderer.getPopupMenu().add(menuCalibrate); + renderer.getPopupMenu().add(menuSaveStack); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuSetROI); + renderer.getPopupMenu().add(menuResetROI); + renderer.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuResetROI.setEnabled(server != null); + menuSetROI.setEnabled(server != null); + menuShowStreamData.setVisible(server != null); + menuCalibrate.setVisible(server != null); + menuCalibrate.setEnabled((calibrationDialolg == null) || (!calibrationDialolg.isShowing())); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + renderer.getPopupMenu().setVisible(false); + + showFit = buttonFit.isSelected(); + showProfile = buttonProfile.isSelected(); + + 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())) { + updatePause(); + } + } + }); + 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()) { + textState.setEnabled(true); + } + } + + @Override + public void onStart() { + super.onStart(); + if (App.hasArgument("ct")) { + boolean direct = App.getArgumentValue("ct").equals("0") || App.getArgumentValue("ct").equalsIgnoreCase("false"); + buttonServer.setSelected(!direct); + buttonDirect.setSelected(direct); + } + } + + @Override + public void onStop() { + try { + if (camera != null) { + camera.close(); + camera = null; + server = null; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + super.onStop(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + comboCameras.setEnabled(false); + if (App.hasArgument("s")) { + renderer.setDevice((Source) getDevice("image")); + renderer.setAutoScroll(true); + ((Source) getDevice("image")).addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + manageFit(bi, data); + manageUserOverlays(bi, data); + } + + @Override + public void onError(Object o, Exception ex) { + } + } + ); + + } else { + usingServer = buttonServer.isSelected(); + updateCameraList(); + comboCameras.setEnabled(true); + setComboCameraSelection(-1); + + if (comboCameras.getModel().getSize() > 0) { + try { + if (App.hasArgument("cam")) { + setComboCameraSelection(App.getArgumentValue("cam")); + comboCamerasActionPerformed(null); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + startTimer(1000); + } + + DefaultComboBoxModel getCameraList(boolean fromServer) throws Exception { + DefaultComboBoxModel model = new DefaultComboBoxModel(); + if (fromServer) { + try (PipelineServer srv = newServer()) { + srv.initialize(); + List cameras = srv.getCameras(); + Collections.sort(cameras); + for (String camera : cameras) { + model.addElement(camera); + } + } + + } else { + ArrayList cameras = (ArrayList) getContext().getClassByName("SfCamera").getMethod("getCameras", new Class[]{}).invoke(null); + for (String cam : cameras) { + model.addElement(cam); + } + } + return model; + } + + PipelineServer newServer() throws IOException { + if (serverUrl != null) { + System.out.println("Connecting to server: " + serverUrl); + server = new PipelineServer(CAMERA_DEVICE_NAME, serverUrl); + } else { + System.out.println("Connecting to server"); + server = new PipelineServer(CAMERA_DEVICE_NAME); + } + return server; + } + + boolean updatingCameraSelection; + + void setComboCameraSelection(Object selection) { + updatingCameraSelection = true; + try { + comboCameras.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + + boolean usingServer; + + void updateCameraList() { + try { + String selected = (String) comboCameras.getSelectedItem(); + DefaultComboBoxModel model = getCameraList(usingServer); + if (App.hasArgument("cam")) { + String cam = App.getArgumentValue("cam"); + if (model.getIndexOf(cam) < 0) { + model.addElement(cam); + } + } + comboCameras.setModel(model); + if (selected != null) { + setComboCameraSelection(selected); + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateStop(); + } + } + + final Object lockOverlays = new Object(); + + void manageFit(BufferedImage bi, Data data) { + Overlay[][] fo = ((bi == null) || ((!showFit && !showProfile))) ? null : getFitOverlays(data); + synchronized (lockOverlays) { + fo = (fo == null) ? new Overlay[][]{null, null} : fo; + renderer.updateOverlays(fo[0], profileOv); + profileOv = fo[0]; + renderer.updateOverlays(fo[1], fitOv); + fitOv = fo[1]; + } + } + + void manageUserOverlays(BufferedImage bi, Data data) { + Overlay[] fo = (bi == null) ? null : getUserOverlays(data); + synchronized (lockOverlays) { + renderer.updateOverlays(fo, userOv); + userOv = fo; + } + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + Thread devicesInitTask; + + class ImageAverager extends SourceBase { + final ArrayList images = new ArrayList(); + ImageAverager() { + super("Image Averager"); + + camera.addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + images.add(bi); + if (images.size()>10){ + images.remove(0); + } + BufferedImage ret = null; + for (BufferedImage ib : images){ + if (ret == null){ + ret = Utils.copy(ib, null, null); + } else { + Utils.add(ret, ib, true); + + } + } + //ret =Utils.scale(ret, 1.0/images.size()); + ImageAverager.this.pushImage(ret); + } + + @Override + public void onError(Object origin, Exception ex) { + } + }); + + } + } + + void setCamera(String cameraName) throws IOException, InterruptedException { + System.out.println("Initializing"); + parseUserOverlays(); + errorOverlay = null; + + if (dataTableDialog != null) { + dataTableDialog.dispose(); + dataTableDialog = null; + } + dataTableModel = null; + + if (calibrationDialolg != null) { + calibrationDialolg.dispose(); + calibrationDialolg = null; + } + + boolean was_server = false; + if (camera != null) { + //camera.removeAllListeners(); + was_server = (server != null); + camera.close(); + camera = null; + server = null; + } + instanceName = null; + renderer.setDevice(null); + + renderer.setShowReticle(false); + renderer.removeOverlays(fitOv); + renderer.removeOverlays(profileOv); + renderer.removeOverlays(userOv); + renderer.clear(); + renderer.resetZoom(); + + boolean changed = !String.valueOf(cameraName).equals(this.cameraName); + this.cameraName = cameraName; + + if (changed || buttonDirect.isSelected()) { + spinnerThreshold.setVisible(false); + spinnerGrThreshold.setVisible(false); + labelGrThreshold.setVisible(false); + spinnerGrScale.setVisible(false); + labelGrScale.setVisible(false); + checkThreshold.setEnabled(false); + checkGoodRegion.setEnabled(false); + } + if (changed) { + checkBackground.setEnabled(false); + if ((devicesInitTask != null) && (devicesInitTask.isAlive())) { + devicesInitTask.interrupt(); + } + if (screen != null) { + screen.close(); + screen = null; + } + if (filter != null) { + filter.close(); + filter = null; + } + } + if (cameraName == null) { + return; + } + + System.out.println("Setting camera: " + cameraName + " [" + (buttonServer.isSelected() ? "server" : "direct") + "]"); + + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + + try { + if (buttonServer.isSelected()) { + camera = newServer(); + camera.getConfig().flipHorizontally = false; + camera.getConfig().flipVertically = false; + camera.getConfig().rotation = 0.0; + camera.getConfig().roiX = 0; + camera.getConfig().roiY = 0; + camera.getConfig().roiWidth = -1; + 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.initialize(); + camera.assertInitialized(); + System.out.println("Camera initialization OK"); + if (server != null) { + //server.start(cameraName, false); + String pipelineName = cameraName + "_sp"; + instanceName = cameraName + "_sp1"; + if (!server.getPipelines().contains(pipelineName)) { + System.out.println("Creating pipeline: " + pipelineName); + HashMap config = new HashMap<>(); + config.put("camera_name", cameraName); + //server.createFromConfig(config, pipelineName); + server.savePipelineConfig(pipelineName, config); + } + server.start(pipelineName, instanceName); + + updateServerControls(); + checkThreshold.setEnabled(true); + checkGoodRegion.setEnabled(true); + } else { + checkThreshold.setSelected(false); + checkGoodRegion.setSelected(false); + if (polling <= 0) { + camera.setMonitored(true); + } else { + camera.setPolling(polling); + } + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + + buttonReticle.setEnabled(camera.getConfig().isCalibrated()); + camera.getConfig().save(); + if (averaging) { + SourceBase source = new ImageAverager(); + renderer.setDevice(source); + } else { + renderer.setDevice(camera); + } + renderer.setAutoScroll(true); + renderer.setMarker(marker); + imageSize = null; + + camera.addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + if (bi != null) { + if ((imageSize == null) || imageSize.width != bi.getWidth() || imageSize.height != bi.getHeight()) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if ((renderer.getMode() == RendererMode.Zoom) || (renderer.getMode() == RendererMode.Fixed)) { + centralizeRenderer(); + } + checkReticle(); + } + }); + imageSize = new Dimension(bi.getWidth(), bi.getHeight()); + } + renderer.setProfileSize(Math.min(bi.getWidth(), bi.getHeight())); + } + //renderer.setCalibration(camera.getCalibration()); + if (!renderer.isPaused()) { + if (data != null) { + synchronized (imageBuffer) { + currentFrame = new Frame(data); + if (imageBufferLenght >= 1) { + imageBuffer.add(currentFrame); + if (imageBuffer.size() > imageBufferLenght) { + imageBuffer.remove(0); + } + } + } + } + manageFit(bi, data); + manageUserOverlays(bi, data); + } + //updateImageData(); + } + + @Override + public void onError(Object o, Exception ex) { + //System.err.println(ex); + } + }); + + } catch (Exception ex) { + ex.printStackTrace(); + showException(ex); + renderer.clearOverlays(); + updateServerControls(); + if (renderer.getDevice() == null) { + //renderer.setZoom(1.0); + //renderer.setMode(RendererMode.Zoom); + errorOverlay = new Text(renderer.getPenErrorText(), ex.toString(), new Font("Verdana", Font.PLAIN, 12), new Point(20, 20)); + errorOverlay.setFixed(true); + errorOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + renderer.addOverlay(errorOverlay); + } + } finally { + //checkReticle(); + onTimer(); + } + onChangeColormap(null); + checkBackground.setEnabled(true); + if (changed) { + comboScreen.setModel(new DefaultComboBoxModel()); comboScreen.setEnabled(false); + comboFilter.setModel(new DefaultComboBoxModel()); comboFilter.setEnabled(false); + if (getCameraType(cameraName).equals("ELECTRONS")){ + //Parallelizing initialization + devicesInitTask = new Thread(() -> { + try { + if (cameraName.contains("DSRM")) { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":POSITION_SP", cameraName + ":POSITION"); + } else { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":SET_SCREEN1_POS", cameraName + ":GET_SCREEN1_POS"); + } + screen.setMonitored(true); + screen.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : screen.getPositions()) { + model.addElement(pos); + } + comboScreen.setModel(model); + comboScreen.setSelectedItem(screen.read()); + + } catch (Exception ex) { + comboScreen.setModel(new DefaultComboBoxModel()); + System.err.println(ex.getMessage()); + screen = null; + } + comboScreen.setEnabled(screen != null); + valueScreen.setDevice(screen); + + try { + filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); + filter.setMonitored(true); + filter.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : filter.getPositions()) { + model.addElement(pos); + } + comboFilter.setModel(model); + comboFilter.setSelectedItem(filter.read()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + filter = null; + } + comboFilter.setEnabled(filter != null); + valueFilter.setDevice(filter); + }); + devicesInitTask.start(); + } + } + + } + + volatile Dimension imageSize; + + void checkReticle() { + if ((renderer.getDevice() != null) && (camera != null) && (camera.getConfig().isCalibrated()) && buttonReticle.isSelected()) { + //renderer.setCalibration(camera.getCalibration()); + renderer.configureReticle(new Dimension(800, 800), 200); + renderer.setShowReticle(true); + } else { + //renderer.setCalibration(null); + renderer.setShowReticle(false); + } + renderer.refresh(); + } + + void checkMarker() { + if (camera != null) { + if (buttonMarker.isSelected()) { + 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)); + marker.setMovable(true); + marker.setPassive(false); + } else { + marker = null; + } + renderer.setMarker(marker); + } + } + + void updateZoom() { + try { + buttonZoomStretch.setSelected(renderer.getMode() == RendererMode.Stretch); + buttonZoomFit.setSelected(renderer.getMode() == RendererMode.Fit); + if (renderer.getMode() == RendererMode.Fixed) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getMode() == RendererMode.Zoom) { + if (renderer.getZoom() == 1) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getZoom() == 0.5) { + buttonZoom05.setSelected(true); + } else if (renderer.getZoom() == 0.25) { + buttonZoom025.setSelected(true); + } else if (renderer.getZoom() == 2.0) { + buttonZoom2.setSelected(true); + } else { + buttonGroup1.clearSelection(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + boolean updatingColormap; + + void updateColormap() { + updatingColormap = true; + try { + if ((camera != null) && (camera instanceof ColormapSource)) { + ColormapSourceConfig config = ((ColormapSource) camera).getConfig(); + comboColormap.setSelectedItem(config.colormap); + if (config.isDefaultColormap()) { + buttonFullRange.setSelected(true); + } else if (config.colormapAutomatic) { + buttonAutomatic.setSelected(true); + } else { + buttonManual.setSelected(true); + } + btFixColormapRange.setVisible(buttonAutomatic.isSelected()); + + //spinnerMin.setVisible(buttonManual.isSelected()); labelMin.setVisible(spinnerMin.isVisible()); + //spinnerMax.setVisible(buttonManual.isSelected()); labelMax.setVisible(spinnerMax.isVisible()); + spinnerMin.setEnabled(buttonManual.isSelected()); + spinnerMax.setEnabled(buttonManual.isSelected()); + //spinnerMin.setValue(Double.isNaN(config.colormapMin) ? 0 : Math.min(Math.max((int) config.colormapMin, 0), 65535)); + //spinnerMax.setValue(Double.isNaN(config.colormapMax) ? 0 : Math.min(Math.max((int) config.colormapMax, 0), 65535)); + if (!Double.isNaN(config.colormapMin)) { + spinnerMin.setValue(Math.min(Math.max((int) config.colormapMin, 0), 65535)); + } + if (!Double.isNaN(config.colormapMax)) { + spinnerMax.setValue(Math.min(Math.max((int) config.colormapMax, 0), 65535)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatingColormap = false; + } + + boolean updatingServerControls; + + void updateServerControls() { + if (server != null) { + updatingServerControls = true; + try { + checkBackground.setSelected(server.getBackgroundSubtraction()); + Double threshold = (server.getThreshold()); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (server.getGoodRegion()); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + spinnerGrThreshold.setValue(((Number) gr.get("threshold")).doubleValue()); + spinnerGrScale.setValue(((Number) gr.get("gfscale")).doubleValue()); + } + } catch (Exception ex) { + } + goodRegion = checkGoodRegion.isSelected(); + spinnerThreshold.setVisible(checkThreshold.isSelected()); + spinnerGrThreshold.setVisible(goodRegion); + labelGrThreshold.setVisible(spinnerGrThreshold.isVisible()); + spinnerGrScale.setVisible(goodRegion); + labelGrScale.setVisible(spinnerGrScale.isVisible()); + updatingServerControls = false; + } + } + + boolean isCameraStopped() { + if (server != null) { + if (!server.isStarted()) { + return true; + } + } + return ((camera == null) || (camera.isClosed()) || !buttonStop.isEnabled()); + } + + void updateStop() { + buttonStop.setEnabled(comboCameras.getSelectedItem() != null); + buttonStop.setText(isCameraStopped() ? "Start" : "Stop"); + + } + + @Override + protected void onTimer() { + for (Device dev : new Device[]{screen, filter}) { + if (dev != null) { + dev.request(); + } + } + + textState.setText((camera == null) ? "" : camera.getState().toString()); + buttonArgs.setEnabled(camera != null); + if (App.hasArgument("s")) { + try { + ((Source) getDevice("image")).initialize(); + } catch (IOException ex) { + Logger.getLogger(ScreenPanel.class.getName()).log(Level.SEVERE, null, ex); + } catch (InterruptedException ex) { + Logger.getLogger(ScreenPanel.class.getName()).log(Level.SEVERE, null, ex); + } + } + if (renderer.isPaused() != buttonPause.isSelected()) { + buttonPause.setSelected(renderer.isPaused()); + buttonPauseActionPerformed(null); + } + if (renderer.getShowReticle() != buttonReticle.isSelected()) { + //buttonReticle.setSelected(renderer.getShowReticle()); + } + if ((renderer.getMarker() == null) && buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + } + if (!renderer.isPaused() && (dataTableDialog != null) && (dataTableDialog.isShowing())) { + updateStreamData(); + } + updateZoom(); + updateColormap(); + updateStop(); + buttonSave.setSelected(renderer.isSnapshotDialogVisible()); + checkHistogram.setSelected((histogramDialog != null) && (histogramDialog.isShowing())); + } + + Pen penFit = new Pen(new Color(192, 105, 0), 0); + Pen penCross = new Pen(new Color(192, 105, 0), 0); + + public Frame getCurrentFrame() { + if ((imageBufferLenght > 1) && (renderer.isPaused())) { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + return (index < imageBuffer.size()) ? imageBuffer.get(index) : null; + } + } + return currentFrame; + } + + Frame getFrame(Data data) { + synchronized (imageBuffer) { + for (Frame f : imageBuffer) { + if (f.data == data) { + return f; + } + } + } + return null; + } + + Overlay[][] getFitOverlays(Data data) { + Overlays.Polyline hgaussian = null; + Overlays.Polyline vgaussian = null; + Overlays.Polyline hprofile = null; + Overlays.Polyline vprofile = null; + Double xMean = null, xSigma = null, xNorm = null, xCom = null, xRms = null; + Double yMean = null, ySigma = null, yNorm = null, yCom = null, yRms = null; + double[] pX = null, pY = null, gX = null, gY = null; + int height = data.getHeight(); + int width = data.getWidth(); + //Double xCom=null, yCom=null; + if (data != null) { + int profileSize = renderer.getProfileSize(); + if ((useServerStats) && (server != null)) { + try { + + ImageData id = getFrame(data); + if (id == null) { + return null; + } + xMean = id.x_fit_mean; + xSigma = id.x_fit_standard_deviation; + yMean = id.y_fit_mean; + ySigma = id.y_fit_standard_deviation; + gX = id.x_fit_gauss_function; + gY = id.y_fit_gauss_function; + pX = id.x_profile; + pY = id.y_profile; + xCom = id.x_center_of_mass; + xRms = id.x_rms; + yCom = id.y_center_of_mass; + yRms = id.y_rms; + + profileSize /= 4; + if (pX != null) { + int[] x = Arr.indexesInt(pX.length); + int[] y = new int[pX.length]; + int[] p = new int[pX.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++) { + if (gX != null) { + y[i] = (int) (height - 1 - (((gX[i] - minPlot) / rangePlot) * profileSize)); + } + p[i] = (int) (height - 1 - (((pX[i] - minPlot) / rangePlot) * profileSize)); + } + + if (goodRegion) { + for (int i = 0; i < x.length; i++) { + y[i] = (Double.isNaN(gX[i])) ? 100000 : y[i]; + } + } + + vgaussian = new Overlays.Polyline(penFit, x, y); + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + + if (pY != null) { + int[] y = Arr.indexesInt(pY.length); + int[] x = new int[pY.length]; + int[] p = new int[pY.length]; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pY)); + 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++) { + if (gY != null) { + x[i] = (int) (((gY[i] - minPlot) / rangePlot) * profileSize); + } + p[i] = (int) (((pY[i] - minPlot) / rangePlot) * profileSize); + } + + if (goodRegion) { + for (int i = 0; i < x.length; i++) { + x[i] = (Double.isNaN(gY[i])) ? -1 : x[i]; + } + } + hgaussian = new Overlays.Polyline(penFit, x, y); + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, y); + } + } 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; + } + if (renderer.getCalibration() != null) { + try { + double[] sum = data.integrateVertically(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] x_egu = renderer.getCalibration().getAxisX(sum.length); + double[] comRms = getComRms(sum, x_egu); + xCom = comRms[0]; + xRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + 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) (height - 1 - ((((fit[i] + min) / height - minPlot) / rangePlot) * profileSize)); + } + vgaussian = new Overlays.Polyline(penFit, x, y); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (height - 1 - (((sum[i] / height - minPlot) / rangePlot) * profileSize)); + } + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + try { + double[] sum = data.integrateHorizontally(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] y_egu = renderer.getCalibration().getAxisY(sum.length); + double[] comRms = getComRms(sum, y_egu); + yCom = comRms[0]; + yRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + + if (showFit) { + double[] gaussian = fitGaussian(saux, 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)) { + 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) / width - minPlot) / rangePlot) * profileSize); + } + hgaussian = new Overlays.Polyline(penFit, y, x); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (((sum[i] / width - minPlot) / rangePlot) * profileSize); + } + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, x); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + if (xSigma != null) { + xSigma *= renderer.getCalibration().getScaleX(); + } + if (ySigma != null) { + ySigma *= renderer.getCalibration().getScaleY(); + } + if (xMean != null) { + xMean = data.getX((int) Math.round(xMean)); + } + if (yMean != null) { + yMean = data.getY((int) Math.round(yMean)); + } + } + } + final String units = (renderer.getCalibration() != null) ? "\u00B5m" : "px"; + final String fmt = "%7.1f" + units; + Overlays.Text textCom = null; + Overlay[] pOv = null, fOv = null; + Point textPosition = new Point(12, 20); + if (showProfile) { + if ((xCom != null) && (yCom != null)) { + String text = String.format("com x: m=" + fmt + " \u03C3=" + fmt + "\ncom y: m=" + fmt + " \u03C3=" + fmt, xCom, xRms, yCom, yRms); + textCom = new Overlays.Text(renderer.getPenProfile(), text, new Font(Font.MONOSPACED, 0, 14), textPosition); + textCom.setFixed(true); + textCom.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + } + pOv = new Overlay[]{hprofile, vprofile, textCom}; + } + if (showFit) { + Overlays.Crosshairs cross = null; + Overlays.Text textFit = null; + if ((xMean != null) && (yMean != null)) { + String text = String.format("fit x: m=" + fmt + " \u03C3=" + fmt + "\nfit y: m=" + fmt + " \u03C3=" + fmt, xMean, xSigma, yMean, ySigma); + textFit = new Overlays.Text(penFit, text, new Font(Font.MONOSPACED, 0, 14), showProfile ? new Point(12, 54) : textPosition); + textFit.setFixed(true); + textFit.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + Point center = new Point(xMean.intValue(), yMean.intValue()); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().convertToImagePosition(new PointDouble(xMean, yMean)); + xSigma /= renderer.getCalibration().getScaleX(); + ySigma /= renderer.getCalibration().getScaleY(); + } + cross = new Overlays.Crosshairs(penCross, center, new Dimension(Math.abs(2 * xSigma.intValue()), 2 * Math.abs(ySigma.intValue()))); + } + fOv = new Overlay[]{hgaussian, vgaussian, cross, textFit}; + + if (goodRegion) { + try { + double[] x = getServerDoubleArray("gr_x_axis"); + double[] y = getServerDoubleArray("gr_y_axis"); + double x1 = x[0]; + double x2 = x[x.length - 1]; + double y1 = y[0]; + double y2 = y[y.length - 1]; + Overlays.Rect goodRegionOv = new Overlays.Rect(new Pen(penFit.getColor(), 0, Pen.LineStyle.dotted)); + goodRegionOv.setCalibration(renderer.getCalibration()); + goodRegionOv.setAbsolutePosition(new PointDouble(x1, y1)); + goodRegionOv.setAbsoluteSize(new DimensionDouble(x2 - x1, y2 - y1)); + fOv = Arr.append(fOv, goodRegionOv); + } catch (Exception ex) { + } + } + + } + return new Overlay[][]{pOv, fOv}; + } + return null; + } + + class UserOverlay { + + String name; + Overlay obj; + String[] channels; + } + ArrayList userOverlayConfig; + + void parseUserOverlays() { + Properties userOverlays = new Properties(); + userOverlayConfig = new ArrayList<>(); + if (userOverlaysConfigFile != null) { + try { + try (FileInputStream in = new FileInputStream(getContext().getSetup().expandPath(userOverlaysConfigFile))) { + userOverlays.load(in); + + for (String name : userOverlays.stringPropertyNames()) { + String val = userOverlays.getProperty(name); + try { + UserOverlay uo = new UserOverlay(); + uo.name = name; + String type = val.substring(0, val.indexOf("(")).trim(); + String pars = val.substring(val.indexOf("(") + 1, val.lastIndexOf(")")).trim(); + String[] tokens = pars.split(","); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + Color color = Color.GRAY; + try { + color = (Color) Color.class.getField(tokens[tokens.length - 1].toUpperCase()).get(null); + } catch (Exception ex) { + } + Pen pen = new Pen(color); + try { + String[] penTokens = tokens[tokens.length - 1].split(":"); + color = (Color) Color.class.getField(penTokens[0].toUpperCase()).get(null); + int width = Integer.valueOf(penTokens[1]); + Pen.LineStyle style = Pen.LineStyle.valueOf(penTokens[2]); + pen = new Pen(color, width, style); + } catch (Exception ex) { + } + switch (type) { + case "Point": + uo.obj = new Overlays.Crosshairs(); + uo.obj.setSize(new Dimension(Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); + break; + case "Line": + uo.obj = new Overlays.Line(); + break; + case "Arrow": + uo.obj = new Overlays.Arrow(); + break; + case "Rect": + uo.obj = new Overlays.Rect(); + break; + case "Ellipse": + uo.obj = new Overlays.Ellipse(); + break; + case "Polyline": + uo.obj = new Overlays.Polyline(); + break; + } + if (type.equals("Polyline") || type.equals("Point")) { + uo.channels = new String[]{tokens[0], tokens[1]}; + } else { + uo.channels = new String[]{tokens[0], tokens[1], tokens[2], tokens[3]}; + } + uo.obj.setPen(pen); + userOverlayConfig.add(uo); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + Overlay[] getUserOverlays(Data data) { + ArrayList ret = new ArrayList<>(); + if (server != null) { + for (UserOverlay uo : userOverlayConfig) { + try { + Overlay ov = uo.obj; + //Overlay ov = (Overlay)uo.cls.newInstance(); + ov.setCalibration(renderer.getCalibration()); + boolean valid = false; + if (ov instanceof Overlays.Polyline) { + double[] x = (uo.channels[0].equals("null")) ? null : getServerDoubleArray(uo.channels[0]); + double[] y = (uo.channels[1].equals("null")) ? null : getServerDoubleArray(uo.channels[1]); + if ((x != null) || (y != null)) { + if (x == null) { + x = (renderer.getCalibration() == null) ? Arr.indexesDouble(y.length) : renderer.getCalibration().getAxisX(y.length); + } + if (y == null) { + y = (renderer.getCalibration() == null) ? Arr.indexesDouble(x.length) : renderer.getCalibration().getAxisY(x.length); + } + ((Overlays.Polyline) ov).updateAbsolute(x, y); + valid = true; + } + } else { + Double x = getServerDouble(uo.channels[0]); + Double y = getServerDouble(uo.channels[1]); + if ((x != null) && (y != null)) { + PointDouble position = new PointDouble(x, y); + ov.setAbsolutePosition(position); + if (!(ov instanceof Overlays.Crosshairs)) { + Double x2 = getServerDouble(uo.channels[2]); + Double y2 = getServerDouble(uo.channels[3]); + if ((x != null) && (y != null)) { + DimensionDouble size = new DimensionDouble(x2 - position.x, y2 - position.y); + ov.setAbsoluteSize(size); + valid = true; + } + } else { + valid = true; + } + } + } + if (valid) { + ret.add(ov); + } + } catch (Exception ex) { + //ex.printStackTrace(); + } + } + } + return ret.toArray(new Overlay[0]); + } + + double[] getComRms(double[] arr, double[] x) { + if (arr != null) { + double xmd = 0; + double xmd2 = 0; + double total = 0; + for (int i = 0; i < arr.length; i++) { + double v = (arr[i] * x[i]); + xmd += v; + xmd2 += (v * x[i]); + total += arr[i]; + } + if (total > 0) { + double com = xmd / total; + double com2 = xmd2 / total; + double rms = Math.sqrt(Math.abs(com2 - com * com)); + return new double[]{com, rms}; + } + } + return new double[]{Double.NaN, Double.NaN}; + } + + double[] fitGaussianScript(int[] y, int[] x) { + ScriptManager sm = Context.getInstance().getScriptManager(); + ArrayProperties pY = ArrayProperties.get(y); + sm.setVar("y", y); + sm.setVar("x", x); + InterpreterResult r = sm.eval("r = fit_gaussians(y, x, [" + pY.maxIndex + ",])"); + if (r.exception != null) { + r.exception.printStackTrace(); + } else { + List ret = (List) sm.getVar("r"); + if ((ret != null) && (ret.size() == 1) && (ret.get(0) instanceof List) && (((List) (ret.get(0))).size() == 3)) { + double norm = (Double) ((List) ret.get(0)).get(0); + double mean = (Double) ((List) ret.get(0)).get(1); + double sigma = (Double) ((List) ret.get(0)).get(2); + return new double[]{norm, mean, sigma}; + } + } + return null; + } + + double[] fitGaussian(double[] y, int[] x) { + try { + ArrayProperties pY = ArrayProperties.get(y); + GaussianCurveFitter fitter = GaussianCurveFitter.create().withStartPoint(new double[]{(pY.max - pY.min) / 2, x[pY.maxIndex], 1.0}).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] getFitFunction(double[] pars, int[] x) { + double[] fit = new double[x.length]; + Gaussian g = new Gaussian(pars[0], pars[1], pars[2]); + for (int i = 0; i < x.length; i++) { + fit[i] = g.value(x[i]); + } + return fit; + } + + void setHistogramVisible(boolean value) { + if (value) { + if ((histogramDialog == null) || (!histogramDialog.isShowing())) { + Histogram histogram = new Histogram(true); + histogram.setRenderer(renderer); + histogramDialog = SwingUtils.showDialog(SwingUtils.getWindow(renderer), "Histogram", null, histogram); + renderer.refresh(); + } + } else { + if (histogramDialog != null) { + histogramDialog.setVisible(false); + histogramDialog = null; + } + } + } + + void setLaserState(boolean value) throws Exception { + System.out.println("Setting laser state: " + value); + 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 { + return (Epics.get("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", Integer.class) == 0); + } + + void elog(String logbook, String title, String message, String[] attachments) throws Exception { + String domain = ""; + String category = "Info"; + String entry = ""; + StringBuffer cmd = new StringBuffer(); + + cmd.append("G_CS_ELOG_add -l \"").append(logbook).append("\" "); + cmd.append("-a \"Author=ScreenPanel\" "); + cmd.append("-a \"Type=pshell\" "); + cmd.append("-a \"Entry=").append(entry).append("\" "); + 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) { + 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()}); + new Thread(() -> { + try { + process.waitFor(); + int bytes = process.getInputStream().available(); + 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); + System.err.println(new String(arr)); + } catch (Exception ex) { + System.err.println(ex); + } + }).start(); + } + + void centralizeRenderer() { + Point center = null; + Dimension size = renderer.getImageSize(); + 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); + } + 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 (index < imageBuffer.size()) { + Data data = imageBuffer.get(index).data; + BufferedImage image = camera.generateImage(data); + renderer.setImage(renderer.getOrigin(), image, data); + imageBufferOverlay.update(Chrono.getTimeStr(data.getTimestamp(), "HH:mm:ss.SSS")); + manageFit(image, data); + manageUserOverlays(image, data); + } + } + } + + /* + void writeFrameMetadata(String path, Frame frame) throws Exception { + getContext().getDataManager().setAttribute("/", "Camera", String.valueOf(cameraName)); + getContext().getDataManager().setAttribute("/", "Screen", String.valueOf(valueScreen.getLabel().getText())); + getContext().getDataManager().setAttribute("/", "Filter", String.valueOf(valueFilter.getLabel().getText())); + Calibration cal = renderer.getCalibration(); + getContext().getDataManager().setAttribute("/", "Calibration", cal == null ? new double[]{1, 1, 0, 0} + : new double[]{cal.getScaleX(), cal.getScaleY(), cal.getOffsetX(), cal.getOffsetY()}); + getContext().getDataManager().setAttribute(path, "Timestamp", Chrono.getTimeStr(frame.data.getTimestamp(), "HH:mm:ss.SSS")); + if (server != null) { + try { + getContext().getDataManager().setAttribute("/", "ROI", server.getRoi()); + } catch (Exception ex) { + getContext().getDataManager().setAttribute("/", "ROI", new int[]{0, 0, -1, -1}); + } + if (frame != null) { + for (Field f : ImageData.class.getFields()) { + Object value = f.get(frame); + getContext().getDataManager().setAttribute(path, f.getName(), (value == null) ? Double.NaN : value); + } + } + for (String name : new String[]{"x_axis", "y_axis", "gr_x_axis", "gr_y_axis"}) { + double[] val = getServerDoubleArray(name); + getContext().getDataManager().setAttribute("/", "GoodRegion", goodRegion); + if (val != null) { + getContext().getDataManager().setAttribute("/", name, val); + } + } + } + } + */ + + void saveSnapshot() throws Exception { + /* + getContext().setExecutionPars("snapshot"); + String path = "/data"; + String snapshotFile = null; + synchronized (imageBuffer) { + Frame id = getCurrentFrame(); + if (id == null) { + throw new Exception("No current image"); + } + Object data = id.data.getMatrix(); + getContext().getDataManager().setDataset(path, data, id.data.isUnsigned()); + writeFrameMetadata(path, id); + getContext().getDataManager().closeOutput(); + //Enforce the same timestamp to data & image files. + //snapshotFile = getContext().getSetup().expandPath("{images}/{date}_{time}_snapshot.png", getContext().getExecutionPars().getStart()); + snapshotFile = getContext().getExecutionPars().getPath() + ".png"; + //renderer.saveSnapshot(snapshotFile, "png", true); + ImageBuffer.saveImage(SwingUtils.createImage(renderer), snapshotFile, "png"); + } + */ + String snapshotFile = null; + synchronized (imageBuffer) { + Frame frame = getCurrentFrame(); + if (frame == null) { + throw new Exception("No current image"); + } + ArrayList frames = new ArrayList<>(); + frames.add(frame); + this.saveFrames("camera_snapshot", frames); + + //Enforce the same timestamp to data & image files. + //snapshotFile = getContext().getSetup().expandPath("{images}/{date}_{time}_snapshot.png", getContext().getExecutionPars().getStart()); + snapshotFile = getContext().getExecutionPars().getPath() + ".png"; + //renderer.saveSnapshot(snapshotFile, "png", true); + ImageBuffer.saveImage(SwingUtils.createImage(renderer), snapshotFile, "png"); + } + + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{0, 180}; //Minimum width + layout.rowHeights = new int[]{30, 30, 30}; //Minimum height + panel.setLayout(layout); + JComboBox comboLogbook = new JComboBox(new String[]{"SwissFEL commissioning data", "SwissFEL commissioning"}); + JTextField textComment = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Data file:"), c); + c.gridy = 1; + panel.add(new JLabel("Logbook:"), c); + c.gridy = 2; + panel.add(new JLabel("Comment:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(textComment, c); + c.gridy = 1; + panel.add(comboLogbook, c); + c.gridy = 0; + panel.add(new JLabel(getContext().getExecutionPars().getPath()), c); + + if (SwingUtils.showOption(getTopLevel(), "Success", panel, OptionType.OkCancel) == OptionResult.Yes) { + StringBuilder message = new StringBuilder(); + message.append("Camera: ").append(cameraName).append(" ("). + append((server != null) ? "server" : "direct").append(")").append("\n"); + message.append("Screen: ").append(String.valueOf(valueScreen.getLabel().getText())).append("\n"); + message.append("Filter: ").append(String.valueOf(valueFilter.getLabel().getText())).append("\n"); + message.append("Data file: ").append(getContext().getExecutionPars().getPath()).append("\n"); + message.append("Comment: ").append(textComment.getText()).append("\n"); + if ((fitOv != null) && (fitOv.length > 5)) { + Overlays.Text text = (Overlays.Text) fitOv[5]; + message.append(text.getText()).append("\n"); + } + elog((String) comboLogbook.getSelectedItem(), "ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); + } + //SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getContext().getExecutionPars().getPath(), 5000); + //elog("SwissFEL commissioning data", "ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); + } + + + + public static String getCameraType(String name){ + for (String s : new String[]{"LCAM"}){ + if (name.contains(s)){ + return "LCAM"; + } + } + for (String s : new String[]{"DSCR", "DSRM", "DLAC"}){ + if (name.contains(s)){ + return "ELECTRONS"; + } + } + for (String s : new String[]{"PROF", "PPRM", "PSSS", "PSCR", "PSRD"}){ + if (name.contains(s)){ + return "PHOTONICS"; + } + } + return "UNKNOWN"; + } + + public Map getProcessingParameters(StreamValue value) throws IOException { + return (Map) JsonSerializer.decode(value.getValue("processing_parameters").toString(), Map.class); + } + + void saveFrames(String name, ArrayList frames) throws IOException{ + ArrayList values = new ArrayList<>(); + for (Frame frame : frames){ + values.add(frame.cache); + } + saveImages(name, values); + } + + void saveImages(String name, ArrayList images) throws IOException{ + int depth = images.size(); + if (depth == 0){ + return; + } + StreamValue first = images.get(0); + String pathRoot = "/camera1/"; + String pathImage = pathRoot + "image"; + String pathPid = pathRoot + "pulse_id"; + String pathTimestampStr = pathRoot + "timestamp_str"; + Map processingPars = getProcessingParameters(first); + System.out.println(processingPars); + String camera = (String) processingPars.get("camera_name"); + String type = getCameraType(camera); + + int width = ((Number)first.getValue("width")).intValue(); + int height = ((Number)first.getValue("height")).intValue(); + Class dataType = first.getValue("image").getClass().getComponentType(); + + getContext().setExecutionPars(name); + DataManager dm = getContext().getDataManager(); + + //Create tables + dm.createDataset(pathImage, dataType, new int[]{depth, height, width}); + dm.createDataset(pathPid, Long.class, new int[]{depth}); + dm.createDataset(pathTimestampStr, String.class, new int[]{depth}); + for (String id : first.getIdentifiers()){ + Object val = first.getValue(id); + if (id.equals("image")){ + } else if (id.equals("processing_parameters")){ + Map pars = getProcessingParameters(first); + for (String key : pars.keySet()){ + if ((pars.get(key) != null) && (pars.get(key) instanceof Map)){ + for (Object k : ((Map)pars.get(key)).keySet()){ + Object v = ((Map)pars.get(key)).get(k); + dm.setAttribute(pathImage, key + " " + k, (v == null)? "" : v); + } + } else { + dm.setAttribute(pathImage, key, (pars.get(key) == null)? "" : pars.get(key)); + } + } + } else if (val.getClass().isArray()) { + dm.createDataset(pathRoot + id, Double.class, new int[]{depth, Array.getLength(val)}); + } else { + dm.createDataset(pathRoot + id, val.getClass(), new int[]{depth}); + } + } + + //Add metadata + dm.setAttribute(pathRoot,"Camera", camera); + dm.setAttribute(pathRoot,"Images", depth); + dm.setAttribute(pathRoot,"Interval", -1); + dm.setAttribute(pathRoot,"Type", type); + if (type.equals("ELECTRONS")){ + dm.setAttribute(pathRoot,"Screen", String.valueOf(valueScreen.getLabel().getText())); + dm.setAttribute(pathRoot,"Filter", String.valueOf(valueFilter.getLabel().getText())); + } + + //Save data + for (int index=0; index x = new ArrayList<>(); + ArrayList y = new ArrayList<>(); + synchronized (imageBuffer) { + for (int i = 0; i < imageBuffer.size(); i++) { + Frame frame = imageBuffer.get(i); + String path = "/data_" + i; + getContext().getDataManager().setDataset(path, frame.data.getMatrix(), frame.data.isUnsigned()); + writeFrameMetadata(path, frame); + x.add(frame.x_fit_mean); + y.add(frame.y_fit_mean); + } + } + DescStatsDouble xs = new DescStatsDouble(x.toArray(new Double[0]), -1); + DescStatsDouble ys = new DescStatsDouble(y.toArray(new Double[0]), -1); + + getContext().getDataManager().closeOutput(); + ) + */ + synchronized (imageBuffer) { + saveFrames("camera_stack", imageBuffer); + } + SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getContext().getExecutionPars().getPath(), 5000); + } + + StandardDialog calibrationDialolg; + + void calibrate() throws Exception { + if (server != null) { + server.resetRoi(); + calibrationDialolg = (StandardDialog) getContext().getClassByName("CameraCalibrationDialog").getConstructors()[0].newInstance(new Object[]{getTopLevel(), server.getCurrentCamera(), renderer}); + SwingUtils.centerComponent(getTopLevel(), calibrationDialolg); + calibrationDialolg.setVisible(true); + calibrationDialolg.setListener(new StandardDialogListener() { + @Override + public void onWindowOpened(StandardDialog dlg) { + } + + @Override + public void onWindowClosed(StandardDialog dlg, boolean accepted) { + if (accepted) { + //comboCamerasActionPerformed(null); + } + } + }); + } + } + + StandardDialog dataTableDialog; + DefaultTableModel dataTableModel; + + void showStreamData() { + dataTableModel = null; + if (server != null) { + + if ((dataTableDialog != null) && (dataTableDialog.isShowing())) { + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + dataTableDialog.requestFocus(); + return; + } + //String msg = String.join("\n", ids); + //SwingUtils.showMessage(getTopLevel(), "Image Data", msg); + dataTableModel = new DefaultTableModel(new Object[0][2], new String[]{"Name", "Value"}) { + public Class getColumnClass(int columnIndex) { + return String.class; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + }; + updateStreamData(); + StreamValue val = server.getStream().take(); + JTable dataTable = new JTable(dataTableModel); + dataTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + dataTable.setCellSelectionEnabled(true); + dataTable.getTableHeader().setReorderingAllowed(false); + dataTable.getTableHeader().setResizingAllowed(true); + dataTableDialog = new StandardDialog(getTopLevel(), "Image Data", false); + dataTableDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setViewportView(dataTable); + scrollPane.setPreferredSize(new Dimension(300, 400)); + dataTableDialog.setContentPane(scrollPane); + dataTableDialog.pack(); + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + dataTableDialog.setVisible(true); + dataTableDialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + dataTableModel = null; + } + }); + } + } + + void updateStreamData() { + if ((dataTableModel != null) && (server != null)) { + StreamValue value = server.getValue(); + + List ids = (value == null) ? new ArrayList<>() : new ArrayList(value.getIdentifiers()); + if (ids.size() + 2 != dataTableModel.getRowCount()) { + dataTableModel.setNumRows(0); + try { + dataTableModel.addRow(new Object[]{"Locator", server.getUrl() + "/" + ((value == null) ? instanceName : server.getCurrentInstance())}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Locator", ex.getMessage()}); + } + try { + dataTableModel.addRow(new Object[]{"Stream", server.getStreamAddress()}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Stream", ex.getMessage()}); + } + Collections.sort(ids); + for (String id : ids) { + dataTableModel.addRow(new Object[]{id, ""}); + } + } + for (int i = 2; i < dataTableModel.getRowCount(); i++) { + String id = String.valueOf(dataTableModel.getValueAt(i, 0)); + Object obj = server.getValue(id); + if (obj != null) { + if (obj.getClass().isArray()) { + obj = obj.getClass().getComponentType().getSimpleName() + "[" + Array.getLength(obj) + "]"; + } else if (obj instanceof Double) { + obj = Convert.roundDouble((Double) obj, 1); + } else if (obj instanceof Float) { + obj = Convert.roundDouble((Float) obj, 1); + } + } + dataTableModel.setValueAt(String.valueOf(obj), i, 1); + } + } + } + + //////// + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + buttonGroup3 = new javax.swing.ButtonGroup(); + buttonGroup4 = new javax.swing.ButtonGroup(); + jProgressBar1 = new javax.swing.JProgressBar(); + jPanel1 = new javax.swing.JPanel(); + jPanel7 = new javax.swing.JPanel(); + buttonMarker = new javax.swing.JToggleButton(); + buttonGrabBackground = new javax.swing.JButton(); + buttonSave = new javax.swing.JToggleButton(); + buttonFit = new javax.swing.JToggleButton(); + buttonReticle = new javax.swing.JToggleButton(); + buttonPause = new javax.swing.JToggleButton(); + buttonProfile = new javax.swing.JToggleButton(); + jPanel6 = new javax.swing.JPanel(); + textState = new javax.swing.JTextField(); + jLabel2 = new javax.swing.JLabel(); + comboCameras = new javax.swing.JComboBox(); + buttonConfig = new javax.swing.JButton(); + jLabel1 = new javax.swing.JLabel(); + buttonArgs = new javax.swing.JButton(); + buttonStop = new javax.swing.JButton(); + renderer = new ch.psi.pshell.imaging.Renderer(); + jPanel4 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + buttonZoomFit = new javax.swing.JRadioButton(); + buttonZoomStretch = new javax.swing.JRadioButton(); + buttonZoomNormal = new javax.swing.JRadioButton(); + buttonZoom025 = new javax.swing.JRadioButton(); + buttonZoom05 = new javax.swing.JRadioButton(); + buttonZoom2 = new javax.swing.JRadioButton(); + jPanel2 = new javax.swing.JPanel(); + checkHistogram = new javax.swing.JCheckBox(); + comboColormap = new javax.swing.JComboBox(); + jLabel3 = new javax.swing.JLabel(); + jLabel4 = new javax.swing.JLabel(); + buttonFullRange = new javax.swing.JRadioButton(); + buttonManual = new javax.swing.JRadioButton(); + buttonAutomatic = new javax.swing.JRadioButton(); + labelMin = new javax.swing.JLabel(); + spinnerMin = new javax.swing.JSpinner(); + spinnerMax = new javax.swing.JSpinner(); + labelMax = new javax.swing.JLabel(); + btFixColormapRange = new javax.swing.JButton(); + jPanel5 = new javax.swing.JPanel(); + buttonServer = new javax.swing.JRadioButton(); + buttonDirect = new javax.swing.JRadioButton(); + panelScreen = new javax.swing.JPanel(); + valueScreen = new ch.psi.pshell.swing.DeviceValuePanel(); + comboScreen = new javax.swing.JComboBox(); + panelScreen1 = new javax.swing.JPanel(); + valueFilter = new ch.psi.pshell.swing.DeviceValuePanel(); + comboFilter = new javax.swing.JComboBox(); + pauseSelection = new ch.psi.pshell.swing.ValueSelection(); + panelScreen2 = new javax.swing.JPanel(); + checkThreshold = new javax.swing.JCheckBox(); + spinnerThreshold = new javax.swing.JSpinner(); + checkBackground = new javax.swing.JCheckBox(); + checkGoodRegion = new javax.swing.JCheckBox(); + spinnerGrScale = new javax.swing.JSpinner(); + spinnerGrThreshold = new javax.swing.JSpinner(); + labelGrThreshold = new javax.swing.JLabel(); + labelGrScale = new javax.swing.JLabel(); + + setPreferredSize(new java.awt.Dimension(873, 600)); + + buttonMarker.setText("Marker"); + buttonMarker.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMarkerActionPerformed(evt); + } + }); + + buttonGrabBackground.setText("Grab Background"); + buttonGrabBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonGrabBackgroundActionPerformed(evt); + } + }); + + buttonSave.setText("Save Snapshot"); + buttonSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSaveActionPerformed(evt); + } + }); + + buttonFit.setSelected(true); + buttonFit.setText("Fit"); + buttonFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFitActionPerformed(evt); + } + }); + + buttonReticle.setSelected(true); + buttonReticle.setText("Reticle"); + buttonReticle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonReticleActionPerformed(evt); + } + }); + + buttonPause.setText("Pause"); + buttonPause.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonPauseActionPerformed(evt); + } + }); + + buttonProfile.setSelected(true); + buttonProfile.setText("Profile"); + buttonProfile.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonProfileActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); + jPanel7.setLayout(jPanel7Layout); + jPanel7Layout.setHorizontalGroup( + jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel7Layout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(buttonPause) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonMarker) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonProfile) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonFit) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonReticle) + .addGap(18, 18, Short.MAX_VALUE) + .addComponent(buttonGrabBackground) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonSave) + .addGap(0, 0, 0)) + ); + + jPanel7Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonFit, buttonMarker, buttonPause, buttonProfile, buttonReticle}); + + jPanel7Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonGrabBackground, buttonSave}); + + jPanel7Layout.setVerticalGroup( + jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel7Layout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonPause) + .addComponent(buttonFit) + .addComponent(buttonMarker) + .addComponent(buttonSave) + .addComponent(buttonReticle) + .addComponent(buttonGrabBackground) + .addComponent(buttonProfile)) + .addGap(0, 0, 0)) + ); + + textState.setEditable(false); + textState.setHorizontalAlignment(javax.swing.JTextField.CENTER); + textState.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + textState.setEnabled(false); + + jLabel2.setText("State:"); + + comboCameras.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboCameras.setMaximumRowCount(30); + comboCameras.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboCamerasActionPerformed(evt); + } + }); + + buttonConfig.setText("Config"); + buttonConfig.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonConfigActionPerformed(evt); + } + }); + + jLabel1.setText("Camera:"); + + buttonArgs.setText("Setup"); + buttonArgs.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonArgsActionPerformed(evt); + } + }); + + buttonStop.setText("Stop"); + buttonStop.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStopActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); + jPanel6.setLayout(jPanel6Layout); + jPanel6Layout.setHorizontalGroup( + jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel6Layout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(comboCameras, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonArgs) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonConfig) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonStop) + .addGap(18, 18, 18) + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0)) + ); + + jPanel6Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonArgs, buttonConfig, buttonStop}); + + jPanel6Layout.setVerticalGroup( + jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel6Layout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel2) + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonArgs) + .addComponent(buttonConfig) + .addComponent(buttonStop)) + .addGap(0, 0, 0)) + ); + + jPanel6Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {comboCameras, textState}); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Zoom")); + + buttonGroup1.add(buttonZoomFit); + buttonZoomFit.setText("Fit"); + buttonZoomFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomFitActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomStretch); + buttonZoomStretch.setText("Stretch"); + buttonZoomStretch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomStretchActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomNormal); + buttonZoomNormal.setText("Normal"); + buttonZoomNormal.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomNormalActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom025); + buttonZoom025.setText("1/4"); + buttonZoom025.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom025ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom05); + buttonZoom05.setText("1/2"); + buttonZoom05.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom05ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom2); + buttonZoom2.setText("2"); + buttonZoom2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom2ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoomFit) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoomStretch)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoom025) + .addComponent(buttonZoom05) + .addComponent(buttonZoom2)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoom025)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomFit) + .addComponent(buttonZoom05)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomStretch) + .addComponent(buttonZoom2)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Colormap")); + + checkHistogram.setText("Histogram"); + checkHistogram.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkHistogramActionPerformed(evt); + } + }); + + comboColormap.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Type:"); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Range:"); + + buttonGroup3.add(buttonFullRange); + buttonFullRange.setText("Full"); + buttonFullRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonManual); + buttonManual.setText("Manual"); + buttonManual.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonAutomatic); + buttonAutomatic.setText("Automatic"); + buttonAutomatic.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + labelMin.setText("Min:"); + + spinnerMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 65535, 1)); + spinnerMin.setEnabled(false); + spinnerMin.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMin.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + spinnerMax.setModel(new javax.swing.SpinnerNumberModel(255, 0, 65535, 1)); + spinnerMax.setEnabled(false); + spinnerMax.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMax.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + labelMax.setText("Max:"); + + btFixColormapRange.setText("Fix"); + btFixColormapRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btFixColormapRangeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel3) + .addComponent(jLabel4)) + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonAutomatic) + .addComponent(buttonFullRange) + .addComponent(buttonManual) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMax) + .addGap(2, 2, 2) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(checkHistogram, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMin) + .addGap(2, 2, 2) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerMin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btFixColormapRange, spinnerMax, spinnerMin}); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3) + .addComponent(checkHistogram)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonAutomatic) + .addComponent(jLabel4) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(labelMin) + .addComponent(spinnerMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonFullRange)) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonManual) + .addComponent(labelMax) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Source")); + + buttonGroup4.add(buttonServer); + buttonServer.setSelected(true); + buttonServer.setText("Server"); + buttonServer.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonServerActionPerformed(evt); + } + }); + + buttonGroup4.add(buttonDirect); + buttonDirect.setText("Direct"); + buttonDirect.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDirectActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); + jPanel5.setLayout(jPanel5Layout); + jPanel5Layout.setHorizontalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonServer) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonDirect) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel5Layout.setVerticalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonServer) + .addComponent(buttonDirect)) + .addContainerGap()) + ); + + panelScreen.setBorder(javax.swing.BorderFactory.createTitledBorder("Screen")); + + comboScreen.setEnabled(false); + comboScreen.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboScreenActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelScreenLayout = new javax.swing.GroupLayout(panelScreen); + panelScreen.setLayout(panelScreenLayout); + panelScreenLayout.setHorizontalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboScreen, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelScreenLayout.setVerticalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreenLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelScreen1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter")); + + comboFilter.setEnabled(false); + comboFilter.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboFilterActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelScreen1Layout = new javax.swing.GroupLayout(panelScreen1); + panelScreen1.setLayout(panelScreen1Layout); + panelScreen1Layout.setHorizontalGroup( + panelScreen1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreen1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboFilter, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelScreen1Layout.setVerticalGroup( + panelScreen1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen1Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + pauseSelection.setDecimals(0); + + panelScreen2.setBorder(javax.swing.BorderFactory.createTitledBorder("Image")); + + checkThreshold.setText("Threshold"); + checkThreshold.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkThresholdActionPerformed(evt); + } + }); + + spinnerThreshold.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99999.0d, 1.0d)); + spinnerThreshold.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerThresholdonChange(evt); + } + }); + + checkBackground.setText("Subtract Background"); + checkBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkBackgroundActionPerformed(evt); + } + }); + + checkGoodRegion.setText("Good Region"); + checkGoodRegion.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkGoodRegionActionPerformed(evt); + } + }); + + spinnerGrScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 100.0d, 1.0d)); + spinnerGrScale.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerGrScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + spinnerGrThreshold.setModel(new javax.swing.SpinnerNumberModel(0.5d, 0.04d, 1.0d, 0.1d)); + spinnerGrThreshold.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerGrThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + labelGrThreshold.setText("Threshold:"); + + labelGrScale.setText("Scale:"); + + javax.swing.GroupLayout panelScreen2Layout = new javax.swing.GroupLayout(panelScreen2); + panelScreen2.setLayout(panelScreen2Layout); + panelScreen2Layout.setHorizontalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addComponent(checkGoodRegion) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(labelGrScale) + .addGap(2, 2, 2) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(labelGrThreshold) + .addGap(2, 2, 2) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addComponent(checkBackground) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addComponent(checkThreshold) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerGrScale, spinnerGrThreshold, spinnerThreshold}); + + panelScreen2Layout.setVerticalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(checkBackground) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkThreshold) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkGoodRegion) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrScale)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrThreshold)) + .addContainerGap()) + ); + + javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); + jPanel4.setLayout(jPanel4Layout); + jPanel4Layout.setHorizontalGroup( + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel4Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) + .addComponent(panelScreen2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel4Layout.setVerticalGroup( + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel4Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + ); + }// //GEN-END:initComponents + + private void comboCamerasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCamerasActionPerformed + try { + if (!updatingCameraSelection) { + if (!comboCameras.isEnabled()) { + throw new Exception("Invalid state"); + } + comboCameras.setEnabled(false); + buttonServer.setEnabled(false); + buttonDirect.setEnabled(false); + final String cameraName = (String) comboCameras.getSelectedItem(); + new Thread(new Runnable() { + @Override + public void run() { + if (requestCameraListUpdate) { + requestCameraListUpdate = false; + try { + updateCameraList(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + try { + setCamera(cameraName); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateStop(); + comboCameras.setEnabled(true); + buttonServer.setEnabled(true); + buttonDirect.setEnabled(true); + } + } + }).start(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboCamerasActionPerformed + + 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); + editor.setTitle(cameraName); + EditorDialog dlg = editor.getDialog(getTopLevel(), false); + dlg.setSize(480, 640); + dlg.setVisible(true); + SwingUtils.centerComponent(getTopLevel(), dlg); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonArgsActionPerformed + + private void buttonConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConfigActionPerformed + try { + if (camera != null) { + this.showDeviceConfigDialog(camera, false); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonConfigActionPerformed + + private void buttonPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPauseActionPerformed + try { + renderer.removeOverlay(imageBufferOverlay); + if (camera != null) { + synchronized (imageBuffer) { + if (buttonPause.isSelected()) { + renderer.pause(); + } else { + imageBuffer.clear(); + renderer.resume(); + } + pauseSelection.setVisible(buttonPause.isSelected() && (imageBuffer.size() > 1)); + if (pauseSelection.isVisible()) { + renderer.addOverlay(imageBufferOverlay); + pauseSelection.setMaxValue(imageBuffer.size()); + pauseSelection.setValue(imageBuffer.size());; + } + } + updateStreamData(); + } + } catch (Exception ex) { + ex.printStackTrace(); + showException(ex); + } + }//GEN-LAST:event_buttonPauseActionPerformed + + private void buttonMarkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMarkerActionPerformed + try { + checkMarker(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonMarkerActionPerformed + + private void buttonFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFitActionPerformed + try { + showFit = buttonFit.isSelected(); + if (showFit) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(fitOv); + fitOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonFitActionPerformed + + private void buttonReticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReticleActionPerformed + try { + checkReticle(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonReticleActionPerformed + + private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed + try { + saveSnapshot(); + } catch (Exception ex) { + ex.printStackTrace(); + showException(ex); + } + }//GEN-LAST:event_buttonSaveActionPerformed + + private void buttonGrabBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGrabBackgroundActionPerformed + try { + if (camera != null) { + if (SwingUtils.showOption(getTopLevel(), "Background", "Do you want to capture background now?", OptionType.YesNo) == OptionResult.Yes) { + boolean laserOn = getLaserState(); + if (laserOn) { + setLaserState(false); + } + try { + System.out.println("Grabbing background for: " + cameraName); + if (server != null) { + server.captureBackground(5); + } else { + camera.captureBackground(5, 0); + } + } finally { + if (laserOn) { + setLaserState(true); + } + } + SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); + } + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonGrabBackgroundActionPerformed + + private void buttonZoomFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomFitActionPerformed + try { + renderer.setMode(RendererMode.Fit); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomFitActionPerformed + + private void buttonZoomStretchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomStretchActionPerformed + try { + renderer.setMode(RendererMode.Stretch); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomStretchActionPerformed + + private void buttonZoomNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomNormalActionPerformed + try { + renderer.setMode(RendererMode.Fixed); + centralizeRenderer(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomNormalActionPerformed + + private void onChangeColormap(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onChangeColormap + try { + if ((camera != null) && (camera instanceof ColormapSource) && !updatingColormap) { + ColormapSource source = (ColormapSource) camera; + Color colorReticule = new Color(16, 16, 16); + Color colorMarker = new Color(128, 128, 128); + source.getConfig().colormap = (Colormap) comboColormap.getSelectedItem(); + switch (source.getConfig().colormap) { + case Grayscale: + case Inverted: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + case Flame: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + } + + renderer.setPenReticle(new Pen(colorReticule)); + renderer.setPenProfile(new Pen(colorReticule, 0)); + renderer.setPenMarker(new Pen(colorMarker, 2)); + renderer.setShowReticle(false); + checkReticle(); + source.getConfig().colormapAutomatic = buttonAutomatic.isSelected(); + source.getConfig().colormapMin = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMin.getValue(); + source.getConfig().colormapMax = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMax.getValue(); + try { + source.getConfig().save(); + } catch (Exception ex) { + Logger.getLogger(ScreenPanel.class.getName()).log(Level.WARNING, null, ex); + } + source.refresh(); + if (buttonPause.isSelected()) { + updatePause(); + } + updateColormap(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_onChangeColormap + + private void onChangeColormapRange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_onChangeColormapRange + onChangeColormap(null); + }//GEN-LAST:event_onChangeColormapRange + + private void buttonZoom025ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom025ActionPerformed + renderer.setZoom(0.25); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom025ActionPerformed + + private void buttonZoom05ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom05ActionPerformed + renderer.setZoom(0.5); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom05ActionPerformed + + private void buttonServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerActionPerformed + if (!usingServer) { + usingServer = true; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonServerActionPerformed + + private void buttonDirectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDirectActionPerformed + if (usingServer) { + usingServer = false; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonDirectActionPerformed + + private void comboScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboScreenActionPerformed + + comboScreen.setEnabled(false); + new Thread(new Runnable() { + @Override + public void run() { + ChannelInteger setpoint = null; + try { + int index = comboScreen.getSelectedIndex(); + if (cameraName.contains("DSRM")) { + setpoint = new ChannelInteger(null, cameraName + ":POSITION_SP"); + } else { + setpoint = new ChannelInteger(null, cameraName + ":SET_SCREEN1_POS"); + } + setpoint.initialize(); + if (setpoint.read() != index) { + setpoint.write(index); + //Must be threaded to control the laser because of sleep in setLaserState + /* + boolean laserOn = getLaserState(); + if (laserOn) { + setLaserState(false); + } + try { + setpoint.write(index); + } finally { + if (laserOn) { + setLaserState(true); + } + } + */ + } + screen.read(); + } catch (Exception ex) { + showException(ex); + } finally { + comboScreen.setEnabled(true); + if (setpoint != null) { + setpoint.close(); + } + } + } + }).start(); + }//GEN-LAST:event_comboScreenActionPerformed + + private void comboFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboFilterActionPerformed + try { + String setpoint = (String) comboFilter.getSelectedItem(); + if (!setpoint.equals(filter.read())) { + filter.write(setpoint); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboFilterActionPerformed + + private void checkHistogramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkHistogramActionPerformed + try { + setHistogramVisible(checkHistogram.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_checkHistogramActionPerformed + + private void buttonZoom2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom2ActionPerformed + renderer.setZoom(2.0); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom2ActionPerformed + + private void spinnerThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setThreshold((Double) spinnerThreshold.getValue()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_spinnerThresholdonChange + + private void checkBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBackgroundActionPerformed + if (server != null) { + if (!updatingServerControls) { + try { + if (server.isStarted()) { + server.setBackgroundSubtraction(checkBackground.isSelected()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + updatingServerControls = true; + checkBackground.setSelected(false); + updatingServerControls = false; + + } + } + } else { + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + }//GEN-LAST:event_checkBackgroundActionPerformed + + private void checkThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkThresholdActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + spinnerThreshold.setVisible(checkThreshold.isSelected()); + server.setThreshold(checkThreshold.isSelected() ? (Double) spinnerThreshold.getValue() : null); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_checkThresholdActionPerformed + + private void buttonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStopActionPerformed + try { + if (buttonStop.getText().equals("Stop")) { + if ((camera != null) && !camera.isClosed()) { + camera.close(); + } + } else { + if (isCameraStopped()) { + comboCamerasActionPerformed(null); + } + } + } catch (Exception ex) { + showException(ex); + } finally { + updateStop(); + } + }//GEN-LAST:event_buttonStopActionPerformed + + private void buttonProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonProfileActionPerformed + try { + showProfile = buttonProfile.isSelected(); + if (showProfile) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(profileOv); + profileOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonProfileActionPerformed + + private void checkGoodRegionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkGoodRegionActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + spinnerGrScale.setVisible(checkGoodRegion.isSelected()); + labelGrScale.setVisible(spinnerGrScale.isVisible()); + spinnerGrThreshold.setVisible(checkGoodRegion.isSelected()); + labelGrThreshold.setVisible(spinnerGrThreshold.isVisible()); + if (checkGoodRegion.isSelected()) { + server.setGoodRegion(((Number) spinnerGrThreshold.getValue()).doubleValue(), ((Number) spinnerGrScale.getValue()).doubleValue()); + } else { + server.setGoodRegion(null); + } + goodRegion = checkGoodRegion.isSelected(); + } + } catch (Exception ex) { + showException(ex); + ex.printStackTrace(); + updateServerControls(); + } + } + }//GEN-LAST:event_checkGoodRegionActionPerformed + + private void spinnerGrThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerGrThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setGoodRegion((Double) spinnerGrThreshold.getValue(), (Double) spinnerGrScale.getValue()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_spinnerGrThresholdonChange + + private void btFixColormapRangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFixColormapRangeActionPerformed + try { + updatingColormap = true; + ArrayProperties properties = currentFrame.data.getProperties(); + spinnerMax.setValue(properties.max.intValue()); + spinnerMin.setValue(properties.min.intValue()); + buttonManual.setSelected(true); + } catch (Exception ex) { + showException(ex); + } finally { + updatingColormap = false; + onChangeColormap(null); + } + }//GEN-LAST:event_btFixColormapRangeActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btFixColormapRange; + private javax.swing.JButton buttonArgs; + private javax.swing.JRadioButton buttonAutomatic; + private javax.swing.JButton buttonConfig; + private javax.swing.JRadioButton buttonDirect; + private javax.swing.JToggleButton buttonFit; + private javax.swing.JRadioButton buttonFullRange; + private javax.swing.JButton buttonGrabBackground; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.ButtonGroup buttonGroup3; + private javax.swing.ButtonGroup buttonGroup4; + private javax.swing.JRadioButton buttonManual; + private javax.swing.JToggleButton buttonMarker; + private javax.swing.JToggleButton buttonPause; + private javax.swing.JToggleButton buttonProfile; + private javax.swing.JToggleButton buttonReticle; + private javax.swing.JToggleButton buttonSave; + private javax.swing.JRadioButton buttonServer; + private javax.swing.JButton buttonStop; + private javax.swing.JRadioButton buttonZoom025; + private javax.swing.JRadioButton buttonZoom05; + private javax.swing.JRadioButton buttonZoom2; + private javax.swing.JRadioButton buttonZoomFit; + private javax.swing.JRadioButton buttonZoomNormal; + private javax.swing.JRadioButton buttonZoomStretch; + private javax.swing.JCheckBox checkBackground; + private javax.swing.JCheckBox checkGoodRegion; + private javax.swing.JCheckBox checkHistogram; + private javax.swing.JCheckBox checkThreshold; + private javax.swing.JComboBox comboCameras; + private javax.swing.JComboBox comboColormap; + private javax.swing.JComboBox comboFilter; + private javax.swing.JComboBox comboScreen; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JProgressBar jProgressBar1; + private javax.swing.JLabel labelGrScale; + private javax.swing.JLabel labelGrThreshold; + private javax.swing.JLabel labelMax; + private javax.swing.JLabel labelMin; + private javax.swing.JPanel panelScreen; + private javax.swing.JPanel panelScreen1; + private javax.swing.JPanel panelScreen2; + private ch.psi.pshell.swing.ValueSelection pauseSelection; + private ch.psi.pshell.imaging.Renderer renderer; + private javax.swing.JSpinner spinnerGrScale; + private javax.swing.JSpinner spinnerGrThreshold; + private javax.swing.JSpinner spinnerMax; + private javax.swing.JSpinner spinnerMin; + private javax.swing.JSpinner spinnerThreshold; + private javax.swing.JTextField textState; + private ch.psi.pshell.swing.DeviceValuePanel valueFilter; + private ch.psi.pshell.swing.DeviceValuePanel valueScreen; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/ScreenPanel2.form b/plugins/ScreenPanel2.form new file mode 100755 index 0000000..6596174 --- /dev/null +++ b/plugins/ScreenPanel2.form @@ -0,0 +1,1162 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ScreenPanel2.form.txt b/plugins/ScreenPanel2.form.txt new file mode 100644 index 0000000..a3e2931 --- /dev/null +++ b/plugins/ScreenPanel2.form.txt @@ -0,0 +1,1121 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ScreenPanel2.java b/plugins/ScreenPanel2.java new file mode 100644 index 0000000..231bc95 --- /dev/null +++ b/plugins/ScreenPanel2.java @@ -0,0 +1,3621 @@ +/* + * 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; +import javax.swing.DefaultComboBoxModel; +import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.imaging.ImageListener; +import ch.psi.utils.State; +import ch.psi.utils.Chrono; +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.data.DataManager; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.Readable.ReadableArray; +import ch.psi.pshell.device.Readable.ReadableNumber; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterArray; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterNumber; +import ch.psi.pshell.device.ReadonlyRegister; +import ch.psi.pshell.device.ReadonlyRegister.ReadonlyRegisterArray; +import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.epics.DiscretePositioner; +import ch.psi.pshell.epics.Epics; +import ch.psi.pshell.imaging.Colormap; +import ch.psi.pshell.imaging.ColormapSource; +import ch.psi.pshell.imaging.ColormapSource.ColormapSourceConfig; +import ch.psi.pshell.ui.App; +import ch.psi.pshell.imaging.Data; +import ch.psi.pshell.imaging.DimensionDouble; +import ch.psi.pshell.imaging.Histogram; +import ch.psi.pshell.imaging.ImageBuffer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Overlays.Text; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.PointDouble; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.imaging.Source; +import ch.psi.pshell.scripting.InterpreterResult; +import ch.psi.pshell.scripting.ScriptManager; +import ch.psi.pshell.swing.DeviceValueChart; +import ch.psi.pshell.swing.ValueSelection; +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.StandardDialog; +import ch.psi.utils.swing.StandardDialog.StandardDialogListener; +import ch.psi.utils.swing.SwingUtils.OptionResult; +import ch.psi.utils.swing.SwingUtils.OptionType; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.event.ActionEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +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.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.AbstractButton; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.DefaultTableModel; +import org.apache.commons.math3.analysis.function.Gaussian; +import org.apache.commons.math3.fitting.GaussianCurveFitter; +import org.apache.commons.math3.fitting.PolynomialCurveFitter; +import org.apache.commons.math3.fitting.WeightedObservedPoint; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; + +/** + * + */ +public class ScreenPanel2 extends Panel { + + public static final String LASER_TYPE = "Laser"; + public static final String ELECTRONS_TYPE = "Electrons"; + public static final String PHOTONICS_TYPE = "Photonics"; + + final String CAMERA_DEVICE_NAME = "CurrentCamera"; + boolean useServerStats = true; + String userOverlaysConfigFile; + ColormapSource camera; + PipelineServer server; + String cameraName; + int polling = 1000; + Overlay marker = null; + JDialog histogramDialog; + DiscretePositioner screen; + DiscretePositioner filter; + boolean showFit; + boolean showProfile; + Overlay[] userOv; + Overlay[] fitOv; + Overlay[] profileOv; + Overlay errorOverlay; + boolean requestCameraListUpdate; + boolean goodRegion; + boolean slicing; + String serverUrl; + String camServerUrl; + String instanceName; + Overlay titleOv = null; + + Double getServerDouble(String name) { + return (Double) Convert.toDouble(server.getValue(name)); + } + + double[] getServerDoubleArray(String name) { + return (double[]) Convert.toDouble(server.getValue(name)); + } + + Double getServerDouble(String name, StreamValue cache) { + return (Double) Convert.toDouble(cache.__getitem__(name)); + } + + double[] getServerDoubleArray(String name, StreamValue cache) { + return (double[]) Convert.toDouble(cache.__getitem__(name)); + } + + class ImageData { + + ImageData() { + if (server != null) { + cache = server.getStream().take(); + String prefix = goodRegion ? "gr_" : ""; + x_fit_mean = getServerDouble(prefix + "x_fit_mean", cache); + y_fit_mean = getServerDouble(prefix + "y_fit_mean", cache); + x_fit_standard_deviation = getServerDouble(prefix + "x_fit_standard_deviation", cache); + y_fit_standard_deviation = getServerDouble(prefix + "y_fit_standard_deviation", cache); + x_fit_gauss_function = getServerDoubleArray(prefix + "x_fit_gauss_function", cache); + y_fit_gauss_function = getServerDoubleArray(prefix + "y_fit_gauss_function", cache); + x_profile = getServerDoubleArray("x_profile", cache); + y_profile = getServerDoubleArray("y_profile", cache); + x_center_of_mass = getServerDouble("x_center_of_mass", cache); + y_center_of_mass = getServerDouble("y_center_of_mass", cache); + x_rms = getServerDouble("x_rms", cache); + y_rms = getServerDouble("y_rms", cache); + if (goodRegion) { + double[] gX2 = new double[x_profile.length]; + Arrays.fill(gX2, Double.NaN); + try { + double x = getServerDoubleArray("gr_x_axis", cache)[0]; + System.arraycopy(x_fit_gauss_function, 0, gX2, (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageX(x) : x), x_fit_gauss_function.length); + } catch (Exception ex) { + } + x_fit_gauss_function = gX2; + double[] gY2 = new double[y_profile.length]; + Arrays.fill(gY2, Double.NaN); + try { + double y = getServerDoubleArray("gr_y_axis", cache)[0]; + System.arraycopy(y_fit_gauss_function, 0, gY2, (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageY(y) : y), y_fit_gauss_function.length); + } catch (Exception ex) { + } + y_fit_gauss_function = gY2; + if (slicing) { + try { + int slices = getServerDouble("slice_amount").intValue(); + sliceCenters = new PointDouble[slices]; + for (int i = 0; i < slices; i++) { + double x = getServerDouble("slice_" + i + "_center_x"); + double y = getServerDouble("slice_" + i + "_center_y"); + sliceCenters[i] = new PointDouble(x, y); + } + } catch (Exception ex) { + } + } + } + } + } + public Double x_fit_mean; + public Double y_fit_mean; + public Double x_center_of_mass; + public Double x_rms; + public Double x_fit_standard_deviation; + public Double y_fit_standard_deviation; + public Double y_center_of_mass; + public Double y_rms; + public double[] x_profile; + public double[] x_fit_gauss_function; + public double[] y_profile; + public double[] y_fit_gauss_function; + public PointDouble[] sliceCenters; + public StreamValue cache; + } + + class Frame extends ImageData { + + Frame(Data data) { + this.data = data; + } + Data data; + } + + final ArrayList imageBuffer = new ArrayList(); + Frame currentFrame; + int imageBufferLenght = 1; + Text imageBufferOverlay; + + public ScreenPanel2() { + try { + initComponents(); + spinnerThreshold.setVisible(false); + btFixColormapRange.setVisible(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + JComponent editor = spinnerSlOrientation.getEditor(); + if (editor instanceof JSpinner.DefaultEditor) { + ((JSpinner.DefaultEditor) editor).getTextField().setHorizontalAlignment(JTextField.RIGHT); + } + renderer.setPersistenceFile(Paths.get(getContext().getSetup().getContextPath(), "Renderer_Cameras.bin")); + //setPersistedComponents(new Component[]{buttonServer, buttonDirect}); + comboCameras.setEnabled(false); + comboType.setEnabled(false); + + SwingUtils.setEnumCombo(comboColormap, Colormap.class); + if (App.hasArgument("poll")) { + try { + polling = Integer.valueOf(App.getArgumentValue("poll")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("zoom")) { + try { + renderer.setDefaultZoom(Double.valueOf(App.getArgumentValue("zoom"))); + renderer.resetZoom(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("buf")) { + try { + imageBufferLenght = Integer.valueOf(App.getArgumentValue("buf")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("usr_ov")) { + try { + userOverlaysConfigFile = App.getArgumentValue("usr_ov"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("srv_url")) { + serverUrl = App.getArgumentValue("srv_url"); + } + + if (App.hasArgument("cam_srv_url")) { + camServerUrl = App.getArgumentValue("cam_srv_url"); + } + + if (App.hasArgument("calc")) { + useServerStats = false; + } + + renderer.setProfileNormalized(true); + renderer.setShowProfileLimits(false); + + JMenuItem menuCalibrate = new JMenuItem("Calibrate..."); + menuCalibrate.addActionListener((ActionEvent e) -> { + try { + calibrate(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuRendererConfig = new JMenuItem("Renderer Parameters"); + menuRendererConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + this.showDeviceConfigDialog(camera, false); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuCameraConfig = new JMenuItem("Camera Configurarion"); + menuCameraConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + String cameraConfigJson = null; + if (usingServer) { + String cameraServerUrl = (camServerUrl == null) ? server.getUrl().substring(0, server.getUrl().length() - 1) + "8" : camServerUrl; + 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 configEditor = new TextEditor(); + configEditor.setText(cameraConfigJson); + configEditor.setReadOnly(true); + configEditor.setTitle(cameraName); + EditorDialog dlg = configEditor.getDialog(getTopLevel(), false); + dlg.setSize(480, 640); + dlg.setVisible(true); + SwingUtils.centerComponent(getTopLevel(), dlg); + } + } catch (Exception ex) { + showException(ex); + } + }); + + + + JMenuItem menuSetImageBufferSize = new JMenuItem("Set Stack Size..."); + menuSetImageBufferSize.addActionListener((ActionEvent e) -> { + try { + String ret = SwingUtils.getString(getTopLevel(), "Enter size of image buffer: ", String.valueOf(imageBufferLenght)); + if (ret!=null){ + this.setImageBufferSize(Integer.valueOf(ret)); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSaveStack = new JMenuItem("Save Stack"); + menuSaveStack.addActionListener((ActionEvent e) -> { + try { + saveStack(); + } catch (Exception ex) { + showException(ex); + } + }); + + + JMenuItem menuSetROI = new JMenuItem("Set ROI..."); + menuSetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + final Overlays.Rect selection = new Overlays.Rect(renderer.getPenMovingOverlay()); + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + try { + renderer.setShowReticle(false); + Rectangle roi = overlay.isFixed() ? renderer.toImageCoord(overlay.getBounds()) : overlay.getBounds(); + if (server.isRoiEnabled()) { + int[] cur = server.getRoi(); + server.setRoi(new int[]{roi.x + cur[0], roi.y + cur[1], roi.width, roi.height}); + } else { + server.setRoi(new int[]{roi.x, roi.y, roi.width, roi.height}); + } + } 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 (server != null) { + try { + renderer.setShowReticle(false); + server.resetRoi(); + } catch (IOException ex) { + showException(ex); + } + } + }); + + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuRendererConfig); + renderer.getPopupMenu().add(menuCameraConfig); + renderer.getPopupMenu().add(menuSetImageBufferSize); + renderer.getPopupMenu().add(menuSaveStack); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuCalibrate); + renderer.getPopupMenu().add(menuSetROI); + renderer.getPopupMenu().add(menuResetROI); + renderer.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuResetROI.setEnabled(server != null); + menuSetROI.setEnabled(server != null); + menuCalibrate.setVisible(server != null); + menuCalibrate.setEnabled((calibrationDialolg == null) || (!calibrationDialolg.isShowing())); + menuSaveStack.setEnabled(imageBufferLenght > 0); + menuSetImageBufferSize.setEnabled(!renderer.isPaused()); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + renderer.getPopupMenu().setVisible(false); + + showFit = buttonFit.isSelected(); + showProfile = buttonProfile.isSelected(); + + 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())) { + updatePause(); + } + } + }); + imageBufferOverlay = new Text(renderer.getPenErrorText(), "", new Font("Verdana", Font.PLAIN, 12), new Point(-100, 42)); + imageBufferOverlay.setFixed(true); + imageBufferOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + if (MainFrame.isDark()) { + textState.setDisabledTextColor(textState.getForeground()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @Override + public void onStart() { + super.onStart(); + if (App.hasArgument("ct")) { + boolean direct = App.getArgumentValue("ct").equals("0") || App.getArgumentValue("ct").equalsIgnoreCase("false"); + buttonServer.setSelected(!direct); + buttonDirect.setSelected(direct); + } + } + + @Override + public void onStop() { + try { + if (camera != null) { + camera.close(); + camera = null; + server = null; + updateButtons(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + super.onStop(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + comboCameras.setEnabled(false); + comboType.setEnabled(false); + if (App.hasArgument("s")) { + renderer.setDevice((Source) getDevice("image")); + renderer.setAutoScroll(true); + ((Source) getDevice("image")).addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + manageFit(bi, data); + manageUserOverlays(bi, data); + } + + @Override + public void onError(Object o, Exception ex) { + } + } + ); + + } else { + usingServer = buttonServer.isSelected(); + updateCameraList(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + setComboCameraSelection(-1); + setComboTypeSelection(0); + + if (comboCameras.getModel().getSize() > 0) { + try { + if (App.hasArgument("cam")) { + setComboCameraSelection(App.getArgumentValue("cam")); + comboCamerasActionPerformed(null); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + updateButtons(); + startTimer(1000); + } + + boolean isVisible(String camera) { + return ((comboType.getSelectedIndex() == 0) || (getCameraType(camera).equals(comboType.getSelectedItem()))); + } + + DefaultComboBoxModel getCameraList(boolean fromServer) throws Exception { + DefaultComboBoxModel model = new DefaultComboBoxModel(); + if (fromServer) { + try (PipelineServer srv = newServer()) { + srv.initialize(); + List cameras = srv.getCameras(); + Collections.sort(cameras); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + + } else { + ArrayList cameras = (ArrayList) getContext().getClassByName("SfCamera").getMethod("getCameras", new Class[]{}).invoke(null); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + if (App.hasArgument("cam")) { + String camera = App.getArgumentValue("cam"); + if (model.getIndexOf(camera) < 0) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + model.addElement(""); + + return model; + } + + PipelineServer newServer() throws IOException { + if (serverUrl != null) { + System.out.println("Connecting to server: " + serverUrl); + server = new PipelineServer(CAMERA_DEVICE_NAME, serverUrl); + } else { + System.out.println("Connecting to server"); + server = new PipelineServer(CAMERA_DEVICE_NAME); + } + updateButtons(); + return server; + } + + boolean updatingCameraSelection; + + void setComboCameraSelection(Object selection) { + updatingCameraSelection = true; + try { + comboCameras.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + + void setComboTypeSelection(Object selection) { + updatingCameraSelection = true; + try { + comboType.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + boolean usingServer; + + void updateCameraList() { + try { + String selected = (String) comboCameras.getSelectedItem(); + comboCameras.setModel(getCameraList(usingServer)); + if (selected != null) { + if (((DefaultComboBoxModel) comboCameras.getModel()).getIndexOf(camera) < 0) { + setComboCameraSelection(selected); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + } + + final Object lockOverlays = new Object(); + + void manageFit(BufferedImage bi, Data data) { + Overlay[][] fo = null; + if ((showFit || showProfile)) { + try { + fo = getFitOverlays(data); + } catch (Exception ex) { + System.err.println(ex); + } + } + synchronized (lockOverlays) { + fo = (fo == null) ? new Overlay[][]{null, null} : fo; + renderer.updateOverlays(fo[0], profileOv); + profileOv = fo[0]; + renderer.updateOverlays(fo[1], fitOv); + fitOv = fo[1]; + } + } + + void manageUserOverlays(BufferedImage bi, Data data) { + Overlay[] fo = (bi == null) ? null : getUserOverlays(data); + synchronized (lockOverlays) { + renderer.updateOverlays(fo, userOv); + userOv = fo; + } + } + + void manageTitleOverlay() { + Overlay to = null; + if ((buttonTitle.isSelected()) && (cameraName != null)) { + Font font = new Font("Arial", Font.PLAIN, 28); + to = new Text(renderer.getPenErrorText(), cameraName, font, new Point(-SwingUtils.getTextSize(cameraName, renderer.getGraphics().getFontMetrics(font)).width - 14, 26)); + to.setFixed(true); + to.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + } + + synchronized (lockOverlays) { + renderer.updateOverlays(to, titleOv); + titleOv = to; + } + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + Thread devicesInitTask; + + void setCamera(String cameraName) throws IOException, InterruptedException { + System.out.println("Initializing"); + parseUserOverlays(); + errorOverlay = null; + + if (dataTableDialog != null) { + dataTableDialog.dispose(); + dataTableDialog = null; + } + dataTableModel = null; + + if (calibrationDialolg != null) { + calibrationDialolg.dispose(); + calibrationDialolg = null; + } + + boolean was_server = false; + if (camera != null) { + //camera.removeAllListeners(); + was_server = (server != null); + camera.close(); + camera = null; + server = null; + } + updateButtons(); + instanceName = null; + renderer.setDevice(null); + renderer.setShowReticle(false); + renderer.removeOverlays(fitOv); + renderer.removeOverlays(profileOv); + renderer.removeOverlays(userOv); + renderer.clear(); + renderer.resetZoom(); + + boolean changed = !String.valueOf(cameraName).equals(this.cameraName); + this.cameraName = cameraName; + + if (changed || buttonDirect.isSelected()) { + spinnerThreshold.setVisible(false); + checkThreshold.setEnabled(false); + checkGoodRegion.setEnabled(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + } + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + if (changed) { + checkBackground.setEnabled(false); + if ((devicesInitTask != null) && (devicesInitTask.isAlive())) { + devicesInitTask.interrupt(); + } + if (screen != null) { + screen.close(); + screen = null; + } + if (filter != null) { + filter.close(); + filter = null; + } + if (renderer.isPaused()) { + renderer.resume(); + renderer.removeOverlay(imageBufferOverlay); + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + manageTitleOverlay(); + if (App.isDetached()) { + getTopLevel().setTitle(cameraName == null ? "ScreenPanel" : cameraName); + } + if (cameraName == null) { + return; + } + + System.out.println("Setting camera: " + cameraName + " [" + (buttonServer.isSelected() ? "server" : "direct") + "]"); + try { + if (buttonServer.isSelected()) { + camera = newServer(); + camera.getConfig().flipHorizontally = false; + camera.getConfig().flipVertically = false; + camera.getConfig().rotation = 0.0; + camera.getConfig().roiX = 0; + camera.getConfig().roiY = 0; + camera.getConfig().roiWidth = -1; + 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.initialize(); + camera.assertInitialized(); + System.out.println("Camera initialization OK"); + if (server != null) { + //server.start(cameraName, false); + String pipelineName = cameraName + "_sp"; + instanceName = cameraName + "_sp1"; + if (!server.getPipelines().contains(pipelineName)) { + System.out.println("Creating pipeline: " + pipelineName); + HashMap config = new HashMap<>(); + config.put("camera_name", cameraName); + //server.createFromConfig(config, pipelineName); + server.savePipelineConfig(pipelineName, config); + } + server.start(pipelineName, instanceName); + + updateServerControls(); + checkThreshold.setEnabled(true); + checkGoodRegion.setEnabled(true); + } else { + checkThreshold.setSelected(false); + checkGoodRegion.setSelected(false); + if (polling <= 0) { + camera.setMonitored(true); + } else { + camera.setPolling(polling); + } + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + updateButtons(); + camera.getConfig().save(); + renderer.setDevice(camera); + renderer.setAutoScroll(true); + renderer.setMarker(marker); + imageSize = null; + + camera.addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + if (bi != null) { + if ((imageSize == null) || imageSize.width != bi.getWidth() || imageSize.height != bi.getHeight()) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if ((renderer.getMode() == RendererMode.Zoom) || (renderer.getMode() == RendererMode.Fixed)) { + centralizeRenderer(); + } + checkReticle(); + } + }); + imageSize = new Dimension(bi.getWidth(), bi.getHeight()); + } + renderer.setProfileSize(Math.min(bi.getWidth(), bi.getHeight())); + } + //renderer.setCalibration(camera.getCalibration()); + if (!renderer.isPaused()) { + if (data != null) { + synchronized (imageBuffer) { + currentFrame = new Frame(data); + if (imageBufferLenght >= 1) { + imageBuffer.add(currentFrame); + if (imageBuffer.size() > imageBufferLenght) { + imageBuffer.remove(0); + } + } + } + } + manageFit(bi, data); + manageUserOverlays(bi, data); + } + //updateImageData(); + } + + @Override + public void onError(Object o, Exception ex) { + //System.err.println(ex); + } + }); + + } catch (Exception ex) { + showException(ex); + renderer.clearOverlays(); + updateServerControls(); + if (renderer.getDevice() == null) { + //renderer.setZoom(1.0); + //renderer.setMode(RendererMode.Zoom); + errorOverlay = new Text(renderer.getPenErrorText(), ex.toString(), new Font("Verdana", Font.PLAIN, 12), new Point(20, 20)); + errorOverlay.setFixed(true); + errorOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + renderer.addOverlay(errorOverlay); + } + } finally { + //checkReticle(); + onTimer(); + } + onChangeColormap(null); + checkBackground.setEnabled(true); + if (changed) { + boolean electrons = getCameraType(cameraName).equals(ELECTRONS_TYPE); + comboScreen.setModel(new DefaultComboBoxModel()); + comboScreen.setEnabled(false); + comboFilter.setModel(new DefaultComboBoxModel()); + comboFilter.setEnabled(false); + panelFilter.setVisible(electrons); + panelScreen.setVisible(electrons); + if (electrons) { + //Parallelizing initialization + devicesInitTask = new Thread(() -> { + try { + if (cameraName.contains("DSRM")) { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":POSITION_SP", cameraName + ":POSITION"); + } else { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":SET_SCREEN1_POS", cameraName + ":GET_SCREEN1_POS"); + } + screen.setMonitored(true); + screen.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : screen.getPositions()) { + model.addElement(pos); + } + comboScreen.setModel(model); + comboScreen.setSelectedItem(screen.read()); + + } catch (Exception ex) { + comboScreen.setModel(new DefaultComboBoxModel()); + System.err.println(ex.getMessage()); + screen = null; + } + comboScreen.setEnabled(screen != null); + valueScreen.setDevice(screen); + + try { + filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); + filter.setMonitored(true); + filter.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : filter.getPositions()) { + model.addElement(pos); + } + comboFilter.setModel(model); + comboFilter.setSelectedItem(filter.read()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + filter = null; + } + comboFilter.setEnabled(filter != null); + valueFilter.setDevice(filter); + }); + devicesInitTask.start(); + } + } + } + + volatile Dimension imageSize; + + void checkReticle() { + if ((renderer.getDevice() != null) && (camera != null) && (camera.getConfig().isCalibrated()) && buttonReticle.isSelected()) { + //renderer.setCalibration(camera.getCalibration()); + renderer.configureReticle(new Dimension(800, 800), 200); + renderer.setShowReticle(true); + } else { + //renderer.setCalibration(null); + renderer.setShowReticle(false); + } + renderer.refresh(); + } + + void checkMarker() { + if (camera != null) { + if (buttonMarker.isSelected()) { + 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)); + marker.setMovable(true); + marker.setPassive(false); + } else { + marker = null; + } + renderer.setMarker(marker); + } + } + + void updateZoom() { + try { + buttonZoomStretch.setSelected(renderer.getMode() == RendererMode.Stretch); + buttonZoomFit.setSelected(renderer.getMode() == RendererMode.Fit); + if (renderer.getMode() == RendererMode.Fixed) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getMode() == RendererMode.Zoom) { + if (renderer.getZoom() == 1) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getZoom() == 0.5) { + buttonZoom05.setSelected(true); + } else if (renderer.getZoom() == 0.25) { + buttonZoom025.setSelected(true); + } else if (renderer.getZoom() == 2.0) { + buttonZoom2.setSelected(true); + } else { + buttonGroup1.clearSelection(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + boolean updatingColormap; + + void updateColormap() { + updatingColormap = true; + try { + if ((camera != null) && (camera instanceof ColormapSource)) { + ColormapSourceConfig config = ((ColormapSource) camera).getConfig(); + comboColormap.setSelectedItem(config.colormap); + if (config.isDefaultColormap()) { + buttonFullRange.setSelected(true); + } else if (config.colormapAutomatic) { + buttonAutomatic.setSelected(true); + } else { + buttonManual.setSelected(true); + } + btFixColormapRange.setVisible(buttonAutomatic.isSelected()); + + //spinnerMin.setVisible(buttonManual.isSelected()); labelMin.setVisible(spinnerMin.isVisible()); + //spinnerMax.setVisible(buttonManual.isSelected()); labelMax.setVisible(spinnerMax.isVisible()); + spinnerMin.setEnabled(buttonManual.isSelected()); + spinnerMax.setEnabled(buttonManual.isSelected()); + //spinnerMin.setValue(Double.isNaN(config.colormapMin) ? 0 : Math.min(Math.max((int) config.colormapMin, 0), 65535)); + //spinnerMax.setValue(Double.isNaN(config.colormapMax) ? 0 : Math.min(Math.max((int) config.colormapMax, 0), 65535)); + if (!Double.isNaN(config.colormapMin)) { + spinnerMin.setValue(Math.min(Math.max((int) config.colormapMin, 0), 65535)); + } + if (!Double.isNaN(config.colormapMax)) { + spinnerMax.setValue(Math.min(Math.max((int) config.colormapMax, 0), 65535)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatingColormap = false; + } + + boolean updatingServerControls; + + void updateServerControls() { + if (server != null) { + updatingServerControls = true; + try { + checkBackground.setSelected(server.getBackgroundSubtraction()); + Double threshold = (server.getThreshold()); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (server.getGoodRegion()); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + spinnerGrThreshold.setValue(((Number) gr.get("threshold")).doubleValue()); + spinnerGrScale.setValue(((Number) gr.get("gfscale")).doubleValue()); + } + Map slicing = (server.getSlicing()); + checkSlicing.setSelected(slicing != null); + if (slicing != null) { + spinnerSlNumber.setValue(((Number) slicing.get("number_of_slices")).intValue()); + spinnerSlScale.setValue(((Number) slicing.get("scale")).doubleValue()); + spinnerSlOrientation.setValue((String) slicing.get("orientation")); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + goodRegion = checkGoodRegion.isSelected(); + spinnerThreshold.setVisible(checkThreshold.isSelected()); + setGoodRegionOptionsVisible(goodRegion); + slicing = goodRegion && checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + updatingServerControls = false; + } + } + + void setGoodRegionOptionsVisible(boolean visible) { + spinnerGrThreshold.setVisible(visible); + labelGrThreshold.setVisible(visible); + spinnerGrScale.setVisible(visible); + labelGrScale.setVisible(visible); + panelSlicing.setVisible(visible); + } + + void setSlicingOptionsVisible(boolean visible) { + spinnerSlNumber.setVisible(visible); + labelSlNumber.setVisible(visible); + spinnerSlScale.setVisible(visible); + labelSlScale.setVisible(visible); + spinnerSlOrientation.setVisible(visible); + labelSlOrientation.setVisible(visible); + } + + boolean isCameraStopped() { + if ((server != null) && !server.isStarted()) { + return true; + } + return ((camera == null) || camera.isClosed()); + } + + boolean updatingButtons; + + void updateButtons() { + updatingButtons = true; + try { + boolean active = !isCameraStopped();//(camera != null); + buttonSave.setEnabled(active); + buttonGrabBackground.setEnabled(active); + buttonMarker.setEnabled(active); + buttonProfile.setEnabled(active); + buttonFit.setEnabled(active); + buttonReticle.setEnabled(active && camera.getConfig().isCalibrated()); + buttonStreamData.setEnabled(active && (server != null)); + buttonPause.setEnabled(active); + //buttonPause.setIcon(getIcon("Play")); + //buttonPause.setToolTipText("Resume"); + //buttonPause.setIcon(getIcon("Pause")); + //buttonPause.setToolTipText("Pause"); + + if (renderer.isPaused() != buttonPause.isSelected()) { + buttonPause.setSelected(renderer.isPaused()); + buttonPauseActionPerformed(null); + } + if (renderer.getShowReticle() != buttonReticle.isSelected()) { + //buttonReticle.setSelected(renderer.getShowReticle()); + } + if ((renderer.getMarker() == null) && buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + } + buttonSave.setSelected(renderer.isSnapshotDialogVisible()); + + } finally { + updatingButtons = false; + } + } + + @Override + protected void onTimer() { + for (Device dev : new Device[]{screen, filter}) { + if (dev != null) { + dev.request(); + } + } + + textState.setText((camera == null) ? "" : camera.getState().toString()); + if (App.hasArgument("s")) { + try { + ((Source) getDevice("image")).initialize(); + } catch (IOException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } catch (InterruptedException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } + } + if (!renderer.isPaused() && (dataTableDialog != null) && (dataTableDialog.isShowing())) { + updateStreamData(); + } + updateZoom(); + updateColormap(); + updateButtons(); + checkHistogram.setSelected((histogramDialog != null) && (histogramDialog.isShowing())); + } + + Pen penFit = new Pen(new Color(192, 105, 0), 0); + Pen penCross = new Pen(new Color(192, 105, 0), 0); + Pen penSlices = new Pen(Color.CYAN.darker(), 1); + + Frame getCurrentFrame() { + if ((imageBufferLenght > 1) && (renderer.isPaused())) { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + return (index < imageBuffer.size()) ? imageBuffer.get(index) : null; + } + } + return currentFrame; + } + + Frame getFrame(Data data) { + synchronized (imageBuffer) { + for (Frame f : imageBuffer) { + if (f.data == data) { + return f; + } + } + } + return null; + } + + void setImageBufferSize(int size) { + if (renderer.isPaused()) { + throw new RuntimeException("Cannot change buffer size whn paused"); + } + synchronized (imageBuffer) { + imageBufferLenght = size; + imageBuffer.clear(); + } + + } + + Overlay[][] getFitOverlays(Data data) { + Overlays.Polyline hgaussian = null; + Overlays.Polyline vgaussian = null; + Overlays.Polyline hprofile = null; + Overlays.Polyline vprofile = null; + Double xMean = null, xSigma = null, xNorm = null, xCom = null, xRms = null; + Double yMean = null, ySigma = null, yNorm = null, yCom = null, yRms = null; + double[] pX = null, pY = null, gX = null, gY = null; + int height = data.getHeight(); + int width = data.getWidth(); + PointDouble[] sliceCenters = null; + //Double xCom=null, yCom=null; + if (data != null) { + int profileSize = renderer.getProfileSize(); + if ((useServerStats) && (server != null)) { + try { + + ImageData id = getFrame(data); + if (id == null) { + return null; + } + xMean = id.x_fit_mean; + xSigma = id.x_fit_standard_deviation; + yMean = id.y_fit_mean; + ySigma = id.y_fit_standard_deviation; + gX = id.x_fit_gauss_function; + gY = id.y_fit_gauss_function; + pX = id.x_profile; + pY = id.y_profile; + xCom = id.x_center_of_mass; + xRms = id.x_rms; + yCom = id.y_center_of_mass; + yRms = id.y_rms; + sliceCenters = id.sliceCenters; + + profileSize /= 4; + if (pX != null) { + int[] x = Arr.indexesInt(pX.length); + int[] y = new int[pX.length]; + int[] p = new int[pX.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++) { + if (gX != null) { + y[i] = (int) (height - 1 - (((gX[i] - minPlot) / rangePlot) * profileSize)); + } + p[i] = (int) (height - 1 - (((pX[i] - minPlot) / rangePlot) * profileSize)); + } + + if (goodRegion) { + for (int i = 0; i < x.length; i++) { + y[i] = (Double.isNaN(gX[i])) ? 100000 : y[i]; + } + } + + vgaussian = new Overlays.Polyline(penFit, x, y); + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + + if (pY != null) { + int[] y = Arr.indexesInt(pY.length); + int[] x = new int[pY.length]; + int[] p = new int[pY.length]; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pY)); + 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++) { + if (gY != null) { + x[i] = (int) (((gY[i] - minPlot) / rangePlot) * profileSize); + } + p[i] = (int) (((pY[i] - minPlot) / rangePlot) * profileSize); + } + + if (goodRegion) { + for (int i = 0; i < x.length; i++) { + x[i] = (Double.isNaN(gY[i])) ? -1 : x[i]; + } + } + hgaussian = new Overlays.Polyline(penFit, x, y); + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, y); + } + } 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; + } + if (renderer.getCalibration() != null) { + try { + double[] sum = data.integrateVertically(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] x_egu = renderer.getCalibration().getAxisX(sum.length); + double[] comRms = getComRms(sum, x_egu); + xCom = comRms[0]; + xRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + 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) (height - 1 - ((((fit[i] + min) / height - minPlot) / rangePlot) * profileSize)); + } + vgaussian = new Overlays.Polyline(penFit, x, y); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (height - 1 - (((sum[i] / height - minPlot) / rangePlot) * profileSize)); + } + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + try { + double[] sum = data.integrateHorizontally(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] y_egu = renderer.getCalibration().getAxisY(sum.length); + double[] comRms = getComRms(sum, y_egu); + yCom = comRms[0]; + yRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + + if (showFit) { + double[] gaussian = fitGaussian(saux, 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)) { + 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) / width - minPlot) / rangePlot) * profileSize); + } + hgaussian = new Overlays.Polyline(penFit, y, x); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (((sum[i] / width - minPlot) / rangePlot) * profileSize); + } + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, x); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + if (xSigma != null) { + xSigma *= renderer.getCalibration().getScaleX(); + } + if (ySigma != null) { + ySigma *= renderer.getCalibration().getScaleY(); + } + if (xMean != null) { + xMean = data.getX((int) Math.round(xMean)); + } + if (yMean != null) { + yMean = data.getY((int) Math.round(yMean)); + } + } + } + final String units = (renderer.getCalibration() != null) ? "\u00B5m" : "px"; + final String fmt = "%7.1f" + units; + Overlays.Text textCom = null; + Overlay[] pOv = null, fOv = null; + Font fontInfoText = new Font(Font.MONOSPACED, 0, 14); + Point textPosition = new Point(12, 20); + if (showProfile) { + if ((xCom != null) && (yCom != null)) { + String text = String.format("com x: m=" + fmt + " \u03C3=" + fmt + "\ncom y: m=" + fmt + " \u03C3=" + fmt, xCom, xRms, yCom, yRms); + textCom = new Overlays.Text(renderer.getPenProfile(), text, fontInfoText, textPosition); + textCom.setFixed(true); + textCom.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + } + pOv = new Overlay[]{hprofile, vprofile, textCom}; + textPosition = new Point(textPosition.x, textPosition.y + 34); + } + if (showFit) { + Overlays.Crosshairs cross = null; + Overlays.Text textFit = null; + if ((xMean != null) && (yMean != null)) { + String text = String.format("fit x: m=" + fmt + " \u03C3=" + fmt + "\nfit y: m=" + fmt + " \u03C3=" + fmt, xMean, xSigma, yMean, ySigma); + textFit = new Overlays.Text(penFit, text, fontInfoText, textPosition); + textFit.setFixed(true); + textFit.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + Point center = new Point(xMean.intValue(), yMean.intValue()); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().convertToImagePosition(new PointDouble(xMean, yMean)); + xSigma /= renderer.getCalibration().getScaleX(); + ySigma /= renderer.getCalibration().getScaleY(); + } + cross = new Overlays.Crosshairs(penCross, center, new Dimension(Math.abs(2 * xSigma.intValue()), 2 * Math.abs(ySigma.intValue()))); + } + textPosition = new Point(textPosition.x, textPosition.y + 34); + fOv = new Overlay[]{hgaussian, vgaussian, cross, textFit}; + + if (goodRegion) { + try { + double[] x = getServerDoubleArray("gr_x_axis"); + double[] y = getServerDoubleArray("gr_y_axis"); + double x1 = x[0]; + double x2 = x[x.length - 1]; + double y1 = y[0]; + double y2 = y[y.length - 1]; + Overlays.Rect goodRegionOv = new Overlays.Rect(new Pen(penFit.getColor(), 0, Pen.LineStyle.dotted)); + goodRegionOv.setCalibration(renderer.getCalibration()); + goodRegionOv.setAbsolutePosition(new PointDouble(x1, y1)); + goodRegionOv.setAbsoluteSize(new DimensionDouble(x2 - x1, y2 - y1)); + fOv = Arr.append(fOv, goodRegionOv); + + if (slicing) { + if (sliceCenters != null) { + for (PointDouble sliceCenter : sliceCenters) { + Overlays.Crosshairs center = new Overlays.Crosshairs(penSlices); + center.setCalibration(renderer.getCalibration()); + center.setAbsolutePosition(sliceCenter); + center.setSize(new Dimension(10, 10)); + fOv = Arr.append(fOv, center); + } + if (sliceCenters.length > 1) { + double[] fit = fitPolynomial(sliceCenters, 1); + double angle = Math.toDegrees(Math.atan(fit[1])); + Overlays.Text text = new Overlays.Text(penSlices, String.format("slice: \u03B8= %5.1fdeg", angle), fontInfoText, textPosition); + text.setFixed(true); + text.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + fOv = Arr.append(fOv, text); + } + } + } + } catch (Exception ex) { + } + } + + } + return new Overlay[][]{pOv, fOv}; + } + return null; + } + + class UserOverlay { + + String name; + Overlay obj; + String[] channels; + } + ArrayList userOverlayConfig; + + void parseUserOverlays() { + Properties userOverlays = new Properties(); + userOverlayConfig = new ArrayList<>(); + if (userOverlaysConfigFile != null) { + try { + try (FileInputStream in = new FileInputStream(getContext().getSetup().expandPath(userOverlaysConfigFile))) { + userOverlays.load(in); + + for (String name : userOverlays.stringPropertyNames()) { + String val = userOverlays.getProperty(name); + try { + UserOverlay uo = new UserOverlay(); + uo.name = name; + String type = val.substring(0, val.indexOf("(")).trim(); + String pars = val.substring(val.indexOf("(") + 1, val.lastIndexOf(")")).trim(); + String[] tokens = pars.split(","); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + Color color = Color.GRAY; + try { + color = (Color) Color.class.getField(tokens[tokens.length - 1].toUpperCase()).get(null); + } catch (Exception ex) { + } + Pen pen = new Pen(color); + try { + String[] penTokens = tokens[tokens.length - 1].split(":"); + color = (Color) Color.class.getField(penTokens[0].toUpperCase()).get(null); + int width = Integer.valueOf(penTokens[1]); + Pen.LineStyle style = Pen.LineStyle.valueOf(penTokens[2]); + pen = new Pen(color, width, style); + } catch (Exception ex) { + } + switch (type) { + case "Point": + uo.obj = new Overlays.Crosshairs(); + uo.obj.setSize(new Dimension(Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); + break; + case "Line": + uo.obj = new Overlays.Line(); + break; + case "Arrow": + uo.obj = new Overlays.Arrow(); + break; + case "Rect": + uo.obj = new Overlays.Rect(); + break; + case "Ellipse": + uo.obj = new Overlays.Ellipse(); + break; + case "Polyline": + uo.obj = new Overlays.Polyline(); + break; + } + if (type.equals("Polyline") || type.equals("Point")) { + uo.channels = new String[]{tokens[0], tokens[1]}; + } else { + uo.channels = new String[]{tokens[0], tokens[1], tokens[2], tokens[3]}; + } + uo.obj.setPen(pen); + userOverlayConfig.add(uo); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + Overlay[] getUserOverlays(Data data) { + ArrayList ret = new ArrayList<>(); + if (server != null) { + for (UserOverlay uo : userOverlayConfig) { + try { + Overlay ov = uo.obj; + //Overlay ov = (Overlay)uo.cls.newInstance(); + ov.setCalibration(renderer.getCalibration()); + boolean valid = false; + if (ov instanceof Overlays.Polyline) { + double[] x = (uo.channels[0].equals("null")) ? null : getServerDoubleArray(uo.channels[0]); + double[] y = (uo.channels[1].equals("null")) ? null : getServerDoubleArray(uo.channels[1]); + if ((x != null) || (y != null)) { + if (x == null) { + x = (renderer.getCalibration() == null) ? Arr.indexesDouble(y.length) : renderer.getCalibration().getAxisX(y.length); + } + if (y == null) { + y = (renderer.getCalibration() == null) ? Arr.indexesDouble(x.length) : renderer.getCalibration().getAxisY(x.length); + } + ((Overlays.Polyline) ov).updateAbsolute(x, y); + valid = true; + } + } else { + Double x = getServerDouble(uo.channels[0]); + Double y = getServerDouble(uo.channels[1]); + if ((x != null) && (y != null)) { + PointDouble position = new PointDouble(x, y); + ov.setAbsolutePosition(position); + if (!(ov instanceof Overlays.Crosshairs)) { + Double x2 = getServerDouble(uo.channels[2]); + Double y2 = getServerDouble(uo.channels[3]); + if ((x != null) && (y != null)) { + DimensionDouble size = new DimensionDouble(x2 - position.x, y2 - position.y); + ov.setAbsoluteSize(size); + valid = true; + } + } else { + valid = true; + } + } + } + if (valid) { + ret.add(ov); + } + } catch (Exception ex) { + //ex.printStackTrace(); + } + } + } + return ret.toArray(new Overlay[0]); + } + + double[] getComRms(double[] arr, double[] x) { + if (arr != null) { + double xmd = 0; + double xmd2 = 0; + double total = 0; + for (int i = 0; i < arr.length; i++) { + double v = (arr[i] * x[i]); + xmd += v; + xmd2 += (v * x[i]); + total += arr[i]; + } + if (total > 0) { + double com = xmd / total; + double com2 = xmd2 / total; + double rms = Math.sqrt(Math.abs(com2 - com * com)); + return new double[]{com, rms}; + } + } + return new double[]{Double.NaN, Double.NaN}; + } + + double[] fitGaussianScript(int[] y, int[] x) { + ScriptManager sm = Context.getInstance().getScriptManager(); + ArrayProperties pY = ArrayProperties.get(y); + sm.setVar("y", y); + sm.setVar("x", x); + InterpreterResult r = sm.eval("r = fit_gaussians(y, x, [" + pY.maxIndex + ",])"); + if (r.exception != null) { + r.exception.printStackTrace(); + } else { + List ret = (List) sm.getVar("r"); + if ((ret != null) && (ret.size() == 1) && (ret.get(0) instanceof List) && (((List) (ret.get(0))).size() == 3)) { + double norm = (Double) ((List) ret.get(0)).get(0); + double mean = (Double) ((List) ret.get(0)).get(1); + double sigma = (Double) ((List) ret.get(0)).get(2); + return new double[]{norm, mean, sigma}; + } + } + return null; + } + + double[] fitGaussian(double[] y, int[] x) { + try { + ArrayProperties pY = ArrayProperties.get(y); + GaussianCurveFitter fitter = GaussianCurveFitter.create().withStartPoint(new double[]{(pY.max - pY.min) / 2, x[pY.maxIndex], 1.0}).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] fitPolynomial(PointDouble[] points, int order) { + double[] y = new double[points.length]; + double[] x = new double[points.length]; + for (int i = 0; i < points.length; i++) { + x[i] = points[i].x; + y[i] = points[i].y; + } + return fitPolynomial(y, x, order); + } + + double[] fitPolynomial(double[] y, double[] x, int order) { + try { + ArrayProperties pY = ArrayProperties.get(y); + PolynomialCurveFitter fitter = PolynomialCurveFitter.create(order).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] getFitFunction(double[] pars, int[] x) { + double[] fit = new double[x.length]; + Gaussian g = new Gaussian(pars[0], pars[1], pars[2]); + for (int i = 0; i < x.length; i++) { + fit[i] = g.value(x[i]); + } + return fit; + } + + void setHistogramVisible(boolean value) { + if (value) { + if ((histogramDialog == null) || (!histogramDialog.isShowing())) { + Histogram histogram = new Histogram(true); + histogram.setRenderer(renderer); + histogramDialog = SwingUtils.showDialog(SwingUtils.getWindow(renderer), "Histogram", null, histogram); + renderer.refresh(); + } + } else { + if (histogramDialog != null) { + histogramDialog.setVisible(false); + histogramDialog = null; + } + } + } + + void setLaserState(boolean value) throws Exception { + System.out.println("Setting laser state: " + value); + 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 { + return (Epics.get("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", Integer.class) == 0); + } + + void elog(String logbook, String title, String message, String[] attachments) throws Exception { + String domain = ""; + String category = "Info"; + String entry = ""; + StringBuffer cmd = new StringBuffer(); + + cmd.append("G_CS_ELOG_add -l \"").append(logbook).append("\" "); + cmd.append("-a \"Author=ScreenPanel\" "); + cmd.append("-a \"Type=pshell\" "); + cmd.append("-a \"Entry=").append(entry).append("\" "); + 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) { + 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()}); + new Thread(() -> { + try { + process.waitFor(); + int bytes = process.getInputStream().available(); + 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); + System.err.println(new String(arr)); + } catch (Exception ex) { + System.err.println(ex); + } + }).start(); + } + + void centralizeRenderer() { + Point center = null; + Dimension size = renderer.getImageSize(); + 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); + } + 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 (index < imageBuffer.size()) { + Data data = imageBuffer.get(index).data; + BufferedImage image = camera.generateImage(data); + renderer.setImage(renderer.getOrigin(), image, data); + imageBufferOverlay.update(Chrono.getTimeStr(data.getTimestamp(), "HH:mm:ss.SSS")); + manageFit(image, data); + manageUserOverlays(image, data); + } + } + if ((dataTableDialog != null) && (dataTableDialog.isShowing())) { + updateStreamData(); + } + } + + void saveSnapshot() throws Exception { + String snapshotFile = null; + synchronized (imageBuffer) { + Frame frame = getCurrentFrame(); + if (frame == null) { + throw new Exception("No current image"); + } + ArrayList frames = new ArrayList<>(); + frames.add(frame); + this.saveFrames("camera_snapshot", frames); + + //Enforce the same timestamp to data & image files. + snapshotFile = getContext().getExecutionPars().getPath() + ".png"; + ImageBuffer.saveImage(SwingUtils.createImage(renderer), snapshotFile, "png"); + } + + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{0, 180}; //Minimum width + layout.rowHeights = new int[]{30, 30, 30}; //Minimum height + panel.setLayout(layout); + JComboBox comboLogbook = new JComboBox(new String[]{"SwissFEL commissioning data", "SwissFEL commissioning"}); + JTextField textComment = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Data file:"), c); + c.gridy = 1; + panel.add(new JLabel("Logbook:"), c); + c.gridy = 2; + panel.add(new JLabel("Comment:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(textComment, c); + c.gridy = 1; + panel.add(comboLogbook, c); + c.gridy = 0; + panel.add(new JLabel(getContext().getExecutionPars().getPath()), c); + + if (SwingUtils.showOption(getTopLevel(), "Success", panel, OptionType.OkCancel) == OptionResult.Yes) { + StringBuilder message = new StringBuilder(); + message.append("Camera: ").append(cameraName).append(" ("). + append((server != null) ? "server" : "direct").append(")").append("\n"); + message.append("Screen: ").append(String.valueOf(valueScreen.getLabel().getText())).append("\n"); + message.append("Filter: ").append(String.valueOf(valueFilter.getLabel().getText())).append("\n"); + message.append("Data file: ").append(getContext().getExecutionPars().getPath()).append("\n"); + message.append("Comment: ").append(textComment.getText()).append("\n"); + if ((fitOv != null) && (fitOv.length > 5)) { + Overlays.Text text = (Overlays.Text) fitOv[5]; + message.append(text.getText()).append("\n"); + } + elog((String) comboLogbook.getSelectedItem(), "ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); + } + } + + void saveStack() throws Exception { + synchronized (imageBuffer) { + saveFrames("camera_stack", imageBuffer); + } + SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getContext().getExecutionPars().getPath(), 5000); + } + + public static String getCameraType(String name) { + if (name == null) { + return ""; + } + for (String s : new String[]{"LCAM"}) { + if (name.contains(s)) { + return LASER_TYPE; + } + } + for (String s : new String[]{"DSCR", "DSRM", "DLAC"}) { + if (name.contains(s)) { + return ELECTRONS_TYPE; + } + } + for (String s : new String[]{"PROF", "PPRM", "PSSS", "PSCR", "PSRD"}) { + if (name.contains(s)) { + return PHOTONICS_TYPE; + } + } + return "Unknown"; + } + + public Map getProcessingParameters(StreamValue value) throws IOException { + return (Map) JsonSerializer.decode(value.getValue("processing_parameters").toString(), Map.class); + } + + void saveFrames(String name, ArrayList frames) throws IOException { + ArrayList values = new ArrayList<>(); + for (Frame frame : frames) { + values.add(frame.cache); + } + saveImages(name, values); + } + + void saveImages(String name, ArrayList images) throws IOException { + int depth = images.size(); + if (depth == 0) { + return; + } + StreamValue first = images.get(0); + String pathRoot = "/camera1/"; + String pathImage = pathRoot + "image"; + String pathPid = pathRoot + "pulse_id"; + String pathTimestampStr = pathRoot + "timestamp_str"; + Map processingPars = getProcessingParameters(first); + String camera = (String) processingPars.get("camera_name"); + String type = getCameraType(camera); + + int width = ((Number) first.getValue("width")).intValue(); + int height = ((Number) first.getValue("height")).intValue(); + Class dataType = first.getValue("image").getClass().getComponentType(); + + getContext().setExecutionPars(name); + DataManager dm = getContext().getDataManager(); + + //Create tables + dm.createDataset(pathImage, dataType, new int[]{depth, height, width}); + dm.createDataset(pathPid, Long.class, new int[]{depth}); + dm.createDataset(pathTimestampStr, String.class, new int[]{depth}); + for (String id : first.getIdentifiers()) { + Object val = first.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(first); + for (String key : pars.keySet()) { + if ((pars.get(key) != null) && (pars.get(key) instanceof Map)) { + for (Object k : ((Map) pars.get(key)).keySet()) { + Object v = ((Map) pars.get(key)).get(k); + dm.setAttribute(pathImage, key + " " + k, (v == null) ? "" : v); + } + } else { + Object value = pars.get(key); + if (value == null) { + value = ""; + } else if (value instanceof List) { + Class cls = (((List) value).size() > 0) ? ((List) value).get(0).getClass() : double.class; + value = Convert.toPrimitiveArray(value, cls); + //value = Convert.toDouble(value); + } + dm.setAttribute(pathImage, key, value); + } + } + } else if (val.getClass().isArray()) { + dm.createDataset(pathRoot + id, Double.class, new int[]{depth, Array.getLength(val)}); + } else { + dm.createDataset(pathRoot + id, val.getClass(), new int[]{depth}); + } + } + + //Add metadata + dm.setAttribute(pathRoot, "Camera", camera); + dm.setAttribute(pathRoot, "Images", depth); + dm.setAttribute(pathRoot, "Interval", -1); + dm.setAttribute(pathRoot, "Type", type); + if (type.equals(ELECTRONS_TYPE)) { + dm.setAttribute(pathRoot, "Screen", String.valueOf(valueScreen.getLabel().getText())); + dm.setAttribute(pathRoot, "Filter", String.valueOf(valueFilter.getLabel().getText())); + } + + //Save data + for (int index = 0; index < depth; index++) { + StreamValue streamValue = images.get(index); + dm.setItem(pathImage, streamValue.getValue("image"), new long[]{index, 0, 0}, new int[]{1, height, width}); + dm.setItem(pathPid, streamValue.getPulseId(), index); + dm.setItem(pathTimestampStr, Chrono.getTimeStr(streamValue.getTimestamp(), "YYYY-MM-dd HH:mm:ss.SSS"), index); + + for (String id : streamValue.getIdentifiers()) { + Object val = streamValue.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + } else if (val.getClass().isArray()) { + dm.setItem(pathRoot + id, val, index); + } else { + dm.setItem(pathRoot + id, val, index); + } + } + } + getContext().getDataManager().closeOutput(); + } + + StandardDialog calibrationDialolg; + + void calibrate() throws Exception { + if (server != null) { + server.resetRoi(); + calibrationDialolg = (StandardDialog) getContext().getClassByName("CameraCalibrationDialog").getConstructors()[0].newInstance(new Object[]{getTopLevel(), server.getCurrentCamera(), renderer}); + SwingUtils.centerComponent(getTopLevel(), calibrationDialolg); + calibrationDialolg.setVisible(true); + calibrationDialolg.setListener(new StandardDialogListener() { + @Override + public void onWindowOpened(StandardDialog dlg) { + } + + @Override + public void onWindowClosed(StandardDialog dlg, boolean accepted) { + if (accepted) { + //comboCamerasActionPerformed(null); + } + } + }); + } + } + + StandardDialog dataTableDialog; + DefaultTableModel dataTableModel; + + void showStreamData() { + dataTableModel = null; + if (server != null) { + + if ((dataTableDialog != null) && (dataTableDialog.isShowing())) { + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + dataTableDialog.requestFocus(); + return; + } + //String msg = String.join("\n", ids); + //SwingUtils.showMessage(getTopLevel(), "Image Data", msg); + dataTableModel = new DefaultTableModel(new Object[0][2], new String[]{"Name", "Value"}) { + public Class getColumnClass(int columnIndex) { + return String.class; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + }; + updateStreamData(); + StreamValue val = server.getStream().take(); + JTable dataTable = new JTable(dataTableModel); + dataTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + dataTable.setCellSelectionEnabled(true); + dataTable.getTableHeader().setReorderingAllowed(false); + dataTable.getTableHeader().setResizingAllowed(true); + dataTableDialog = new StandardDialog(getTopLevel(), "Image Data", false); + dataTableDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setViewportView(dataTable); + scrollPane.setPreferredSize(new Dimension(300, 400)); + dataTableDialog.setContentPane(scrollPane); + dataTableDialog.pack(); + dataTableDialog.setVisible(true); + dataTableDialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + dataTableModel = null; + } + }); + dataTable.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + try { + int index = dataTable.getSelectedRow(); + dataTable.setToolTipText(null); + if (index>1){ + String id = String.valueOf(dataTable.getModel().getValueAt(index, 0)); + String locator = String.valueOf(dataTable.getModel().getValueAt(0, 1)); + dataTable.setToolTipText(locator+ " " + id); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(new StringSelection(locator+ " " + id), (Clipboard clipboard1, Transferable contents) -> {}); + if ((e.getClickCount() == 2) && (!e.isPopupTrigger())) { + Object obj = getCurrentFrame().cache.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(getCurrentFrame().cache); + StringBuilder sb = new StringBuilder(); + for (String key : pars.keySet()) { + sb.append(key).append(" = ").append(Str.toString(pars.get(key), 10)).append("\n"); + } + SwingUtils.showMessage(dataTableDialog, "Processing Parameters", sb.toString()); + } else if ((obj!=null) && (obj.getClass().isArray() || (obj instanceof Number))) { + DeviceValueChart chart = new DeviceValueChart(); + Device dev = null; + if (obj.getClass().isArray()){ + dev = new ReadableRegisterArray(new ReadableArray() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + @Override + public int getSize() { + return Array.getLength(getCurrentFrame().cache.getValue(id)); + } + }); + } else { + dev = new ReadableRegisterNumber(new ReadableNumber() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + }); + } + dev.setPolling(1000); + chart.setDevice(dev); + JDialog dlg = SwingUtils.showDialog(dataTableDialog, cameraName +" " + id, null, chart); + } + } + } + } catch (Exception ex) { + showException(ex); + } + } + }); + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + } + } + + void updateStreamData() { + if ((dataTableModel != null) && (server != null)) { + StreamValue value = server.getValue(); + + List ids = (value == null) ? new ArrayList<>() : new ArrayList(value.getIdentifiers()); + if (ids.size() + 2 != dataTableModel.getRowCount()) { + dataTableModel.setNumRows(0); + try { + dataTableModel.addRow(new Object[]{"Locator", server.getUrl() + "/" + ((value == null) ? instanceName : server.getCurrentInstance())}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Locator", ex.getMessage()}); + } + try { + dataTableModel.addRow(new Object[]{"Stream", server.getStreamAddress()}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Stream", ex.getMessage()}); + } + Collections.sort(ids); + for (String id : ids) { + dataTableModel.addRow(new Object[]{id, ""}); + } + } + Frame frame = getCurrentFrame(); + if ((frame != null) && (frame.cache!=null)){ + for (int i = 2; i < dataTableModel.getRowCount(); i++) { + String id = String.valueOf(dataTableModel.getValueAt(i, 0)); + //Object obj = server.getValue(id); + Object obj = frame.cache.getValue(id); + if (obj != null) { + if (obj.getClass().isArray()) { + obj = obj.getClass().getComponentType().getSimpleName() + "[" + Array.getLength(obj) + "]"; + } else if (obj instanceof Double) { + obj = Convert.roundDouble((Double) obj, 1); + } else if (obj instanceof Float) { + obj = Convert.roundDouble((Float) obj, 1); + } + } + dataTableModel.setValueAt(String.valueOf(obj), i, 1); + } + } + } + } + + ImageIcon getIcon(String name) { + ImageIcon ret = null; + try { + //Path path = Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(),"resources", name + ".png"); + String dir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "resources/"; + if (new File(dir + name + ".png").exists()) { + ret = new javax.swing.ImageIcon(dir + name + ".png"); + } else { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/" + name + ".png")); + if (MainFrame.isDark()) { + try { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/dark/" + name + ".png")); + } catch (Exception e) { + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return ret; + } + + String getIconName(JButton button) { + String ret = button.getIcon().toString(); + if (ret.indexOf(".") > 0) { + ret = ret.substring(0, ret.indexOf(".")); + } + return ret; + } + + //////// + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + buttonGroup3 = new javax.swing.ButtonGroup(); + buttonGroup4 = new javax.swing.ButtonGroup(); + jProgressBar1 = new javax.swing.JProgressBar(); + sidePanel = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + buttonZoomFit = new javax.swing.JRadioButton(); + buttonZoomStretch = new javax.swing.JRadioButton(); + buttonZoomNormal = new javax.swing.JRadioButton(); + buttonZoom025 = new javax.swing.JRadioButton(); + buttonZoom05 = new javax.swing.JRadioButton(); + buttonZoom2 = new javax.swing.JRadioButton(); + jPanel2 = new javax.swing.JPanel(); + checkHistogram = new javax.swing.JCheckBox(); + comboColormap = new javax.swing.JComboBox(); + jLabel3 = new javax.swing.JLabel(); + jLabel4 = new javax.swing.JLabel(); + buttonFullRange = new javax.swing.JRadioButton(); + buttonManual = new javax.swing.JRadioButton(); + buttonAutomatic = new javax.swing.JRadioButton(); + labelMin = new javax.swing.JLabel(); + spinnerMin = new javax.swing.JSpinner(); + spinnerMax = new javax.swing.JSpinner(); + labelMax = new javax.swing.JLabel(); + btFixColormapRange = new javax.swing.JButton(); + jPanel5 = new javax.swing.JPanel(); + buttonServer = new javax.swing.JRadioButton(); + buttonDirect = new javax.swing.JRadioButton(); + textState = new javax.swing.JTextField(); + filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767)); + panelScreen = new javax.swing.JPanel(); + valueScreen = new ch.psi.pshell.swing.DeviceValuePanel(); + comboScreen = new javax.swing.JComboBox(); + panelFilter = new javax.swing.JPanel(); + valueFilter = new ch.psi.pshell.swing.DeviceValuePanel(); + comboFilter = new javax.swing.JComboBox(); + panelScreen2 = new javax.swing.JPanel(); + checkThreshold = new javax.swing.JCheckBox(); + spinnerThreshold = new javax.swing.JSpinner(); + checkBackground = new javax.swing.JCheckBox(); + checkGoodRegion = new javax.swing.JCheckBox(); + spinnerGrScale = new javax.swing.JSpinner(); + spinnerGrThreshold = new javax.swing.JSpinner(); + labelGrThreshold = new javax.swing.JLabel(); + labelGrScale = new javax.swing.JLabel(); + panelSlicing = new javax.swing.JPanel(); + checkSlicing = new javax.swing.JCheckBox(); + labelSlScale = new javax.swing.JLabel(); + spinnerSlScale = new javax.swing.JSpinner(); + labelSlNumber = new javax.swing.JLabel(); + spinnerSlNumber = new javax.swing.JSpinner(); + labelSlOrientation = new javax.swing.JLabel(); + spinnerSlOrientation = new javax.swing.JSpinner(); + topPanel = new javax.swing.JPanel(); + toolBar = new javax.swing.JToolBar(); + buttonSidePanel = new javax.swing.JToggleButton(); + buttonStreamData = new javax.swing.JButton(); + buttonSave = new javax.swing.JToggleButton(); + buttonGrabBackground = new javax.swing.JButton(); + buttonPause = new javax.swing.JToggleButton(); + jSeparator6 = new javax.swing.JToolBar.Separator(); + buttonMarker = new javax.swing.JToggleButton(); + buttonProfile = new javax.swing.JToggleButton(); + buttonFit = new javax.swing.JToggleButton(); + buttonReticle = new javax.swing.JToggleButton(); + buttonTitle = new javax.swing.JToggleButton(); + pauseSelection = new ch.psi.pshell.swing.ValueSelection(); + panelCameraSelection = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + comboCameras = new javax.swing.JComboBox(); + jLabel5 = new javax.swing.JLabel(); + comboType = new javax.swing.JComboBox(); + renderer = new ch.psi.pshell.imaging.Renderer(); + + setPreferredSize(new java.awt.Dimension(873, 600)); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Zoom")); + + buttonGroup1.add(buttonZoomFit); + buttonZoomFit.setText("Fit"); + buttonZoomFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomFitActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomStretch); + buttonZoomStretch.setText("Stretch"); + buttonZoomStretch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomStretchActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomNormal); + buttonZoomNormal.setText("Normal"); + buttonZoomNormal.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomNormalActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom025); + buttonZoom025.setText("1/4"); + buttonZoom025.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom025ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom05); + buttonZoom05.setText("1/2"); + buttonZoom05.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom05ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom2); + buttonZoom2.setText("2"); + buttonZoom2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom2ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoomFit) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoomStretch)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoom025) + .addComponent(buttonZoom05) + .addComponent(buttonZoom2)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoom025)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomFit) + .addComponent(buttonZoom05)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomStretch) + .addComponent(buttonZoom2)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Colormap")); + + checkHistogram.setText("Histogram"); + checkHistogram.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkHistogramActionPerformed(evt); + } + }); + + comboColormap.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Type:"); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Range:"); + + buttonGroup3.add(buttonFullRange); + buttonFullRange.setText("Full"); + buttonFullRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonManual); + buttonManual.setText("Manual"); + buttonManual.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonAutomatic); + buttonAutomatic.setText("Automatic"); + buttonAutomatic.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + labelMin.setText("Min:"); + + spinnerMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 65535, 1)); + spinnerMin.setEnabled(false); + spinnerMin.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMin.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + spinnerMax.setModel(new javax.swing.SpinnerNumberModel(255, 0, 65535, 1)); + spinnerMax.setEnabled(false); + spinnerMax.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMax.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + labelMax.setText("Max:"); + + btFixColormapRange.setText("Fix"); + btFixColormapRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btFixColormapRangeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel3) + .addComponent(jLabel4)) + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonAutomatic) + .addComponent(buttonFullRange) + .addComponent(buttonManual) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMax) + .addGap(2, 2, 2) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(checkHistogram, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMin) + .addGap(2, 2, 2) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerMin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btFixColormapRange, spinnerMax, spinnerMin}); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3) + .addComponent(checkHistogram)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonAutomatic) + .addComponent(jLabel4) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(labelMin) + .addComponent(spinnerMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonFullRange)) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonManual) + .addComponent(labelMax) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Source")); + + buttonGroup4.add(buttonServer); + buttonServer.setSelected(true); + buttonServer.setText("Server"); + buttonServer.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonServerActionPerformed(evt); + } + }); + + buttonGroup4.add(buttonDirect); + buttonDirect.setText("Direct"); + buttonDirect.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDirectActionPerformed(evt); + } + }); + + textState.setEditable(false); + textState.setHorizontalAlignment(javax.swing.JTextField.CENTER); + textState.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + textState.setEnabled(false); + + javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); + jPanel5.setLayout(jPanel5Layout); + jPanel5Layout.setHorizontalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonServer) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonDirect) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(56, 56, 56)) + ); + jPanel5Layout.setVerticalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonServer) + .addComponent(buttonDirect) + .addGroup(jPanel5Layout.createSequentialGroup() + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + panelScreen.setBorder(javax.swing.BorderFactory.createTitledBorder("Screen")); + + comboScreen.setEnabled(false); + comboScreen.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboScreenActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelScreenLayout = new javax.swing.GroupLayout(panelScreen); + panelScreen.setLayout(panelScreenLayout); + panelScreenLayout.setHorizontalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboScreen, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelScreenLayout.setVerticalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreenLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter")); + + comboFilter.setEnabled(false); + comboFilter.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboFilterActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelFilterLayout = new javax.swing.GroupLayout(panelFilter); + panelFilter.setLayout(panelFilterLayout); + panelFilterLayout.setHorizontalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelFilterLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboFilter, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelFilterLayout.setVerticalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelFilterLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelScreen2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pipeline")); + + checkThreshold.setText("Threshold"); + checkThreshold.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkThresholdActionPerformed(evt); + } + }); + + spinnerThreshold.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99999.0d, 1.0d)); + spinnerThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerThresholdonChange(evt); + } + }); + + checkBackground.setText("Subtract Background"); + checkBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkBackgroundActionPerformed(evt); + } + }); + + checkGoodRegion.setText("Good Region"); + checkGoodRegion.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkGoodRegionActionPerformed(evt); + } + }); + + spinnerGrScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerGrScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + spinnerGrThreshold.setModel(new javax.swing.SpinnerNumberModel(0.5d, 0.04d, 1.0d, 0.1d)); + spinnerGrThreshold.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerGrThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + labelGrThreshold.setText("Threshold:"); + + labelGrScale.setText("Scale:"); + + checkSlicing.setText("Slicing"); + checkSlicing.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkSlicingActionPerformed(evt); + } + }); + + labelSlScale.setText("Scale:"); + + spinnerSlScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerSlScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlNumber.setText("Slices:"); + + spinnerSlNumber.setModel(new javax.swing.SpinnerNumberModel(2, 0, 1000, 1)); + spinnerSlNumber.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlNumber.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlOrientation.setText("Orientation:"); + + spinnerSlOrientation.setModel(new javax.swing.SpinnerListModel(new String[] {"vertical", "horizontal"})); + spinnerSlOrientation.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlOrientation.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + javax.swing.GroupLayout panelSlicingLayout = new javax.swing.GroupLayout(panelSlicing); + panelSlicing.setLayout(panelSlicingLayout); + panelSlicingLayout.setHorizontalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addComponent(checkSlicing) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlNumber) + .addGap(2, 2, 2) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlScale) + .addGap(2, 2, 2) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(labelSlOrientation) + .addGap(2, 2, 2) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + panelSlicingLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerSlNumber, spinnerSlOrientation, spinnerSlScale}); + + panelSlicingLayout.setVerticalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkSlicing) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlNumber)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlScale)))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlOrientation))) + ); + + javax.swing.GroupLayout panelScreen2Layout = new javax.swing.GroupLayout(panelScreen2); + panelScreen2.setLayout(panelScreen2Layout); + panelScreen2Layout.setHorizontalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addComponent(checkThreshold) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addComponent(checkGoodRegion) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(labelGrScale)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(labelGrThreshold))) + .addGap(2, 2, 2))) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + .addComponent(panelSlicing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addGap(6, 6, 6) + .addComponent(checkBackground) + .addGap(106, 106, 106)) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerGrScale, spinnerGrThreshold, spinnerThreshold}); + + panelScreen2Layout.setVerticalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(checkBackground) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkThreshold) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkGoodRegion) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrScale)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrThreshold)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelSlicing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + javax.swing.GroupLayout sidePanelLayout = new javax.swing.GroupLayout(sidePanel); + sidePanel.setLayout(sidePanelLayout); + sidePanelLayout.setHorizontalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + sidePanelLayout.setVerticalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + toolBar.setFloatable(false); + toolBar.setRollover(true); + + buttonSidePanel.setIcon(getIcon("List")); + buttonSidePanel.setSelected(true); + buttonSidePanel.setText(" "); + buttonSidePanel.setToolTipText("Show Side Panel"); + buttonSidePanel.setFocusable(false); + buttonSidePanel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSidePanel.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSidePanelActionPerformed(evt); + } + }); + toolBar.add(buttonSidePanel); + + buttonStreamData.setIcon(getIcon("Details")); + buttonStreamData.setText(" "); + buttonStreamData.setToolTipText("Show Data Window"); + buttonStreamData.setFocusable(false); + buttonStreamData.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonStreamData.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStreamDataActionPerformed(evt); + } + }); + toolBar.add(buttonStreamData); + + buttonSave.setIcon(getIcon("Save")); + buttonSave.setText(" "); + buttonSave.setToolTipText("Save Snapshot"); + buttonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSaveActionPerformed(evt); + } + }); + toolBar.add(buttonSave); + + buttonGrabBackground.setIcon(getIcon("Background")); + buttonGrabBackground.setText(" "); + buttonGrabBackground.setToolTipText("Grab Background"); + buttonGrabBackground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonGrabBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonGrabBackgroundActionPerformed(evt); + } + }); + toolBar.add(buttonGrabBackground); + + buttonPause.setIcon(getIcon("Pause")); + buttonPause.setText(" "); + buttonPause.setToolTipText("Pause"); + buttonPause.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonPause.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonPauseActionPerformed(evt); + } + }); + toolBar.add(buttonPause); + + jSeparator6.setMaximumSize(new java.awt.Dimension(20, 32767)); + jSeparator6.setPreferredSize(new java.awt.Dimension(20, 0)); + jSeparator6.setRequestFocusEnabled(false); + toolBar.add(jSeparator6); + + buttonMarker.setIcon(getIcon("Marker")); + buttonMarker.setText(" "); + buttonMarker.setToolTipText("Show Marker"); + buttonMarker.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonMarker.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMarkerActionPerformed(evt); + } + }); + toolBar.add(buttonMarker); + + buttonProfile.setIcon(getIcon("Profile" + + "")); + buttonProfile.setSelected(true); + buttonProfile.setText(" "); + buttonProfile.setToolTipText("Show Image Profile"); + buttonProfile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonProfile.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonProfileActionPerformed(evt); + } + }); + toolBar.add(buttonProfile); + + buttonFit.setIcon(getIcon("Fit")); + buttonFit.setSelected(true); + buttonFit.setText(" "); + buttonFit.setToolTipText("Show Fit"); + buttonFit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFitActionPerformed(evt); + } + }); + toolBar.add(buttonFit); + + buttonReticle.setIcon(getIcon("Reticule")); + buttonReticle.setSelected(true); + buttonReticle.setText(" "); + buttonReticle.setToolTipText("Show Reticle"); + buttonReticle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonReticle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonReticleActionPerformed(evt); + } + }); + toolBar.add(buttonReticle); + + buttonTitle.setIcon(getIcon("Title")); + buttonTitle.setText(" "); + buttonTitle.setToolTipText("Show Camera Name"); + buttonTitle.setFocusable(false); + buttonTitle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonTitle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonTitleActionPerformed(evt); + } + }); + toolBar.add(buttonTitle); + + pauseSelection.setDecimals(0); + + jLabel1.setText("Camera:"); + + comboCameras.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboCameras.setMaximumRowCount(30); + comboCameras.setMinimumSize(new java.awt.Dimension(127, 27)); + comboCameras.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboCamerasActionPerformed(evt); + } + }); + + jLabel5.setText("Type:"); + + comboType.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboType.setMaximumRowCount(30); + comboType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Laser", "Electrons", "Photonics" })); + comboType.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboTypeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelCameraSelectionLayout = new javax.swing.GroupLayout(panelCameraSelection); + panelCameraSelection.setLayout(panelCameraSelectionLayout); + panelCameraSelectionLayout.setHorizontalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addGap(0, 0, 0) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0)) + ); + panelCameraSelectionLayout.setVerticalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel5) + .addComponent(jLabel1) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0)) + ); + + javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel); + topPanel.setLayout(topPanelLayout); + topPanelLayout.setHorizontalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, topPanelLayout.createSequentialGroup() + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(18, 18, 18) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + topPanelLayout.setVerticalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(topPanelLayout.createSequentialGroup() + .addGap(1, 1, 1) + .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addComponent(sidePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(sidePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE))) + ); + }// //GEN-END:initComponents + + private void buttonZoomFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomFitActionPerformed + try { + renderer.setMode(RendererMode.Fit); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomFitActionPerformed + + private void buttonZoomStretchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomStretchActionPerformed + try { + renderer.setMode(RendererMode.Stretch); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomStretchActionPerformed + + private void buttonZoomNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomNormalActionPerformed + try { + renderer.setMode(RendererMode.Fixed); + centralizeRenderer(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomNormalActionPerformed + + private void onChangeColormap(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onChangeColormap + try { + if ((camera != null) && (camera instanceof ColormapSource) && !updatingColormap) { + ColormapSource source = (ColormapSource) camera; + Color colorReticule = new Color(16, 16, 16); + Color colorMarker = new Color(128, 128, 128); + source.getConfig().colormap = (Colormap) comboColormap.getSelectedItem(); + switch (source.getConfig().colormap) { + case Grayscale: + case Inverted: + case Red: + case Green: + case Blue: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + case Flame: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + } + + renderer.setPenReticle(new Pen(colorReticule)); + renderer.setPenProfile(new Pen(colorReticule, 0)); + renderer.setPenMarker(new Pen(colorMarker, 2)); + renderer.setShowReticle(false); + checkReticle(); + source.getConfig().colormapAutomatic = buttonAutomatic.isSelected(); + source.getConfig().colormapMin = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMin.getValue(); + source.getConfig().colormapMax = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMax.getValue(); + try { + source.getConfig().save(); + } catch (Exception ex) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex); + } + source.refresh(); + if (buttonPause.isSelected()) { + updatePause(); + } + updateColormap(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_onChangeColormap + + private void onChangeColormapRange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_onChangeColormapRange + onChangeColormap(null); + }//GEN-LAST:event_onChangeColormapRange + + private void buttonZoom025ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom025ActionPerformed + renderer.setZoom(0.25); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom025ActionPerformed + + private void buttonZoom05ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom05ActionPerformed + renderer.setZoom(0.5); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom05ActionPerformed + + private void buttonServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerActionPerformed + if (!usingServer) { + usingServer = true; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonServerActionPerformed + + private void buttonDirectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDirectActionPerformed + if (usingServer) { + usingServer = false; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonDirectActionPerformed + + private void comboScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboScreenActionPerformed + + comboScreen.setEnabled(false); + new Thread(new Runnable() { + @Override + public void run() { + ChannelInteger setpoint = null; + try { + int index = comboScreen.getSelectedIndex(); + if (cameraName.contains("DSRM")) { + setpoint = new ChannelInteger(null, cameraName + ":POSITION_SP"); + } else { + setpoint = new ChannelInteger(null, cameraName + ":SET_SCREEN1_POS"); + } + setpoint.initialize(); + if (setpoint.read() != index) { + setpoint.write(index); + //Must be threaded to control the laser because of sleep in setLaserState + /* + boolean laserOn = getLaserState(); + if (laserOn) { + setLaserState(false); + } + try { + setpoint.write(index); + } finally { + if (laserOn) { + setLaserState(true); + } + } + */ + } + screen.read(); + } catch (Exception ex) { + showException(ex); + } finally { + comboScreen.setEnabled(true); + if (setpoint != null) { + setpoint.close(); + } + } + } + }).start(); + }//GEN-LAST:event_comboScreenActionPerformed + + private void comboFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboFilterActionPerformed + try { + String setpoint = (String) comboFilter.getSelectedItem(); + if (!setpoint.equals(filter.read())) { + filter.write(setpoint); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboFilterActionPerformed + + private void checkHistogramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkHistogramActionPerformed + try { + setHistogramVisible(checkHistogram.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_checkHistogramActionPerformed + + private void buttonZoom2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom2ActionPerformed + renderer.setZoom(2.0); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom2ActionPerformed + + private void spinnerThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setThreshold((Double) spinnerThreshold.getValue()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_spinnerThresholdonChange + + private void checkBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBackgroundActionPerformed + if (server != null) { + if (!updatingServerControls) { + try { + if (server.isStarted()) { + server.setBackgroundSubtraction(checkBackground.isSelected()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + updatingServerControls = true; + checkBackground.setSelected(false); + updatingServerControls = false; + + } + } + } else { + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + }//GEN-LAST:event_checkBackgroundActionPerformed + + private void checkThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkThresholdActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + spinnerThreshold.setVisible(checkThreshold.isSelected()); + server.setThreshold(checkThreshold.isSelected() ? (Double) spinnerThreshold.getValue() : null); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_checkThresholdActionPerformed + + private void checkGoodRegionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkGoodRegionActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + goodRegion = checkGoodRegion.isSelected(); + setGoodRegionOptionsVisible(goodRegion); + if (goodRegion) { + server.setGoodRegion(((Number) spinnerGrThreshold.getValue()).doubleValue(), ((Number) spinnerGrScale.getValue()).doubleValue()); + } else { + server.setGoodRegion(null); + } + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_checkGoodRegionActionPerformed + + private void spinnerGrThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerGrThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setGoodRegion((Double) spinnerGrThreshold.getValue(), (Double) spinnerGrScale.getValue()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_spinnerGrThresholdonChange + + private void btFixColormapRangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFixColormapRangeActionPerformed + try { + updatingColormap = true; + ArrayProperties properties = currentFrame.data.getProperties(); + spinnerMax.setValue(properties.max.intValue()); + spinnerMin.setValue(properties.min.intValue()); + buttonManual.setSelected(true); + } catch (Exception ex) { + showException(ex); + } finally { + updatingColormap = false; + onChangeColormap(null); + } + }//GEN-LAST:event_btFixColormapRangeActionPerformed + + private void checkSlicingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSlicingActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + slicing = checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + if (slicing) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } else { + server.setSlicing(null); + } + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_checkSlicingActionPerformed + + private void spinnerSlicingChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerSlicingChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } + } catch (Exception ex) { + showException(ex); + updateServerControls(); + } + } + }//GEN-LAST:event_spinnerSlicingChange + + private void buttonReticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReticleActionPerformed + try { + checkReticle(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonReticleActionPerformed + + private void buttonFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFitActionPerformed + try { + showFit = buttonFit.isSelected(); + if (showFit) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(fitOv); + fitOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonFitActionPerformed + + private void buttonProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonProfileActionPerformed + try { + showProfile = buttonProfile.isSelected(); + if (showProfile) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(profileOv); + profileOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonProfileActionPerformed + + private void buttonMarkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMarkerActionPerformed + try { + checkMarker(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonMarkerActionPerformed + + private void buttonPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPauseActionPerformed + try { + if (!updatingButtons){ + renderer.removeOverlay(imageBufferOverlay); + if (camera != null) { + boolean pause = !renderer.isPaused(); + synchronized (imageBuffer) { + if (pause) { + renderer.pause(); + } else { + imageBuffer.clear(); + renderer.resume(); + } + + if (pause && (imageBuffer.size() > 1)) { + panelCameraSelection.setVisible(false); + pauseSelection.setVisible(true); + renderer.addOverlay(imageBufferOverlay); + pauseSelection.setMaxValue(imageBuffer.size()); + pauseSelection.setValue(imageBuffer.size());; + updatePause(); + } else { + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + updateStreamData(); + } + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonPauseActionPerformed + + private void buttonGrabBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGrabBackgroundActionPerformed + try { + if (camera != null) { + boolean laserOn = getLaserState(); + OptionResult ret = null; + if (laserOn) { + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to put laser on delay for capturing background?", OptionType.YesNoCancel); + if (ret == OptionResult.No) { + laserOn = false; + } + } else { + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to capture background now?", OptionType.OkCancel); + } + + if (ret == OptionResult.Cancel) { + return; + } + + if (laserOn) { + setLaserState(false); + } + try { + System.out.println("Grabbing background for: " + cameraName); + if (server != null) { + server.captureBackground(5); + } else { + camera.captureBackground(5, 0); + } + } finally { + if (laserOn) { + setLaserState(true); + } + } + SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonGrabBackgroundActionPerformed + + private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed + try { + saveSnapshot(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonSaveActionPerformed + + private void buttonStreamDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStreamDataActionPerformed + try { + showStreamData(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonStreamDataActionPerformed + + private void buttonSidePanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSidePanelActionPerformed + sidePanel.setVisible(buttonSidePanel.isSelected()); + }//GEN-LAST:event_buttonSidePanelActionPerformed + + private void comboTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTypeActionPerformed + try { + updateCameraList(); + if ((cameraName != null) && (!cameraName.equals(comboCameras.getSelectedItem()))) { + setCamera(null); + } else { + setCamera(cameraName); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + }//GEN-LAST:event_comboTypeActionPerformed + + private void comboCamerasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCamerasActionPerformed + try { + if (!updatingCameraSelection) { + if (!comboCameras.isEnabled()) { + throw new Exception("Invalid state"); + } + comboCameras.setEnabled(false); + comboType.setEnabled(false); + buttonServer.setEnabled(false); + buttonDirect.setEnabled(false); + final String cameraName = (String) comboCameras.getSelectedItem(); + new Thread(new Runnable() { + @Override + public void run() { + if (requestCameraListUpdate) { + requestCameraListUpdate = false; + try { + updateCameraList(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + try { + setCamera(cameraName.trim().isEmpty() ? null : cameraName); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + buttonServer.setEnabled(true); + buttonDirect.setEnabled(true); + } + } + }).start(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboCamerasActionPerformed + + private void buttonTitleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTitleActionPerformed + try { + manageTitleOverlay(); + } catch (Exception ex) { + showException(ex); + } finally { + } + }//GEN-LAST:event_buttonTitleActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btFixColormapRange; + private javax.swing.JRadioButton buttonAutomatic; + private javax.swing.JRadioButton buttonDirect; + private javax.swing.JToggleButton buttonFit; + private javax.swing.JRadioButton buttonFullRange; + private javax.swing.JButton buttonGrabBackground; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.ButtonGroup buttonGroup3; + private javax.swing.ButtonGroup buttonGroup4; + private javax.swing.JRadioButton buttonManual; + private javax.swing.JToggleButton buttonMarker; + private javax.swing.JToggleButton buttonPause; + private javax.swing.JToggleButton buttonProfile; + private javax.swing.JToggleButton buttonReticle; + private javax.swing.JToggleButton buttonSave; + private javax.swing.JRadioButton buttonServer; + private javax.swing.JToggleButton buttonSidePanel; + private javax.swing.JButton buttonStreamData; + private javax.swing.JToggleButton buttonTitle; + private javax.swing.JRadioButton buttonZoom025; + private javax.swing.JRadioButton buttonZoom05; + private javax.swing.JRadioButton buttonZoom2; + private javax.swing.JRadioButton buttonZoomFit; + private javax.swing.JRadioButton buttonZoomNormal; + private javax.swing.JRadioButton buttonZoomStretch; + private javax.swing.JCheckBox checkBackground; + private javax.swing.JCheckBox checkGoodRegion; + private javax.swing.JCheckBox checkHistogram; + private javax.swing.JCheckBox checkSlicing; + private javax.swing.JCheckBox checkThreshold; + private javax.swing.JComboBox comboCameras; + private javax.swing.JComboBox comboColormap; + private javax.swing.JComboBox comboFilter; + private javax.swing.JComboBox comboScreen; + private javax.swing.JComboBox comboType; + private javax.swing.Box.Filler filler1; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel5; + private javax.swing.JProgressBar jProgressBar1; + private javax.swing.JToolBar.Separator jSeparator6; + private javax.swing.JLabel labelGrScale; + private javax.swing.JLabel labelGrThreshold; + private javax.swing.JLabel labelMax; + private javax.swing.JLabel labelMin; + private javax.swing.JLabel labelSlNumber; + private javax.swing.JLabel labelSlOrientation; + private javax.swing.JLabel labelSlScale; + private javax.swing.JPanel panelCameraSelection; + private javax.swing.JPanel panelFilter; + private javax.swing.JPanel panelScreen; + private javax.swing.JPanel panelScreen2; + private javax.swing.JPanel panelSlicing; + private ch.psi.pshell.swing.ValueSelection pauseSelection; + private ch.psi.pshell.imaging.Renderer renderer; + private javax.swing.JPanel sidePanel; + private javax.swing.JSpinner spinnerGrScale; + private javax.swing.JSpinner spinnerGrThreshold; + private javax.swing.JSpinner spinnerMax; + private javax.swing.JSpinner spinnerMin; + private javax.swing.JSpinner spinnerSlNumber; + private javax.swing.JSpinner spinnerSlOrientation; + private javax.swing.JSpinner spinnerSlScale; + private javax.swing.JSpinner spinnerThreshold; + private javax.swing.JTextField textState; + private javax.swing.JToolBar toolBar; + private javax.swing.JPanel topPanel; + private ch.psi.pshell.swing.DeviceValuePanel valueFilter; + private ch.psi.pshell.swing.DeviceValuePanel valueScreen; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Sender.java b/plugins/Sender.java new file mode 100755 index 0000000..aec625c --- /dev/null +++ b/plugins/Sender.java @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ +package ch.psi.pshell.data; + +import ch.psi.bsread.DataChannel; +import ch.psi.bsread.Utils; +import ch.psi.bsread.common.allocator.ByteBufferAllocator; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import ch.psi.bsread.common.helper.ByteBufferHelper; +import ch.psi.bsread.compression.Compression; +import ch.psi.bsread.converter.ByteConverter; +import ch.psi.bsread.converter.MatlabByteConverter; +import ch.psi.bsread.message.ChannelConfig; +import ch.psi.bsread.message.DataHeader; +import ch.psi.bsread.message.MainHeader; +import ch.psi.bsread.message.Timestamp; +import ch.psi.bsread.message.Type; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Array; +import java.util.HashMap; +import java.util.Map; +import java.util.function.IntFunction; + +public class Sender { + + final MainHeader mainHeader; + + final Compression dataHeaderCompression; + final ByteConverter byteConverter; + final ObjectMapper objectMapper; + final IntFunction compressedValueAllocator; + final IntFunction valueAllocator; + + private byte[] dataHeaderBytes; + private String dataHeaderMD5 = ""; + + private List> channels = new ArrayList<>(); + + public Sender(ObjectMapper objectMapper) { + this(objectMapper, Compression.none); + } + + public Sender(ObjectMapper objectMapper,Compression dataHeaderCompression) { + this(objectMapper, dataHeaderCompression, new MatlabByteConverter(), ByteBufferAllocator.DEFAULT_ALLOCATOR, ByteBufferAllocator.DEFAULT_ALLOCATOR); + } + + public Sender(ObjectMapper objectMapper, Compression dataHeaderCompression, ByteConverter byteConverter, IntFunction compressedValueAllocator, IntFunction valueAllocator) { + this.dataHeaderCompression = dataHeaderCompression; + this.byteConverter = byteConverter; + this.objectMapper = objectMapper; + this.compressedValueAllocator = compressedValueAllocator; + this.valueAllocator = valueAllocator; + mainHeader = new MainHeader(); + } + + int autoPulseId; + public String encode() throws JsonProcessingException { + long nanos = System.nanoTime(); + return encode(autoPulseId++, new Timestamp((long)(nanos/1e9), (long)(nanos%1e9))); + } + + public String encode(long pulseId, Timestamp globalTimestamp) throws JsonProcessingException { + DataChannel channel; + ByteOrder byteOrder; + + mainHeader.setPulseId(pulseId); + mainHeader.setGlobalTimestamp(globalTimestamp); + mainHeader.setHash(dataHeaderMD5); + mainHeader.setDataHeaderCompression(dataHeaderCompression); + + try { + Map ret = new HashMap(); + ret.put("header", objectMapper.writeValueAsString(mainHeader)); + ret.put("data_header", new String(dataHeaderBytes)); + + for (int i = 0; i < channels.size(); ++i) { + channel = channels.get(i); + byteOrder = channel.getConfig().getByteOrder(); + final Object value = channel.getValue(pulseId); + + ByteBuffer valueBuffer = byteConverter.getBytes(value, channel.getConfig().getType(), byteOrder, valueAllocator); + valueBuffer = channel + .getConfig() + .getCompression() + .getCompressor() + .compressData(valueBuffer, valueBuffer.position(), valueBuffer.remaining(), 0, + compressedValueAllocator, channel.getConfig().getType().getBytes()); +System.out.println((new String(valueBuffer.array())).length()); +System.out.println(channel.getConfig().getName() + ": " + new String(valueBuffer.array())); + ret.put(channel.getConfig().getName(), new String(valueBuffer.array())); + + Timestamp timestamp = channel.getTime(pulseId); + ByteBuffer timeBuffer = byteConverter.getBytes(timestamp.getAsLongArray(), Type.Int64, byteOrder, valueAllocator); + ret.put(channel.getConfig().getName() + "_timestamp", new String(timeBuffer.array())); + } + return objectMapper.writeValueAsString(ret); + } catch (Exception e) { + throw new IllegalStateException("Unable to serialize message", e); + } + } + + /** + * (Re)Generate the data header based on the configured data channels + */ + private void generateDataHeader() { + DataHeader dataHeader = new DataHeader(); + + for (DataChannel channel : channels) { + dataHeader.addChannel(channel.getConfig()); + } + + try { + dataHeaderBytes = objectMapper.writeValueAsBytes(dataHeader); + if (!Compression.none.equals(dataHeaderCompression)) { + ByteBuffer tmpBuf = dataHeaderCompression.getCompressor().compressDataHeader(ByteBuffer.wrap(dataHeaderBytes), + compressedValueAllocator); + dataHeaderBytes = ByteBufferHelper.copyToByteArray(tmpBuf); + } + // decided to compute hash from the bytes that are send to Receivers + // (allows to check consistency without uncompressing the bytes at + // receivers side) + dataHeaderMD5 = Utils.computeMD5(dataHeaderBytes); + } catch (JsonProcessingException e) { + throw new RuntimeException("Unable to generate data header", e); + } + } + + public void addChannel(DataChannel channel) { + channels.add(channel); + generateDataHeader(); + } + + public void removeChannel(DataChannel channel) { + channels.remove(channel); + generateDataHeader(); + } + + + public DataChannel addConstant(String name, Object data){ + return addConstant(name, data, Compression.none); + } + + public DataChannel addConstant(String name, Object data, boolean unsigned){ + return addConstant(name, data, unsigned, Compression.none); + } + + public DataChannel addConstant(String name, Object data, Compression compression){ + return addConstant(name, data, false, Compression.none); + } + + public DataChannel addConstant(String name, Object data, boolean unsigned, Compression compression){ + DataChannel channel = null; + Class cls = data.getClass(); + Type type = classToType(cls, unsigned); + int[] shape = {1}; + if (cls.isArray()){ + shape = new int[] {Array.getLength(data)}; + } + + channel = new DataChannel(new ChannelConfig(name, type, shape, 1, 0, ChannelConfig.DEFAULT_ENCODING, compression)) { + @Override + public Object getValue(long pulseId) { + return data; + } + }; + + addChannel(channel); + return channel; + } + + public static Type classToType(Class cls, boolean unsigned){ + if ((cls == Double.class) ||(cls == double[].class)){ + return Type.Float64; + } + if ((cls == Float.class) ||(cls == float[].class)){ + return Type.Float32; + } + if ((cls == Byte.class) ||(cls == byte[].class)){ + return Type.Int8; + } + if ((cls == Short.class) ||(cls == short[].class)){ + return unsigned ? Type.UInt8 : Type.Int16; + } + if ((cls == Integer.class) ||(cls == int[].class)){ + return unsigned ? Type.UInt16 : Type.Int32; + } + if ((cls == Long.class) ||(cls == long[].class)){ + return unsigned ? Type.UInt32 : Type.Int64; + } + if ((cls == String.class) ||(cls == String[].class)){ + return Type.String; + } + if ((cls == Boolean.class) ||(cls == Boolean[].class)){ + return Type.Bool; + } + throw new IllegalArgumentException("Invalid class: " + cls); + } + + /** + * Returns the currently configured data channels as an unmodifiable list + * + * @return Unmodifiable list of data channels + */ + public List> getChannels() { + return Collections.unmodifiableList(channels); + } + + public static void main(String[] args) throws Exception { + + ByteConverter byteConverter = new MatlabByteConverter(); + + + Sender sender = new Sender(new ObjectMapper(),Compression.none); + + // Register data sources ... + sender.addConstant("Double", 10.0); + /* + sender.addConstant("Float", 10.0f); + sender.addConstant("Byte", (byte)-10); + sender.addConstant("Short", (short)-10); + sender.addConstant("Int", (int)-10); + sender.addConstant("Long", (long)-10); + sender.addConstant("UByte", (short)-10, true); + sender.addConstant("UShort", (int)-10, true); + sender.addConstant("UInt", (long)-10, true); + sender.addConstant("Bool", true); + sender.addConstant("String", "Test"); + sender.addConstant("Double Arr", new double[]{10.0, 20.0, 30.0}, Compression.bitshuffle_lz4); + sender.addConstant("Byte Arr", new byte[]{10, 20, 30}, Compression.bitshuffle_lz4); + */ + + /*sender.addChannel(new DataChannel(new ChannelConfig("ABC", Type.Float64, 1, 0)) { + @Override + public Double getValue(long pulseId) { + return (double) 10.0; + } + }); + */ + //sender.addConstant("Double Arr", new double[3]); + + String json = sender.encode(); + System.out.println(json.length()); + System.out.println(json); + + + + ObjectMapper mapper = new ObjectMapper(); + Map message = mapper.readValue(json, Map.class); + MainHeader mainHeader = mapper.readValue((String)message.get("header"), MainHeader.class); + System.out.println(mainHeader); + DataHeader dataHeader = mapper.readValue(((String)message.get("data_header")).getBytes(),DataHeader.class); + System.out.println(dataHeader); + + + for (ChannelConfig channelConfig : dataHeader.getChannels()) { + ChannelConfig timestampConfig = new ChannelConfig(); + timestampConfig.setType(Type.Int64); + timestampConfig.setShape(new int[]{2}); + timestampConfig.setByteOrder(channelConfig.getByteOrder()); + ByteBuffer timestampBuffer = ByteBuffer.wrap(((String)message.get(channelConfig.getName()+"_timestamp")).getBytes()); + long[] timestampArr = byteConverter.getValue(mainHeader, dataHeader, timestampConfig, timestampBuffer, mainHeader.getGlobalTimestamp()); + Timestamp timestamp = new Timestamp(timestampArr[0], timestampArr[1]); + System.out.println(timestamp); + + ByteBuffer valueBuffer = ByteBuffer.wrap(((String)message.get(channelConfig.getName())).getBytes()); + Object data = byteConverter.getValue(mainHeader, dataHeader, channelConfig, valueBuffer, timestamp); + System.out.println(data); + } + + + } +} diff --git a/plugins/SfCamera.java b/plugins/SfCamera.java new file mode 100755 index 0000000..b019fa6 --- /dev/null +++ b/plugins/SfCamera.java @@ -0,0 +1,237 @@ + +import ch.psi.pshell.core.JsonSerializer; +import ch.psi.pshell.epics.PsiCamera; +import ch.psi.utils.IO; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.logging.Level; +import javax.swing.DefaultComboBoxModel; + +public class SfCamera extends PsiCamera{ + + static String configFolder = "/afs/psi.ch/intranet/SF/Applications/config/camtool_n"; + + public static String getConfigFolder() { + return configFolder; + } + + public static void setConfigFolder(String value) { + configFolder = value; + } + + public static ArrayList getCameras() { + ArrayList ret = new ArrayList<>(); + File[] cameraConfigFiles = new File[0]; + cameraConfigFiles = IO.listFiles(configFolder, new String[]{"json"}); + Arrays.sort(cameraConfigFiles, (a, b) -> a.compareTo(b)); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (File file : cameraConfigFiles) { + String prefix = IO.getPrefix(file); + if (!prefix.startsWith("#") && !prefix.endsWith("_parameters")) { + ret.add(prefix); + } + } + return ret; + } + + public static class CameraConfig { + + public HashMap camera; + + public HashMap getCalibration() { + return (HashMap) camera.get("calibration"); + } + + public ArrayList getCalibrationRefMarker() { + return (ArrayList) getCalibration().get("reference_marker"); + } + + public double getCalOffsetX() { + ArrayList calibration = getCalibrationRefMarker(); + double ret = -(calibration.get(0) + calibration.get(2)) / 2; + return ret; + } + + public double getCalOffsetY() { + ArrayList calibration = getCalibrationRefMarker(); + double ret = -(calibration.get(1) + calibration.get(3)) / 2; + return ret; + } + + public double getScaleX() { + ArrayList calibration = getCalibrationRefMarker(); + double width = Math.abs(calibration.get(2) - calibration.get(0)); + return getCalibrationWidth() / width; + } + + public double getScaleY() { + ArrayList calibration = getCalibrationRefMarker(); + double height = Math.abs(calibration.get(3) - calibration.get(1)); + return getCalibrationHeight() / height; + } + + public Double getCalibrationHeight() { + Double ret = (Double) getCalibration().get("reference_marker_height"); + return (ret == null) ? 100.0 : ret; + } + + public Double getCalibrationWidth() { + Double ret = (Double) getCalibration().get("reference_marker_width"); + return (ret == null) ? 100.0 : ret; + } + + public Double getCalibrationHorizontalAngle() { + return (Double) getCalibration().get("horizontal_camera_angle"); + } + + public Double getCalibrationVerticalAngle() { + return (Double) getCalibration().get("vertical_camera_angle"); + } + + public boolean getMirrorX() { + Boolean ret = (Boolean) camera.get("mirror_x"); + return (ret == null) ? false : ret; + } + + public boolean getMirrorY() { + Boolean ret = (Boolean) camera.get("mirror_y"); + return (ret == null) ? false : ret; + } + + public int getRotate() { + Integer ret = (Integer) camera.get("rotate"); + return (ret == null) ? 0 : ret; + } + + public ArrayList getRoi() { + return (ArrayList) camera.get("roi"); + } + + public Boolean getRoiEnable() { + if ((camera.get("roi_enable") == null) || (camera.get("roi") == null)) { + return false; + } + return (Boolean) camera.get("roi_enable"); + } + } + + public static class CameraPars { + + public HashMap parameter; + + public Boolean getBackgroundSubtraction() { + if (parameter.get("background_subtration") == null){ + return false; + } + return (Boolean) parameter.get("background_subtration"); + } + + public ArrayList getRoi() { + return (ArrayList) parameter.get("region_of_interest"); + } + + public Boolean getRoiEnable() { + ArrayList roi = getRoi(); + return ((roi != null) && (roi.size()>=4)); + } + + public HashMap getGoodRegion() { + return (HashMap) parameter.get("good_region"); + } + + public Double getThresholde() { + return (Double) parameter.get("threshold"); + } + + + } + + + CameraConfig setup; + String json; + public final String prefix; + + public SfCamera(String name, String prefix) { + super(name, prefix); + this.prefix = prefix; + } + + public String getJson(){ + return json; + } + + public CameraConfig getSetup(){ + return setup; + } + + @Override + protected void doInitialize() throws IOException, InterruptedException{ + super.doInitialize(); + Path configFile = Paths.get(configFolder, prefix + ".json"); + if (!configFile.toFile().exists()) { + throw new IOException("Cannot open camera config file: " + configFile.toFile()); + } + json = new String(Files.readAllBytes(configFile)); + setup = (CameraConfig) JsonSerializer.decode(json, CameraConfig.class); + + CameraPars cameraPars = null; + getConfig().roiX = 0; getConfig().roiY = 0; + getConfig().roiWidth = -1; getConfig().roiHeight =-1; + + try{ + Path parsFile = Paths.get(configFolder, prefix + "_parameters.json"); + if (parsFile.toFile().exists()){ + String cameraParsJson = new String(Files.readAllBytes(parsFile)); + cameraPars = (CameraPars) JsonSerializer.decode(cameraParsJson, CameraPars.class); + if (cameraPars.getRoiEnable()){ + getConfig().roiX = cameraPars.getRoi().get(0); + getConfig().roiY = cameraPars.getRoi().get(2); + getConfig().roiWidth = cameraPars.getRoi().get(1); + getConfig().roiHeight = cameraPars.getRoi().get(3); + } + + } + } catch (Exception ex){ + getLogger().log(Level.WARNING, null, ex); + } + + getConfig().flipHorizontally = setup.getMirrorX(); + getConfig().flipVertically = setup.getMirrorY(); + //getConfig().rotation = config.getRotate(); + //getConfig().rotationCrop = true; + switch (setup.getRotate()) { + case 1: + getConfig().rotation = 270; + break; + case 2: + getConfig().rotation = 180; + break; + case 3: + getConfig().rotation = 90; + break; + } + getConfig().rotationCrop = false; + try { + getConfig().spatialCalOffsetX = setup.getCalOffsetX(); + getConfig().spatialCalOffsetY = setup.getCalOffsetY(); + } catch (Exception ex) { + getConfig().spatialCalOffsetX = 0.0; + getConfig().spatialCalOffsetY = 0.0; + } + try { + getConfig().spatialCalScaleX = -setup.getScaleX(); + getConfig().spatialCalScaleY = -setup.getScaleY(); + } catch (Exception ex) { + getConfig().spatialCalScaleX = 1.0; + getConfig().spatialCalScaleY = 1.0; + } + getConfig().save(); + } + +} diff --git a/plugins/TestLdap.java b/plugins/TestLdap.java new file mode 100755 index 0000000..64acf4c --- /dev/null +++ b/plugins/TestLdap.java @@ -0,0 +1,34 @@ + +import java.util.Hashtable; +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; + +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + + +public class TestLdap { + private static void getUserInfo(String userName) throws NamingException{ + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, "ldap://d.psi.ch"); + + DirContext ctx = new InitialDirContext(env); + Attributes attrs = ctx.getAttributes("cn="+userName+",ou=users,ou=psi,dc=d,dc=psi,dc=ch"); + if(attrs == null){ + System.out.println("nothing found for " + userName); + }else{ + System.out.println( attrs.get("sn").get().toString()); + System.out.println( attrs.get("mail").get().toString()); + } + } + + public static void main(String[] args) throws Exception { + getUserInfo("gobbo_a"); + + } +} diff --git a/plugins/TestPlot.form b/plugins/TestPlot.form new file mode 100755 index 0000000..1d0c0c3 --- /dev/null +++ b/plugins/TestPlot.form @@ -0,0 +1,84 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/TestPlot.java b/plugins/TestPlot.java new file mode 100755 index 0000000..180bddb --- /dev/null +++ b/plugins/TestPlot.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2014-2017 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.Plot; +import ch.psi.pshell.scan.Scan; +import ch.psi.pshell.scan.ScanListener; +import ch.psi.pshell.scan.ScanRecord; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.Arr; +import ch.psi.utils.ArrayProperties; +import ch.psi.utils.Convert; +import ch.psi.utils.State; +import java.awt.Color; +import java.util.ArrayList; + +/** + * + */ +public class TestPlot extends Panel { + + LinePlotSeries series = new LinePlotSeries("Values"); + public TestPlot() { + initComponents(); + plot.addSeries(series); + plot.getAxis(Plot.AxisId.X).setLabel("sample"); + plot.getAxis(Plot.AxisId.Y).setLabel("value"); + + + } + + @Override + public void onStart() { + super.onStart(); + getContext().addScanListener(scanListener); + } + + @Override + public void onStop() { + getContext().removeScanListener(scanListener); + super.onStop(); + + } + + + + + ScanListener scanListener = new ScanListener() { + @Override + public void onScanStarted(Scan scan, String plotTitle) { + if (getScriptName().equals(getContext().getExecutionPars().getName())){ + plot.removeMarker(null); + series.clear(); + } + } + + @Override + public void onNewRecord(Scan scan, ScanRecord record) { + if (getScriptName().equals(getContext().getExecutionPars().getName())){ + series.appendData((Double)record.getPositions()[0], (Double)record.getValues()[0]); + } + } + + @Override + public void onScanEnded(Scan scan, Exception ex) { + } + }; + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + String getScriptName(){ + return "TestPlot"; + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jButton1 = new javax.swing.JButton(); + panelPlot = new javax.swing.JPanel(); + plot = new ch.psi.pshell.plot.LinePlotJFree(); + spinner = new javax.swing.JSpinner(); + + jButton1.setText("jButton1"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + panelPlot.setLayout(new java.awt.BorderLayout()); + + plot.setTitle(""); + panelPlot.add(plot, java.awt.BorderLayout.CENTER); + + spinner.setModel(new javax.swing.SpinnerNumberModel(0.0d, null, 10.0d, 1.0d)); + spinner.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerStateChanged(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(15, 15, 15) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinner)) + .addGap(18, 18, 18) + .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(panelPlot, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGap(68, 68, 68) + .addComponent(jButton1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(86, 86, 86))) + .addGap(0, 0, 0)) + ); + }// //GEN-END:initComponents + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + try { + ArrayList args = new ArrayList(); + + spinner.setValue(0.0); + runAsync(getScriptName(), args).handle((ret, ex) -> { + if (ex != null) { + ex.printStackTrace(); + } else { + spinner.setValue(ret); + } + return ret; + }); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_jButton1ActionPerformed + + private void spinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerStateChanged + try { + plot.removeMarker(null); + plot.addMarker((Double)spinner.getValue(), Plot.AxisId.X, "Selection",Color.BLUE); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_spinnerStateChanged + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JPanel panelPlot; + private ch.psi.pshell.plot.LinePlotJFree plot; + private javax.swing.JSpinner spinner; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/TestScan.form b/plugins/TestScan.form new file mode 100755 index 0000000..1eca698 --- /dev/null +++ b/plugins/TestScan.form @@ -0,0 +1,133 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/TestScan.java b/plugins/TestScan.java new file mode 100755 index 0000000..70ab360 --- /dev/null +++ b/plugins/TestScan.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2014-2017 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + */ +public class TestScan extends Panel { + + public TestScan() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + spinnerStart = new javax.swing.JSpinner(); + jLabel2 = new javax.swing.JLabel(); + spinnerEnd = new javax.swing.JSpinner(); + jLabel3 = new javax.swing.JLabel(); + spinnerSteps = new javax.swing.JSpinner(); + buttonStart = new javax.swing.JButton(); + buttonAbort = new javax.swing.JButton(); + + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel1.setText("Start:"); + + spinnerStart.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 100.0d, 1.0d)); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("End:"); + + spinnerEnd.setModel(new javax.swing.SpinnerNumberModel(10.0d, 0.0d, 100.0d, 1.0d)); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Steps:"); + + spinnerSteps.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1)); + + buttonStart.setText("Start"); + buttonStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStartActionPerformed(evt); + } + }); + + buttonAbort.setText("Abort"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerSteps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(338, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonAbort)) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonStart))) + .addGap(47, 47, 47)))) + ); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3}); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerEnd, spinnerStart, spinnerSteps}); + + layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonAbort, buttonStart}); + + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(spinnerStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonStart)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(spinnerEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonAbort)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(spinnerSteps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(29, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + try { + abort(); + } catch (InterruptedException ex) { + Logger.getLogger(TestScan.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_buttonAbortActionPerformed + + private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed + try { + java.util.ArrayList pars = new java.util.ArrayList(); + pars.add(spinnerStart.getValue()); + pars.add(spinnerEnd.getValue()); + pars.add(spinnerSteps.getValue()); + runAsync("TestScan", pars); + } catch (Exception ex) { + Logger.getLogger(TestScan.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_buttonStartActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonStart; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JSpinner spinnerEnd; + private javax.swing.JSpinner spinnerStart; + private javax.swing.JSpinner spinnerSteps; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/XPSSpectrum.form b/plugins/XPSSpectrum.form new file mode 100755 index 0000000..01713ab --- /dev/null +++ b/plugins/XPSSpectrum.form @@ -0,0 +1,396 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/XPSSpectrum.java b/plugins/XPSSpectrum.java new file mode 100755 index 0000000..6390e71 --- /dev/null +++ b/plugins/XPSSpectrum.java @@ -0,0 +1,653 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.core.Context; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.DeviceAdapter; +import ch.psi.pshell.device.DeviceListener; +import ch.psi.pshell.epics.Scienta; +import ch.psi.pshell.plot.LinePlotSeries; +import ch.psi.pshell.plot.RangeSelectionPlot.RangeSelection; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.IO; +import ch.psi.utils.State; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.pshell.core.JsonSerializer; +import ch.psi.utils.Convert; +import java.awt.Component; +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; +import javax.swing.JFileChooser; +import javax.swing.SwingUtilities; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.table.DefaultTableModel; + +/** + * + */ +public class XPSSpectrum extends Panel { + + boolean detailedScan; + boolean running; + Scienta scienta; + + public XPSSpectrum() { + initComponents(); + buttonSkip.setVisible(false); + rangeSelectionPanel.setAditionalColumns(new String[]{"Time", "Size", "Iter"}, new Class[]{Double.class, Double.class, Integer.class}); + final DefaultTableModel model = (DefaultTableModel) rangeSelectionPanel.getTable().getModel(); + model.addTableModelListener(new TableModelListener() { + @Override + public void tableChanged(TableModelEvent e) { + if (e.getType() == TableModelEvent.INSERT) { + final int row = e.getFirstRow(); + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + if (row > 0) { + for (int col = 3; col < 6; col++) { + model.setValueAt(model.getValueAt(row - 1, col), row, col); + } + } else { + model.setValueAt(valueTime.getValue(), row, 3); + model.setValueAt(valueSize.getValue(), row, 4); + model.setValueAt((int)valueIterations.getValue(), row, 5); + } + } + }); + } + } + }); + setPersistedComponents(new Component[]{valueLow, valueHigh, valueTime, valueSize, valueIterations,comboPass, txt, sp, ck }); + } + + @Override + public void onInitialize(int runCount) { + scienta = (Scienta) getDevice("scienta"); + scienta.getTotalChannels().addListener(progressListener); + scienta.getCurrentChannel().addListener(progressListener); + } + + @Override + public void onStateChange(State state, State former) { + setEnabled(state == State.Ready); + if (!state.isProcessing()){ + buttonSkip.setVisible(false); + if (running){ + stopTimer(); + running = false; + getView().getStatusBar().setProgress(-1); + } + } + } + + @Override + public void onExecutedFile(String fileName, Object result) { + String script = IO.getPrefix(fileName); + if (script != null) { + switch (script) { + case "XPSSpectrum": + if (result instanceof Exception) { + //SwingUtils.showMessage(getComponent(), "Error in " + fileName, exception.getMessage()); + } else { + if (detailedScan) { + + } else { + Object[] ret = (Object[]) ((Object[]) result)[0]; + if (ret.length > 0) { + //double[] data = (double[]) Convert.wrapperArrayToPrimitiveArray(ret[0], Double.class); + double[] xdata = (double[]) ret[0]; + double[] ydata = (double[]) ret[1]; + + //double[] data = new double[]{1.0,1.0,1.0,1.0,1.0}; + LinePlotSeries series = new LinePlotSeries("Data"); + rangeSelectionPanel.setSeries(series); + series.setData(xdata, ydata); + } + } + } + break; + } + } + detailedScan = false; + updateButtons(); + } + + @Override + public void setEnabled(boolean value) { + super.setEnabled(value); + rangeSelectionPanel.setEnabled(value); + valueLow.setEnabled(value); + valueHigh.setEnabled(value); + valueTime.setEnabled(value); + valueSize.setEnabled(value); + valueIterations.setEnabled(value); + comboPass.setEnabled(value); + updateButtons(); + } + + void updateButtons() { + buttonInitialScan.setEnabled(isEnabled()); + buttonDetailedScan.setEnabled(isEnabled() && rangeSelectionPanel.getPlot().getSelectedRanges().length > 0); + btLoad.setEnabled(isEnabled()); + btSave.setEnabled(buttonDetailedScan.isEnabled()); + } + + DeviceListener progressListener = new DeviceAdapter() { + + @Override + public void onValueChanged(Device device, Object o, Object o1) { + if (running){ + getView().getStatusBar().setProgress(scienta.getProgress()); + } + } + }; + public final String CURRERNT_RANGE_VAR = "cur_range"; + public final String CURRERNT_ITERATION_VAR = "cur_iteration"; + int currentScanIndex ; + RangeSelection[] scanRanges; + + @Override + protected void onTimer() { + try{ + Object index = XPSSpectrum.this.eval(CURRERNT_RANGE_VAR, true); + if ((index!=null) && (index instanceof Integer) && ((Integer)index >= 0)){ + int scanIndex = (Integer)index; + if (scanIndex!=currentScanIndex){ + buttonSkip.setEnabled(true); + } + currentScanIndex = scanIndex; + + int current_iteration = (Integer) XPSSpectrum.this.eval(CURRERNT_ITERATION_VAR, true); + int iterations = (Integer)scanRanges[currentScanIndex].getVars()[2]; + + buttonSkip.setVisible((iterations>1) && (current_iteration < (iterations-1))); + + if (detailedScan){ + RangeSelection range = rangeSelectionPanel.getRangesOrdered()[scanIndex]; + for (int row = 0; row< rangeSelectionPanel.getTable().getRowCount(); row++){ + if (range.equals((Double)rangeSelectionPanel.getTable().getValueAt(row, 0), (Double)rangeSelectionPanel.getTable().getValueAt(row, 2))){ + rangeSelectionPanel.getTable().setRowSelectionInterval(row, row); + break; + } + if (row == (rangeSelectionPanel.getTable().getRowCount()-1)){ + rangeSelectionPanel.getTable().clearSelection(); + } + } + } + } else { + rangeSelectionPanel.getTable().clearSelection(); + } + } catch (Exception ex){ + getLogger().log(Level.FINE, null, ex); + } + } + + void start() throws Context.ContextStateException{ + HashMap args = new HashMap<>(); + args.put("ranges", scanRanges); + args.put("pass_energy", Integer.valueOf(comboPass.getSelectedItem().toString())); + + currentScanIndex = -1; + runAsync("XPSSpectrum", args); + startTimer(500,10); + running = true; + } + + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + valueIterations = new ch.psi.pshell.swing.ValueSelection(); + jLabel9 = new javax.swing.JLabel(); + valueTime = new ch.psi.pshell.swing.ValueSelection(); + comboPass = new javax.swing.JComboBox(); + valueSize = new ch.psi.pshell.swing.ValueSelection(); + jLabel11 = new javax.swing.JLabel(); + valueLow = new ch.psi.pshell.swing.ValueSelection(); + jLabel2 = new javax.swing.JLabel(); + valueHigh = new ch.psi.pshell.swing.ValueSelection(); + jLabel8 = new javax.swing.JLabel(); + jLabel17 = new javax.swing.JLabel(); + buttonScientaSetup = new javax.swing.JButton(); + txt = new javax.swing.JTextField(); + sp = new javax.swing.JSpinner(); + ck = new javax.swing.JCheckBox(); + jPanel2 = new javax.swing.JPanel(); + btLoad = new javax.swing.JButton(); + btSave = new javax.swing.JButton(); + buttonInitialScan = new javax.swing.JButton(); + buttonDetailedScan = new javax.swing.JButton(); + rangeSelectionPanel = new ch.psi.pshell.swing.RangeSelectionPanel() { + protected void onSeriesChanged() { + updateButtons(); + } + protected void onSelectionChanged() { + updateButtons(); + } + } + ; + buttonAbort = new javax.swing.JButton(); + buttonSkip = new javax.swing.JButton(); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Arguments")); + + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel1.setText("Low:"); + + valueIterations.setDecimals(0); + valueIterations.setMaxValue(1000.0); + valueIterations.setMinValue(0.0); + valueIterations.setShowButtons(false); + valueIterations.setValue(1.0); + + jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel9.setText("Size:"); + + valueTime.setDecimals(2); + valueTime.setMaxValue(1000.0); + valueTime.setMinValue(0.0); + valueTime.setShowButtons(false); + valueTime.setValue(1.0); + + comboPass.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2", "5", "10", "20", "50", "100", "200" })); + comboPass.setToolTipText(""); + + valueSize.setDecimals(2); + valueSize.setMaxValue(1000.0); + valueSize.setMinValue(0.0); + valueSize.setShowButtons(false); + valueSize.setValue(1.0); + + jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel11.setText("Pass:"); + + valueLow.setDecimals(2); + valueLow.setMaxValue(1000.0); + valueLow.setMinValue(0.0); + valueLow.setShowButtons(false); + valueLow.setValue(0.0); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("High:"); + + valueHigh.setDecimals(2); + valueHigh.setMaxValue(1000.0); + valueHigh.setMinValue(0.0); + valueHigh.setShowButtons(false); + valueHigh.setValue(100.0); + + jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel8.setText("Time:"); + + jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel17.setText("Iter:"); + + buttonScientaSetup.setText("Scienta Setup"); + buttonScientaSetup.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScientaSetupActionPerformed(evt); + } + }); + + txt.setText("jTextField1"); + + sp.setModel(new javax.swing.SpinnerNumberModel(5.0d, 0.0d, 5.0d, 1.0d)); + + ck.setText("jCheckBox1"); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(ck)) + .addComponent(buttonScientaSetup, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueLow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueHigh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel8) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel9) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel17) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueIterations, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(comboPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(sp, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(1, 1, 1))) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboPass, valueHigh, valueIterations, valueLow, valueSize, valueTime}); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel11, jLabel17, jLabel2, jLabel8, jLabel9}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(valueLow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel2) + .addComponent(valueHigh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel8) + .addComponent(valueTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel9) + .addComponent(valueSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel17) + .addComponent(valueIterations, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jLabel11) + .addComponent(comboPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(sp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(ck) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonScientaSetup) + .addGap(24, 24, 24)) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Scan Control")); + + btLoad.setText("Load"); + btLoad.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btLoadActionPerformed(evt); + } + }); + + btSave.setText("Save"); + btSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btSaveActionPerformed(evt); + } + }); + + buttonInitialScan.setText("Simple Scan"); + buttonInitialScan.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonInitialScanActionPerformed(evt); + } + }); + + buttonDetailedScan.setText("Detailed Scan"); + buttonDetailedScan.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDetailedScanActionPerformed(evt); + } + }); + + buttonAbort.setText("Stop"); + buttonAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonAbortActionPerformed(evt); + } + }); + + buttonSkip.setText("Skip"); + buttonSkip.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSkipActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(342, 349, Short.MAX_VALUE) + .addComponent(btLoad) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(btSave)) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup() + .addGap(20, 20, 20) + .addComponent(buttonInitialScan) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(buttonDetailedScan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonSkip) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonAbort)) + .addComponent(rangeSelectionPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btLoad, btSave, buttonAbort, buttonDetailedScan, buttonInitialScan, buttonSkip}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonInitialScan) + .addComponent(buttonDetailedScan) + .addComponent(buttonAbort) + .addComponent(buttonSkip)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(rangeSelectionPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(btLoad, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(btSave, javax.swing.GroupLayout.Alignment.TRAILING)) + .addContainerGap()) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + private void buttonAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAbortActionPerformed + try { + abort(); + scienta.stop(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonAbortActionPerformed + + private void buttonInitialScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonInitialScanActionPerformed + try { + rangeSelectionPanel.clear(); + detailedScan = false; + + RangeSelection initialRange = new RangeSelection(valueLow.getValue(),valueHigh.getValue()); + int iterations = (int)valueIterations.getValue(); + initialRange.setVars(new Object[]{valueSize.getValue(),valueTime.getValue(),iterations}); + scanRanges = new RangeSelection[]{initialRange}; + + start(); + } catch (Exception ex) { + showException(ex); + } + + }//GEN-LAST:event_buttonInitialScanActionPerformed + + private void buttonDetailedScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDetailedScanActionPerformed + try { + detailedScan = true; + scanRanges = rangeSelectionPanel.getRangesOrdered(); + start(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonDetailedScanActionPerformed + + private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed + try { + JFileChooser chooser = new JFileChooser(getContext().getSetup().getContextPath()); + FileNameExtensionFilter filter = new FileNameExtensionFilter("XPS Spectrum scan definition file", "xps"); + chooser.setFileFilter(filter); + int rVal = chooser.showSaveDialog(this); + if (rVal == JFileChooser.APPROVE_OPTION) { + File f = chooser.getSelectedFile(); + if (IO.getExtension(f).isEmpty()){ + f = new File(f.getPath() + ".xps"); + } + Object[] obj = new Object[]{SwingUtils.getTableData(rangeSelectionPanel.getTable()), + rangeSelectionPanel.getPlot().getSeries(0).getX(), + rangeSelectionPanel.getPlot().getSeries(0).getY()}; + //Files.write(f.toPath(), Serializer.encode(obj, Serializer.EncoderType.bin)); + Files.write(f.toPath(), JsonSerializer.encode(obj, true).getBytes()); + + } + } catch (Exception ex) { + showException(ex); + } + + }//GEN-LAST:event_btSaveActionPerformed + + private void btLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLoadActionPerformed + try { + JFileChooser chooser = new JFileChooser(getContext().getSetup().getContextPath()); + FileNameExtensionFilter filter = new FileNameExtensionFilter("XPS Spectrum scan definition file", "xps"); + chooser.setFileFilter(filter); + int rVal = chooser.showOpenDialog(this); + if (rVal == JFileChooser.APPROVE_OPTION) { + rangeSelectionPanel.removeAllRanges(); + //Object[] obj = (Object[])Serializer.decode(Files.readAllBytes(chooser.getSelectedFile().toPath()), Serializer.EncoderType.bin); + Object aux = (Object[])JsonSerializer.decode(new String(Files.readAllBytes(chooser.getSelectedFile().toPath())), Object[].class); + Object[] obj = (Object[]) aux; + ArrayList table = (ArrayList) obj[0]; + if (!rangeSelectionPanel.getPlot().hasData()){ + double[] x = (double[]) Convert.toPrimitiveArray(((ArrayList) obj[1]).toArray(new Double[0])); + double[] y = (double[]) Convert.toPrimitiveArray(((ArrayList) obj[2]).toArray(new Double[0])); + LinePlotSeries series = new LinePlotSeries("Data"); + rangeSelectionPanel.setSeries(series); + series.setData(x, y); + } + //SwingUtils.showMessage(null, "ad", aux.getClass().getName()); + + for (ArrayList row:table){ + rangeSelectionPanel.getPlot().addRange(row.get(0), row.get(2)); + } + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + for (int row = 0; row < table.size(); row++) { + for (int col = 3; col < 6; col++) { + rangeSelectionPanel.getTable().setValueAt(table.get(row).get(col), row , col); + } + } + } + }); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_btLoadActionPerformed + + private void buttonSkipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSkipActionPerformed + try { + this.eval("skip_iteration = True", true); + buttonSkip.setEnabled(false); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonSkipActionPerformed + + private void buttonScientaSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScientaSetupActionPerformed + try{ + showDevicePanel("scienta"); + } catch (Exception ex){ + SwingUtils.showException(this, ex); + } + }//GEN-LAST:event_buttonScientaSetupActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btLoad; + private javax.swing.JButton btSave; + private javax.swing.JButton buttonAbort; + private javax.swing.JButton buttonDetailedScan; + private javax.swing.JButton buttonInitialScan; + private javax.swing.JButton buttonScientaSetup; + private javax.swing.JButton buttonSkip; + private javax.swing.JCheckBox ck; + private javax.swing.JComboBox comboPass; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel17; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private ch.psi.pshell.swing.RangeSelectionPanel rangeSelectionPanel; + private javax.swing.JSpinner sp; + private javax.swing.JTextField txt; + private ch.psi.pshell.swing.ValueSelection valueHigh; + private ch.psi.pshell.swing.ValueSelection valueIterations; + private ch.psi.pshell.swing.ValueSelection valueLow; + private ch.psi.pshell.swing.ValueSelection valueSize; + private ch.psi.pshell.swing.ValueSelection valueTime; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/importer.java b/plugins/importer.java new file mode 100755 index 0000000..64979da --- /dev/null +++ b/plugins/importer.java @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.core.Context; +import ch.psi.pshell.ui.Importer; +import ch.psi.pshell.ui.Plugin; +import ch.psi.utils.Str; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * + */ +public class importer implements Plugin { + public static class MyImporter implements Importer{ + StringBuffer sb; + @Override + public String getDescription() { + return "X-Treme scan files"; + } + + @Override + public String[] getExtensions() { + return new String[]{"txt"}; + } + + List[] getBlocks(List lines){ + ArrayList> ret = new ArrayList<>(); + + List block = new ArrayList<>(); + for (String line:lines){ + line = line.trim(); + if (!line.isEmpty()){ + block.add(line); + if (line.equals("start")){ + ret.add(block); + block = new ArrayList<>(); + } + } + } + if (block.size()>0){ + ret.add(block); + } + return ret.toArray(new List[0]); + } + + String getRanges(String fileName) throws Exception{ + File file = new File(fileName); + if (!file.exists()){ + file = Paths.get(Context.getInstance().getSetup().getScriptPath(), fileName).toFile(); + if (!file.exists()){ + throw new Exception("Invalid ranges file: " + fileName); + } + } + StringBuffer ret = new StringBuffer(); + ret.append("ranges = ["); + for (String str : Files.readAllLines(file.toPath())){ + str = str.trim(); + str = Str.removeMultipleSpaces(str); + String[] tokens = str.split(" "); + if (tokens.length == 3){ + ret.append("(").append(tokens[0]).append(",").append(tokens[1]).append(",").append(tokens[2]).append("),"); + } + } + ret.append("]"); + return ret.toString(); + } + + String[] getTokens(String line){ + return line.replaceAll("\\s+", " ").split(" ");//remove multiple spaces + } + + HashMap getPars(String[] tokens){ + HashMap pars = new HashMap<>(); + for (String par : new String[]{"off", "delay", "repeat", "file", "ppe"}){ + for (int i = 1; i block, int repeat){ + String ident = ""; + if (repeat > 1){ + ident = " "; + sb.append("for i in range(").append(repeat).append("):\n"); + } + String scanCommand = null; + + String atEnd = null; + for (String line:block){ + try{ + String[] tokens = getTokens(line); + HashMap pars = getPars(tokens); + String delayStr = pars.get("delay") != null ? ", delay=" + pars.get("delay") : ""; + System.out.println("----"); + System.out.println(line); + System.out.println(pars); + + switch (tokens[0]){ + case "set": + switch (tokens[1]){ + case "Hx": + sb.append(ident).append("set_hx(").append(tokens[2]).append(")").append("\n"); + continue; + case "Hz": + sb.append(ident).append("set_hz(").append(tokens[2]).append(")").append("\n"); + continue; + case "pol": + String offset = pars.get("off") != null ? pars.get("off") : "None"; + switch (tokens[2]){ + case "c+": + sb.append(ident).append("set_pol_cplus(offset = ").append(offset).append(")").append("\n"); + continue; + case "c-": + sb.append(ident).append("set_pol_cminus(offset = ").append(offset).append(")").append("\n"); + continue; + case "pol": + sb.append(ident).append("set_pol_lin(angle = ").append(tokens[3]).append(", offset = ").append(offset).append(")").append("\n"); + continue; + } + continue; + case "hor": + sb.append(ident).append("sample_hor.move(").append(tokens[2]).append(")").append("\n"); + continue; + case "vert": + sb.append(ident).append("sample_vert.move(").append(tokens[2]).append(")").append("\n"); + continue; + case "rot": + sb.append(ident).append("sample_rot.move(").append(tokens[2]).append(")").append("\n"); + continue; + case "needle": + sb.append(ident).append("sample_vert.write(").append(tokens[2]).append(")").append("\n"); + continue; + case "temp": + sb.append(ident).append("set_temp(").append(tokens[2]).append(delayStr).append(")").append("\n"); + continue; + case "E": + sb.append(ident).append("set_energy(").append(tokens[2]).append(delayStr).append(")").append("\n"); + continue; + case "cff": + sb.append(ident).append("set_cff(").append(tokens[2]).append(")").append("\n"); + continue; + case "slit": + sb.append(ident).append("set_slit(").append(tokens[2]).append(")").append("\n"); + continue; + case "har": + sb.append(ident).append("set_har(").append(tokens[2]).append(")").append("\n"); + continue; + case "volt": + sb.append(ident).append("set_volt(").append(tokens[2]).append(", ").append(tokens[3]).append(delayStr).append(")").append("\n"); + continue; + case "FE": + sb.append(ident).append("set_fe(").append(tokens[2]).append(")").append("\n"); + continue; + } + break; + case "open": + sb.append(ident).append("open_valve(").append(delayStr.substring(2)).append(")").append("\n"); + continue; + case "close": + sb.append(ident).append("close_valve()").append("\n"); + continue; + case "range": + sb.append(ident).append("set_range(").append(tokens[1]).append(", ").append(tokens[2]).append(")\n"); + continue; + case "wait_temp": + waitTemp = true; + continue; + case "refill1K": + refill1K = true; + continue; + case "no_beam_check": + noBeamCkeck = true; + continue; + case "wait_inj": + waitInj = true; + continue; + case "file": + fileName = tokens[1]; + continue; + case "at_end": + atEnd = tokens[1]+"()"; + continue; + case "otf": + case "hyst": + case "scan": + System.out.println("GOT"); + if (scanCommand!=null){ + throw new Exception("Two scan commands in a single block"); + } + scanCommand = line; + continue; + } + sb.append("# TODO: ").append(line).append("\n"); + } catch (Exception ex){ + sb.append("# Exception: ").append(ex.getMessage()).append( " in ").append(line).append("\n"); + } + } + + if (scanCommand!=null){ + try{ + if (waitTemp){ + sb.append(ident).append("wait_temp()").append("\n"); + } + if (refill1K){ + sb.append(ident).append("refill_1k()").append("\n"); + } + if (waitInj){ + sb.append(ident).append("wait_inj()").append("\n"); + } + if (!noBeamCkeck){ + sb.append(ident).append("wait_beam()").append("\n"); + } + if (fileName!=null){ + sb.append(ident).append("set_file('").append(fileName).append("')\n"); + } + + String[] tokens = getTokens(scanCommand); + HashMap pars = getPars(tokens); + String delayStr = pars.get("delay") != null ? ", delay=" + pars.get("delay") : ""; + switch (tokens[0]){ + case "otf": + String init = "start=" + tokens[1] + ", "; + String finish = "end=" + tokens[2] + + ", "; + String time = "time=" + tokens[3]; + sb.append(ident).append("otf(").append(init).append(finish).append(time).append(delayStr).append(")\n"); + break; + case "hyst": + String ppe = ""; + if (pars.containsKey("ppe")){ + //TODO + scanCommand = scanCommand.substring(0, scanCommand.lastIndexOf("ppe")).trim(); + ppe = ", ppe=" + pars.get("ppe"); + } + String energies = "energies=[" + scanCommand.substring(scanCommand.lastIndexOf(" E ") + 3).trim().replace(" ", ", ") + "]" + ppe; + tokens = getTokens(scanCommand.substring(0, scanCommand.lastIndexOf(" E ")).trim()); + String field; + switch (tokens[1]){ + case "cont": + field = "field=" + tokens[2] + ", "; + if (tokens.length == 4){ + String file = tokens[3]; + sb.append(ident).append("hyst_cont_mult(").append(field).append(getRanges(file)).append(", ").append(energies).append(")\n"); + } else { + String start = "init_field=" + tokens[3] + ", "; + String end = "final_field=" + tokens[4] + ", "; + String ramp = "ramp_speed=" + tokens[5] + ", "; + sb.append(ident).append("hyst_cont(").append(field).append(start).append(end).append(ramp).append(energies).append(")\n"); + } + break; + case "step": + String forward = tokens[2].equals("for") ? "forward = True, ": "forward = False, "; + field = "field=" + tokens[3] + ", "; + if (tokens.length == 5){ + String file = tokens[4]; + sb.append(ident).append("hyst_step_mult(").append(forward).append(field).append(getRanges(file)).append(", ").append(energies).append(")\n"); + } else { + String start = "init_field=" + tokens[4] + ", "; + String end = "final_field=" + tokens[5] + ", "; + String ramp = "ramp_speed=" + tokens[6] + ", "; + sb.append(ident).append("hyst_step(").append(forward).append(field).append(start).append(end).append(ramp).append(energies).append(")\n"); + } + break; + default: + throw new Exception("Invalid scan command type"); + } + break; + case "scan": + switch (tokens[1]){ + case "E": + if (tokens.length == 3){ + String file = tokens[2]; + sb.append(ident).append("scan_e_mult(").append(getRanges(file)).append(")\n"); + } else { + sb.append(ident).append("scan_e(").append(tokens[2]).append(", ").append(tokens[3]).append(", ").append(tokens[4]).append(")\n"); + } + break; + case "V": + sb.append(ident).append("scan_v(").append(tokens[2]).append(", ").append(tokens[3]).append(", ").append(tokens[4]).append(", ").append(tokens[5]).append(")\n"); + break; + default: + throw new Exception("Invalid scan command type"); + } + break; + default: + throw new Exception("Invalid scan command type"); + } + } catch (Exception ex){ + sb.append("# Exception: ").append(ex.getMessage()).append( " in ").append(scanCommand).append("\n"); + } + } + + if (atEnd!=null){ + sb.append(atEnd).append("\n"); + } + } + + @Override + public String importFile(File file) throws Exception { + waitTemp = false; + refill1K = false; + noBeamCkeck = false; + waitInj = false; + fileName = null; + + sb = new StringBuffer(); + List[] blocks = getBlocks(Files.readAllLines(file.toPath())); + for (List block : blocks){ + for (String line:block){ + sb.append("#").append(line).append("\n"); + } + //Execution block + if (block.size()>=2) { + String[] tokens = getTokens(block.get(block.size()-1)); + if (tokens[0].equals("start")){ + HashMap pars = getPars(tokens); + if (pars.get("file")!=null){ + sb.append("# TODO: 'start file' not supported").append("\n"); + } + int repeat = 1; + try{ + repeat = Integer.valueOf( pars.get("repeat")); + }catch (Exception ex){ + } + + block.remove(block.size()-1); + parse(block, repeat); + } + } + sb.append("\n"); + } + return sb.toString(); + } + + } + @Override + public void onStart() { + Importer.addServiceProvider(MyImporter.class); + } +} diff --git a/plugins/panel.py b/plugins/panel.py new file mode 100755 index 0000000..01ba7ca --- /dev/null +++ b/plugins/panel.py @@ -0,0 +1,7 @@ +from javax.swing import JPanel + +class panel(Panel): + def onStart(self): + Panel.onStart(self) + + diff --git a/plugins/plugin-1.0-SNAPSHOT.jar b/plugins/plugin-1.0-SNAPSHOT.jar new file mode 100755 index 0000000..2a49d10 Binary files /dev/null and b/plugins/plugin-1.0-SNAPSHOT.jar differ diff --git a/plugins/resources/Background.png b/plugins/resources/Background.png new file mode 100755 index 0000000..a168169 Binary files /dev/null and b/plugins/resources/Background.png differ diff --git a/plugins/resources/Fit.png b/plugins/resources/Fit.png new file mode 100755 index 0000000..44f80c6 Binary files /dev/null and b/plugins/resources/Fit.png differ diff --git a/plugins/resources/Marker.png b/plugins/resources/Marker.png new file mode 100755 index 0000000..d097a02 Binary files /dev/null and b/plugins/resources/Marker.png differ diff --git a/plugins/resources/Profile.png b/plugins/resources/Profile.png new file mode 100755 index 0000000..8a8209b Binary files /dev/null and b/plugins/resources/Profile.png differ diff --git a/plugins/resources/Reticule.png b/plugins/resources/Reticule.png new file mode 100755 index 0000000..762f01f Binary files /dev/null and b/plugins/resources/Reticule.png differ diff --git a/plugins/resources/Save.png b/plugins/resources/Save.png new file mode 100755 index 0000000..d1480a0 Binary files /dev/null and b/plugins/resources/Save.png differ diff --git a/plugins/resources/Sidebar.png b/plugins/resources/Sidebar.png new file mode 100755 index 0000000..8328264 Binary files /dev/null and b/plugins/resources/Sidebar.png differ diff --git a/plugins/resources/Title.png b/plugins/resources/Title.png new file mode 100644 index 0000000..d07dc34 Binary files /dev/null and b/plugins/resources/Title.png differ diff --git a/plugins/sb1.groovy b/plugins/sb1.groovy new file mode 100755 index 0000000..8487407 --- /dev/null +++ b/plugins/sb1.groovy @@ -0,0 +1,14 @@ +import groovy.swing.SwingBuilder +import java.awt.BorderLayout as BL + +count = 0 +new SwingBuilder().edt { + frame(title: 'Frame', size: [300, 300], show: true) { + borderLayout() + textlabel = label(text: 'Click the button!', constraints: BL.NORTH) + button(text:'Click Me', + actionPerformed: {count++; textlabel.text = "Clicked ${count} time(s)."; println "clicked"}, constraints:BL.SOUTH) + button(text:'Run', + actionPerformed: { Thread.start {controller.evalLine(":run test1")}}, constraints:BL.SOUTH) + } +} \ No newline at end of file diff --git a/plugins/test.py b/plugins/test.py new file mode 100755 index 0000000..b44f5e0 --- /dev/null +++ b/plugins/test.py @@ -0,0 +1,11 @@ + +class test(Plugin): + def __init__(self): + print "Constructor" + + def onStart(self): + print "Start - state = " + str(self.context.state) + + def onStop(self): + print "Stop - state = " + str(self.context.state) + diff --git a/plugins/test/Final.java b/plugins/test/Final.java new file mode 100755 index 0000000..0a22b82 --- /dev/null +++ b/plugins/test/Final.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +package test; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +public class Final { + public static class TestClass { + protected void method1() { + System.out.println("On protected"); + } + final public void method2() { + System.out.println("On final public"); + } + final protected void method3() { + System.out.println("On final protected"); + } + } + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); + + engine.eval("import test.Final.TestClass"); + + engine.eval("class MyClass(test.Final.TestClass):\n" + + " def m1(self):\n" + + " self.method1()\n" + + " def m2(self):\n" + + " self.method2()\n" + + " def m3(self):\n" + + " self.method3()\n"); + engine.eval("o = MyClass()"); + + engine.eval("o.m1()"); + engine.eval("o.m2()"); + engine.eval("o.m3()"); + } +} \ No newline at end of file diff --git a/script/10_LineScan.js b/script/10_LineScan.js new file mode 100755 index 0000000..404c420 --- /dev/null +++ b/script/10_LineScan.js @@ -0,0 +1,14 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate the use of Line Scan: one or multiple positioners move together linearly. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Execute the scan: 100 steps, a1 from 0 to 40 +r1 = lscan(ao1, [ai1,ai2,wf1], 0, 40, 100, 0.01) + +//Steps of size 1.0, a1 from 0 to 40 +r2 = lscan(ao1, [ai1,ai2,wf1], 0, 40, 1.0, 0.01) + +//2 positioners moving together in 10 steps. Also sampling an image: +r3 = lscan([ao1,ao2], [ai1,ai2,wf1,im1], [0, 0], [40, 100], 4, 0.01) + diff --git a/script/11_TimeScan.js b/script/11_TimeScan.js new file mode 100755 index 0000000..0a9cc31 --- /dev/null +++ b/script/11_TimeScan.js @@ -0,0 +1,8 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate the use of Time Scan: time-based sensor sampling +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Execute the scan: 100 samples, 10ms sampling interval +r1 = tscan((ai1,ai2,wf1), 100, 0.01) + diff --git a/script/12_AreaScan.js b/script/12_AreaScan.js new file mode 100755 index 0000000..ea91053 --- /dev/null +++ b/script/12_AreaScan.js @@ -0,0 +1,10 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Area Scan: Multiple positioners, each one is one dimension. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//The second sensor is an array. In the plot window it is overwritten in every same x position. +//The data window never displays 3d data, but the 3d data can be accesses during the scan in the Data tab. +r1 = ascan([m1,m2], [ai1,wf1], [0.0,0.0], [2.0,1.0], [10,10]) + + diff --git a/script/13_VectorScan.js b/script/13_VectorScan.js new file mode 100755 index 0000000..66910ec --- /dev/null +++ b/script/13_VectorScan.js @@ -0,0 +1,20 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate use of Vector Scan: one or multiple positioners set according to a position vector. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//1D vector scan, plot to 1D Vector tab +vector = [ 1, 3, 5, 10, 25, 40, 45, 47, 49] +r1 = vscan(ao1, [ai1,ai2], vector, false, 0.5, false, undefined, undefined, undefined, undefined, title = "1D Vector") + + + + +//2D vector scan, plot to 2D Vector tab +vector = [ [1,1] , [1,2] , [1,3] , [1,4] , + [1.5,2.5] , + [2,1] , [2,2] , [2,3] , [2,4] , + [2.5,2.5] , + [3,1] , [3,2] , [3,3] , [3,4] ] + +r2 = vscan([m1,m2], [ai1,ai2], vector, false, 0.1, false, undefined, undefined, undefined, undefined, title = "2D Vector") \ No newline at end of file diff --git a/script/14_RegionScan.js b/script/14_RegionScan.js new file mode 100755 index 0000000..0c8065e --- /dev/null +++ b/script/14_RegionScan.js @@ -0,0 +1,11 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate the use of Region Scan: one positioner move linearly in multiple regions. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + + +//Execute the scan: 3 regions with different number of steps +r1 = rscan(ao1, [ai1,ai2], [[0,5,5], [10,15,20], [20,25,5]] , 0.01) + +//Execute the scan: 3 regions with different step size +r2 = rscan(ao1, [ai1,ai2], [[0,5,1.0], [10,15,0.2], [20,25,1.0]] , 0.01) \ No newline at end of file diff --git a/script/15_ContinuousScan.js b/script/15_ContinuousScan.js new file mode 100755 index 0000000..34e526f --- /dev/null +++ b/script/15_ContinuousScan.js @@ -0,0 +1,17 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate the use of Continuous Scan Scan: a Linear Scan with continuous motor move and +// sampling on the fly. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +m1.move(0.0) + +//A single motor at current speed +r1 = cscan(m1, (ai1,ai2), -2, 3 , steps=10, undefined, undefined ,true) + +//A single motor in a given time +r2 = cscan(m1, (ai1,ai2), -2.0, 3.0, 100 , undefined , 4.0, true) + +//Multiple motors in a given time +r3 = cscan((m1, m2), (ai1,ai2), (-2.0, -3), (3.0, 5.0), steps=100, undefined, time = 4.0, relative=true) + diff --git a/script/16_HardwareScan.js b/script/16_HardwareScan.js new file mode 100755 index 0000000..7944828 --- /dev/null +++ b/script/16_HardwareScan.js @@ -0,0 +1,46 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Use of HardwareScan +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +CrlogicPositioner = Java.type('ch.psi.pshell.crlogic.CrlogicPositioner') +CrlogicSensor = Java.type('ch.psi.pshell.crlogic.CrlogicSensor') + +//sc1.stop() +//sc1.setOneShot() +//sc1.channels[0].setPreset(false) +//sc1.channels[0].setPresetValue(0) +//sc1.start() + +config = {} +config["class"] = "ch.psi.pshell.crlogic.CrlogicScan" +config["prefix"] = "MTEST-HW3-CRL" +config["ioc"] = "MTEST-VME-HW3.psi.ch" +config["integrationTime"] = 0.01 +config["additionalBacklash"] = 0.0 + +pos = new CrlogicPositioner("CrlogicPositioner", "MTEST-HW3:MOT1", null) + +sensors = [ + new CrlogicSensor("Trigger0", "TRIGGER0"), + new CrlogicSensor("Trigger1", "TRIGGER1"), + new CrlogicSensor("Scaler0", "SCALER0", true), + new CrlogicSensor("Scaler1", "SCALER1", true), + new CrlogicSensor("Timestamp", "TIMESTAMP"), + ] + + + +//pos.initialize() +//pos.move(0.0) + +try { + r1 = hscan(config, pos, sensors,0.0, 10.0, 0.1,1, false) +} +catch(err) { + +} +finally { + pos.close() +} + diff --git a/script/20101216_hyst_meas_Dy.txt b/script/20101216_hyst_meas_Dy.txt new file mode 100755 index 0000000..ae1c2e9 --- /dev/null +++ b/script/20101216_hyst_meas_Dy.txt @@ -0,0 +1,26 @@ +wait_temp + +set pol c+ off 0 +hyst cont Hx -6.0 6.0 2.0 E 1289.2 1297 ppe 90 +file Cr_hyst +start + +set pol c- off 1 +hyst cont Hx 6.0 -6.0 2.0 E 1289.2 1297 ppe 90 +file Cr_hyst +start + +hyst cont Hx -6.0 6.0 2.0 E 1289.2 1297 ppe 90 +file Cr_hyst +start + +set pol c+ off 0 +hyst cont Hx 6.0 -6.0 2.0 E 1289.2 1297 ppe 90 +file Cr_hyst +start + +set Hx 0.0 +otf 560 600 2 +file Cr_energy +start repeat 4 + diff --git a/script/20110203_Cr_xmcd_different_fields.txt b/script/20110203_Cr_xmcd_different_fields.txt new file mode 100755 index 0000000..3164fd3 --- /dev/null +++ b/script/20110203_Cr_xmcd_different_fields.txt @@ -0,0 +1,402 @@ +wait_temp + + +set Hx -6.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx 6.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx 5.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx -5.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + + +set Hx -4.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx 4.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + + +set Hx 3.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx -3.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx -2.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx 2.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + + +set Hx 1.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + + + +set Hx -1.0 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + + + +set Hx -0.5 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy + +start + + +set Hx 0.5 +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c- off 1 +file Cr_energy +start + +otf 560 600 2 +set pol c+ off 0 +file Cr_energy +at_end shutdown +start + + diff --git a/script/20150418_0012_Tb_hyst_plus.xml b/script/20150418_0012_Tb_hyst_plus.xml new file mode 100755 index 0000000..af3cf69 --- /dev/null +++ b/script/20150418_0012_Tb_hyst_plus.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + 1236.9 1243.9 + + + + + + + + + + + + + + + 0.0 + 110.0 + 1.0 + + + + + + + + + + + + + + + + + + diff --git a/script/20150418_1152_DyE_minus.xml b/script/20150418_1152_DyE_minus.xml new file mode 100755 index 0000000..8149fff --- /dev/null +++ b/script/20150418_1152_DyE_minus.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/script/20_Relative.js b/script/20_Relative.js new file mode 100755 index 0000000..0b7e35d --- /dev/null +++ b/script/20_Relative.js @@ -0,0 +1,13 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate use of Relative Line Scan. +// The arguments start and end are relative to the current position. +// After the scan the positioner(s) move back to the initial position. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +print ("Initial position = " + m1.position) + +r1 = lscan(m1, [ai1,ai2,wf1], start = -2, end =2, steps = 20, latency = undefined, relative = true) + + +print ("Final position = " + m1.position) \ No newline at end of file diff --git a/script/21_MultipassAndZigzag.js b/script/21_MultipassAndZigzag.js new file mode 100755 index 0000000..94b1cc3 --- /dev/null +++ b/script/21_MultipassAndZigzag.js @@ -0,0 +1,13 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Multi-pass and zigzag scans +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Linear with 2 passes +a= lscan(m1, [ai1,wf1], -0.2, 0.2, 20, latency = 0.0, relative = true, passes = 4) + +//Linear with 4 passes and zigzag +a= lscan(m1, [ai1,wf1], -0.2, 0.2, 20, latency = 0.0, relative = true, passes = 4, zigzag = true) + +//Multi-dimentional zigzag +x = ascan ([m1,m2], ai1, [0,0], [1, 1], [0.25,0.25], latency=0.01, relative = undefined, passes = undefined, zigzag=true) diff --git a/script/22_ScanCallbacks.js b/script/22_ScanCallbacks.js new file mode 100755 index 0000000..88352a1 --- /dev/null +++ b/script/22_ScanCallbacks.js @@ -0,0 +1,23 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate use of scan callbacks to trigger a detector at falling edge. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +function BeforeReadout(position){ + ao1.write(1) + ao1.write(0) + //Example with an epics direct channel access + //caput("CHANNEL_NAME", 1) + //caput("CHANNEL_NAME", 0) + print ("In position: " + position[0] + ", " + position[1]) +} + + + + +function AfterReadout(record, scan){ + print ("Aquired frame: " + record.index) +} + +a= lscan([m1,m2], [ai1, ai2], [0,0], [4,8], steps=20, latency = 0.01, relative = undefined, + passes = undefined, zigzag = undefined,before_read=BeforeReadout, after_read=AfterReadout) \ No newline at end of file diff --git a/script/23_Metadata.js b/script/23_Metadata.js new file mode 100755 index 0000000..3f9ea32 --- /dev/null +++ b/script/23_Metadata.js @@ -0,0 +1,21 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate adding attributs to scan groups and datasets. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Execute the scan: 200 steps, a1 from 0 to 40 +a= lscan(ao1, [ai1,ai2], 0, 40, 10, 0.01) + + +//Setting attributes to the scan group +path = get_exec_pars().group +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", true) + +//Setting attributes to the scan datasets +set_attribute(path + ao1.name, "AttrInteger", 2) +set_attribute(path + ai1.name, "AttrInteger", 3) +set_attribute(path + ai2.name, "AttrInteger", 4) + diff --git a/script/24_ScanDataManipulation.js b/script/24_ScanDataManipulation.js new file mode 100755 index 0000000..2132dbe --- /dev/null +++ b/script/24_ScanDataManipulation.js @@ -0,0 +1,19 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Processing and plotting scan data. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +ao1.write(0.0) +scan1= lscan(ao1, [ai1,ai2,wf1], 0, 40, 40, 0.01, false) +scan2= lscan(ao1, [ai1,ai2,wf1], 0, 40, 40, 0.01, false) + + +result=[] +for (var i=0; i 1.02) { + print ("Value over limit-> aborting") + abort() + } + }, + } +ai1.addListener(listenerAI) + + +var ListenerAO = Java.extend(DeviceListener) +var listenerAO = new ListenerAO() { + onStateChanged: function (device, state, former) { + + }, + onValueChanged: function (device, value, former) { + print ("Moved to: " + value) + }, + onValueChanginf: function (device, value, former) { + if (value > 20) { + throw "Forbidden move to " + value + } + print( "Moving to: " + value + " ... ") + }, + } + +ao1.addListener(listenerAO) + + + + +try{ + lscan(ao1, (ai1), 0, 40, 200, 0.01) +} catch (ex){ + print ("Aborted" ) +} +finally{ + ai1.removeListener(listenerAI) + ao1.removeListener(listenerAO) +} diff --git a/script/27_ResamplingRecord.js b/script/27_ResamplingRecord.js new file mode 100755 index 0000000..e430bea --- /dev/null +++ b/script/27_ResamplingRecord.js @@ -0,0 +1,19 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +//Resampling a scan record if a fail condition is met. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +index=0 + +function AfterReadout(rec){ + print (rec.getIndex() + " - " + to_array(rec.values)) + //Only accept records if ai2 is positive + if (ai2.take() < 0){ + sleep(1.0) + print("Invalidating") + rec.invalidate() + } +} + + +a= lscan(m1, [ai1,ai2], [0,], [0.4,], 20, 0.1, relative = undefined, passes = undefined, zigzag = undefined, before_read = undefined, after_read=AfterReadout) \ No newline at end of file diff --git a/script/28_Averaging.js b/script/28_Averaging.js new file mode 100755 index 0000000..3b71f4a --- /dev/null +++ b/script/28_Averaging.js @@ -0,0 +1,9 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Scan averaging +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +av = create_averager(ai2, 50, 0.05) +//set_preference(Preference.PLOT_TYPES, {av.name:'minmax'}) //This is to display min/max instead of sigma. +res= lscan(ao1, [av, av.samples], 0, 40, 20, 0.1) + diff --git a/script/29_ArrayCalibration.js b/script/29_ArrayCalibration.js new file mode 100755 index 0000000..f0e2d69 --- /dev/null +++ b/script/29_ArrayCalibration.js @@ -0,0 +1,55 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Calibrating array and matrix pseudo-devices +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +var ArrayCalibrated = Java.extend(ReadableArray, ReadableCalibratedArray) +var ac1 = new ArrayCalibrated() { + read: function () { + return wf1.read() + }, + getSize: function (value) { + return wf1.size + }, + getCalibration: function (value) { + return new ArrayCalibration(5,1000) + }, + } + + +var ac2 = new ArrayCalibrated() { + read: function () { + return wf1.read() + }, + getSize: function (value) { + return wf1.size + }, + getCalibration: function (value) { + return new ArrayCalibration(5,1000) + }, + } + + + var MatrixCalibrated = Java.extend(ReadableMatrix, ReadableCalibratedMatrix) +var mc1 = new MatrixCalibrated() { + read: function () { + return im1.read() + }, + getWidth: function (value) { + return im1.width + }, + getHeight: function (value) { + return im1.height + }, + getCalibration: function (value) { + return new MatrixCalibration(2,4,100,200) + }, + } + +set_device_alias(ac1, "wf1_calib") +set_device_alias(ac2, "wf1_calib_1d") +set_device_alias(mc1, "im1_calib") + +set_preference(Preference.PLOT_TYPES, {"wf1_calib_1d":1}) + +a= lscan(ao1, [wf1, ac1, im1, mc1, ac2], 0, 40, 50, 0.02) \ No newline at end of file diff --git a/script/30_ScanPlotSetup.js b/script/30_ScanPlotSetup.js new file mode 100755 index 0000000..9dd51d6 --- /dev/null +++ b/script/30_ScanPlotSetup.js @@ -0,0 +1,30 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate configuring scan plot options +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//This optional preference limits the displayed plots +set_preference(Preference.ENABLED_PLOTS, [ai1, wf1]) + +//This optional preference displays wf1 as a 1d plot at each scan point, instead of a matrix plot +set_preference(Preference.PLOT_TYPES, {wf1:1}) + + +//This optional preference disables printing the scan table +//set_preference(Preference.PLOT_DISABLED, true) + +//This optional preference disable all scan plotting +//set_preference( Preference.TABLE_DISABLED, true) + +//Execute the scan: 200 steps, a1 from 0 to 40 +a= lscan(ao1, [ai1,ai2,wf1], 0, 40, 100, 0.01) + + + + +//This optional preference displays wf1 as a 1d plot at each scan point, instead of a matrix plot +set_preference(Preference.PLOT_TYPES, {wf1:1}) + +ascan([m1,m2], [ai1,wf1], [0.0,0.0], [2.0,1.0], [4,4]) + + diff --git a/script/31_UsersPlots.js b/script/31_UsersPlots.js new file mode 100755 index 0000000..6e877f1 --- /dev/null +++ b/script/31_UsersPlots.js @@ -0,0 +1,24 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Direct creation of plots +/////////////////////////////////////////////////////////////////////////////////////////////////// + +data_1d = [10.0, 20.0, 30.0, 40.0, 50.0] +data_2d = [ data_1d, data_1d, data_1d, data_1d, data_1d] +data_3d = [ data_2d, data_2d , data_2d, data_2d, data_2d] +data_x = [1.0, 2.0, 3.0, 4.0, 5.0] +data_y = [2.0, 4.0, 6.0, 8.0, 10.0] + +//1d-plot with optional xdata +plot(data_1d, name = undefined, xdata = data_x, ydata = undefined, title = "1d") + +//2d-plot with optional xdata and ydata +plot(data_2d, name = undefined, xdata = data_x, ydata = data_y, title = "2d") + +//3d-plot +plot(data_3d, name = undefined, xdata = undefined, ydata = undefined, title = "3d") + +//3 plots in the save panel +plot([data_1d, data_2d, data_3d], ["1d", "2d", "3d"]) + + + diff --git a/script/32_MultipleSeries.js b/script/32_MultipleSeries.js new file mode 100755 index 0000000..922b001 --- /dev/null +++ b/script/32_MultipleSeries.js @@ -0,0 +1,29 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Advanced plotting examples +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//2 series in the same plot +var xdata = [10,20,30,40,50,60] +var p = plot(null, name="Data 1")[0] +p.addSeries(new LinePlotSeries("Data2")) +p.getSeries(0).setData(xdata, [1,2,3,4,5,6]) +p.getSeries(1).setData(xdata, [6,5,4,3,2,1]) +p.addMarker(35.0, null, "This is the answer", Color.BLACK) + + +//2 series in the same plot, setting range & appending point by point +var p = plot(null,name="Data 1", title = "Plot 2")[0] +p.getAxis(AxisId.X).setRange(0.0,80.0) +p.getAxis(AxisId.Y).setRange(0.0,7.0) +p.addSeries(new LinePlotSeries("Data2")) +for (var i = 0; i< xdata.length; i++){ + p.getSeries(0).appendData(xdata[i], i) + p.getSeries(1).appendData(xdata[i], 1.0/(i+1)) +} + + + + + + diff --git a/script/33_CustomScanPlot.js b/script/33_CustomScanPlot.js new file mode 100755 index 0000000..af9190b --- /dev/null +++ b/script/33_CustomScanPlot.js @@ -0,0 +1,18 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Custom plot: Example of creating a 1D plot for a 2D scan where each scanned row is a series +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Setting the 1d preference would create in the place of the matrix plot, a 1d plot where +//each scanned column is a series +//setup_plotting(line_plots = (ai1,)) + +p = plot(null, name=undefined, xdata=undefined, ydata=undefined, title="1D Plot")[0] +function AfterReadout(record, scan){ + if (record.setpoints[1] == scan.getStart()[1]){ + p.addSeries(new LinePlotSeries(record.positions[0].toString())) + } + p.getSeries(p.numberOfSeries-1).appendData(record.positions[1], record.values[0]) +} + +ascan([ao1,ao2], [ai1], [0,10], [20,30], [20,20], 0.1, relative = undefined, passes = undefined, zigzag = undefined, before_read = undefined, after_read=AfterReadout) \ No newline at end of file diff --git a/script/34_ErrorPlot.js b/script/34_ErrorPlot.js new file mode 100755 index 0000000..9a8dcc1 --- /dev/null +++ b/script/34_ErrorPlot.js @@ -0,0 +1,57 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Example creating error plots +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +plots=plot([null,null,null],["y","x", "xy"]) +py = plots[0] +px = plots[1] +pxy = plots[2] + +//Y error plot +py.setStyle(LinePlotStyle.ErrorY) +py.setLegendVisible(true) + +sy1 = new LinePlotErrorSeries("F1") +py.addSeries(sy1) +sy1.appendData(1.0, 10.0, 9.0, 11.0) +sy1.appendData(10.0, 6.1, 4.34, 7.54) +sy1.appendData(17.8, 4.5, 3.1, 5.8) +//One can define error instead of min/max (appendData(x, y, error)) +sy2 = new LinePlotErrorSeries("F2") +py.addSeries(sy2) +sy2.setLinesVisible(false) +sy2.appendData(3.0, 7.0, 2.0); +sy2.appendData(13.0, 13.0, 2.0); +sy2.appendData(24.0, 16.1, 1.0); + +//X error plot +px.setStyle(LinePlotStyle.ErrorX) +px.setLegendVisible(true) +sx = new LinePlotErrorSeries("F3") +px.addSeries(sx) +sx.appendData(1.0, 10.0, 0.5, 1.5) +sx.appendData(10.0, 6.1, 9.0, 10.3) +sx.appendData(17.8, 4.5, 17.0, 18.0) +//One can define error instead of min/max (appendData(x, y, error)) +sx2 = new LinePlotErrorSeries("F4") +px.addSeries(sx2) +sx2.setLinesVisible(false) +sx2.appendData(1.0, 3.0, 1.0) +sx2.appendData(10.0, 5.1, 1.0) +sx2.appendData(17.8, 7.5, 0.5) + +//XY error plot +pxy.setStyle(LinePlotStyle.ErrorXY) +pxy.setLegendVisible(true) +sxy = new LinePlotErrorSeries("F5") +pxy.addSeries(sxy) +sxy.appendData(1.0,0.5,1.5, 10.0, 9.0, 11.0) +sxy.appendData(10.0,9.0, 11.0, 6.1, 4.34, 7.54) +sxy.appendData(17.8, 17.0, 18.0, 4.5, 3.1, 5.8) +//One can define error instead of min/max (appendData(x, y, errorX, errorY)) +sxy2 = new LinePlotErrorSeries("F6") +pxy.addSeries(sxy2) +sxy2.appendData(3.0, 7.0, 0.5, 4.0); +sxy2.appendData(13.0, 13.0, 0.5, 3.0); +sxy2.appendData(24.0, 16.1, 0.2, 2.0); \ No newline at end of file diff --git a/script/35_LinePlotStyles.js b/script/35_LinePlotStyles.js new file mode 100755 index 0000000..1ca893a --- /dev/null +++ b/script/35_LinePlotStyles.js @@ -0,0 +1,12 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Example changing plot styles +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +data = [0,3,5,1,3,5,3,4,3,2,1,0] +plots = plot([data, data, data], ["normal", "step", "spline"]) +p1 = plots[0] +p2 = plots[1] +p3 = plots[2] +p2.setStyle(LinePlotStyle.Step) +p3.setStyle(LinePlotStyle.Spline) \ No newline at end of file diff --git a/script/36_LogarithmicScales.js b/script/36_LogarithmicScales.js new file mode 100755 index 0000000..5106ae0 --- /dev/null +++ b/script/36_LogarithmicScales.js @@ -0,0 +1,12 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Displaying logarithmic scales +/////////////////////////////////////////////////////////////////////////////////////////////////// + +p = plot([10,500,1000,5000,1000], name = undefined, xdata = [0.1,1,10,100,1000, 10000])[0] +p.getAxis(AxisId.X).logarithmic = true +p.getAxis(AxisId.Y).setRange(1, 100000) +p.getAxis(AxisId.Y).logarithmic = true + + + + diff --git a/script/37_SecondaryDomainAxis.js b/script/37_SecondaryDomainAxis.js new file mode 100755 index 0000000..4244cb3 --- /dev/null +++ b/script/37_SecondaryDomainAxis.js @@ -0,0 +1,27 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Creating a secondary X axis, using the underlying JFreeChart libraey API +/////////////////////////////////////////////////////////////////////////////////////////////////// + +importClass(org.jfree.chart.axis.NumberAxis) +importClass(org.jfree.chart.axis.LogarithmicAxis) + +p = plot([1,2,3,4,5])[0] + +x2 = new NumberAxis("Secondary X Axis") //Linear scale +//x2 = new LogarithmicAxis("Secondary X Axis") //Logarithmic scale +x2.setRange(0.1, 100) +p.getAxis(AxisId.X).setRange(-2, 5) // So the relation between X1 and X2 is enforced + + +jf = p.chart.plot +jf.setDomainAxis(1, x2 ) + +//This is just for formatting te new axis fonts and colors, equals to the first axis +jf.getDomainAxis(1).labelPaint = jf.getDomainAxis(0).labelPaint +jf.getDomainAxis(1).labelFont = jf.getDomainAxis(0).labelFont +jf.getDomainAxis(1).tickLabelPaint = jf.getDomainAxis(0).tickLabelPaint +jf.getDomainAxis(1).tickLabelFont = jf.getDomainAxis(0).tickLabelFont + + + + diff --git a/script/40_SimultaneousScans.js b/script/40_SimultaneousScans.js new file mode 100755 index 0000000..45ab25b --- /dev/null +++ b/script/40_SimultaneousScans.js @@ -0,0 +1,16 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Example on running simultaneous scans. They should not manipulate same writables +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +function scan1(){ + print ("scan1") + return lscan(ao1, ai1, 0, 40, 20, 0.1) +} + +function scan2(){ + print ("scan2") + return lscan(ao2, wf1, 0, 40, 20, 0.1, undefined, undefined, undefined, undefined, undefined, title = "scan2") +} + +parallelize(scan1, scan2) diff --git a/script/41_ManualScan.js b/script/41_ManualScan.js new file mode 100755 index 0000000..0abde02 --- /dev/null +++ b/script/41_ManualScan.js @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Manual scan: Manually setting positioners and reading back sensors, but still using +// the standard data handling and plotting of built-in scans. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +var MOTOR_RANGE = [0.0, 8.0] +var OUTPUT_SETPOINTS = [1.0, 2.0, 3.0] +var FIXED_X = true + + +writables_names = to_array([m1.getName(), ao1.getName()], 's') +readable_names = to_array([ai1.getName(), ai2.getName()], 's') +start = to_array( [ FIXED_X ? MOTOR_RANGE[0] : -1, OUTPUT_SETPOINTS[0]] , 'd') +stop =to_array([ FIXED_X ? MOTOR_RANGE[1] : -1, OUTPUT_SETPOINTS[OUTPUT_SETPOINTS.length-1]] , 'd') +steps = to_array([Math.round(MOTOR_RANGE[1]-MOTOR_RANGE[0]), OUTPUT_SETPOINTS.length-1] , 'i') + +print (to_array(writables_names)) +print (to_array(readable_names)) +print (to_array(start)) +print (to_array(stop)) +print (to_array(steps)) + +scan = new ManualScan(writables_names, readable_names, start, stop, steps, false) + + +//This option is to plot the foe each output value one 1D series, instead of all in a matrix plot +set_preference(Preference.PLOT_TYPES, {"ai1":1, "ai2":1}) + + +scan.start() +m1.setSpeed(10.0) +for (var setpoint1 = MOTOR_RANGE[0]; setpoint1 <=MOTOR_RANGE[1]; setpoint1+=1.0){ + m1.move(setpoint1) + for (var setpoint2 in OUTPUT_SETPOINTS){ + ao1.write(setpoint2) + scan.append (to_array([setpoint1, setpoint2], 'd'), to_array([m1.read(), ao1.read()], 'd'), to_array([ai1.read(), ai2.read()], 'd')) + } +} + +scan.end() diff --git a/script/42_MaximumSearch.js b/script/42_MaximumSearch.js new file mode 100755 index 0000000..ec6ea45 --- /dev/null +++ b/script/42_MaximumSearch.js @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Using bsearch(Binary Search) and hsearch(Hill Climbing Search) to find optimum +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +var FitnessFunction = Java.extend(ReadonlyRegisterBase) +add_device(new FitnessFunction("fitness") { + doRead: function () { + return 1000.0 - (Math.pow(ao1.take()-18, 2) + Math.pow(ao2.take()-6, 2)) + }, +}, true) + + + +//Plot Fitness Function +r = ascan([ao1, ao2], fitness, [0.0,0.0], [21.0,26.0], [1.0, 1.0], title = "Fitness") + +//Binary Search +strategy = "Normal" // or "Boundary" or "FullNeighborhood" +r = bsearch([ao1, ao2], fitness, [0.0,0.0], [21.0,26.0], [0.1, 0.1], maximum=true, strategy = strategy, latency = 0.01, relative=false, before_read=undefined, after_read=undefined, title = "Binary Search") +//Relative search: +//ao1.write(10.5); ao2.write(13.0) +//r = bsearch([ao1, ao2], fitness, [-10.5,-13.0], [10.5,13.0], [0.1, 0.1],maximum=true, strategy = strategy, latency = 0.01, relative = true, before_read=undefined, after_read=undefined, title = "Binary Search") + +print ("--------------- Binary Search -----------------") +print (r) +print (r.print()) +print (r.getRecords().length) + + +//Hill Climbing Search +ao1.write(10.5) +ao2.write(13.0) +r = hsearch([ao1, ao2], fitness,[0.0,0.0], [21.0,26.0], [1.0, 1.0], [0.1, 0.1], 1, maximum=true, latency = 0.01, relative=false, before_read=undefined, after_read=undefined, title = "Hill Climbing") +print ("--------------- Hill Climbing Search -----------------") +print (r) +print (r.print()) +print (r.getRecords().length) diff --git a/script/43_BeamSynchronousScan.js b/script/43_BeamSynchronousScan.js new file mode 100755 index 0000000..456c8a0 --- /dev/null +++ b/script/43_BeamSynchronousScan.js @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Scans with beam synchronous streams +/////////////////////////////////////////////////////////////////////////////////////////////////// + +//Creating a stream, assuming a provided named "dispatcher". +st1 = new Stream("st1", dispatcher) + +//Adding channels to that stream +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 10, 0) +s2=st1.addScalar("Float64Scalar", "Float64Scalar", 10, 0) +w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 10, 0) +mt1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) +st1.initialize() + +try{ + //The stream can be used on any conventional scan. The next stream value is sampled. + //Readable values belong to same pulse id. + tscan (st1.getReadables(), 10 , 0.2) + + //The bscan command performs samples every stream element + //Readable values belong to same pulse id. + bscan (st1, 10) //Sampling 10 elements + + //An individual stream channel can be used in a conventional scan, but in this case the stream + //must be explicitly started, and there is no guarantee the values belong to the same PulseID + //(likely they are since as only cached values are taken). + st1.start(true) + tscan ([s1,s2], 10 , 0.2) + + //If waveform individual stream channel is used, and no size is provided in constructor/config, + //then it must be read previously to the scan to update the size value. + st1.start(true) + w1.update() + tscan ([s1,w1,mt1], 10 , 0.2) +} finally{ + st1.close() +} diff --git a/script/50_DataManipulation.js b/script/50_DataManipulation.js new file mode 100755 index 0000000..8d520d3 --- /dev/null +++ b/script/50_DataManipulation.js @@ -0,0 +1,86 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +//Data Manipulation: Using the data access API to generate and retrieve data +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Creating a 1D dataset from an array +path="group/data1" +data1d = [1.0, 2.0, 3.0, 4.0, 5.0] +save_dataset(path, data1d) +//Reading ii back +read =load_data(path) +print(to_array(read) +) +assert (data1d.toString() == to_array(read).toString() ) +plot(read) + +//Creating a 2D dataset from an array with some attributes +data2d = [ [1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0, ], [3.0, 4.0, 5.0, 6.0, 7.0]] +path="group/data2" +save_dataset(path, data2d) +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", true) +//Reading it back +read =load_data(path) +print(to_array(read) +) +plot(read) + +//Creating a 3D dataset from an array +data3d = [ [ [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]], [ [3,2,3,4,5], [4,3,4,5,6], [5,4,5,6,7]]] +path="group/data3" +save_dataset(path, data3d) +//Reading it back +read =load_data(path,0) +print(to_array(read)) +read =load_data(path,1) +print(to_array(read)) + +//Creating a INT dataset adding elements one by one +path = "group/data4" +create_dataset(path, 'i') +for (var i=0; i<10; i++){ + append_dataset(path,i) +} + + +//Creating a 2D data FLOAT dataset adding lines one by one +path = "group/data5" +create_dataset(path, 'd', false, [0,0]) +for (var row in data2d){ + append_dataset(path, data2d[row]) +} + +//Creating a Table (compund type) +path = "group/data6" +names = ["a", "b", "c", "d"] +types = ["d", "d", "d", "[d"] +lenghts = [0,0,0,5] +table = [ [1,2,3,[0,1,2,3,4]], + [2,3,4,[3,4,5,6,7]], + [3,4,5,[6,7,8,9,4]] ] +create_table(path, names, types, lenghts) +for (var row in table){ + append_table(path, table[row]) +} +flush_data() +//Read it back +read =load_data(path) +print(read +) + + +//Writing scalars (datasets with rank 0) +save_dataset("group/val1", 1) +save_dataset("group/val2", 3.14) +save_dataset("group/val3", "test") +print (load_data("group/val1") +) +print (load_data("group/val2") +) +print (load_data("group/val3") +) + + diff --git a/script/51_Parallelization.js b/script/51_Parallelization.js new file mode 100755 index 0000000..f37353c --- /dev/null +++ b/script/51_Parallelization.js @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +//// Using Parallelization API to execute tasks concurrently +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Simple parallization +function task1(){ + m1.moveRel(1.0) + return m1.getPosition() +} + +function task2(){ + m2.moveRel(1.0) + return m1.getPosition() +} + +function task3(){ + return ai1.read() +} + +ret = parallelize(task1, task2, task3) +print (ret ) + + +//Fork amd join +ret = fork(task1, task2, task3) +print (ai1.read() ) +ret = join(ret) +print (ret ) + + + +//Functions with parameters +function moveRelative(motor, step){ + motor.moveRel(step) + return motor.getPosition() +} + +ret = parallelize([moveRelative,[m1,-2]], [moveRelative,[m2,-2]]) +print (ret ) + + +//Exception in parallel task is thrown back to script +try{ + parallelize([moveRelative,[ai1,1]], [moveRelative,[ai2,1]]) +}catch (ex){ + print ("Ok, caught exception:" ) + print(ex) +} + + + + + diff --git a/script/52_ParametersAndReturn.js b/script/52_ParametersAndReturn.js new file mode 100755 index 0000000..9866611 --- /dev/null +++ b/script/52_ParametersAndReturn.js @@ -0,0 +1,21 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Setting script parameters and return value +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Providing a map of global variables +//run ("52_ParametersAndReturn", {"start":10.0, "end":50.0, "step":40}) + + +//Setting sys.argv: +//run ("52_ParametersAndReturn", [10.0, 50.0, 2.0]) + +//In this case the parameters would be parsed as: +//start = argv[0] +//end = argv[1] +//step = argv[2] + + +a= lscan(ao1, ai1, start, end, step, 0.1) +a.getReadable(0) +set_return(a.getReadable(0)) \ No newline at end of file diff --git a/script/53_DirectEpicsAccess.js b/script/53_DirectEpicsAccess.js new file mode 100755 index 0000000..4d2a4e2 --- /dev/null +++ b/script/53_DirectEpicsAccess.js @@ -0,0 +1,68 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// EPICS direct channel access. +// EPICS devices implemented are included in PShell, package ch.psi.pshell.epics. +// However direct channel access builtin functions are available. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +channel_name = "TESTIOC:TESTCALCOUT:Output" + +//reading/writing to a channel +print (caget(channel_name)) +caput(channel_name, 0.0) +//Put with no wait +caput(channel_name, 0.0) +print (caget(channel_name)) + +//waiting for a channel value +cawait(channel_name, 0.0, timeout = 10.0) + +//If many IO it is better to keep the same CA connection +channel = create_channel(channel_name, 'd') +for (var i=0; i<10; i++){ + print (channel.get() +) +} +channel.close() + + +//The create_channel_device method return a device implements Readable and Writable and therefore can be used in scans +channel = create_channel_device(channel_name, 'd', null, "My Channel") +lscan(channel, ai2, 0, 10, 0.1) +channel.close() + + +//Or else we can use a Device +ChannelDouble= Java.type('ch.psi.pshell.epics.ChannelDouble') +channel = new ChannelDouble("My Channel", channel_name) +channel.initialize() +lscan(channel, ai2, 0, 10, 0.1) +channel.close() + + + +//Creating a table reading set of channels for each scan step. +attrs_dataset = null +attrs_names = ["TESTIOC:TESTCALCOUT:Input", + "TESTIOC:TESTCALCOUT:Output", + "TESTIOC:TESTSINUS:SinCalc", + "TESTIOC:TESTWF2:MyWF"] +attrs_types = ["d", "d", "d", "[d"] +attrs_lenghts = [0,0,0,10] + + +function AfterReadout(rec){ + if (attrs_dataset == null){ + attrs_dataset = get_exec_pars().group + "attributes" + create_table(attrs_dataset, attrs_names, attrs_types, attrs_lenghts) + } + record = [] + for (var i=0; i4)){ + return false + } + return true + }, +} + + +/* +//Motor group +var MyInterlock2 = Java.extend(Interlock) +var interlock2 = new MyInterlock2( [mg1, p1]) { + check: function (pos) { + print(pos) + mg=pos[0] + p=pos[1] + print(to_array(mg)) + if ((p<500) && (mg[0]<5) && (mg[1]>4)){ + return false + } + return true + }, +} +*/ + +/* +//Discrete Positioner +var MyInterlock3 = Java.extend(Interlock) +interlock3 = new MyInterlock3( [dp1, p1]) { + check: function (pos) { + dp=pos[0] + p=pos[1] + print ("DP " + dp) + print ("P " + p) + if ((p<500) && (dp=="Out")){ + return false + } + return true + }, +} +*/ diff --git a/script/56_ExecutingCPython.js b/script/56_ExecutingCPython.js new file mode 100755 index 0000000..1b7a99b --- /dev/null +++ b/script/56_ExecutingCPython.js @@ -0,0 +1,9 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Executing CPython in external process. +// Requires cpython.py to be put in the scripts folder, or else in the python path. +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +//Executing a module +ret = exec_cpython("cpython", []) +print (ret ) diff --git a/script/57_EmbeddingCPython.js b/script/57_EmbeddingCPython.js new file mode 100755 index 0000000..87ad5a3 --- /dev/null +++ b/script/57_EmbeddingCPython.js @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Embedding CPython with JEP: USe of numpy, pandas and matpplotlib in the same process. +// Requires cpython.py to be put in the scripts folder, or else in the python path. +/////////////////////////////////////////////////////////////////////////////////////////////////// + +//Requirements to the use of JEP: +// 1- PYTHONHOME is set to the python interpreter home folder. +// 2- jep*.so is in LD_LIBRARY_PATH (e.g. in extensions folder ) +// 3- jep*.jar is in the CLASS_PATH (e.g. in extensions folder ) +//JEP works with python 2 and 3. + +run("jeputils") + +//In order to use matplotlib we must set Tk backend before importing plt +eval_jep("import matplotlib") +eval_jep("matplotlib.use('TkAgg')") + + +//Evaluating statements +eval_jep("import sys") +eval_jep("import numpy as np") +eval_jep("a = np.array((100, 100), )") +eval_jep("print (a)") + +eval_jep("\ +def stderr(str): \n\ + if sys.version_info < (3,0) :\n\ + exec(\"print >> sys.stderr, '\" + str + \"'\") \n\ + else: \n\ + exec(\"print ('\" + str + \"', file=sys.stderr)\") \n\ +") + +eval_jep("stderr('Testing stderr')") + + +//Accessing a numpy array +a=get_jep("a") +print (a.getData() +) +print (a.getDimensions() +) + + +//Setting numpy array with scan data +steps = [3,4] +dims = [steps[0]+1 , steps[1]+1 ] +r = ascan([m1,m2], [ai1], [0.0,0.0], [0.2,0.2], steps) +data = r.getReadable(0) +a = new_numpy_array(data, dims,'d') +print (to_array(a.getDimensions())) +print (to_array(a.getData())) +plot( Convert.reshape(a.getData(),a.getDimensions()),null, null, null, "Scan Data") + + +//Calling a module function +b = call_jep("numpy", "transpose", [a,]) +print (to_array(b.getDimensions())) +print (to_array(b.getData())) +plot( Convert.reshape(b.getData(),b.getDimensions()),null, null, null, title="Transposed") + + + + +//More calculations calling numpy +a = call_jep("numpy", "ones", [[400,200],'d']) +for (var i=0; i<100; i++){ + b = call_jep("numpy", "ones", [[400,200],'d']) + a = call_jep("numpy", "add", [a,b]) + s = call_jep("numpy", "sum", [a,]) + print (a.getData()[0] + " " + s +) + sleep(0.001) +} + +//Calling a local function +data = [1,2,3,4,5,6,7,8,9,0] +dims = [2,5] +array = new_numpy_array(data, dims,'d') //Auxiliary function to create numpy arrays from lists or java arrays. +ret = call_jep("cpython", "calc", [array,]) +print (ret.getDimensions() + " - " + ret.getData() +) + + +//Testing pandas +ret = call_jep("cpython", "test_pandas") + + +//Testing tkinter +ret = call_jep("cpython", "test_tkinter") + + +//Testing matplotlib +ret = call_jep("cpython", "test_matplotlib", [0.1, 4, 0.4]) + + +//Running a modole +run_jep("cpython") + diff --git a/script/60_Fitting.js b/script/60_Fitting.js new file mode 100755 index 0000000..5e26ed0 --- /dev/null +++ b/script/60_Fitting.js @@ -0,0 +1,68 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Function fitting and peak search with mathutils.py +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +run("mathutils") + + +start = 0 +end = 10 +step_size = 0.1 + +result= lscan(ao1,ai1,start,end,[step_size,],0.01) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +function get_function_data(func, start, end, resolution){ + ret = [] + for (var x=start; x<=end; x+=resolution){ + fit_polinomial.push(func.value(x)) + } +} + + +pars_polynomial = fit_polynomial(readable, positions, 6) + //(a0, a1, a2, a3, a4, a5, a6) +fitted_polynomial_function = new PolynomialFunction(pars_polynomial) +print (pars_polynomial) + +pars_gaussian = fit_gaussian(readable, positions) +normalization = pars_gaussian[0] +mean_val = pars_gaussian[1] +sigma = pars_gaussian [2] +fitted_gaussian_function = new Gaussian(normalization, mean_val, sigma) +print (normalization + " " + mean_val + " " + sigma) + +pars_harmonic= fit_harmonic(readable, positions) +amplitude = pars_harmonic[0] +angular_frequency = pars_harmonic[1] +phase = pars_harmonic[2] +fitted_harmonic_function = new HarmonicOscillator(amplitude, angular_frequency, phase) +print (amplitude+ " " + angular_frequency+ " " + phase) + + +resolution = step_size/100 +fit_polinomial = [] +fit_gaussian = [] +fit_harmonic = [] +for (var x=start; x<=end; x+=resolution){ + fit_polinomial.push(fitted_polynomial_function.value(x)) + fit_gaussian.push(fitted_gaussian_function.value(x)) + fit_harmonic.push(fitted_harmonic_function.value(x)) +} +x = range(start, end+resolution, resolution) + + +peaks = calculate_peaks(fitted_polynomial_function, start, end) + +plots = plot([readable, fit_polinomial, fit_gaussian, fit_harmonic] , + ["data", "polinomial", "gaussian", "harmonic"], xdata = [positions,x,x,x], ydata=undefined, title="Data") + +for (var p in peaks){ + print ("Max: " + p) + plots[0].addMarker(p, null, "Max=" + Math.round(p,2), Color.LIGHT_GRAY) +} + +plots[0].addMarker(mean_val, null, "Mean=" + Math.round(mean_val,2), Color.LIGHT_GRAY) \ No newline at end of file diff --git a/script/61_MultipleGaussianFit.js b/script/61_MultipleGaussianFit.js new file mode 100755 index 0000000..6909617 --- /dev/null +++ b/script/61_MultipleGaussianFit.js @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Multiple Gaussians peak search with mathutils.py +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +run("mathutils") + +start = 0 +end = 50 +step_size = 0.2 + +result= lscan(ao1,ai1,start,end,[step_size,]) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +min = Math.min.apply(null, readable) +max = Math.max.apply(null, readable) + +threshold = (min + max)/2 +min_peak_distance = 5.0 + +peaks = estimate_peak_indexes(readable, positions, threshold, min_peak_distance) +print ("Peak indexes: " + peaks) +print ("Peak x: " + peaks.map(function(x) {return positions[x]})) +print ("Peak y: " + peaks.map(function(x) {return readable[x]})) + +gaussians = fit_gaussians(readable, positions, peaks) + +plots = plot([readable],["sin"],[positions], undefined, title="Data" ) +for (var i=0; i< peaks.length; i++){ + peak = peaks[i] + pars_gaussian = gaussians[i] + normalization = pars_gaussian[0] + mean_val = pars_gaussian[1] + sigma = pars_gaussian [2] + if (Math.abs(mean_val - positions[peak]) < min_peak_distance){ + print ("Peak -> " + mean_val) + plots[0].addMarker(mean_val, null, "N="+ Math.round(normalization,2), new Color(210,0,0)) + }else { + print ("Invalid gaussian fit: " + mean_val) + } +} \ No newline at end of file diff --git a/script/62_FFT.js b/script/62_FFT.js new file mode 100755 index 0000000..5d0e973 --- /dev/null +++ b/script/62_FFT.js @@ -0,0 +1,30 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Demonstrate the use of fft function in mathutils.py +/////////////////////////////////////////////////////////////////////////////////////////////////// + +run("mathutils") + + + +//The signal is composed by 3 sinusoids (100Hz, 200Hz, 400Hz) and a background noise (a sin waveform is A.sin(2.pi.f.t)) +function signal_generator(t){ + return Math.sin(100*2*Math.PI*t) + 0.5 * Math.sin(200*2*Math.PI*t) + 0.25 * Math.sin(400*2*Math.PI*t) + 0.5* Math.random() +} + +sampling_frequency = 1024.0 +number_of_samples = 1024 + + +time_vector = range(0, number_of_samples, 1).map(function(x) {return x / sampling_frequency}) +signal = time_vector.map(function(x) {return signal_generator(x)}) +tranform = fft(signal) + +two_side_spectrum = get_modulus(tranform).map(function(x) {return x / number_of_samples}) +spectrum = two_side_spectrum.slice(1,two_side_spectrum.length/2 + 1).map(function(x) {return (x * x)}) +spectrum.splice(0,0,two_side_spectrum[0]) + +number_of_samples = tranform.length // Signal may have been padded to next power of two +freq_vector = range(0, spectrum.length , 1).map(function(x) {return x * sampling_frequency / parseFloat(number_of_samples)}) + +plot([signal,spectrum], ["signal", "spectrum"],[time_vector, freq_vector]) + \ No newline at end of file diff --git a/script/63_OnlineSpectrumAnalyser.js b/script/63_OnlineSpectrumAnalyser.js new file mode 100755 index 0000000..2111dbb --- /dev/null +++ b/script/63_OnlineSpectrumAnalyser.js @@ -0,0 +1,50 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Create an online spectrum analyser uysing mathutils.py +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +run("mathutils") + +function plot_spectrum(signal, sampling_freq){ + if (!is_defined(plots)) plots = null + signal = to_array(signal) + number_of_samples = signal.length + time_vector = range(0, number_of_samples, 1).map(function(x) {return x / sampling_freq}) + tranform = fft(signal) + two_side_spectrum = get_modulus(tranform).map(function(x) {return x / number_of_samples}) + spectrum = two_side_spectrum.slice(1,two_side_spectrum.length/2 + 1).map(function(x) {return x * x}) + spectrum.splice(0,0,two_side_spectrum[0]) + number_of_samples = tranform.length // Signal may have been padded to next power of two + freq_vector = range(0, spectrum.length , 1).map(function(x) {return x * sampling_freq / parseFloat(number_of_samples)}) + if (plots == null){ + plots = plot([signal,spectrum], ["signal", "spectrum"],[time_vector, freq_vector], undefined, title = "Spectrum") + plots[0].getAxis(AxisId.Y).setRange(-1.5,2.5) + plots[1].getAxis(AxisId.Y).setRange(0.0,1.1) + } else { + plots[0].getSeries(0).setData(time_vector,signal) + plots[1].getSeries(0).setData(freq_vector,spectrum) + } + return plots +} + +function get_sample(samples, sampling_freq){ + return range(0,samples,1).map(function(t) {return Math.sin(200*2*Math.PI*t/sampling_freq) + Math.random()}) + //Simple example sampling a device: + //set_exec_pars(undefined, undefined, undefined, undefined, persist=false) + //set_preference(Preference.PLOT_DISABLED, true) + //set_preference(Preference.TABLE_DISABLED, true) + //return tscan(ai1, samples, 1/sampling_freq).getReadable(0) +} + +plots = null +samples = 1024 +sampling_freq = 1024.0 + +while(true){ + signal = get_sample(samples, sampling_freq) + plots = plot_spectrum(signal, sampling_freq, plots) + sleep(0.1) + if (plots[0].displayable == false){ + break + } +} diff --git a/script/64_NumericalAnalysis.js b/script/64_NumericalAnalysis.js new file mode 100755 index 0000000..74b0138 --- /dev/null +++ b/script/64_NumericalAnalysis.js @@ -0,0 +1,39 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Use of numerical analysis functions in mathutils +/////////////////////////////////////////////////////////////////////////////////////////////////// + +run("mathutils") + +//interpolation +var fy = [0, 1, 4,10,50,25,12, 5, 3, 0] +var fx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +types = ["linear", "cubic", "akima", "loess", "neville", "newton"] +functions = types.map(function(t) {return interpolate(fy,fx,t)}) + +plot_x = range (0,9,0.01) +values = functions.map(function(f) {return get_values(f,plot_x)}) +plots=plot(values,types,plot_x) + +//derivative +for (var i=0; i0){ + get_plots(title)[0].clear() +} + +for (var step=1; step<=5; step++){ + x=[] + y=[] + for (var i=0; i<=50 ; i++){ + x.push(Math.random() * 100 / step) + y.push(Math.random() * 100/ step) + } + add_convex_hull_plot (title, x,y,"Scan " + step) +} + diff --git a/script/66_WeightedPolynomialFit.js b/script/66_WeightedPolynomialFit.js new file mode 100755 index 0000000..0325a40 --- /dev/null +++ b/script/66_WeightedPolynomialFit.js @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Example if fitting with weights +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +run("mathutils") +run("plotutils") + + +fx = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] +fy = [36.0, 66.0, 121.0, 183.0, 263.0, 365.0, 473.0, 603.0, 753.0, 917.0] +num_samples = fx.length + +p=plot(fy, "Observed Data", xdata=fx)[0] +p.setLegendVisible(true) + +pars_polynomial= fit_polynomial(fy, fx, 1, null) +func = new PolynomialFunction(pars_polynomial) +plot_function(p, func, "1st order", fx) + +var w = []; size=num_samples; while(size--) w.push(1.0); +w[5]=20.0 +pars_polynomial= fit_polynomial(fy, fx, 1, null, w) +func = new PolynomialFunction(pars_polynomial) +plot_function(p, func, "1st order Weighted: " + w , fx) + +pars_polynomial= fit_polynomial(fy, fx, 2, null, w) +func = new PolynomialFunction(pars_polynomial) +plot_function(p, func, "2nd order" + w , fx) +for (var xp in fx){ + print (fx[xp] + " " + poly(fx[xp], pars_polynomial)) +} + +print ("") +w = [ 10.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 10.0] +pars_polynomial= fit_polynomial(fy, fx, 2, null, w) +func = new PolynomialFunction(pars_polynomial) +plot_function(p, func, "2n order Weighted: " + w , fx) +for (var xp in fx){ + print (fx[xp] + " " + poly(fx[xp], pars_polynomial)) +} diff --git a/script/67_LeastSquares.js b/script/67_LeastSquares.js new file mode 100755 index 0000000..6a4f00c --- /dev/null +++ b/script/67_LeastSquares.js @@ -0,0 +1,122 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Example of least squares optimization +// http://commons.apache.org/proper/commons-math/userguide/leastsquares.html +/////////////////////////////////////////////////////////////////////////////////////////////////// + +run("mathutils") +run("plotutils") + + +plots = plot([null, null], [null, null]) +p1=plots[0] +p2=plots[1] + +/////////////////////////////////////////////////////////////////////////////////////////////////// +//Fitting the quadratic function f(x) = a x2 + b x + c +/////////////////////////////////////////////////////////////////////////////////////////////////// +var fx = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] +var fy = [36.0, 66.0, 121.0, 183.0, 263.0, 365.0, 473.0, 603.0, 753.0, 917.0] +num_samples = fx.length +weigths = []; size=num_samples; while(size--) weigths.push(1.0) + +p1.getSeries(0).setData(fx, fy) +p1.getSeries(0) + + +var Model = Java.extend(MultivariateJacobianFunction) +var model = new Model() { + value: function (variables) { + value = new ArrayRealVector(num_samples) + jacobian = new Array2DRowRealMatrix(num_samples, 3) + for (var i=0; i< num_samples; i++){ + a=variables.getEntry(0) + b=variables.getEntry(1) + c=variables.getEntry(2) + model = a*fx[i]*fx[i] + b*fx[i] + c + value.setEntry(i, model) + jacobian.setEntry(i, 0, fx[i]*fx[i]) // derivative with respect to p0 = a + jacobian.setEntry(i, 1, fx[i]) // derivative with respect to p1 = b + jacobian.setEntry(i, 2, 1.0) // derivative with respect to p2 = c + } + return new Pair(value, jacobian) + }, + } + +initial = [1.0, 1.0, 1.0] //parameters = a, b, c +target = fy.slice(0) //the target is to have all points at the positios + +ret = optimize_least_squares(model, target, initial, weigths) + +parameters = ret[0] +residuals = ret[1] +rms = ret[2] +evals = ret[3] +iters = ret[4] + +a = parameters[0] +b = parameters[1] +c = parameters[2] + +print ("A: " + a + " B: "+ b, " C: "+ c +) +print ("RMS: " + rms+ " evals: " + evals+ " iters: " + iters +) +for (var i=0; i " + str(mean_val) + plots[0].addMarker(mean_val, None, "N="+str(round(normalization,2)), Color(210,0,0)) + else: + print "Invalid gaussian fit: " + str(mean_val) diff --git a/script/HoloScan.py b/script/HoloScan.py new file mode 100755 index 0000000..612cb0c --- /dev/null +++ b/script/HoloScan.py @@ -0,0 +1,15 @@ +""" +Arguments: + +SENSORS (list) +PHI_RANGE (tuple (min, max)) +THETA_RANGE (tuple (min, max)) +STEPS (tuple (phi, theta)) +LATENCY (double) +RELATIVE (BOOLEAN) +""" + + +#set_preference(Preference.ENABLED_PLOTS, [phi, theta, scienta.dataMatrix, integration]) +set_preference(Preference.PLOT_TYPES, {integration:1}) +ascan((motor, motor2), SENSORS, (PHI_RANGE[0], THETA_RANGE[0]), (PHI_RANGE[1], THETA_RANGE[1]), STEPS, LATENCY, RELATIVE, before_read=trig_scienta) \ No newline at end of file diff --git a/script/HystScan.py b/script/HystScan.py new file mode 100755 index 0000000..0543e47 --- /dev/null +++ b/script/HystScan.py @@ -0,0 +1,157 @@ +#Script imported from: Fe_hyst_plus.xml + +#Parameters +START_FIELD = -0.2 +END_FIELD = 0.2 +ENERGIES = (707.90, 703.90) +RAMP_RATE = 2.0 +ENERGY_CHANGE_SLEEP = 0.5 + +#Pre-actions +#cawait('ACOAU-ACCU:OP-MODE', 'Light Available', type = 's') +#caput('X07MA-ID:MODE', 'CIRC +') +sleep(1.0) +#cawait('X07MA-ID:DONE', 'DONE', ype = 's') +#caput('X07MA-ID:ENERGY-OFFS', '-1.0') +#cawait('X07MA-ID:DONE', 'DONE', type = 's') +caputq('X07MA-PC:CSCALER.INPB', '1') +caputq('X07MA-PC-PS2:SET:DMD:RAMPRATE:TPM', RAMP_RATE) +#sleep(15.0) + +if len(ENERGIES) ==2: + dif_series = plot([],"Dif", title="Dif")[0].getSeries(0) +else: + dif_series = None + +set_preference(Preference.ENABLED_PLOTS, ['field', 'tey_norm', 'trans_norm']) +set_preference(Preference.PLOT_TYPES, {'tey_norm':1, 'trans_norm':1}) + +#scan = ManualScan(['field', 'Energy'], ['TEY', 'I0', 'trans', 'polarization', 'polAngle', 'temperature', 'RingCurrent', 'fieldAnalogX', 'tey_norm','trans_norm']) +scan = ManualScan(['field', 'Energy'], ['TEY', 'I0', 'trans', 'polarization', 'polAngle', 'temperature', 'RingCurrent', 'fieldAnalogX', 'tey_norm','trans_norm'], [0.0, ENERGIES[0]], [0.0, ENERGIES[-1]], [0, len(ENERGIES)-1]) +scan.start() + +#Stop condition +ramp_done = Channel('X07MA-PC-MAG:X:RAMP:DONE', type = 'i') + +#Creating channels: dimension 1 +#RegionPositioner field +#field = Channel('X07MA-PC:GO', type = 'd') +fieldReadback = Channel('X07MA-PC-PS2:STS:PMCURRENT', type = 'd') +#Creating channels: dimension 2 +#ArrayPositioner Energy +Energy = sim_energy #Channel('X07MA-PHS-E:GO.A', type = 'd') +EnergyReadback = sim_energy_readback # Channel('X07MA-PGM:CERBK', type = 'd') +#ScalarDetector TEY +TEY = Channel('X07MA-ES1-AI:SIGNAL0', type = 'd') +#ScalarDetector I0 +I0 = Channel('X07MA-ES1-AI:SIGNAL1', type = 'd') +#ScalarDetector trans +trans = Channel('X07MA-ES1-AI:SIGNAL2', type = 'd') +#ScalarDetector polarization +#polarization = Channel('X07MA-ID:MODE', type = 'd') +#ScalarDetector polAngle +#polAngle = Channel('X07MA-ID:ALPHA', type = 'd') +#ScalarDetector temperature +temperature = Channel('X07MA-PC-TC:STS:T1', type = 'd') +#ScalarDetector RingCurrent +RingCurrent = Channel('ARIDI-PCT:CURRENT', type = 'd') +#ScalarDetector fieldAnalogX +fieldAnalogX = Channel('X07MA-ES1-AI:SIGNAL4', type = 'd') + + +print "Waiting for start field" +""" +#WORKAROUND TO BUG IN DRIVER +if abs(fieldReadback.get() - START_FIELD) < 0.005: + caput('X07MA-PC-PS2:M:GO.A', START_FIELD + 0.01) +caput('X07MA-PC-PS2:M:GO.A', START_FIELD) +#caputq('X07MA-PC-PS2:M:GO.A', START_FIELD) +""" + +caput("X07MA-PC-MAG:X:DMD", START_FIELD) +caput("X07MA-PC-MAG:STARTRAMP.PROC", 1) +ramp_done.wait_for_value(1.0) +print "Set end field" +caput("X07MA-PC-MAG:X:DMD", END_FIELD) +caputq("X07MA-PC-MAG:STARTRAMP.PROC", 1) + + +index = 0 +while(True): + #ArrayPositioner Energy + for setpoint2 in ENERGIES: + Energy.put(setpoint2, timeout=None) # TODO: Set appropriate timeout + sleep( ENERGY_CHANGE_SLEEP ) # Settling time + + readback2 = EnergyReadback.get() + if abs(readback2 - setpoint2) > 0.1 : # TODO: Check accuracy + raise Exception('Actor Energy could not be set to the value ' + str(setpoint2)) + + #Detector field readback + field_readback = fieldReadback.get() + + #Detector TEY + detector1 = TEY.get() + #Detector I0 + detector2 = I0.get() + #Detector trans + detector3 = trans.get() + #Detector polarization + detector4 = sim_energy_readback.read() # polarization.get() + #Detector polAngle + detector5 = sim_energy_readback.read() #polAngle.get() + #Detector temperature + detector6 = temperature.get() + #Detector RingCurrent + detector7 = RingCurrent.get() + #Detector fieldAnalogX + detector8 = fieldAnalogX.get() + + + #Manipulation tey_norm + #Variable Mappings + + #TODO: Move, if needed, this import to the file header: import math + tey_norm = detector1/detector2 + + #Manipulation trans_norm + #Variable Mappings + + #TODO: Move, if needed, this import to the file header: import math + trans_norm = detector3/detector2 + + + if dif_series is not None: + if setpoint2 == ENERGIES[0]: + first = tey_norm + else: + dif = tey_norm-first + dif_series.appendData(field_readback,dif) + print [field_readback, setpoint2] + print [field_readback, readback2] + print [detector1, detector2, detector3, detector4, detector5, detector6, detector7, detector8, tey_norm, trans_norm] + scan.append ([field_readback, setpoint2], [field_readback, readback2], [detector1, detector2, detector3, detector4, detector5, detector6, detector7, detector8, tey_norm, trans_norm]) + + + print "Field = " + str(fieldReadback.get()) + if ramp_done.get() == 1: #If not ramping + print "Not ramping, breaking execution" + break + index = index+1 + +#Closing channels +Energy.close() +EnergyReadback.close() +TEY.close() +I0.close() +trans.close() +#polarization.close() +#polAngle.close() +temperature.close() +RingCurrent.close() +fieldAnalogX.close() +#field.close() +fieldReadback.close() +ramp_done.close() + +scan.end() diff --git a/script/HystScan2.py b/script/HystScan2.py new file mode 100755 index 0000000..8e4d6da --- /dev/null +++ b/script/HystScan2.py @@ -0,0 +1,50 @@ +#Script imported from: Fe_hyst_plus.xml + +#Parameters +START_FIELD = -1.0 +END_FIELD = 1.0 +ENERGIES = (707.90, 703.90, 700.90) +RAMP_RATE = 2.0 + + +if len(ENERGIES) ==2: + dif_series = plot([],"Dif", title="Dif")[0].getSeries(0) +else: + dif_series = None + +set_preference(Preference.ENABLED_PLOTS, ['field', 'tey_norm', 'trans_norm']) +set_preference(Preference.PLOT_TYPES, {'tey_norm':1, 'trans_norm':1}) + +scan = ManualScan(['field', 'Energy'], ['tey_norm','trans_norm'], [0.0, ENERGIES[0]], [0.0, ENERGIES[-1]], [0, len(ENERGIES)-1]) +scan.start() + +#Stop condition + + + +index = 0 +while(True): + #Dimension 2 + #ArrayPositioner Energy + for setpoint2 in ENERGIES: + out.write(setpoint2) # TODO: Set appropriate timeout + readback2 = out.read() + + tey_norm = sin.read() + if dif_series is not None: + if setpoint2 == ENERGIES[0]: + first = tey_norm + else: + dif = tey_norm-first + dif_series.appendData(index,dif) + + scan.append ([index, setpoint2], [index, readback2], [tey_norm, sinp.read()]) + + + index = index+1 + if index >1000: + break + + + +scan.end() \ No newline at end of file diff --git a/script/ImageStats.py b/script/ImageStats.py new file mode 100755 index 0000000..33b7df0 --- /dev/null +++ b/script/ImageStats.py @@ -0,0 +1,38 @@ +from ijutils import * +from mathutils import fit_gaussian +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Pen as Pen + + +image = img +image = tst + +def wait_next(): + camera.waitNext(250) + +def get_centroid(): + bi = image.getImage() + op = show_panel(bi, "Original") + if bi is None: + return None + ip = load_image(bi) + grayscale(ip) + invert(ip) + gaussian_blur(ip) + auto_threshold(ip) + + #binary_erode(ip) + show_panel(ip.getBufferedImage(), "Image") + (results,output_img)=analyse_particles(ip, 1000,20000, print_table=True) + op.clearOverlays() + show_panel(output_img.getBufferedImage(), "Outlines") + if results.size()>0: + print results + centroid = (results.getValue("XM",0), results.getValue("YM",0)) + ov = Crosshairs(Pen(java.awt.Color.ORANGE), java.awt.Point(int(centroid[0]),int(centroid[1])), java.awt.Dimension(15,15)) + op.addOverlay(ov) + return centroid + + + +get_centroid() \ No newline at end of file diff --git a/script/InitialScan.py b/script/InitialScan.py new file mode 100755 index 0000000..8a1159d --- /dev/null +++ b/script/InitialScan.py @@ -0,0 +1,4 @@ +ret = lscan(out,inp,0,100,[1.0,],0.01) + + +set_return (ret.getReadable(0).toArray()) \ No newline at end of file diff --git a/script/Inventory.py b/script/Inventory.py new file mode 100755 index 0000000..c87c793 --- /dev/null +++ b/script/Inventory.py @@ -0,0 +1,152 @@ +import requests + +def inventory_request(url, attributes): + """ + Thin wrapper for PSI Inventory system (I4). This wrapper does nothing + more than sanitises output (decompresses dict) and takes care of dict + to json conversion for attributes and json to dict conversion for + response. + + Use: https://inventory.psi.ch/#action=Introspection for details + + + Example usage: + + Query: + + query = {"query": [ + {"Field": "Holy List Name", "Operator": "Is", "Value": holy_name}, + {"Field": 'Type', "Operator": "Is", "Value": type} + + ], "columns": ["Label"]} + attr = {"search": query} + + r = inventory_request('https://inventory.psi.ch/DataAccess.asmx/FindObjects', attr) + + Fetch atributes for part: + + attributes = inventory_request('https://inventory.psi.ch/DataAccess.asmx/GetPartAttributes', {'psiLabel': part_id}) + + + + + :param url: Inventory URL endpoint + :param attributes: Python dict of attributes + :return: + """ + r = requests.post(url, json=attributes) + + if not r.ok: + raise ConnectionError("Inventory returned error: ", r.json()) + + return r.json()['d'] + + +def find_partid_by_holy(holy_name, type="DSCR"): + """ + :param holy_name: + :param type: + :return: Returns first partId that matches holy_name and type + """ + query = {"query": [ + {"Field": "Holy List Name", "Operator": "Is", "Value": holy_name}, + {"Field": 'Type', "Operator": "Is", "Value": type} + + ], "columns": ["Label"]} + attr = {"search": query} + + r = inventory_request('https://inventory.psi.ch/DataAccess.asmx/FindObjects', attr) + try: + id = r['Rows'][0][0] + except: + return None + + return id + + +def find_all_by_type(type="DSCR", column = "Holy List Name"): + """ + :param type: Type to match + :param column: Label, Holy List Name, ... + :return: List + """ + + query = {"query": [ + {"Field": 'Type', "Operator": "Is", "Value": type} + + ], "columns": [column]} + attr = {"search": query} + + r = inventory_request('https://inventory.psi.ch/DataAccess.asmx/FindObjects', attr) + + rows = [] + for i in r['Rows']: + rows.append(i[0]) + + return rows + +def get_part_attributes_from_inventory(part_label = None, holy_name = None): + if holy_name: + part_label = find_partid_by_holy(holy_name, "DSCR") + if not part_label: raise RuntimeError("Could not find inventory part for >>{}<<".format(holy_name)) + + return inventory_request('https://inventory.psi.ch/DataAccess.asmx/GetPartAttributes', {'psiLabel': part_label}) + +def get_logbook_from_inventory(part_label = None, holy_name = None): + import re + attributes = get_part_attributes_from_inventory(part_label, holy_name) + + elog_link = None + for a in attributes: + if a['Name'] == 'Elog': + try: + elog_link = a['Value'] + elog_link = re.findall('http(?:s|)://[^\s]*') + if elog_link: + elog_link = elog_link[0] + else: + elog_link = None + + except TypeError: + elog_link = None + + return elog_link + +def get_calib_from_invetory(part_label = None, holy_name = None): + horizontal_dist = 0.0 + vertical_dist = 0.0 + horizontal_tilt = 0.0 + vertical_tilt = 0.0 + + attributes = get_part_attributes_from_inventory(part_label, holy_name) + + for a in attributes: + if a['Name'] == 'Crystal angle in x (e-beam system) [deg]': + try: + horizontal_tilt = float(a['Value']) + except TypeError: + pass + + if a['Name'] == 'Crystal angle in y (e-beam system) [deg]': + try: + vertical_tilt = float(a['Value']) + except TypeError: + pass + + if a['Name'] == 'Mark distance in x (e-beam system) [mm]': + try: + horizontal_dist = float(a['Value']) * 1e3 + except TypeError: + pass + + if a['Name'] == 'Mark distance in y (e-beam system) [mm]': + try: + vertical_dist = float(a['Value']) * 1e3 + except TypeError: + pass + + return horizontal_dist, vertical_dist, horizontal_tilt, vertical_tilt + + + +print get_calib_from_invetory(None, "SINEG01-DSCR190") diff --git a/script/K_spacing_prototype.xml b/script/K_spacing_prototype.xml new file mode 100755 index 0000000..d3d6ca3 --- /dev/null +++ b/script/K_spacing_prototype.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + 3990.0 + 3995.0 + 1.0 + + + 1.0 + 14.0 + 1.0 + + + + + + + + + 3990.0 + 3995.0 + 1.0 + + + + + + 0.0 + 10.0 + 1.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/script/Laser_gun_alignment.py b/script/Laser_gun_alignment.py new file mode 100755 index 0000000..3a8c339 --- /dev/null +++ b/script/Laser_gun_alignment.py @@ -0,0 +1,134 @@ +# Tool to align the solenoid on the gun. +# S. Bettoni, A. Gobbo, D. Voulot +# 06/06/2016 +#Code ok with the GUI + +# Procedure: + # switch off all the magnets between the gun solenoid and the screen or BPM used for the measurement + # change the current of the gun soleoid + # look at the centroid position (BPM or screen) downstream of the gun. + +import datetime + +mode = "camtool" # "camtool", "bpm" or "direct" +camera_name = "simulation" + + +def laser_on(): + print "Laser On" + +def laser_off(): + print "Laser Off" + +def is_laser_on(): + return False + +def switch_off_magnets(magnets = None): + print "switch_off_magnets" + + + +gun_phase = cv + + +if get_exec_pars().source == CommandSource.ui: + phi1= 95.0 + phi2 = 100.0 + dphi = 0.5 + settling_time = 0.5 + plot_image = False + number_images = 5 + use_background = False + multiple_background = False + number_backgrounds = 5 + do_elog = False + centroid_excursion_plot = True +else: + centroid_excursion_plot = False + +#check_camtool() + +laser_was_on = is_laser_on() +original_phase = gun_phase.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 + +plot_name = datetime.datetime.fromtimestamp(time.time()).strftime('%H%M%S') + +if mode == "camtool": + if (camtool.getCurrentCamera() != camera_name) or (camtool.getPipelinePars()["background_subtration"] != use_background): + camtool.start(camera_name, None, use_background, None, None, None) + setBackgroundSubtraction + if use_background: + laser_off() + if not multiple_background: + camtool.grabBackground(None, number_backgrounds) +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)) + +#switch_off_magnets() + +# add here gun phase setting see wiki page + +def before_sample(): + if multiple_background: + camtool.grabBackground(None, number_backgrounds) + laser_on() + if mode != "camtool": + image_stats.update() + + +def after_sample(): + if multiple_background: + laser_off() + +r = None +if not multiple_background: + laser_on() + +try: + if mode != "camtool": + sensors = [image_stats.com_x_mean, image_stats.com_y_mean, image_stats.com_x_stdev, image_stats.com_y_stdev] + else: + sensors = [CamtoolValue("gr_x_fit_mean"), CamtoolValue("gr_y_fit_mean"), CamtoolValue("gr_x_fit_standard_deviation"), CamtoolValue("gr_y_fit_standard_deviation")] + if plot_image and (mode == "camtool"): + sensors.append(CamtoolImage()) + r = lscan(gun_phase, sensors , phi1, phi2, dphi, settling_time, before_read = before_sample, after_read = after_sample) + #tscan(sensors, 10, 1.0, before_read = before_sample, after_read = after_sample) +finally: + pass + +gun_phase.write(original_phase) +if laser_was_on: + laser_on() +else: + laser_off() + +# take the result of the scan and generate convex hull plot +if centroid_excursion_plot: + (hx,hy)=add_convex_hull_plot ("Centroid excursion", r.getReadable(0),r.getReadable(1), plot_name) +else: + (hx,hy)= convex_hull(x=r.getReadable(0), y=r.getReadable(1)) + hx.append(hx[0]); hy.append(hy[0]) + +""" +# save the entry in the logbook +gsa_log_msg = "Data file: " + get_exec_pars().path +gsa_log_msg = gsa_log_msg + "\nImages: " + str(number_images) + " Background: enabled=" + str(use_background) + " multiple=" + str(multiple_background) + " number=" + str(number_backgrounds) +gsa_log_msg = gsa_log_msg + "\nPhase range: " + str(phi1) + " to " + str(phi2) +gsa_log_msg = gsa_log_msg + "\nLaser position on cathod: " + str(caget("SLG-LCAM-C103:FIT-XPOS")) + "/" + str(caget("SLG-LCAM-C103:FIT-YPOS")) +gsa_log_msg = gsa_log_msg + "\n\n" + r.print() +if do_elog: + elog("Laser alignment with phase scan", gsa_log_msg , get_plot_snapshots()) +""" +set_return([r, hx, hy]) + + + + diff --git a/script/ManipulatorScan.py b/script/ManipulatorScan.py new file mode 100755 index 0000000..16d7e46 --- /dev/null +++ b/script/ManipulatorScan.py @@ -0,0 +1,13 @@ +""" +Arguments: + +MOTOR (device) +SENSORS (list) +RANGE (tuple (min, max)) +STEPS (int or tuple) +LATENCY (double) +RELATIVE (BOOLEAN) +""" + +set_preference(Preference.PLOT_TYPES,{'integration':1}); +lscan(MOTOR, SENSORS, RANGE[0], RANGE[1], STEPS, LATENCY, RELATIVE, before_read=trig_scienta) \ No newline at end of file diff --git a/script/Metadata.py b/script/Metadata.py new file mode 100755 index 0000000..19afbc3 --- /dev/null +++ b/script/Metadata.py @@ -0,0 +1,15 @@ +################################################################################################### +# Demonstrate adding attributs to scan groups and datasets. +################################################################################################### + + +#Execute the scan: 200 steps, a1 from 0 to 40 +a= lscan(ao1, (ai1,ai2), 0, 40, 10, 0.01) + + +#Setting attributes to the scan group +path = get_exec_pars().scanPath +set_attribute(path, "User", "Mr. Black") +set_attribute(path, "Temperature", 38.0) +set_attribute(path, "Test Mode", True) + diff --git a/script/MonitorScan.py b/script/MonitorScan.py new file mode 100755 index 0000000..617d28e --- /dev/null +++ b/script/MonitorScan.py @@ -0,0 +1,18 @@ +################################################################################################### +# Demonstrate the use of Monitor Scan: sampling based on device change event +################################################################################################### + +set_device_alias(sc1, None) +setup_plotting( line_plots =[sc1] ) + + +#Execute the scan: 50 samples +r1 = mscan(sc1, [sc1], 50) + +#Execute the scan: 50 samples, with a timeout of 2s, including a second device +r2 = mscan(sc1, [sc1, sin], 50, 2.0) + +#Execute the scan: sampling for 5s, an undefined number of sample +#The second device is cached so the scan is entirely asynchronous (the trigger device is always cached). +r3 = mscan(sc1, [sc1, sin.cache], -1, 5.0) + diff --git a/script/MultiPassAndZigzag.py b/script/MultiPassAndZigzag.py new file mode 100755 index 0000000..0b022d8 --- /dev/null +++ b/script/MultiPassAndZigzag.py @@ -0,0 +1,13 @@ +################################################################################################### +# Multi-pass and zigzag scans +################################################################################################### + + +#Linear with 2 passes +a= lscan(m1, (ai1,wf1), -0.2, 0.2, 10, relative = True, passes = 4) + +#Linear with 4 passes and zigzag +a= lscan(m1, (ai1,wf1), -0.2, 0.2, 10, relative = True, passes = 4, zigzag = True) + +#Multi-dimentional zigzag +a = ascan ([m1,m2], ai1, [0,0], [1, 1], [0.25,0.25], latency=0.001, zigzag=True) diff --git a/script/MultiplePlot.py b/script/MultiplePlot.py new file mode 100755 index 0000000..16b40e7 --- /dev/null +++ b/script/MultiplePlot.py @@ -0,0 +1,64 @@ +import random + + +def clear_plot(): + title = "test" + plots = get_plots(title = title) + if len(plots)>0: + plots[0].clear() + + +def add_plot(x,y, name=None, clear = False): + title = "test" + plots = get_plots(title = title) + p = None + if len(plots)==0: + p = plot(None,name=name, title = title)[0] + p.getAxis(p.AxisId.X).setRange(-50,150) + p.getAxis(p.AxisId.Y).setRange(-50,150) + p.setLegendVisible(True) + else: + p = plots[0] + if clear: + p.clear() + p.addSeries(LinePlotSeries(name)) + s = p.getSeries(name) + s.setLinesVisible(False) + s.setPointSize(3) + s.setData(x, y) + + #In the first time the plot shows, it takes some time for the color to be assigned + while s.color is None: + time.sleep(0.001) + + hull = LinePlotSeries(name + " Hull", s.color) + + """ + #Bounding box + x1,x2,y1,y2 = min(x), max(x), min(y), max(y) + (hx,hy) = ([x1,x2, x2, x1, x1], [y1, y1, y2, y2, y1]) + """ + + #Convex Hull + (hx,hy) = convex_hull(x=x, y=y) + hx.append(hx[0]) + hy.append(hy[0]) + + p.addSeries(hull) + hull.setLineWidth(2) + hull.setData(hx,hy) + hull.setColor(s.color) + + + +clear_plot() + +x=[] +y=[] +for step in range(1,5): + x=[] + y=[] + for i in range(20): + x.append(random.random() * 100 / step) + y.append(random.random() * 100/ step) + add_plot (x,y,"Step " + str(step)) \ No newline at end of file diff --git a/script/PhotonEnergy.py b/script/PhotonEnergy.py new file mode 100755 index 0000000..9a715a8 --- /dev/null +++ b/script/PhotonEnergy.py @@ -0,0 +1,38 @@ +""" +Arguments: + +VECTOR (Double[][], Scan vector: Eph,Elow,Ehigh or Eph,Ecenter) +SENSORS (list) +LATENCY (double) +MODE ('fixed' or 'swept') +TYPE ('CIS' or 'CFS') +STEP (double) +""" +EnergyDistribution = scienta.getSpectrum() +AngleDistribution = scienta.getSpectrum() +Scienta = scienta +Eph = out +if MODE == "swept": + Scienta.setAcquisitionMode(ch.psi.pshell.epics.Scienta.AcquisitionMode.Swept) +else: + Scienta.setAcquisitionMode(ch.psi.pshell.epics.Scienta.AcquisitionMode.Fixed) + +if len(VECTOR[0]) == 2: + #FIXED + Scienta.centerEnergy.write(VECTOR[0][1]) + writables = (Eph, Scienta.centerEnergy) +else: + #SWEPT + Scienta.lowEnergy.write(VECTOR[0][1]) + Scienta.highEnergy.write(VECTOR[0][2]) + writables = (Eph, Scienta.lowEnergy, Scienta.highEnergy) + +#adjust_sensors() +#set_adc_averaging() +#set_preference(Preference.PLOT_TYPES, {'Scienta spectrum':1}) + +try: + vscan(writables, SENSORS, VECTOR, True, LATENCY,False) +finally: + if ENDSCAN: + after_scan() diff --git a/script/Plot Styles.py b/script/Plot Styles.py new file mode 100755 index 0000000..de89bb5 --- /dev/null +++ b/script/Plot Styles.py @@ -0,0 +1,20 @@ +################################################################################################### +# Example changing plot styles +################################################################################################### + + +#Logarithmic scales +p = plot([10,500,1000,5000,1000], xdata = [0.1,1,10,100,1000, 10000])[0] +p.getAxis(p.AxisId.X).logarithmic = True +p.getAxis(p.AxisId.Y).setRange(1, 100000) +p.getAxis(p.AxisId.Y).logarithmic = True + + +#plot styles +data = [0,3,5,1,3,5,3,4,3,2,1,0] +[p1, p2, p3] = plot([data, data, data], ["normal", "step", "spline"]) +p2.setStyle(p1.Style.Step) +p3.setStyle(p1.Style.Spline) + + + diff --git a/script/Plotting.py b/script/Plotting.py new file mode 100755 index 0000000..d1116da --- /dev/null +++ b/script/Plotting.py @@ -0,0 +1,22 @@ +################################################################################################### +# Direct creation of plots +################################################################################################### + +data_1d = [10.0, 20.0, 30.0, 40.0, 50.0] +data_2d = [ data_1d, data_1d, data_1d, data_1d, data_1d] +data_3d = [ data_2d, data_2d , data_2d, data_2d, data_2d] +data_x = [1.0, 2.0, 3.0, 4.0, 5.0] +data_y = [2.0, 4.0, 6.0, 8.0, 10.0] + +#1d-plot with optional xdata +plot(data_1d, title = "1d", xdata = data_x) + +#2d-plot with optional xdata and ydata +plot(data_2d, title = "2d", xdata = data_x, ydata = data_y) + +#3d-plot +plot(data_3d, title = "3d") + +#3 plots in the save panel +plot([data_1d, data_2d, data_3d], ["1d", "2d", "3d"]) + diff --git a/script/PseudoDevices.py b/script/PseudoDevices.py new file mode 100755 index 0000000..fb82557 --- /dev/null +++ b/script/PseudoDevices.py @@ -0,0 +1,25 @@ +################################################################################################### +# Using pseudo-device to : +# - Add calculations to scan data. +# - Execute logic during scan +################################################################################################### + + +class Clock(Readable): + def read(self): + return time.clock() + +class Average(Readable): + def read(self): + arr = wf1.take() #Gets the CACHED waveform + return reduce(lambda x, y: x + y, arr) / len(arr) + +class PseudoPositioner(Writable): + def write(self,pos): + print "Step = " + str(pos) + +clock=Clock() +av=Average() +positioner=PseudoPositioner() +setup_plotting(plot_list = [av,clock]) +a= lscan((ao1,positioner),(wf1, ai2,av,clock),(0,0),(40,20),20,0.1) \ No newline at end of file diff --git a/script/RecordInvalidation.py b/script/RecordInvalidation.py new file mode 100755 index 0000000..8507ec8 --- /dev/null +++ b/script/RecordInvalidation.py @@ -0,0 +1,18 @@ +################################################################################################### +#Resampling a scan record if no beam +################################################################################################### + + +index=0 + + +def before_sampling(rec): + while beam_ok.read() == "No": + time.sleep(0.1) + +def after_sampling(rec): + if beam_ok.read() == "No": + rec.invalidate() + + +a= lscan((m1), (ai1,ai2), (0,), (0.4,), 20, 0.2, before_read=before_sampling, after_read=after_sampling) \ No newline at end of file diff --git a/script/ScanDataManipulation.py b/script/ScanDataManipulation.py new file mode 100755 index 0000000..355d29b --- /dev/null +++ b/script/ScanDataManipulation.py @@ -0,0 +1,16 @@ +################################################################################################### +# Processing and plotting scan data. +################################################################################################### + + +ao1.write(0.0) +scan1= lscan(ao1, (ai1,ai2,wf1), 0, 40, 40, 0.01, False, title="Scan 1") +scan2= lscan(ao1, (ai1,ai2,wf1), 0, 40, 40, 0.01, False, title="Scan 2") + + +from operator import add +result = map(add, scan1.getReadable(0), scan2.getReadable(0)) + +plot(result) +print result + diff --git a/script/ScanTypes.py b/script/ScanTypes.py new file mode 100755 index 0000000..8ce3bd4 --- /dev/null +++ b/script/ScanTypes.py @@ -0,0 +1,28 @@ +#Line scan +r1 = lscan(ao1, (ai1,wf1), 0, 40, 100, 0.01) + +#Time scan +r = tscan((m1,wf1), 100, 0.01) + +#Area scan +r = ascan((m1,m2), (ai1,wf1), (0.0,0.0), (1.0,0.5), (5,8)) + +#1D-vector scan +vector = [ 1, 3, 5, 10, 25, 40, 45, 47, 49] +r = vscan(ao1,(ai1,ai2),vector,False, 0.5, title = "1D Vector") + +#2D-vector scan +vector = [ [1,1] , [1,2] , [1,3] , [1,4] , + [1.5,2.5] , + [2,1] , [2,2] , [2,3] , [2,4] , + [2.5,2.5] , + [3,1] , [3,2] , [3,3] , [3,4] ] +r = vscan((m1,m2),(ai1,ai2),vector,False, 0.01, title = "2D Vector") + +#Region scan +r = rscan(ao1, (ai1,ai2), [(0,5,5), (10,15,20), (20,25,5)] , 0.1) + +#Continuous scan +r = cscan(m1, (ai1,ai2), -2, 3 , steps=10, relative=True) + +#And also hardware scan (hscan)... \ No newline at end of file diff --git a/script/SimulatedDevices.groovy b/script/SimulatedDevices.groovy new file mode 100755 index 0000000..42a790e --- /dev/null +++ b/script/SimulatedDevices.groovy @@ -0,0 +1,189 @@ +import random + +#################################################################################################### +# Simulated Devices +#################################################################################################### + +class AnalogOutput(RegisterBase): + def doRead(self): + return self.val if hasattr(self, 'val') else 0.0 + + def doWrite(self, val): + self.val = val + +class AnalogInput(ReadonlyRegisterBase): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + +class Waveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + + def getSize(self): + return len(self.take(-1)) #only reads if cache is None + +class Image(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + + def getWidth(self): + return len(self.take(-1)[0]) + + def getHeight(self): + return len(self.take(-1)) + + + +class Random(AnalogInput): + def calc(self): + return random.random() + + +class SinusoidSample(AnalogInput): + def calc(self): + self.x = self.x + 0.1 if hasattr(self, 'x') else 0.0 + noise = (random.random() - 0.5) / 10.0 + return math.sin(self.x) + noise + +class SinusoidTime(AnalogInput): + def calc(self): + noise = (random.random() - 0.5) / 10.0 + return math.sin(time.time()) + noise + + +class SinusoidWaveform(Waveform): + def calc(self): + ret = [] + x = random.random() + for i in range (20): + ret.append(math.sin(x)) + x = x + 0.1 + return ret + +class SinusoidImage(Image): + def calc(self): + (width, height) = (200, 100) + ret = [] + x = random.random(); + base = [] + for i in range (width): + base.append( math.sin(x)) + x = x + 0.05 + for i in range (height): + noise = (random.random() - 0.5)/5.0 + ret.append([x+noise for x in base]) + return ret + + +#Defintion +add_device(DummyMotor("m1"), True) +add_device(DummyMotor("m2"), True) +add_device(DummyRegister("reg1",3), True) +add_device(AnalogOutput("ao1"), True) +add_device(AnalogOutput("ao2"), True) +add_device(SinusoidSample("ai1"), True) +add_device(SinusoidTime("ai2"), True) +add_device(Random("ai3"), True) +add_device(SinusoidWaveform("wf1"), True) +add_device(SinusoidImage("im1"), True) +add_device(DummyPositioner("p1"),True) +add_device(MotorGroupBase("mg1", m1, m2), True) +add_device(MotorGroupDiscretePositioner("dp1", mg1), True) + + + +#Initial Configuration +if p1.config.unit is None: + p1.config.minValue = 0.0 #Not persisted + p1.config.maxValue = 1000.0 + p1.config.unit = "mm" + p1.config.save() + p1.initialize() + +if dp1.config.positions is None: + dp1.config.positions = ["Park","Ready","Out","Clear"] + dp1.config.motor1 = ["0.0","4.0","8.0" ,"0.0"] + dp1.config.motor2 = ["0.0","5.0","3.0" ,"NaN"] + dp1.config.save() + dp1.initialize() + + + +#Update +m1.setMonitored(True) +m2.setMonitored(True) + + + + +#################################################################################################### +# Simple Readable / Writable objects can be created and used in scans +#################################################################################################### +class WritableScalar(Writable): + def write(self, value): + pass + +class ReadableScalar(Readable): + def read(self): + return random.random() + + +class ReadableWaveform(ReadableArray): + def getSize(self): + return 20 + + def read(self): + ret = [] + for i in range (self.getSize()): + ret.append(random.random()) + return ret + +class ReadableImage(ReadableMatrix): + def read(self): + ret = [] + for i in range (self.getHeight()): + ret.append([random.random()] * self.getWidth()) + return to_array(ret, 'd') + + def getWidth(self): + return 80 + + def getHeight(self): + return 40 + + + +ws1 = WritableScalar() +rs1 = ReadableScalar() +rw1 = ReadableWaveform() +ri1 = ReadableImage() + + +#################################################################################################### +# Imaging +#################################################################################################### + +configured = os.path.exists(Device.getConfigFileName("src1")) + +add_device(RegisterMatrixSource("src1", im1), True) +add_device(RegisterMatrixSource("src2", ri1), True) + +src1.polling = 100 +src2.polling = 100 + +#Some configuration for so the imaging will work out of the box +if not configured: + import ch.psi.pshell.imaging.Colormap + src1.config.colormapAutomatic = True + src1.config.colormap = ch.psi.pshell.imaging.Colormap.Temperature + src1.config.save() + src2.config.colormapAutomatic = True + src2.config.save() + + diff --git a/script/SimulatedDevices.js b/script/SimulatedDevices.js new file mode 100755 index 0000000..4fa9c9c --- /dev/null +++ b/script/SimulatedDevices.js @@ -0,0 +1,252 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Simulated Devices +/////////////////////////////////////////////////////////////////////////////////////////////////// + +var AnalogOutput = Java.extend(RegisterBase) +var dev = new AnalogOutput("ao1") { + i:double = 0.0, + doRead: function () { + return this.i + }, + doWrite: function (value) { + this.i=value + }, + } +add_device(dev, true) + + +var AnalogOutput = Java.extend(RegisterBase) +var dev = new AnalogOutput("ao2") { + i:double = 0.0, + doRead: function () { + return this.i + }, + doWrite: function (value) { + this.i=value + }, + } +add_device(dev, true) + +var SinusoidSample = Java.extend(ReadonlyRegisterBase) +var dev = new SinusoidSample("ai1") { + x:double = 0.0, + doRead: function () { + sleep(0.001) + this.x += 0.1 + var noise = (Math.random() - 0.5) / 10.0 + return Math.sin(this.x) + noise + }, + } +add_device(dev, true) + + +var SinusoidTime = Java.extend(ReadonlyRegisterBase) +var dev = new SinusoidTime("ai2") { + doRead: function () { + sleep(0.001) + var noise = (Math.random() - 0.5) / 10.0 + return Math.sin(Date.now()) + noise + }, + } +add_device(dev, true) + + +var Random = Java.extend(ReadonlyRegisterBase) +var dev = new Random("ai3") { + doRead: function () { + sleep(0.001) + return Math.random() + }, + } + +add_device(dev, true) + + + + +var SinusoidWaveform = Java.extend(ReadonlyRegisterBase, ReadonlyRegisterArray) +var dev = new SinusoidWaveform("wf1") { + doRead: function () { + sleep(0.001) + var ret = [] + var x = Math.random() + for (var i = 0; i < 20; i++) { + ret.push(Math.sin(x)) + x = x + 0.1 + } + return to_array(ret, 'd') + }, + + getSize: function () { + //return wf1.take(-1).length + return SinusoidWaveformSuper.take(-1).length + }, + + } +var SinusoidWaveformSuper = Java.super(dev) +add_device(dev, true) + + +var SinusoidImage = Java.extend(ReadonlyRegisterBase, ReadonlyRegisterMatrix) +var dev = new SinusoidImage("im1") { + doRead: function () { + sleep(0.001) + var ret = [] + var width = 200 + var height = 100 + var x = Math.random() + var base = [] + for (var i = 0; i < width ; i++) { + base.push(Math.sin(x)) + x = x + 0.05 + } + for (var i = 0; i < height ; i++) { + var noise = (Math.random() - 0.5)/5.0 + var row = [] + for (var j = 0; j < width ; j++) { + row.push(base[j]+noise) + } + ret.push(row) + } + return to_array(ret, 'd') + }, + + getWidth: function () { + return SinusoidSuper.take(-1)[0].length + }, + + + getHeight: function () { + return SinusoidSuper.take(-1).length + }, + + } +var SinusoidSuper = Java.super(dev) +add_device(dev, true)| + + + +//Defintion +add_device(new DummyMotor("m1"), true) +add_device(new DummyMotor("m2"), true) +add_device(new DummyRegister("reg1",3), true) +add_device(new DummyPositioner("p1"),true) +add_device(new MotorGroupBase("mg1", m1, m2), true) +add_device(new MotorGroupDiscretePositioner("dp1", mg1), true) + + +//Initial Configuration +if (p1.config.unit == null) { + p1.config.minValue = 0.0 //Not persisted + p1.config.maxValue = 1000.0 + p1.config.unit = "mm" + p1.config.save() + p1.initialize() +} + +if (dp1.config.positions == null) { + dp1.config.positions = ["Park","Ready","Out","Clear"] + dp1.config.motor1 = ["0.0","4.0","8.0" ,"0.0"] + dp1.config.motor2 = ["0.0","5.0","3.0" ,"NaN"] + dp1.config.save() + dp1.initialize() +} + + +//Update +m1.setMonitored(true) +m2.setMonitored(true) + + + + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Simple Readable / Writable objects can be created and used in scans +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +var WritableScalar = Java.extend(Writable) +var ws1 = new WritableScalar() { + write: function (value) { + }, + } + + +var ReadableScalar = Java.extend(Readable) +var rs1 = new ReadableScalar() { + read: function (value) { + return Math.random() + }, + } + + +var ReadableWaveform = Java.extend(ReadableArray) +var rw1 = new ReadableWaveform() { + + read: function (value) { + ret = [] + for (var i=0; i< this.getSize(); i++){ + ret.push(Math.random()) + } + return to_array(ret, 'd') + }, + + getSize: function () { + return 20 + }, + + } + + +var ReadableImage = Java.extend(ReadableMatrix) +var ri1 = new ReadableImage() { + read: function (value) { + var ret = [] + for (var i=0; i< this.getHeight(); i++){ + var row = [] + for (var j=0; j< this.getWidth(); j++){ + row.push(Math.random()) + } + ret.push(row) + } + return to_array(ret, 'd') + }, + + getWidth: function () { + return 80 + }, + + getHeight: function () { + return 40 + }, + } + + + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Imaging +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +GenericDevice = Java.type('ch.psi.pshell.device.GenericDevice') +File = Java.type('java.io.File') +var f = new File(GenericDevice.getConfigFileName("m1")) +configured = f.exists() + +add_device(new RegisterMatrixSource("src1", im1), true) +add_device(new RegisterMatrixSource("src2", ri1), true) + +src1.polling = 100 +src2.polling = 100 + +//Some configuration for so the imaging will work out of the box +if (!configured){ + Colormap = Java.type('ch.psi.pshell.imaging.Colormap') + src1.config.colormapAutomatic = true + src1.config.colormap = configured.Temperature + src1.config.save() + src2.config.colormapAutomatic = true + src2.config.save() +} + + diff --git a/script/TEST12.xml b/script/TEST12.xml new file mode 100755 index 0000000..b752c43 --- /dev/null +++ b/script/TEST12.xml @@ -0,0 +1,22 @@ + + + + + + + 6.0 + 6.15 + 0.002 + + + + + + 14.2 + 14.02 + 0.002 + + + + + diff --git a/script/TestAlignmentScan.py b/script/TestAlignmentScan.py new file mode 100755 index 0000000..020fd17 --- /dev/null +++ b/script/TestAlignmentScan.py @@ -0,0 +1,127 @@ +# Tool to align the solenoid on the gun. +# S. Bettoni, A. Gobbo, D. Voulot +# 06/06/2016 +#Code ok with the GUI + +# Procedure: + # switch off all the magnets between the gun solenoid and the screen or BPM used for the measurement + # change the current of the gun soleoid + # look at the centroid position (BPM or screen) downstream of the gun. + +import datetime + +mode = "camtool" # "camtool", "bpm" or "direct" +camera_name = "simulation" +#camera_name = "SLG-LCAM-C041" +use_good_region=False + +if True: #get_exec_pars().source == CommandSource.ui: + I1 = 95.0 + I2 = 100.0 + dI = 1.0 + settling_time = 0.1 + plot_image = False + number_images = 3 + use_background = False + 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") + +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 + +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(); + camtool.start(camera_name, 0, use_background, None, 0.0, None) + if camtool.value is not None: print "Started " , camtool.value.getTimestamp() + wait_camtool_message() + 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)) + +#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) +finally: + if mode == "camtool": camtool.stop() + #pass + +positioner.write(original_gun_solenoid) +#if laser_was_on: +# laser_on() +#else: +# laser_off() + + +# take the result of the scan and generate convex hull plot +if centroid_excursion_plot: + (hx,hy)=add_convex_hull_plot ("Centroid excursion", r.getReadable(0),r.getReadable(1), plot_name) +else: + (hx,hy)= convex_hull(x=r.getReadable(0), y=r.getReadable(1)) + hx.append(hx[0]); hy.append(hy[0]) + +# save the entry in the logbook +gsa_log_msg = "Data file: " + get_exec_pars().path +gsa_log_msg = gsa_log_msg + "\nImages: " + str(number_images) +gsa_log_msg = gsa_log_msg + "\nBackground: enabled=" + str(use_background) + " multiple=" + str(multiple_background) + " number=" + str(number_backgrounds) +gsa_log_msg = gsa_log_msg + "\n\n" + r.print() +if do_elog: + elog("Gun solenoid current scan", gsa_log_msg , get_plot_snapshots()) + +set_return([r, hx, hy]) diff --git a/script/TestAveragePlot.py b/script/TestAveragePlot.py new file mode 100755 index 0000000..df4ff13 --- /dev/null +++ b/script/TestAveragePlot.py @@ -0,0 +1,9 @@ + + +#av1 = create_averager(sin, 5, -1) + +r= lscan(out, av1 , 0, 40, 10, 0.01) +plot(r.getReadable(0), title = "Data" ) +to_array(r.getReadable(0),'d') + + diff --git a/script/TestBsMonitorScan.py b/script/TestBsMonitorScan.py new file mode 100755 index 0000000..fa2be9f --- /dev/null +++ b/script/TestBsMonitorScan.py @@ -0,0 +1,37 @@ +from datetime import datetime + + +st1 = Stream("st1", dispatcher) + +#Adding channels to that stream +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 1, 0) +#s2=st1.addScalar("Float64Scalar", "Float64Scalar", 1, 0) +#w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 1, 0) +#mt1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) +st1.initialize() +st1.start() + + + +def after(rec, scan): + path = get_exec_pars().group+"/TimeIOC" + pathpc = get_exec_pars().group+"/TimePC" + if rec.index==0: + create_dataset(path, 's') + create_dataset(pathpc, 's') + nanos = st1.timestampNanos + dt = datetime.fromtimestamp(nanos/1e9) + time_str = str(dt).ljust(26,'0') + str(int(nanos % 1000)).zfill(3) + append_dataset(path, time_str , type = 's') + + append_dataset(pathpc, str(datetime.fromtimestamp(time.time())) , type = 's') + +#bscan (st1, 10) #Sampling 10 elements + +#tscan (st1.getReadables(), 10 , 0.2) + + + +mscan (st1, st1.getReadables(), -1, 3.0, after_read = after) + +st1.close() \ No newline at end of file diff --git a/script/TestBsread2.py b/script/TestBsread2.py new file mode 100755 index 0000000..15022da --- /dev/null +++ b/script/TestBsread2.py @@ -0,0 +1,3 @@ +while(True): + print bsget(["Int32Scalar", "Int8Scalar"]) + time.sleep(0.01) \ No newline at end of file diff --git a/script/TestFitProfile.py b/script/TestFitProfile.py new file mode 100755 index 0000000..44799c5 --- /dev/null +++ b/script/TestFitProfile.py @@ -0,0 +1,127 @@ +################################################################################################### +# Least square optimization problem to fit a gaussian with offset +################################################################################################### + +from mathutils import * +from plotutils import * + +run("CPython/GaussFit_wrapper") +################################################################################################### +#Fitting the gaussian function with offset f(x) = a + b * exp(-(pow((x - c), 2) / (2 * pow(d, 2)))) +################################################################################################### + +camtool.start("Simulation") + +time.sleep(2.0) +xdata =camtool.getValue("x_axis") +ydata = camtool.getValue("x_profile") + + +p = plot(ydata, "Data" , xdata)[0] +p.setLegendVisible(True) + +def fit_gaussian_offset(y, x, start_point = None, weights = None): + """Fits data into a gaussian with offset. + f(x) = a + b * exp(-(pow((x - c), 2) / (2 * pow(d, 2)))) + + Args: + x(float array or list): observed points x + y(float array or list): observed points y + start_point(optional tuple of float): initial parameters (normalization, mean, sigma) + weights(optional float array or list): weight for each observed point + Returns: + Tuples of gaussian parameters: (offset, normalization, mean, sigma) + """ + + # For normalised gauss curve sigma=1/(amp*sqrt(2*pi)) + if start_point is None: + off = min(y) # good enough starting point for offset + com = x[y.index(max(y))] + amp = max(y) - off + sigma = trapz([v-off for v in y], x) / (amp*math.sqrt(2*math.pi)) + start_point = [off, amp, com , sigma] + + class Model(MultivariateJacobianFunction): + def value(self, variables): + value = ArrayRealVector(len(x)) + jacobian = Array2DRowRealMatrix(len(x), 4) + for i in range(len(x)): + (a,b,c,d) = (variables.getEntry(0), variables.getEntry(1), variables.getEntry(2), variables.getEntry(3)) + v = math.exp(-(math.pow((x[i] - c), 2) / (2 * math.pow(d, 2)))) + model = a + b * v + value.setEntry(i, model) + jacobian.setEntry(i, 0, 1) # derivative with respect to p0 = a + jacobian.setEntry(i, 1, v) # derivative with respect to p1 = b + v2 = b*v*((x[i] - c)/math.pow(d, 2)) + jacobian.setEntry(i, 2, v2) # derivative with respect to p2 = c + jacobian.setEntry(i, 3, v2*(x[i] - c)/d ) # derivative with respect to p3 = d + return Pair(value, jacobian) + + model = Model() + target = [v for v in y] #the target is to have all points at the positios + (parameters, residuals, rms, evals, iters) = optimize_least_squares(model, target, start_point, weights) + return parameters + + + start = time.time() +(off, amp, com, sigma) = fit_gaussian_offset(ydata, xdata, None, None) +f = Gaussian(amp, com, sigma) +gauss = [f.value(i)+off for i in xdata] +s = LinePlotSeries("Fit with offset") +p.addSeries(s) +s.setData(to_array(xdata,'d'), to_array(gauss,'d')) +error=0 +for i in range(len(ydata)) : error += abs(ydata[i]-gauss[i]) +print "\nFit with offset:\off: ", off , " amp: ", amp, " com: ", com, " sigma: ", sigma, " error: ", error +print "Time: ",(time.time()-start) + +start = time.time() +(amp, com, sigma) = fit_gaussian(ydata, xdata, None, None) +f = Gaussian(amp, com, sigma) +gauss = [f.value(i) for i in xdata] +s = LinePlotSeries("Normal Fit") +p.addSeries(s) +s.setData(to_array(xdata,'d'), to_array(gauss,'d')) +error=0 +for i in range(len(ydata)) : error += abs(ydata[i]-gauss[i]) +print "\nNormal fit:\amp: ", amp, " com: ", com, sigma, " error: ", error, " time: ", (time.time()-start) + +start = time.time() +[off, amp, com, sigma] = gfitoff(xdata, ydata, off=None, amp=None, com=None, sigma=None) +from mathutils import Gaussian +g = Gaussian(amp, com, sigma) +gauss = [g.value(i)+off for i in xdata] +s = LinePlotSeries("CPython Fit") +p.addSeries(s) +s.setData(to_array(xdata,'d'), to_array(gauss,'d')) +error=0 +for i in range(len(ydata)) : error += abs(ydata[i]-gauss[i]) +print "\nCPython Fit:\n", off , " amp: ", amp, " com: ", com, " sigma: ", sigma, error, " time: ", (time.time()-start) + + + + + +off = min(ydata) # good enough starting point for offset +com = xdata[ydata.index(max(ydata))] +amp = max(ydata) - off +sigma = trapz([v-off for v in ydata], xdata) / (amp*math.sqrt(2*math.pi)) +g = Gaussian(amp, com, sigma) +gauss = [g.value(i)+off for i in xdata] +s = LinePlotSeries("Start Point") +p.addSeries(s) +s.setData(to_array(xdata,'d'), to_array(gauss,'d')) +error=0 +for i in range(len(ydata)) : error += abs(ydata[i]-gauss[i]) +print "\nStartPoint:\n", off , " amp: ", amp, " com: ", com, " sigma: ", sigma, error, " time: ", (time.time()-start) + + +fit_point_list = create_fit_point_list(ydata, xdata, None) +(amp, com, sigma) = GaussianCurveFitter.ParameterGuesser(fit_point_list).guess().tolist() +gauss = [g.value(i)+off for i in xdata] +s = LinePlotSeries("Default SP") +p.addSeries(s) +s.setData(to_array(xdata,'d'), to_array(gauss,'d')) +error=0 +for i in range(len(ydata)) : error += abs(ydata[i]-gauss[i]) +print "\Default SP:\n", off , " amp: ", amp, " com: ", com, " sigma: ", sigma, error, " time: ", (time.time()-start) diff --git a/script/TestMultiCycles.py b/script/TestMultiCycles.py new file mode 100755 index 0000000..dea0e7c --- /dev/null +++ b/script/TestMultiCycles.py @@ -0,0 +1,30 @@ +scan_complete=False + +def check_end_scan(record, scan): + global scan_complete + if record.index>=50: + print "Data aquisition completed" + scan.abort() + scan_complete=True + record.cancel() + elif (record.index>0) and (record.index % 10 == 0): + get_context().dataManager.splitScanData(scan) + + + +def do_scan(): + global scan_complete + scan_complete=False + try: + mscan (sin, sin, -1, -1, after_read = check_end_scan) + except: + if not scan_complete: + raise + + +set_exec_pars(group="x_{count}"); +do_scan() + +set_exec_pars(group="y_{count}", reset=True) +do_scan() + diff --git a/script/TestPlot.py b/script/TestPlot.py new file mode 100755 index 0000000..629fe39 --- /dev/null +++ b/script/TestPlot.py @@ -0,0 +1,6 @@ +start = 0 +end = 10.0 +steps = 10 + + +r = lscan (out, sin, start, end, steps, 0.2) diff --git a/script/TestProsilica.py b/script/TestProsilica.py new file mode 100755 index 0000000..b5128c7 --- /dev/null +++ b/script/TestProsilica.py @@ -0,0 +1,39 @@ + +prosilica.writeParameter("FrameStartTriggerMode","Freerun") +prosilica.writeParameter("PixelFormat","Bayer8" ) +prosilica.writeParameter("GainValue",0) +prosilica.writeParameter("ExposureValue",15000) +prosilica.writeParameter("FrameRate",5.000) + + + + +print prosilica.readParameter("AcquisitionMode") +print prosilica.readParameter("AcquisitionFrameCount") +print prosilica.readParameter("FrameRate") + + +print prosilica.readParameterRange("AcquisitionMode") +print prosilica.readParameterRange("AcquisitionFrameCount") +print prosilica.readParameterRange("FrameRate") + + +print prosilica.writeParameter("AcquisitionMode", "SingleFrame") +print prosilica.writeParameter("AcquisitionFrameCount", 2) +print prosilica.writeParameter("FrameRate", 6.0) + + +print prosilica.readParameter("AcquisitionMode") +print prosilica.readParameter("AcquisitionFrameCount") +print prosilica.readParameter("FrameRate") + + + +print prosilica.writeParameter("AcquisitionMode", "Continuous") +print prosilica.writeParameter("AcquisitionFrameCount", 1) +print prosilica.writeParameter("FrameRate", 5.0) + + +print prosilica.readParameter("AcquisitionMode") +print prosilica.readParameter("AcquisitionFrameCount") +print prosilica.readParameter("FrameRate") diff --git a/script/TestPseudo.py b/script/TestPseudo.py new file mode 100755 index 0000000..3ea29ee --- /dev/null +++ b/script/TestPseudo.py @@ -0,0 +1,8 @@ +class PseudoDevice(ReadonlyRegisterBase): + def doRead(self): + return sin.take()/take.read() + +pd = PseudoDevice() +pd.triggers = [sin, out] +pd.initialize() +add_device(pd, True) \ No newline at end of file diff --git a/script/TestRecordNull.py b/script/TestRecordNull.py new file mode 100755 index 0000000..7f1bb7f --- /dev/null +++ b/script/TestRecordNull.py @@ -0,0 +1,39 @@ +index = 0 +class AnalogInput(ReadonlyRegisterBase): + def doRead(self): + global index + index = index+1 + if index<5: + return None + return sin.read() + +class Waveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + global index + index = index+1 + if index<5: + return None + return arr.read() + + def getSize(self): + return arr.size + +class Image(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def doRead(self): + global index + index = index+1 + if index<5: + return None + return matrix.read() + + def getWidth(self): + return matrix.width + + def getHeight(self): + return matrix.height + +add_device(AnalogInput("tst"), True) +add_device(Waveform("tst2"), True) +add_device(Image("tst3"), True) + +tscan(tst3, 10, 0.1) \ No newline at end of file diff --git a/script/TestScan.py b/script/TestScan.py new file mode 100755 index 0000000..858fb14 --- /dev/null +++ b/script/TestScan.py @@ -0,0 +1,16 @@ +print args +if get_exec_pars().source == CommandSource.ui: + msg = None + start = 0 + end = 10.0 + steps = 10 +else: + msg = args[0] + start = float(args[1]) + end = float(args[2]) + steps = int(args[3]) + + +print msg +r = lscan (out, sin, start, end, steps, 0.2) + diff --git a/script/TestScanControlledVar.py b/script/TestScanControlledVar.py new file mode 100755 index 0000000..51f6374 --- /dev/null +++ b/script/TestScanControlledVar.py @@ -0,0 +1,13 @@ +import ch.psi.pshell.epics.ControlledVariable as ControlledVariable + +phase = ControlledVariable("Phase", "TESTIOC:TESTCALCOUT:Input", "TESTIOC:TESTSINUS:SinCalc") +phase.config.minValue = 0 +phase.config.maxValue = 1000 +phase.config.resolution = 1 +phase.initialize() + +try: + r = lscan(phase, sin, 0, 100, 10, latency=0.5) +finally: + phase.close() + #st.close() \ No newline at end of file diff --git a/script/TestWaitChange.py b/script/TestWaitChange.py new file mode 100755 index 0000000..4c034b5 --- /dev/null +++ b/script/TestWaitChange.py @@ -0,0 +1,7 @@ +start = time.time() +for i in range(20): + #sin.waitTimestampChange(0) + sin.waitValueChange(0) + print sin.take() + +print "TIME: " , time.time() - start \ No newline at end of file diff --git a/script/TriggerScan.py b/script/TriggerScan.py new file mode 100755 index 0000000..b357a9b --- /dev/null +++ b/script/TriggerScan.py @@ -0,0 +1,23 @@ +import random + +class Trigger(ReadonlyRegisterBase): + def doRead(self): + return None + +trigger = Trigger() +trigger.initialize() +sca = "asd" + +def scan(): + global sca + sca = mscan(trigger, [sc1, sin.cache], 20) + + +scan_task = fork(scan) + +time.sleep(0.5) +for i in range(10): + trigger.update() + time.sleep(random.random()/5) + +#ret = join(scan_task) diff --git a/script/XPSSpectrum.py b/script/XPSSpectrum.py new file mode 100755 index 0000000..e74b3eb --- /dev/null +++ b/script/XPSSpectrum.py @@ -0,0 +1,108 @@ +#Parameters (global variables): +# ranges: list of RangeSelection havinf args = (step_size, step_time, iterations) +# pass_energy +# +# skip_iteration: if set to 1 then skips after end of current iteration + +from ch.psi.pshell.data.LayoutDefault import ATTR_WRITABLE_DIMENSION as ATTR_WRITABLE_DIMENSION + +cur_range = 0 +cur_iteration = 0 + + + +print "back = ", str(get_exec_pars().background) + +print "source = ", str(get_exec_pars().source) + +print "args = ", +print get_exec_pars().args + + +if scienta.acquisitionMode == scienta.AcquisitionMode.Fixed: + scienta.acquisitionMode = scienta.AcquisitionMode.Swept +ret=[] + + +#Global arguments +scienta.passEnergy = pass_energy + +names=[] +names.append("Spectrum") +for i in range(len(ranges)): + names.append(str(ranges[i])) +plots = plot(None, names) +spectrum_plot = plots[0] + +def plot_cur_spectrum(): + global spectrum_plot + count = 1 + try: + while True: + y = scienta.spectrum.take() + y[10] = count + count = count + 1 + x = scienta.spectrumX + spectrum_plot.getSeries(0).setData(x, y) + #plots[len(names)-1].update(False) + time.sleep(0.1) + finally: + print "Quit" + +task = fork(plot_cur_spectrum) + + +try: + for cur_range in range(len(ranges)): + cur_iteration = 0 + skip_iteration = False + scienta.lowEnergy.write(ranges[cur_range].min) + scienta.highEnergy.write(ranges[cur_range].max) + scienta.update() + + vars = ranges[cur_range].vars + scienta.stepTime.write(vars[0]) + scienta.stepSize.write(vars[1]) + scienta.setIterations(1) + + #iterations done in script + xdata = None + ydata = None + for cur_iteration in range(vars[2]): + plots[cur_range+1].setTitle(str(ranges[cur_range]) + " - iteration " + str(cur_iteration+1)) + trig_scienta() + spectrum_array = scienta.spectrum.read() + if ydata is None: + ydata = spectrum_array + else: + for k in range (len(spectrum_array)): + ydata[k] = ydata[k] + spectrum_array[k] + if xdata is None: + xdata = scienta.spectrumX + plots[cur_range+1].getSeries(0).setData(xdata, ydata) + if skip_iteration: + break + + plots[cur_range+1].setTitle(str(ranges[cur_range])) + ret.append((xdata, ydata)) + + data1d = [1,2,3,4,5] + path="scan" + str(cur_range+1) + "/" + save_dataset(path + "spectrum", ydata) + save_dataset(path + "channels", xdata) + set_attribute(path + "channels", ATTR_WRITABLE_DIMENSION, 1) + set_attribute(path, "Range Low", ranges[cur_range].min) + set_attribute(path, "Range High", ranges[cur_range].max) + set_attribute(path, "Step Time",vars[0]) + set_attribute(path, "Step Size",vars[1]) + set_attribute(path, "Pass Energy",pass_energy) + set_attribute(path, "Iterations",cur_iteration+1) + + +finally: + cur_range = -1 + if not scienta.isReady(): + scienta.stop() + scienta.update() + task[0].cancel(True) +set_return(to_array(ret,'o')) \ No newline at end of file diff --git a/script/back.py b/script/back.py new file mode 100755 index 0000000..a3d775f --- /dev/null +++ b/script/back.py @@ -0,0 +1,15 @@ + +#print locals() + +### +import java.util.logging.Logger as Logger +logger = Logger.getLogger("back") +logger.info("Started") + +#sleep(10.0) +log("quit") +print "quit" + + + + \ No newline at end of file diff --git a/script/back2.py b/script/back2.py new file mode 100755 index 0000000..b020efe --- /dev/null +++ b/script/back2.py @@ -0,0 +1,16 @@ + +#print locals() + +### +import java.util.logging.Logger as Logger +logger = Logger.getLogger("back") +logger.info("Started") + +#sleep(10.0) +log("quit") +print "quit" +### +print "quit" + + + \ No newline at end of file diff --git a/script/back3.py b/script/back3.py new file mode 100755 index 0000000..ec14590 --- /dev/null +++ b/script/back3.py @@ -0,0 +1,15 @@ + +#print locals() + +### +import java.util.logging.Logger as Logger +logger = Logger.getLogger("back") +logger.info("Started") + +#sleep(10.0) +log("quit") +print "quit" +### +print "quit" + + diff --git a/script/back4.py b/script/back4.py new file mode 100755 index 0000000..e83b23c --- /dev/null +++ b/script/back4.py @@ -0,0 +1,16 @@ + +#print locals() + +### +import java.util.logging.Logger as Logger +logger = Logger.getLogger("back") +logger.info("Started") + +#sleep(10.0) +log("quit") +print "quit" +### +print "quit" + + + \ No newline at end of file diff --git a/script/back5.py b/script/back5.py new file mode 100755 index 0000000..e69de29 diff --git a/script/bs.py b/script/bs.py new file mode 100755 index 0000000..a00b82c --- /dev/null +++ b/script/bs.py @@ -0,0 +1,33 @@ +import ch.psi.bsread.Receiver as Receiver +import ch.psi.bsread.ReceiverConfig as ReceiverConfig +import ch.psi.bsread.configuration.Channel as ReceiverChannel + + +c1 = ReceiverChannel("Int32Scalar", 10) +config = ReceiverConfig("tcp://sf-lc6-64:9999") +#config.setReqbsuestedChannels([c1,]) + +receiver = Receiver(config) +receiver.connect() + +message = None +# Its also possible to register callbacks for certain message parts. +# These callbacks are triggered within the receive() function +# (within the same thread) it is guaranteed that the sequence is ordered +# main header, data header, values + +# receiver.addDataHeaderHandler(header -> System.out.println(header)); +# receiver.addMainHeaderHandler(header -> System.out.println(header) ); +# receiver.addValueHandler(data -> System.out.println(data)); +try: + while(True): + message = receiver.receive() + #print (message.getMainHeader()) + #print (message.getDataHeader()) + #print (message.getValues()) + print "----------------" + for channel in message.getValues().keys(): + print channel , " = " , message.getValues()[channel].getValue().array().tolist() + break +finally: + receiver.close() \ No newline at end of file diff --git a/script/bs2.py b/script/bs2.py new file mode 100755 index 0000000..d6e1d5b --- /dev/null +++ b/script/bs2.py @@ -0,0 +1,19 @@ +import ch.psi.bsread.Receiver as Receiver +import ch.psi.bsread.ReceiverConfig as ReceiverConfig +import ch.psi.bsread.configuration.Channel as ReceiverChannel +\ +c1 = ReceiverChannel("Int32Scalar", 10) +config = ReceiverConfig(socket) + +receiver = Receiver(config) +receiver.connect() + +try: + while(True): + message = receiver.receive() + print "----------------" + for channel in message.getValues().keys(): + print channel , " = " , message.getValues()[channel].getValue().array().tolist() + break +finally: + receiver.close() diff --git a/script/bs3.py b/script/bs3.py new file mode 100755 index 0000000..f7c42b7 --- /dev/null +++ b/script/bs3.py @@ -0,0 +1,40 @@ +import ch.psi.pshell.bs.Scalar as Scalar +import ch.psi.pshell.bs.Waveform as Waveform +import ch.psi.pshell.bs.Stream as Stream +import ch.psi.bsread.configuration.Channel as ReceiverChannel + + +def str1(): + s1 = Stream("stream1", bs) + channels = [ 'Int8Scalar', 'Int16Scalar', 'Int32Scalar', 'Int64Scalar', + 'UInt8Scalar', 'UInt16Scalar', 'UInt32Scalar', 'UInt64Scalar', + 'Float32Scalar', 'Float64Scalar', 'BoolScalar', 'StringScalar',] + for c in channels: + add_device(Scalar(c, s1, c, 10), True) + add_device(s1, True) + s1.start() + +def str2(): + s2 = Stream("stream2", bs) + channels = [ 'Int8Waveform', 'Int16Waveform', 'Int32Waveform', 'Int64Waveform', + 'UInt8Waveform', 'UInt16Waveform', 'UInt32Waveform', 'UInt64Waveform', + 'Float32Waveform', 'Float64Waveform', 'BoolWaveform'] + for c in channels: + add_device(Waveform(c, s2, c, 10), True) + add_device(s2, True) + s2.start() + + +#str1() +parallelize(str1, str2) + + + + +#s.start() + + + +#s.stop() + +#s.close() \ No newline at end of file diff --git a/script/bs4.py b/script/bs4.py new file mode 100755 index 0000000..d19f73f --- /dev/null +++ b/script/bs4.py @@ -0,0 +1,27 @@ +import ch.psi.pshell.bs.Scalar as Scalar +import ch.psi.pshell.bs.Waveform as Waveform +import ch.psi.pshell.bs.Stream as Stream +import ch.psi.bsread.configuration.Channel as ReceiverChannel + +s = Stream("stream", bs) + +channels = ['Int8Scalar', + 'Int16Scalar', 'Int32Scalar', 'Int64Scalar', + 'UInt8Scalar', 'UInt16Scalar', 'UInt32Scalar', 'UInt64Scalar', + 'Float32Scalar', 'Float64Scalar' + #, 'BoolScalar', 'StringScalar', + ] +for c in channels: + add_device(Scalar(c, s, c, 10), True) + +channels = [ 'Int8Waveform', 'Int16Waveform', 'Int32Waveform', 'Int64Waveform', + 'UInt8Waveform', 'UInt16Waveform', 'UInt32Waveform', 'UInt64Waveform', + 'Float32Waveform', 'Float64Waveform', 'BoolWaveform'] +#for c in channels: +# add_device(Waveform(c, s, c, 10), True) + +add_device(s, True) + +set_device_alias(stream, "PulseID") + +bscan(s , 100) diff --git a/script/bs5.py b/script/bs5.py new file mode 100755 index 0000000..acd3245 --- /dev/null +++ b/script/bs5.py @@ -0,0 +1,24 @@ +#st1 = Stream("st1", bs) +st1 = Stream("st1", dispatcher) + +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 10, 0) +s2=st1.addScalar("Float64Scalar", "Float64Scalar", 10, 0) +s2=st1.addScalar("BoolScalar", "BoolScalar", 10, 0) +w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 10, 0) +w2=st1.addWaveform("BoolWaveform", "BoolWaveform", 10, 0) +m1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) + +st1.setFilter("Int8Scalar>50") +st1.initialize() +#st1.setFilter("Int8Scalar>20") + +try: + tscan (st1.getReadables(), 100, 0) + + #The bscan command performs samples every stream element + #bscan (st1, 10) #Sampling 10 elements + + #st1.start(True) + #tscan ([s1,w1], 10 , 0.2) +finally: + st1.close() diff --git a/script/bs6.py b/script/bs6.py new file mode 100755 index 0000000..b91f518 --- /dev/null +++ b/script/bs6.py @@ -0,0 +1,33 @@ +st1 = Stream("st1", dispatcher) + + +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 10, 0) +s2=st1.addScalar("Float64Scalar", "Float64Scalar", 10, 0) +w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 10, 0) +mt1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) +st1.initialize() + +try: + #The stream can be used on any conventional scan. The next stream value is sampled. + #Readable values belong to same pulse id. + tscan (st1.getReadables(), 10 , 0.2) + + #The bscan command performs samples every stream element + #Readable values belong to same pulse id. + bscan (st1, 10) #Sampling 10 elements + + #An individual stream channel can be used in a conventional scan, but in this case the stream + #must be explicitly started, and there is no guarantee the values belong to the same PulseID + #(likely they are since as only cached values are taken). + st1.start(True) + tscan ([s1,s2], 10 , 0.2) + + #If waveform individual stream channel is used, and no size is provided in constructor/config, + #then it must be read previously to the scan to update the size value. + st1.start(True) + w1.update() + tscan ([s1,w1,mt1], 10 , 0.2) + + +finally: + st1.close() diff --git a/script/bug.py b/script/bug.py new file mode 100755 index 0000000..6d5b037 --- /dev/null +++ b/script/bug.py @@ -0,0 +1,76 @@ +task = None +running = False + +for i in range (2): + for j in range (2): + task = None + running = False + print '.', + running = False +print "Next" + +print '.', +print '.', +print '.', +print '.', +print "Next" + +import ch.psi.utils.swing.SwingUtils as SwingUtils + +print SwingUtils.getString(None, "Select:" , ["a","b","c"],'a'); + +def _startPlot(type): + global running + print "Starting plot: type " + str(type) + running = True + p = plot(None,name="")[0] + s= p.getSeries(0) + from random import randint + while running: + try: + s.appendData(time.time(),randint(0,9)) + time.sleep(0.1) + except: + pass + print "Done Plotting" + + +def startPlot(type = 1): + global task + task = fork((_startPlot,(type,)),) + +def stopPlot(): + global task, running + running = False + ret = join(task) + + +for i in range (5): + startPlot() + try: + time.sleep(1.0) + finally: + stopPlot() + + + +""" +from startup import * + +def test(): + lscan(inp, (sin,out,arr), 0, 40, 20, 0.1) +""" + + +""" +for i in range(1000): + #caget("13SIM1:image1:ArrayData","[b") + caget("TESTIOC:TESTWF2:MyWF","[b") + #caget("TESTIOC:TESTSINUS:SinCalc",'d') + print "->", + #det.data.read() + #sin.read() + arr.read() + print i +""" + diff --git a/script/bug2.py b/script/bug2.py new file mode 100755 index 0000000..104a67e --- /dev/null +++ b/script/bug2.py @@ -0,0 +1,8 @@ +''' +Line Scan +''' +#set_preference(Preference.ENABLED_PLOTS, [arr,]) +#TEST +print get_exec_pars().path + + print get_exec_pars().path \ No newline at end of file diff --git a/script/bug3.py b/script/bug3.py new file mode 100755 index 0000000..04fc715 --- /dev/null +++ b/script/bug3.py @@ -0,0 +1,10 @@ +''' +Line Scan +''' + +#set_preference(Preference.ENABLED_PLOTS, [arr,]) +#TEST +print get_exec_pars().path + + +print get_exec_pars().path \ No newline at end of file diff --git a/script/calc.groovy b/script/calc.groovy new file mode 100755 index 0000000..0034558 --- /dev/null +++ b/script/calc.groovy @@ -0,0 +1,6 @@ + + +def calc(a){ + a*2 +} + diff --git a/script/calc.js b/script/calc.js new file mode 100755 index 0000000..65c0271 --- /dev/null +++ b/script/calc.js @@ -0,0 +1,5 @@ + + +function calc(a) { + return a * 5; + } \ No newline at end of file diff --git a/script/calc.py b/script/calc.py new file mode 100755 index 0000000..0006d1e --- /dev/null +++ b/script/calc.py @@ -0,0 +1,3 @@ +def calc(a): + return a*2 + diff --git a/script/camtool.py b/script/camtool.py new file mode 100755 index 0000000..f0d0737 --- /dev/null +++ b/script/camtool.py @@ -0,0 +1,47 @@ +class CamtoolValue(Readable): + def __init__(self, channel, alias = None): + self.channel=channel + set_device_alias(self, channel if (alias is None) else alias) + + def read(self): + return camtool.getValue(self.channel) + +class CamtoolArray(ReadableArray): + def __init__(self, channel, alias = None): + self.channel=channel + set_device_alias(self, channel if (alias is None) else alias) + + def read(self): + return camtool.getValue(self.channel) + + def getSize(self): + return len(camtool.getValue(self.channel)) + + + +class CamtoolImage(ReadableMatrix): + def __init__(self, alias = None): + set_device_alias(self, camtool.getCurrentCamera() + " image" if (alias is None) else alias) + + def read(self): + return camtool.getData().matrix + + def getWidth(self): + return camtool.getData().width + + def getHeight(self): + return camtool.getData().height + +sensors = [ + CamtoolImage(), + CamtoolArray("x_fit_gauss_function"), + CamtoolValue("gr_x_fit_mean"), + CamtoolValue("gr_y_fit_mean"), + CamtoolValue("gr_x_fit_standard_deviation"), + CamtoolValue("gr_y_fit_standard_deviation")] + + +if camtool.getCurrentCamera() != "simulation": + camtool.start("simulation") + +tscan(sensors, 10, 1.0) diff --git a/script/caqt.py b/script/caqt.py new file mode 100755 index 0000000..9b6f221 --- /dev/null +++ b/script/caqt.py @@ -0,0 +1,40 @@ +import ch.psi.pshell.epics.CAS as CAS + + + +class ScanDevice(ReadonlyAsyncRegisterBase, ReadonlyRegisterArray): + def getSize(self): + global scan_result + return len(self.take()) + + def append(self, value): + c = self.take() + c.append(value) + self.set(c) + + def set(self, value): + self.onReadout(to_array(value, 'd')) + + +add_device(ScanDevice("scan_pos"), True) +add_device(ScanDevice("scan_val"), True) +scan_pos.set([]) +scan_val.set([]) + +CAS.setServerPort(12345) +cas1 = CAS("PSHELL:scanpos",scan_pos, "double") +cas2 = CAS("PSHELL:scanval",scan_val, "double") +cas3 = CAS("PSHELL:var",sin) + + + +scan_pos.set([]) +scan_val.set([]) +#res = lscan(inp, (sin,out), 0, 40, 40, 0.1) +#scan_pos.set(res.getPositions(0)) +#scan_val.set(res.getReadable(0)) + + + + + diff --git a/script/channelDefinition.py b/script/channelDefinition.py new file mode 100755 index 0000000..d1330c0 --- /dev/null +++ b/script/channelDefinition.py @@ -0,0 +1,47 @@ +#! /usr/bin/env python +# Federica Marone, July 2, 2014 + +from epicsMotor import epicsMotor +from epicsPV import epicsPV + +chScanType=epicsPV("X02DA-ES1-SCAN1:TYPE") +chSystemOffset=epicsPV("X02DA-SCAN-CAM1:SYSOFF") + +# Machine +chRingCurrentStatus=epicsPV("ARIDI-PCT:CURRENT") +chRingCurrentStartFake=epicsPV("X02DA-SCAN-SCN1:CURR") +chRingCurrentStartFake.setMonitor() +chInterlockStatus=epicsPV("X02DA-FE-AB1:ILK-STATE") +chInterlockStatus.setMonitor() +chAbsorberStatus=epicsPV("X02DA-FE-AB1:CLOSE4BL") +chAbsorberStatus.setMonitor() + +# Energy +chCrystal1Pitch=epicsMotor("X02DA-OP-MO1:C1THE") +chBeamEnergy=epicsPV("X02DA-OP-ENE:ACTUAL") +chStripe=epicsPV("X02DA-OP-MO1:ACT_STR") + +# Filters +chFEFilter=epicsPV("X02DA-FE-FI1:READ") +chOPFilter1=epicsPV("X02DA-OP-FI1:READ") +chOPFilter2=epicsPV("X02DA-OP-FI2:READ") +chOPFilter3=epicsPV("X02DA-OP-FI3:READ") +chOPFilter4=epicsMotor('X02DA-OP-FI4:TRY') + +# Box +chBoxModeSelection=epicsPV("X02DA-ES1-BOX:MODE_SEL") + +chCamera=epicsPV("X02DA-ES1-CAM1:CAM_SEL") +chMicroscope=epicsPV("X02DA-ES1-MS:MS_SEL") +chScintillator=epicsPV("X02DA-ES1-MS1:SCINTIL") +chPixelSize=epicsPV("X02DA-ES1-CAM1:ACT_PIXL_SIZE") +chMagnification=epicsPV("X02DA-ES1-MS:MAGNF") + +# DPC +chGridStartRaw=epicsPV("X02DA-SCAN-SCN1:GRIDMIN.VAL") +chGridEndRaw=epicsPV("X02DA-SCAN-SCN1:GRIDMAX.VAL") +chGridNSteps=epicsPV("X02DA-SCAN-SCN1:GRIDSTEP") +chGridNPeriods=epicsPV("X02DA-SCAN-SCN1:GRIDPER") +chPiezo=epicsMotor("X02DA-ES1-PZOSTG2:DTR1") +chActualStep=epicsPV("X02DA-SCAN-SCN1:ACTSTEP") +chMillisecondShutter=epicsPV("X02DA-ES1-MSSH1:EXP-MODE") diff --git a/script/cls.groovy b/script/cls.groovy new file mode 100755 index 0000000..071cd03 --- /dev/null +++ b/script/cls.groovy @@ -0,0 +1,7 @@ +package script +class cls { + double val = 1.0 + void exec(){ + println "Exec" + } +} \ No newline at end of file diff --git a/script/cls.py b/script/cls.py new file mode 100755 index 0000000..e07b2c3 --- /dev/null +++ b/script/cls.py @@ -0,0 +1,4 @@ +class cls: + def execute(self): + print "Execute" + diff --git a/script/corr.py b/script/corr.py new file mode 100755 index 0000000..f109aa5 --- /dev/null +++ b/script/corr.py @@ -0,0 +1,60 @@ +import math + +from mathutils import fit_polynomial, PolynomialFunction +from plotutils import plot_line, plot_function +import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation + +if get_exec_pars().source == CommandSource.ui: + dx = sin + dy = isin + interval = 0.10 + window = 40 + p = plot(None, "Data")[0] + +if isinstance(dx, basestring): dx = Channel(dx) +if isinstance(dy, basestring): dy = Channel(dy) + +sd=p.getSeries(0) +sd.setLinesVisible(False) +sd.setPointSize(4) +marker=None + +while(True): + #Sample and plot data + x=dx.read() + y=dy.read() + sd.appendData(x, y) + if len(sd.x) > window: + #Remove First Element + sd.token.remove(0) + ax = sd.x + ay = sd.y + if len(ax)>2: + x1, x2 = min(ax), max(ax) + res = (x2-x1)/100 + if x1!=x2: + #Display correlation + corr= PearsonsCorrelation().correlation(to_array(ax,'d'), to_array(ay,'d')) + s = "Correlation=" + str(round(corr,4)) + #print s + if marker is not None: + p.removeMarker(marker) + marker = p.addMarker(x2+res, p.AxisId.X, s, p.getBackground()) + marker.setLabelPaint(Color.BLACK) + + #Calculate, print and plot linear fit + pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1) + #print "Fit lin a1:" , a1, " a0:",a0 + y1 = poly(x1, pars_lin) + y2 = poly(x2, pars_lin) + plot_line(p, x1, y1, x2, y2, width = 2, color = Color.BLUE, name = "Fit Linear") + + #Calculate, print and plot quadratic fit + pars_quad = (a0,a1,a2) = fit_polynomial(ay, ax, 2) + #print "Fit quad a2:" , a2, "a1:" , a1, " a0:",a0 + fitted_quad_function = PolynomialFunction(pars_quad) + ax = frange(x1, x2, res, True) + plot_function(p, fitted_quad_function, "Fit Quadratic", ax, color=Color.GREEN) + + time.sleep(interval) + \ No newline at end of file diff --git a/script/cpython.py b/script/cpython.py new file mode 100755 index 0000000..6ab4f88 --- /dev/null +++ b/script/cpython.py @@ -0,0 +1,113 @@ +################################################################################################### +# This moddule is called by demo scripts to execute and embed CPython. +# Must be put in the scripts folder, or else in the python path. +################################################################################################### + +import sys +import os + +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt + +try: + import tkinter as tk +except: + import Tkinter as tk + + +def calc(array): + return np.transpose(array + array) + + +def test_pandas(): + s = pd.Series([1,3,5,np.nan,6,8]) + print (s) + dates = pd.date_range('20130101', periods=6) + print (dates) + df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) + print (df) + df2 = pd.DataFrame({ 'A' : 1., + 'B' : pd.Timestamp('20130102'), + 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), + 'D' : np.array([3] * 4,dtype='int32'), + 'E' : pd.Categorical(["test","train","test","train"]), + 'F' : 'foo' }) + print (df2) + print (df2.dtypes) + print (df.head()) + print (df.tail(3)) + print (df.values) + print (df.describe()) + print (df.T) + print (df.sort_index(axis=1, ascending=False)) + #print (df.sort_values(by='B')) + print (df['A']) + print (df[0:3]) + print (df.mean()) + return str(df.mean()) + + +def test_tkinter(): + root = tk.Tk() + listb = tk.Listbox(root) + for item in ["Hello", "World"]: + listb.insert(0,item) + listb.pack() + root.mainloop() + + +def test_matplotlib(start,stop,step): + import threading + x = np.arange(start,stop,step) + y = np.exp(-x) + + # example variable error bar values + yerr = 0.1 + 0.2*np.sqrt(x) + xerr = 0.1 + yerr + + # First illustrate basic pyplot interface, using defaults where possible. + plt.figure() + plt.errorbar(x, y, xerr=0.2, yerr=0.4) + plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") + + # Now switch to a more OO interface to exercise more features. + fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) + ax = axs[0,0] + ax.errorbar(x, y, yerr=yerr, fmt='o') + ax.set_title('Vert. symmetric') + + # With 4 subplots, reduce the number of axis ticks to avoid crowding. + ax.locator_params(nbins=4) + + ax = axs[0,1] + ax.errorbar(x, y, xerr=xerr, fmt='o') + ax.set_title('Hor. symmetric') + + ax = axs[1,0] + ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o') + ax.set_title('H, V asymmetric') + + ax = axs[1,1] + ax.set_yscale('log') + # Here we have to be careful to keep all y values positive: + ylower = np.maximum(1e-2, y - yerr) + yerr_lower = y - ylower + + ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr, + fmt='o', ecolor='g', capthick=2) + ax.set_title('Mixed sym., log y') + + fig.suptitle('Variable errorbars') + + plt.show() + return [start,stop,step] + + +if __name__ == "__main__": + x = np.arange(0, 5, 0.1) + y = np.sin(x) + plt.plot(x, y) + plt.show() + + diff --git a/script/cpython/GaussFit.py b/script/cpython/GaussFit.py new file mode 100755 index 0000000..006589a --- /dev/null +++ b/script/cpython/GaussFit.py @@ -0,0 +1,32 @@ +import numpy as np +import scipy.optimize + + +# Profile statistics #### +def gfitoff(x, y, off=None, amp=None, com=None, sigma=None): + if off is None: + off = y.min() # good enough starting point for offset + + if com is None: + com = x[y.argmax()] + + if amp is None: + amp = y.max() - off + + # For normalised gauss curve sigma=1/(amp*sqrt(2*pi)) + if sigma is None: + surface = np.trapz((y-off), x=x) + sigma = surface / (amp * np.sqrt(2 * np.pi)) + try: + popt, pcov = scipy.optimize.curve_fit(gauss_fn, x, y, p0=[off, amp, com, sigma], method='lm') + popt[3] = abs(popt[3]) # sigma should be returned as positive + print("Gauss fitting successful.\n") + except Exception as e: + print("Gauss fitting not successful.\n" + str(e)) + popt = [off, amp, com, abs(sigma)] + + return popt + + +def gauss_fn(x, a, b, c, d): + return a + b * np.exp(-(np.power((x - c), 2) / (2 * np.power(d, 2)))) \ No newline at end of file diff --git a/script/cpython/SimulatedCamera.py b/script/cpython/SimulatedCamera.py new file mode 100755 index 0000000..0dd78a3 --- /dev/null +++ b/script/cpython/SimulatedCamera.py @@ -0,0 +1,111 @@ +import numpy +import time + + + +class SimulatedCamera(): + """ + Camera simulation for debugging purposes. + """ + + def __init__(self, camera_config = None, size_x=1280, size_y=960, number_of_dead_pixels=100, noise=0.1, + beam_size_x=100, beam_size_y=20): + """ + Initialize the camera simulation. + :param size_x: Image width. + :param size_y: Image height. + :param number_of_dead_pixels: Number of simulated dead pixels. + :param noise: How much noise to introduce. + :param beam_size_x: Beam width. + :param beam_size_y: Beam height. + """ + self.camera_config = camera_config + self.channel_image = None + self.width_raw = size_x + self.height_raw = size_y + self.noise = noise # double {0,1} noise amplification factor + self.dead_pixels = self._generate_dead_pixels(number_of_dead_pixels) + self.beam_size_x = beam_size_x + self.beam_size_y = beam_size_y + + def _generate_dead_pixels(self, number_of_dead_pixel): + dead_pixels = numpy.zeros((self.height_raw, self.width_raw)) + + for _ in range(number_of_dead_pixel): + x = numpy.random.randint(0, self.height_raw) + y = numpy.random.randint(0, self.width_raw) + dead_pixels[x, y] = 1 + + return dead_pixels + + def get_image(self, raw=False): + """ + Get the simulated image. + :param raw: If true, return a simulated camera wihtout the beam (just noise). + :return: Camera image. + """ + + if raw: + image = numpy.zeros((self.size_y, self.size_x)) + else: + beam_x = numpy.linspace(-self.beam_size_x + numpy.random.rand(), + self.beam_size_x + numpy.random.rand(), + self.height_raw) + beam_y = numpy.linspace(-self.beam_size_y + numpy.random.rand(), + self.beam_size_y + numpy.random.rand(), + self.width_raw) + x, y = numpy.meshgrid(beam_y, beam_x) + image = numpy.exp(-(x ** 2 + y ** 2)) + + # Add some noise + if self.noise: + image += numpy.random.random((self.height_raw, self.width_raw)) * self.noise + + # Add dead pixels + image += self.dead_pixels + + image.clip(0, 0.9, out=image) + image *= (numpy.power(2, 16) - 1) + + return self._get_image(image, raw=raw) + + def _get_image(self, value, raw=False): + + if value is None: + return None + + # Convert type - we are using f because of better performance + # floats (32bit-ones) are way faster to calculate than 16 bit ints, actually even faster than native + # int type (32/64uint) since we can leverage SIMD instructions (SSE/SSE2 on Intels). + value = value.astype('u2').astype(numpy.float32) + + # Shape image + value = value[:(self.width_raw * self.height_raw)].reshape((self.height_raw, self.width_raw)) + + # Return raw image without any corrections + if raw: + return value + + if self.camera_config is not None: + # Correct image + if self.camera_config.parameters["mirror_x"]: + value = numpy.fliplr(value) + + if self.camera_config.parameters["mirror_y"]: + value = numpy.flipud(value) + value = numpy.rot90(value, self.camera_config.parameters["rotate"]) + + return numpy.ascontiguousarray(value) + + + +simulated_camera = None +def new_simulated_camera( camera_config = None, size_x=1280, size_y=960, number_of_dead_pixels=100, noise=0.1, beam_size_x=100, beam_size_y=20): + global simulated_camera + simulated_camera = SimulatedCamera(camera_config, size_x, size_y, number_of_dead_pixels, noise,beam_size_x, beam_size_y) + return simulated_camera + + +def get_image(raw=False): + return simulated_camera.get_image(raw) + diff --git a/script/cpython/wrapper.py b/script/cpython/wrapper.py new file mode 100755 index 0000000..51ee494 --- /dev/null +++ b/script/cpython/wrapper.py @@ -0,0 +1,22 @@ +from jeputils import * + + +def gfitoff(x, y, off=None, amp=None, com=None, sigma=None): + ret = call_jep("cpython/GaussFit", "gfitoff", [to_npa(x), to_npa(y), off, amp, com, sigma]) + return ret if ret is None or is_list(ret) else ret.data + + + + +from jeputils import * +MODULE = "cpython/SimulatedCamera" + + +def new_simulated_camera(size_x=1280, size_y=960, number_of_dead_pixels=100, noise=0.1, beam_size_x=100, beam_size_y=20): + ret = call_jep("cpython/SimulatedCamera", "new_simulated_camera", [None, size_x, size_y, number_of_dead_pixels, noise, beam_size_x, beam_size_y ]) + return ret + +def get_image(raw=False): + ret = call_jep("cpython/SimulatedCamera", "get_image", [raw]) + return ret.data + \ No newline at end of file diff --git a/script/cpython2.py b/script/cpython2.py new file mode 100755 index 0000000..c69ca17 --- /dev/null +++ b/script/cpython2.py @@ -0,0 +1,51 @@ +import numpy as np +import matplotlib.pyplot as plt + + +def run(start,stop,step): + import threading + x = np.arange(start,stop,step) + print threading.current_thread().__class__.__name__ + y = np.exp(-x) + + # example variable error bar values + yerr = 0.1 + 0.2*np.sqrt(x) + xerr = 0.1 + yerr + + # First illustrate basic pyplot interface, using defaults where possible. + plt.figure() + plt.errorbar(x, y, xerr=0.2, yerr=0.4) + plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") + + # Now switch to a more OO interface to exercise more features. + fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) + ax = axs[0,0] + ax.errorbar(x, y, yerr=yerr, fmt='o') + ax.set_title('Vert. symmetric') + + # With 4 subplots, reduce the number of axis ticks to avoid crowding. + ax.locator_params(nbins=4) + + ax = axs[0,1] + ax.errorbar(x, y, xerr=xerr, fmt='o') + ax.set_title('Hor. symmetric') + + ax = axs[1,0] + ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o') + ax.set_title('H, V asymmetric') + + ax = axs[1,1] + ax.set_yscale('log') + # Here we have to be careful to keep all y values positive: + ylower = np.maximum(1e-2, y - yerr) + yerr_lower = y - ylower + + ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr, + fmt='o', ecolor='g', capthick=2) + ax.set_title('Mixed sym., log y') + + fig.suptitle('Variable errorbars') + + plt.show() + return [start,stop,step] + diff --git a/script/cpython3.py b/script/cpython3.py new file mode 100755 index 0000000..967cef3 --- /dev/null +++ b/script/cpython3.py @@ -0,0 +1,39 @@ +import tinynumpy.tinynumpy as np +import tinynumpy.tinylinalg as linalg + + +a = np.array([[1, 2, 3], [3, 4, 6.7], [5, 9.0, 5]]) +print a +print a.transpose() + +print linalg.det(a) + +c = np.ones(3, 3) * 2 + +print c + +print np.dot(a, c) + + + +""" + +from ctypes import * + +TenIntegers = c_int * 10 + +ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +print ii + +for i in ii: print i, + +print "" + + +#['CDLL', 'LibraryLoader', 'POINTER', 'Structure', 'Union', '_AggregateMetaClass', '_ArrayCData', '_CData', '_CTypeMetaClass', '_Function', '_ScalarCData', '_StructLayoutBuilder', '_StructMetaClass', '_TypeMap', '_UnionMetaClass', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__version__', '_pointer_type_cache', 'addressof', 'alignment', 'byref', 'c_bool', 'c_byte', 'c_char_p', 'c_double', 'c_float', 'c_int', 'c_int16', 'c_int32', 'c_int64', 'c_int8', 'c_long', 'c_longlong', 'c_short', 'c_size_t', 'c_ssize_t', 'c_ubyte', 'c_uint', 'c_uint16', 'c_uint32', 'c_uint64', 'c_uint8', 'c_ulong', 'c_ulonglong', 'c_ushort', 'c_void_p', 'cdll', 'jffi', 'memmove', 'memset', 'pointer', 'sizeof'] + + +print isinstance(ii, ctypes._CData) +print ctypes.addressof(ii) +""" \ No newline at end of file diff --git a/script/cpython4.py b/script/cpython4.py new file mode 100755 index 0000000..5dc66f7 --- /dev/null +++ b/script/cpython4.py @@ -0,0 +1,12 @@ +import numpy as np +from numpy.random import rand +from numpy.linalg import solve, inv +a = np.array([[1, 2, 3], [3, 4, 6.7], [5, 9.0, 5]]) +print a.transpose() +print inv(a) +b = np.array([3, 2, 1]) +print solve(a, b) # solve the equation ax = b + +c = rand(3, 3) # create a 3x3 random matrix +print c +print np.dot(a, c) # matrix multiplication diff --git a/script/cpython5.py b/script/cpython5.py new file mode 100755 index 0000000..6c2c1cc --- /dev/null +++ b/script/cpython5.py @@ -0,0 +1,50 @@ +import pandas as pd +import numpy as np +#import matplotlib.pyplot as plt + +s = pd.Series([1,3,5,np.nan,6,8]) +print s + +dates = pd.date_range('20130101', periods=6) +print dates + + +df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) +print df + + +df2 = pd.DataFrame({ 'A' : 1., + 'B' : pd.Timestamp('20130102'), + 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), + 'D' : np.array([3] * 4,dtype='int32'), + 'E' : pd.Categorical(["test","train","test","train"]), + 'F' : 'foo' }) +print df2 + +print df2.dtypes + +print df.head() +print df.tail(3) + +print df.values + +print df.describe() + +print df.T + +print df.sort_index(axis=1, ascending=False) + + +#print df.sort_values(by='B') + + +print df['A'] + +print df[0:3] + + + + +print df.mean() + + diff --git a/script/cpython6.py b/script/cpython6.py new file mode 100755 index 0000000..49564a6 --- /dev/null +++ b/script/cpython6.py @@ -0,0 +1,48 @@ + + +from Tkinter import * + + +root = Tk() +li = 'Carl Patrick Lindsay Helmut Chris Gwen'.split() +listb = Listbox(root) # Create a listbox widget +for item in li: # Insert each item within li into the listbox + listb.insert(0,item) + +listb.pack() # Pack listbox widget +root.mainloop() + + +#import Tkinter + + +#import matplotlib +#matplotlib.use('TkAgg') + +#print matplotlib.get_backend() +""" +[u'pgf', u'cairo', u'MacOSX', u'CocoaAgg', u'gdk', u'ps', u'GTKAgg', u'nbAgg', u'GTK', u'Qt5Agg', u'template', u'emf', u'GTK3Cairo', u'GTK3Agg', u'WX', u'Qt4Agg', u'TkAgg', u'agg', u'svg', u'GTKCairo', u'WXAgg', u'WebAgg', u'pdf'] in jeptest4.py at line number 15 +""" +#print matplotlib.get_backend() +#plt.ion() + + + +#import threading + +#from cpython.pythread cimport PyThread_init_thread +#PyThread_init_thread() +#threading.current_thread.__init__() + +#import pandas as pd + + +import numpy as np +import matplotlib.pyplot as plt + +x = np.arange(0, 5, 0.1) +y = np.sin(x) +plt.plot(x, y) +plt.show() + +#print threading.current_thread().name \ No newline at end of file diff --git a/script/cpython7.py b/script/cpython7.py new file mode 100755 index 0000000..61e3365 --- /dev/null +++ b/script/cpython7.py @@ -0,0 +1,16 @@ + + +import signal, os, sys + +import thread +print thread.get_ident() + + +def handler(signum, frame): + print 'Signal handler called with signal', signum + raise IOError("Couldn't open device!") + +# Set the signal handler and a 5-second alarm +signal.signal(4, handler) + +#signal diff --git a/script/data.groovy b/script/data.groovy new file mode 100755 index 0000000..0996ac0 --- /dev/null +++ b/script/data.groovy @@ -0,0 +1,11 @@ +path="group/data1" +data1d = [1.0, 2.0, 3.0, 4.0, 5.0] +save_dataset(path, data1d) +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", true) +read =load_data(path) +print (read) +print (get_attributes(path)) +plot(read) \ No newline at end of file diff --git a/script/data.js b/script/data.js new file mode 100755 index 0000000..a459876 --- /dev/null +++ b/script/data.js @@ -0,0 +1,11 @@ +path="group/data1" +data1d = [1.0, 2.0, 3.0, 4.0, 5.0] +save_dataset(path, data1d) +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", true) +read =load_data(path) +print (to_array(read)) +print (get_attributes(path)) +plot(read) \ No newline at end of file diff --git a/script/data.py b/script/data.py new file mode 100755 index 0000000..0f4e1a9 --- /dev/null +++ b/script/data.py @@ -0,0 +1,72 @@ +get_context().dataManager.openOutput() +print "Data file: " + get_context().dataManager.output + +#Writing scalar values (datasets with rank 0) +save_dataset("group/val1", 1) +save_dataset("group/val2", 3.14) +save_dataset("group/val3", "test") +print load_data("group/val1") +print load_data("group/val2") +print load_data("group/val3") + +data1d = [1,2,3,4,5] +path="group/data1" +save_dataset(path, data1d) +read =load_data(path) +print read.tolist() + +#plot(read) + + +data2d = [ [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]] +path="group/data2" +save_dataset(path, data2d) +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", True) +read =load_data(path) +print read.tolist() +plot(read) + +data3d = [ [ [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]], [ [3,2,3,4,5], [4,3,4,5,6], [5,4,5,6,7]]] +path="group/data3" +save_dataset(path, data3d) +read =load_data(path,0) +print read.tolist() +read =load_data(path,1) +print read.tolist() + + +path = "group/data4" +create_dataset(path, 'i') +for i in range(10): + append_dataset(path,i) + + +path = "group/data5" +create_dataset(path, 'd', False, (0,0)) +for row in data2d: + append_dataset(path, row) + +path = "group/data6" +names = ["a", "b", "c", "d"] +types = ["d", "d", "d", "[d"] +dims = [0,0,0,5] + + +table = [ [1,2,3,[0,1,2,3,4]], + [2,3,4,[3,4,5,6,7]], + [3,4,5,[6,7,8,9,4]] ] + +create_table(path, names, types, dims) +for row in table: + append_table(path, row) +flush_data() + +read =load_data(path) +print read + + + + diff --git a/script/dev.groovy b/script/dev.groovy new file mode 100755 index 0000000..59e3fb5 --- /dev/null +++ b/script/dev.groovy @@ -0,0 +1,20 @@ +import ch.psi.pshell.device.RegisterBase as RegisterBase + +//@groovy.transform.InheritConstructors +class AnalogOutput extends RegisterBase { + Number val = 0.0 + AnalogOutput(String name) { + super(name) + } + def Number doRead(){ + return val + } + def void doWrite(Number val){ + this.val = val + } +} + + +ao1 = new AnalogOutput("ao1") + +add_device(ao1, true) \ No newline at end of file diff --git a/script/dev.js b/script/dev.js new file mode 100755 index 0000000..a9f7a27 --- /dev/null +++ b/script/dev.js @@ -0,0 +1,131 @@ +var SinusoidImage = Java.extend(Java.type("ch.psi.pshell.device.ReadonlyRegisterBase"), Java.type("ch.psi.pshell.device.ReadonlyRegister.ReadonlyRegisterMatrix")) +var dev = new SinusoidImage("im1") { + doRead: function () { + sleep(0.001) + var ret = [] + var width = 200 + var height = 100 + x = Math.random() + var base = [] + for (var i = 0; i < width ; i++) { + base.push(Math.sin(x)) + x = x + 0.05 + } + for (var i = 0; i < height ; i++) { + var noise = (Math.random() - 0.5)/5.0 + var row = [] + for (var j = 0; j < width ; j++) { + row.push(base[j]+noise) + } + ret.push(row) + } + print ("len = " + ret.length) + return to_array(ret, 'd') + }, + + getWidth: function () { + return SinusoidSuper.take(-1)[0].length + }, + + + getHeight: function () { + return SinusoidSuper.take(-1).length + }, + + } +var SinusoidSuper = Java.super(dev) +add_device(dev, true) + + +var SinusoidWaveform = Java.extend(Java.type("ch.psi.pshell.device.ReadonlyRegisterBase"), Java.type("ch.psi.pshell.device.ReadonlyRegister.ReadonlyRegisterArray")) +var dev = new SinusoidWaveform("wf1") { + doRead: function () { + sleep(0.001) + var ret = [] + x = Math.random() + for (var i = 0; i < 20; i++) { + ret.push(Math.sin(x)) + x = x + 0.1 + } + return ret + }, + + getSize: function () { + //return wf1.take(-1).length + return SinusoidWaveformSuper.take(-1).length + }, + + } +var SinusoidWaveformSuper = Java.super(dev) +add_device(dev, true) +print (wf1.read()) +print (wf1.take(-1).length) +print (wf1.getSize()) + + +tscan(wf1, 10, 0.1) + + + + + +var AnalogOutput = Java.extend(Java.type("ch.psi.pshell.device.RegisterBase")) +var dev = new AnalogOutput("ao1") { + i:double = 0.0, + doRead: function () { + return this.i + }, + doWrite: function (value) { + i=value + }, + } +add_device(dev, true) + + +var SinusoidSample = Java.extend(Java.type("ch.psi.pshell.device.ReadonlyRegisterBase")) +var dev = new SinusoidSample("ai1") { + x:double = 0.0, + doRead: function () { + sleep(0.001) + this.x += 0.1 + var noise = (Math.random() - 0.5) / 10.0 + return Math.sin(this.x) + noise + }, + } +add_device(dev, true) + + +var SinusoidTime = Java.extend(Java.type("ch.psi.pshell.device.ReadonlyRegisterBase")) +var dev = new SinusoidTime("ai2") { + doRead: function () { + sleep(0.001) + var noise = (Math.random() - 0.5) / 10.0 + return Math.sin(Date.now()) + noise + }, + } +add_device(dev, true) + + +var Random = Java.extend(Java.type("ch.psi.pshell.device.ReadonlyRegisterBase")) +var dev = new Random("ai3") { + doRead: function () { + sleep(0.001) + return Math.random() + }, + } + +add_device(dev, true) + + +print(ao1.read()) +print(ai1.read()) +print(ai2.read()) +print(ai3.read()) + + + + + + + + diff --git a/script/emit_meas_phase4p.m b/script/emit_meas_phase4p.m new file mode 100755 index 0000000..e68d2fa --- /dev/null +++ b/script/emit_meas_phase4p.m @@ -0,0 +1,1126 @@ +function varargout = emit_meas_phase4p(varargin) +% EMIT_MEAS_PHASE4 M-file for emit_meas_phase4.fig +% EMIT_MEAS_PHASE4, by itself, creates a new EMIT_MEAS_PHASE4 or raises the existing +% singleton*. +% +% H = EMIT_MEAS_PHASE4 returns the handle to a new EMIT_MEAS_PHASE4 or the handle to +% the existing singleton*. +% +% EMIT_MEAS_PHASE4('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in EMIT_MEAS_PHASE4.M with the given input arguments. +% +% EMIT_MEAS_PHASE4('Property','Value',...) creates a new EMIT_MEAS_PHASE4 or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before emit_meas_phase4_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to emit_meas_phase4_OpeningFcn via varargin. +% +% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one +% instance to run (singleton)". +% +% See also: GUIDE, GUIDATA, GUIHANDLES + +% Edit the above text to modify the response to help emit_meas_phase4 + +% Last Modified by GUIDE v2.5 15-Jan-2014 11:43:41 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @emit_meas_phase4_OpeningFcn, ... + 'gui_OutputFcn', @emit_meas_phase4_OutputFcn, ... + 'gui_LayoutFcn', [] , ... + 'gui_Callback', []); +if nargin && ischar(varargin{1}) + gui_State.gui_Callback = str2func(varargin{1}); +end + +if nargout + [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); +else + gui_mainfcn(gui_State, varargin{:}); +end +% End initialization code - DO NOT EDIT + + +% --- Executes just before emit_meas_phase4 is made visible. +function emit_meas_phase4_OpeningFcn(hObject, eventdata, handles, varargin) +% This function has no output args, see OutputFcn. +% hObject handle to figure +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +% varargin command line arguments to emit_meas_phase4 (see VARARGIN) + +% Choose default command line output for emit_meas_phase4 +handles.output = hObject; + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes emit_meas_phase4 wait for user response (see UIRESUME) +% uiwait(handles.emit_meas); + + +% --- Outputs from this function are returned to the command line. +function varargout = emit_meas_phase4_OutputFcn(hObject, eventdata, handles) +% varargout cell array for returning output args (see VARARGOUT); +% hObject handle to figure +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Get default command line output from handles structure +varargout{1} = handles.output; + + +% --- Executes on button press in pushbutton1. +function pushbutton1_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + + +global LOCATION SYSTEM APPNAME DAQFILENAME energy nmeas coupling nslices meas_type +global phase0 phase_steps phase_dif phase_range +global bunch_l bunch_l_err cal cal_error oper right_q +global PROFILEMONITOR K_STEPS +global background screen +global TDC_cal + +freq = 2997.912e6; %frequency of TDC + +if meas_type==1 % projected multi quad + quad_names = {'F10D1_MQUA35','F10D1_MQUA45','F10D1_MQUA55'}; % EPICs names +elseif meas_type==0 % projected single quad + quad_names = {'F10D1_MQUA55'}; % EPICs name +elseif meas_type==2 % slice in x using the TDC + quad_names = {'F10D1_MQUA35','F10D1_MQUA40','F10D1_MQUA45','F10D1_MQUA50','F10D1_MQUA55'}; % EPICs names +elseif meas_type==3 %slice in y using dispersion + quad_names = {'F10D1_MQUA10','F10D1_MQUA20','F10D1_MQUA30','F10D1_MQUA40','F10D1_MQUA50'}; % EPICs names +elseif meas_type==4 % slice in x using dispersion + quad_names = {'F10D1_MQUA35','F10D1_MQUA40','F10D1_MQUA45','F10D1_MQUA50','F10D1_MQUA55'}; % EPICs names +end +screen = PROFILEMONITOR; + +% set proper values for quadrupoles +if right_q==0 + % measurement kl-values for the 10 quads between BC and FODO + if meas_type==4 + kld(1) = 4.525199912180098*0.15; %F10D1.MQUA10 + kld(2) = 3.874148656932072*0.15; %F10D1.MQUA20 + kld(3) = -3.249774821515966*0.15; %F10D1.MQUA30 + kld(4) = -4.797555982557675*0.15; %F10D1.MQUA40 + kld(5) = 3.615370265142409*0.15; %F10D1.MQUA50 + kld(6) = 0; %F10D1.MQUA60 + kld(7) = 0; %F10D1.MQUA70 + kld(8) = 0; %F10D1.MQUA80 + kld(9) = 0; %F10D1.MQUA90 + kld(10) = 0; %F10D1.MQUA100 + else + kld(1) = 1.335685250670285*0.15; %F10D1.MQUA10 + kld(2) = 5.211233759043508e-001*0.15; %F10D1.MQUA20 + kld(3) = -3.108334644187179e-001*0.15; %F10D1.MQUA30 + kld(4) = 0; %F10D1.MQUA40 + kld(5) = -9.113260060549501e-001*0.15; %F10D1.MQUA50 + kld(6) = -2.190291790302469*0.15; %F10D1.MQUA60 + kld(7) = 0.3966673632905451*0.15; %F10D1.MQUA70 + kld(8) = 2.731046534825306*0.15; %F10D1.MQUA80 + kld(9) = -0.5417341705156887*0.15; %F10D1.MQUA90 + kld(10) = 0; %F10D1.MQUA100 + end + qnames0 = {'F10D1-MQUA10','F10D1-MQUA15','F10D1-MQUA20','F10D1-MQUA25','F10D1-MQUA30',... + 'F10D1-MQUA35','F10D1-MQUA40','F10D1-MQUA45','F10D1-MQUA50','F10D1-MQUA55','F10D1-MQUA60','F10D1-MQUA65',... + 'F10D1-MQUA70','F10D1-MQUA80','F10D1-MQUA85','F10D1-MQUA90','F10D1-MQUA95'}; + + % I exclude the quads upstream the TDC, since sometimes are used to match the beam + exc5 = 0; + if exc5 + qnames0 = qnames0(6:12); + kld = kld(6:10); + end + for i=1:length(kld) + Id(i)=KLquad2Curr(kld(i),energy); + end + + % since the safe-set button is less reliable than the mood of my + % girlfriend, I will first cycle all quads, and then set the current + + % delay the gun before cycling + SetPV('FINSS-RLLE-RIOC:RF-ENABLE',2) + BeamOnOff(0); % close the shutter before cycling + for i=1:length(qnames0) + ch=[qnames0{i} ':B-CYC']; + SetPV(ch,0) + SetPV(ch,1) + end + pause(20); % wait 20 seconds until cycling is done (15s should be fine) + BeamOnOff; % restore the previous state + + if (meas_type==1)||(meas_type==2)||(meas_type==4) + %set design optics for the 5 quads between BC and TDC + if ~exc5 + for i=1:5 + ch=[qnames0{i} ':I-SET']; + %ch=[qnames0{i} ':SEQ-ISET']; + ch = regexprep(ch, '\.', '-'); + SetPV(ch, Id(i)) + end + end + elseif meas_type==0 + %set design for the 10 quads + if ~exc5 + for i=1:10 + ch=[qnames0{i} ':I-SET']; + SetPV(ch,Id(i)) + end + else + for i=1:5 + ch=[qnames0{i} ':I-SET']; + SetPV(ch,Id(i)) + end + end + end + % put the gun at the right timing again + SetPV('FINSS-RLLE-RIOC:RF-ENABLE',1) +end + + +%knob definition --------------------------------------------------------- +knob = LoadKnobDefinition('PhaseAdvanceScanXYquads103050screen10'); + +switch screen + case {'F10D1_DSCR75_CCAM1', 'F10D1_DSCR75_CCAM2'} + Ldx = 0; % additional drift as compared to the pre-calculated files + Ld = 10.831-0.15; % drift between the used quad and the screen + case 'F10D1_DSCR80_CCAM1' + Ldx = 0.386; + Ld = 11.217-0.15; + otherwise + error('unknown screen') +end + + +if meas_type==1 % projected multi quad + load proj_emitx_20110905.mat + k0 = k; + load proj_emity_20110905.mat + kini = [[k0];[k]]; +elseif meas_type==0 % projected single quad + Lq = 0.15; + beta_x = 15; + %beta_y = 15; + %alpha_x = 1.38490; + %alpha_y = 1.38490; + mu = [15:5:165]; + k0 = ((1 - (Ld./(sind(mu).*beta_x)) .* (cosd(mu)+beta_x.*sind(mu)/Ld)) / Ld)/Lq; + kini = k0'; + quads = {'F10D1.MQUA100'}; +elseif meas_type==2 % slice in x using the TDC + load slice_emit_20110905.mat + kini = k; +elseif meas_type==3 % slice in y using dispersion + %load slice_emit_20121218.mat % this was for optics in phase3 + load slice_emit_20130515.mat % this is for optics in phase 4 + kini = k; +elseif meas_type==4 + load slice_emit_20130430.mat + kini = k; +end + +k = kini([1:K_STEPS:length(kini)],:); + +if meas_type==0 + k=k'; +end +Lm = 0.15; + +% prepare Knobs for daq.m +for i=1:length(quads) + temp = size(k); + if (meas_type==1)||(meas_type==2)||(meas_type==3)||(meas_type==4) + for j=1:length(k(:,1)) + I(j,i) = KLquad2Curr(k(j,i)*Lm,energy); + end + knob.Conversions{i} = [[1:1:temp(1)]',[I(:,i)]]; + knob.SetpointValues = 1:temp(1); + elseif meas_type==0 + for j=1:length(k) + I(j,i) = KLquad2Curr(k(j)*Lm,energy); + end + knob.Conversions{i} = [[1:1:length(k)]',[I(:)]]; + knob.SetpointValues = [1:1:length(k)]; + end + knob.Knobs{i}=LoadKnobDefinition(quad_names{i}); + + if meas_type==0 + knob.Knobs(3) = []; + knob.Knobs(2) = []; + knob.Conversions(3) = []; + knob.Conversions(2) = []; + end +end + + +% define knobs for slice emittance measurement (add TDC phase and more) +if meas_type==2 + if TDC_cal + temp = knob.Conversions; + + ind_p = length(quad_names) + 1; + knob.Knobs{ind_p}.Name = 'F10D1_RLLE_RUPC_PHASE'; + knob.Knobs{ind_p}.Description = 'Phase from Transverse Deflector F10D1'; + knob.Knobs{ind_p}.Author = 'Eduard Prat'; + knob.Knobs{ind_p}.SetpointAddress = 'F10D1-RLLE-RUPC:PHASE'; + knob.Knobs{ind_p}.HowToDetermineSuccess = 'SetAndForget'; + knob.Knobs{ind_p}.WaitTime = 0.2; + knob.Knobs{ind_p}.ReadbackAddress = 'F10D1-RLLE-RUPC:PHASE'; + knob.Knobs{ind_p}.Max = 360; + knob.Knobs{ind_p}.Min = -360; + + phase_range = [(phase0-phase_steps*phase_dif):phase_dif:(phase0+phase_steps*phase_dif)]; + + for i=1:length(quads) + for m=1:size(k,1) + for j=1:length(phase_range) + ind0 = length(phase_range)*(m-1)+j; + temp2 = temp{i}(m,2); + knob.Conversions{i}(ind0,2) = temp2; + knob.Conversions{i}(ind0,1) = ind0; + + % values for the phase + knob.Conversions{length(quads)+1}(ind0,1) = ind0; + knob.Conversions{length(quads)+1}(ind0,2) = phase_range(j); + knob.SetpointValues(ind0) = ind0; + end + + end + end + end +end + +% instrument definition -------------------------------------------------- +instrument = LoadInstrumentDefinition(screen); + +if (meas_type == 2)||(meas_type)==0 ||(meas_type==3)||(meas_type==4) + coupling = 0; +end + + +instrument.Actions = []; +N=0; +instrument.Actions{N+1}.Function = 'StartServer'; +instrument.Actions{N+1}.Active = 0; % not required for DSCR80 +instrument.Actions{N+1}.Parameters = []; +N=N+1; +instrument.Actions{N+1}.Function = 'StoreCameraData'; +instrument.Actions{N+1}.Active = 1; +instrument.Actions{N+1}.Parameters = []; + +if background == 1 + N=N+1; + instrument.Actions{N+1}.Function = 'MultipleBackgroundImages'; + instrument.Actions{N+1}.Active = 0; + instrument.Actions{N+1}.Parameters.NumberBackgroundImages = 5; + instrument.Actions{N+1}.Parameters.StoreBackgroundImages = 1; + N=N+1; + instrument.Actions{N+1}.Function = 'SubtractBackgroundImage'; + instrument.Actions{N+1}.Active = 1; + instrument.Actions{N+1}.Parameters.NumberBackgroundImages = 10; + instrument.Actions{N+1}.Parameters.StoreBackgroundImages = 1; +elseif background == 2 + N=N+1; + instrument.Actions{N+1}.Function = 'MultipleBackgroundImages'; + instrument.Actions{N+1}.Active = 1; + instrument.Actions{N+1}.Parameters.NumberBackgroundImages = 5; + instrument.Actions{N+1}.Parameters.StoreBackgroundImages = 1; + N=N+1; + instrument.Actions{N+1}.Function = 'SubtractBackgroundImage'; + instrument.Actions{N+1}.Active = 0; + instrument.Actions{N+1}.Parameters.NumberBackgroundImages = 10; + instrument.Actions{N+1}.Parameters.StoreBackgroundImages = 1; +end + +N=N+1; +instrument.Actions{N+1}.Function = 'SubtractOffset'; +instrument.Actions{N+1}.Active = 0; +instrument.Actions{N+1}.Parameters = []; +N=N+1; +instrument.Actions{N+1}.Function = 'GaussFit'; +instrument.Actions{N+1}.Active = 1; +if coupling + instrument.Actions{N+1}.Parameters.AdaptiveROI = 1; + instrument.Actions{N+1}.Parameters.AllowOffset = 0; +else + instrument.Actions{N+1}.Parameters = []; +end +if coupling + N=N+1; + instrument.Actions{N+1}.Function = 'NoiseCut'; + instrument.Actions{N+1}.Active = 1; + instrument.Actions{N+1}.Parameters.Threshold = 0.2; + N=N+1; + instrument.Actions{N+1}.Function = 'xy_slope'; + instrument.Actions{N+1}.Active = 1; + instrument.Actions{N+1}.Parameters = []; +end + + +%info -------------------------------------------------------------------- +if oper + Info.OperatorPresent = 1; +else + Info.OperatorPresent = 0; +end +Info.Author = APPNAME; +Info.Title = 'Multiknob Emittance Measurement'; +Info.eLog = Localize('eLog',LOCATION); +Info.Text = []; +Info.StartTime = now; + +%set up ------------------------------------------------------------------ +Setup.Function = 'scan'; +Setup.Repeat = nmeas; +Setup.SaveSR = 1; + + +% load transfer matrices to put them in Setup +if meas_type==1 + load mat_f10d165_quad6080100.mat +elseif meas_type==2 + load mat_slice_phase3.mat +elseif meas_type==3 + %load mat_slicey_phase3.mat % this is for phase 3 optics + load mat_slicey_phase4.mat % this is for phase 4 optics + R11=R33; + R12=R34; + R22=R44; + R21=R43; +elseif meas_type==4 + load mat_slicex_phase3.mat +end + +% add an additional drift (this depends on the screen; see the definition of Ldx above) +if meas_type==1 || meas_type==2 || meas_type==3 || meas_type==4 + Mdx = Drift(Ldx); % additional drift between DSCR75 and DSCR80 + for i=1:length(kini) + M0 = [R11(i) R12(i) 0 0; R21(i) R22(i) 0 0; 0 0 R33(i) R34(i); 0 0 R43(i) R44(i)]; + M = Mdx * M0; + R11(i) = M(1,1); + R12(i) = M(1,2); + R21(i) = M(2,1); + R22(i) = M(2,2); + R33(i) = M(3,3); + R34(i) = M(3,4); + R43(i) = M(4,3); + R44(i) = M(4,4); + end +elseif meas_type==0 %in this case I calculate the matrices directly here + phi10 = Lq*sqrt(abs(kini)); + Md1 = [[1 Ld 0 0 0 0];[0 1 0 0 0 0];[0 0 1 Ld 0 0];[0 0 0 1 0 0];[0 0 0 0 1 0];[0 0 0 0 0 1]]; + for i=1:length(kini) + + if kini(i)<0 + Mq10 = [[cosh(phi10(i)) sinh(phi10(i))/sqrt(abs(kini(i))) 0 0 0 0]; [sqrt(abs(kini(i)))*sinh(phi10(i)) cosh(phi10(i)) 0 0 0 0];[0 0 cos(phi10(i)) sin(phi10(i))/sqrt(abs(kini(i))) 0 0];[0 0 -sin(phi10(i))*sqrt(abs(kini(i))) cos(phi10(i)) 0 0];[0 0 0 0 1 0];[0 0 0 0 0 1]]; + elseif kini(i)==0 + Mq10 = [[1 Lq 0 0 0 0];[0 1 0 0 0 0];[0 0 1 Lq 0 0];[0 0 0 1 0 0];[0 0 0 0 1 0];[0 0 0 0 0 1]]; + else + Mq10 = [[cos(phi10(i)) sin(phi10(i))/sqrt(abs(kini(i))) 0 0 0 0];[-sin(phi10(i))*sqrt(abs(kini(i))) cos(phi10(i)) 0 0 0 0];[0 0 cosh(phi10(i)) sinh(phi10(i))/sqrt(abs(kini(i))) 0 0]; [0 0 sqrt(abs(kini(i)))*sinh(phi10(i)) cosh(phi10(i)) 0 0];[0 0 0 0 1 0];[0 0 0 0 0 1]]; + end + M=Md1*Mq10; + R11(i) = M(1,1); + R12(i) = M(1,2); + R21(i) = M(2,1); + R22(i) = M(2,2); + R33(i) = M(3,3); + R34(i) = M(3,4); + R43(i) = M(4,3); + R44(i) = M(4,4); + end +end + +R11 = R11([1:K_STEPS:length(kini)]); +R12 = R12([1:K_STEPS:length(kini)]); +R21 = R21([1:K_STEPS:length(kini)]); +R22 = R22([1:K_STEPS:length(kini)]); +R33 = R33([1:K_STEPS:length(kini)]); +R34 = R34([1:K_STEPS:length(kini)]); +R43 = R43([1:K_STEPS:length(kini)]); +R44 = R44([1:K_STEPS:length(kini)]); + +Setup.AnalyzeTripleQuadScan.R = {R11, R12, 0, 0; R21, R22, 0, 0; 0, 0, R33, R34; 0, 0, R43, R44}; +Setup.AnalyzeTripleQuadScan.k = k; +Setup.AnalyzeTripleQuadScan.energy = energy; +%design optical functions and emittance (entrance of F10D1.MQUA60) +if meas_type==0 + Setup.AnalyzeTripleQuadScan.beta_x0 = 15*1; + Setup.AnalyzeTripleQuadScan.beta_y0 = 15*1; + Setup.AnalyzeTripleQuadScan.alpha_x0 = 1.3849*1; + Setup.AnalyzeTripleQuadScan.alpha_y0 = 1.3849*1; +elseif (meas_type==1)||(meas_type==2) + Setup.AnalyzeTripleQuadScan.beta_x0 = 9.4801; + Setup.AnalyzeTripleQuadScan.beta_y0 = 40.0155; + Setup.AnalyzeTripleQuadScan.alpha_x0 = -1.0220; + Setup.AnalyzeTripleQuadScan.alpha_y0 = -0.0207; +elseif meas_type==3 % entrance of quad10 + Setup.AnalyzeTripleQuadScan.beta_y0 = 8.5084; + Setup.AnalyzeTripleQuadScan.beta_x0 = 19.2849; + Setup.AnalyzeTripleQuadScan.alpha_y0 = -1.4147; + Setup.AnalyzeTripleQuadScan.alpha_x0 = 0.6847; +elseif meas_type==4 + Setup.AnalyzeTripleQuadScan.beta_x0 = 31.4326; + Setup.AnalyzeTripleQuadScan.beta_y0 = 17.12275; + Setup.AnalyzeTripleQuadScan.alpha_x0 = -9.497579; + Setup.AnalyzeTripleQuadScan.alpha_y0 = 6.811337; +end + +Setup.AnalyzeTripleQuadScan.gamma_x0 = (1+Setup.AnalyzeTripleQuadScan.alpha_x0^2)/Setup.AnalyzeTripleQuadScan.beta_x0; +Setup.AnalyzeTripleQuadScan.gamma_y0 = (1+Setup.AnalyzeTripleQuadScan.alpha_y0^2)/Setup.AnalyzeTripleQuadScan.beta_y0; + +% data acquisition ------------------------------------------------------- +[DAQFileName, Setup, knob, instrument, Info] = daq(Setup,{knob},{instrument},Info); +%[Setup, Info, knob, instrument] = RetrieveData('/afs/psi.ch/intranet/FIN/Data/FIN250-Phase4+/2014-10-08/MKE20141008T132836.h5'); + +% put the quadrupole back to zero in the single quad scan +if meas_type==0 + SetPV('F10D1-MQUA55:I-SET.VAL',0) +end + + +% get TDC calibration and other longitudinal parameters for the different +% quad configurations +clear bunch_l bunch_l_err +if meas_type==2 + if TDC_cal + indg = find(abs(phase_range-phase0)<0.001); + % first get all vertical centroids and beam sizes + for i=1:length(phase_range)*size(k,1) + % all values are in mm + rms_y0(i) = mean(instrument{1}.BeamSizeGaussfit(2,:,i)); + rms_err_y0(i) = sqrt(var(instrument{1}.BeamSizeGaussfit(2,:,i))); + + y0(i) = mean(instrument{1}.BeamPositionGaussfit(2,:,i)); + y_err0(i) = sqrt(var(instrument{1}.BeamPositionGaussfit(2,:,i))); + end + + rms_y = reshape(rms_y0,length(phase_range),size(k,1))'; + rms_err_y = reshape(rms_err_y0,length(phase_range),size(k,1))'; + y = reshape(y0,length(phase_range),size(k,1))'; + y_err = reshape(y_err0,length(phase_range),size(k,1))'; + + for i=1:size(k,1) + y2 = y(i,:); + y_err2 = y_err(i,:); + + if nmeas>1 + [p,s] = polyfit3(phase_range,y2,1,[],1./y_err2); % linear fit weighthing with measurement errors + elseif nmeas==1 + [p,s] = polyfit(phase_range,y2,1); + end + %y_pred = polyval(p,phase_range); + + % error of the fit + ste = sqrt(diag(inv(s.R)*inv(s.R')).*s.normr.^2./s.df); + + % calibration in mm per ps + cal(i) = p(1)*360*freq/1e12; + % calibration error + cal_err(i) = ste(1)*360*freq/1e12; + + % bunch length (in ps) + bunch_l(i,:) = abs(rms_y(i,:)/cal(i)); + + % bunch length error (assuming no correlation between calibration error and vertical beam size measurement error) + bunch_l_err(i,:) = bunch_l(i,:) .* ( (cal_err(i)/cal(i))^2 + (rms_err_y(i,:)./rms_y(i,:)).^2 ) .^ 0.5; + % slice separation for the analysis + y_sep0(i,:) = rms_y(i,:) / nslices; + for j=1:length(phase_range) + % determine valid measurements (no significant bunch length variation from zero phase) + if (bunch_l(i,indg) < (bunch_l(i,j)+bunch_l_err(i,j))) + if (bunch_l(i,indg) > (bunch_l(i,j)-bunch_l_err(i,j))) + indb0(i,j) = i; + else + indb0(i,j) = 0; + end + else + indb0(i,j) = 0; + end + end + %ysep1(i) = mean(y_sep0(~(indb0(i,:)==0))); + end + % slice image analysis + input.ind = reshape(indb0',length(phase_range)*size(k,1),1); + input.y_sep = reshape(y_sep0',1,length(phase_range)*size(k,1))'; + input.cur_cut = 0.3; + % + [output] = Slicer(instrument,input); + instrument{1}.input = input; + output.y_sep = mean(mean(bunch_l))/nslices; + instrument{1}.slice = output; + instrument{1}.ind_val = input.ind; + else + for i=1:size(k,1) + % all values are in mm + rms_y0(i) = mean(instrument{1}.BeamSizeGaussfit(2,:,i)); + rms_err_y0(i) = sqrt(var(instrument{1}.BeamSizeGaussfit(2,:,i))); + + y0(i) = mean(instrument{1}.BeamPositionGaussfit(2,:,i)); + y_err0(i) = sqrt(var(instrument{1}.BeamPositionGaussfit(2,:,i))); + end + + rms_y = reshape(rms_y0,1,size(k,1))'; + rms_err_y = reshape(rms_err_y0,1,size(k,1))'; + y = reshape(y0,1,size(k,1))'; + y_err = reshape(y_err0,1,size(k,1))'; + + + % slice image analysis + input.y_sep = reshape(rms_y' / nslices,1,size(k,1))'; + input.yflip = 0; + [output] = Slicer(instrument,input); + instrument{1}.input = input; + instrument{1}.slice = output; + end +end + +if meas_type==3 + % first get all horizontal centroids and beam sizes + for i=1:size(k,1) + % all values are in mm + rms_x0(i) = mean(instrument{1}.BeamSizeGaussfit(1,:,i)); + rms_err_x0(i) = sqrt(var(instrument{1}.BeamSizeGaussfit(1,:,i))); + + x0(i) = mean(instrument{1}.BeamPositionGaussfit(1,:,i)); + x_err0(i) = sqrt(var(instrument{1}.BeamPositionGaussfit(1,:,i))); + end + + rms_x = reshape(rms_x0,1,size(k,1))'; + rms_err_x = reshape(rms_err_x0,1,size(k,1))'; + x = reshape(x0,1,size(k,1))'; + x_err = reshape(x_err0,1,size(k,1))'; + + + % slice image analysis + input.y_sep = reshape(rms_x' / nslices,1,size(k,1))'; + input.yflip = 1; + [output] = Slicer(instrument,input); + instrument{1}.input = input; + instrument{1}.slice = output; +end + +if meas_type==4 + % first get all horizontal centroids and beam sizes + for i=1:size(k,1) + % all values are in mm + rms_y0(i) = mean(instrument{1}.BeamSizeGaussfit(2,:,i)); + rms_err_y0(i) = sqrt(var(instrument{1}.BeamSizeGaussfit(2,:,i))); + + y0(i) = mean(instrument{1}.BeamPositionGaussfit(2,:,i)); + y_err0(i) = sqrt(var(instrument{1}.BeamPositionGaussfit(2,:,i))); + end + + rms_y = reshape(rms_y0,1,size(k,1))'; + rms_err_y = reshape(rms_err_y0,1,size(k,1))'; + y = reshape(y0,1,size(k,1))'; + y_err = reshape(y_err0,1,size(k,1))'; + + + % slice image analysis + input.y_sep = reshape(rms_y' / nslices,1,size(k,1))'; + input.yflip = 0; + [output] = Slicer(instrument,input); + instrument{1}.input = input; + instrument{1}.slice = output; +end + +%------------------------------------------------------------------------- +% calculation of emittance and optics + +%save workspace + +if (meas_type==1)||(meas_type==0) + [ResultStructure, figh, analfile] ... + = AnalyzeTripleQuadScanCoupling(Setup, knob, instrument, Info) +elseif meas_type==2 || meas_type==3 || meas_type==4 + [ResultStructure, figh, analfile] ... + = AnalyzeTripleQuadScanCouplingSliceEnergy(Setup, knob, instrument, Info) +end + + +% make entry in the logbook +eLog = Localize('eLog',LOCATION); +MakeLogbookEntry(eLog,'Multiknob Emittance Measurement','','Nice operator',DAQFileName,analfile,figh) + +%set(handles.pushbutton2,'Enable','on') + + + +function edit1_Callback(hObject, eventdata, handles) +% hObject handle to edit1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit1 as text +% str2double(get(hObject,'String')) returns contents of edit1 as a double +global energy +energy = str2double(get(hObject,'String')); + +% --- Executes during object creation, after setting all properties. +function edit1_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called +global energy +set(hObject,'String',energy) + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + +% --- Executes during object creation, after setting all properties. +function emit_meas_CreateFcn(hObject, eventdata, handles) +% hObject handle to emit_meas (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called +%addpath /afs/psi.ch/intranet/FIN/Applications/Development/Eduard/MatchingTool/trunk + +% set useful defaults + +global LOCATION SYSTEM APPNAME DAQFILENAME energy nmeas coupling +global meas_type nslices phase0 phase_dif phase_steps oper right_q +global PROFILEMONITOR K_STEPS +global background en_chirp +global TDC_cal + +TDC_cal = 1; +energy = 220; % energy in MeV -- if this is changed, change also the GUI default string +en_chirp = 0; % energgy chirp along the bunch in % +nmeas = 10; %number of measurements per measurement point +coupling = 0; %include coupling? +meas_type = 0; % 1 is projected measurement with triple quads scan, 0 is projected with single quad, 2 is slice +nslices = 5; % number of slices for slice emittance measurement +oper=0; %operator present +right_q = 1; %right initial values for quads? +K_STEPS = 2; % skip every other setpoint +background = 1; % 1 is single background subtraction, 2 is multiple + +SetPath + +LOCATION= 'wlha'; +SYSTEM = 'epics'; +APPNAME = 'Multiknob emittance measurement'; +DAQFILENAME = 'MKE'; + +% phase control parameters (for TDC calibration measurements) +phase0 = GetPV('F10D1-RLLE-RUPC:PHASE'); +phase_dif = 1; +phase_steps = 1; + +PROFILEMONITOR = 'F10D1_DSCR80_CCAM1'; + + + + + + + +function edit2_Callback(hObject, eventdata, handles) +% hObject handle to edit2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +global nmeas +nmeas = str2double(get(hObject,'String')); + +% --- Executes during object creation, after setting all properties. +function edit2_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +global nmeas +set(hObject,'String',nmeas) + + +% --- Executes on button press in check_coupling. +function check_coupling_Callback(hObject, eventdata, handles) +% hObject handle to check_coupling (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +global coupling + +if get(hObject,'Value') + coupling =1; +else + coupling=0; +end +% Hint: get(hObject,'Value') returns toggle state of check_coupling + + +% --- Executes during object creation, after setting all properties. +function check_coupling_CreateFcn(hObject, eventdata, handles) +global coupling all_objects meas_type + +all_objects.coupling = hObject; + +if coupling + set(hObject,'Value',1) +else + set(hObject,'Value',0) +end + +if (meas_type==0)||(meas_type==2) + set(hObject,'Enable','off') +else + set(hObject,'Enable','on') +end + +% hObject handle to check_coupling (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes on button press in pushbutton2. +function pushbutton2_Callback(hObject, eventdata, handles) +matching_phase4p +% hObject handle to pushbutton2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + + + + + + +function edit3_Callback(hObject, eventdata, handles) +global nslices +nslices = str2double(get(hObject,'String')); +% hObject handle to edit3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit3 as text +% str2double(get(hObject,'String')) returns contents of edit3 as a double + + +% --- Executes during object creation, after setting all properties. +function edit3_CreateFcn(hObject, eventdata, handles) +global nslices all_objects +set(hObject,'String',nslices) +all_objects.nslices = hObject; +% hObject handle to edit3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + + +function edit4_Callback(hObject, eventdata, handles) +global phase_steps +phase_steps = str2double(get(hObject,'String')); +% hObject handle to edit4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit4 as text +% str2double(get(hObject,'String')) returns contents of edit4 as a double + + +% --- Executes during object creation, after setting all properties. +function edit4_CreateFcn(hObject, eventdata, handles) +global phase_steps all_objects +set(hObject,'String',phase_steps) +all_objects.phase_steps = hObject; + +% hObject handle to edit4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + + +function edit5_Callback(hObject, eventdata, handles) +global phase_dif +phase_dif = str2double(get(hObject,'String')); +% hObject handle to edit5 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit5 as text +% str2double(get(hObject,'String')) returns contents of edit5 as a double + + +% --- Executes during object creation, after setting all properties. +function edit5_CreateFcn(hObject, eventdata, handles) +global phase_dif all_objects +set(hObject,'String',phase_dif) +all_objects.phase_dif = hObject; + +% hObject handle to edit5 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + + +function edit6_Callback(hObject, eventdata, handles) +global phase0 +phase0 = str2double(get(hObject,'String')); +% hObject handle to edit6 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit6 as text +% str2double(get(hObject,'String')) returns contents of edit6 as a double + + +% --- Executes during object creation, after setting all properties. +function edit6_CreateFcn(hObject, eventdata, handles) +global phase0 all_objects +set(hObject,'String',phase0) +all_objects.phase0 = hObject; + +% hObject handle to edit6 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + +% --- Executes during object creation, after setting all properties. +function pushbutton2_CreateFcn(hObject, eventdata, handles) +global all_objects +all_objects.matching = hObject; +% hObject handle to pushbutton2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes when selected object is changed in uipanel4. +function uipanel4_SelectionChangeFcn(hObject, eventdata, handles) +global meas_type +if strcmp(get(hObject,'String'),'Projected multi quad') + meas_type = 1; +elseif strcmp(get(hObject,'String'),'Slice X (TDC)') + meas_type = 2; +elseif strcmp(get(hObject,'String'),'Projected single quad') + meas_type = 0; +elseif strcmp(get(hObject,'String'),'Slice Y (disp.)') + meas_type = 3; +elseif strcmp(get(hObject,'String'),'Slice X (disp.)') + meas_type = 4; +end + +en_dis(hObject, eventdata, handles) + +% hObject handle to the selected object in uipanel4 +% eventdata structure with the following fields (see UIBUTTONGROUP) +% EventName: string 'SelectionChanged' (read only) +% OldValue: handle of the previously selected object or empty if none was selected +% NewValue: handle of the currently selected object +% handles structure with handles and user data (see GUIDATA) + + +% --- Executes on button press in checkbox2. +function checkbox2_Callback(hObject, eventdata, handles) +global oper + +if get(hObject,'Value') + oper =1; +else + oper = 0; +end +% hObject handle to checkbox2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox2 + + +% --- Executes during object creation, after setting all properties. +function checkbox2_CreateFcn(hObject, eventdata, handles) +global oper all_objects + +all_objects.oper = hObject; + +if oper + set(hObject,'Value',1) +else + set(hObject,'Value',0) +end + +% hObject handle to checkbox2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes on button press in checkbox3. +function checkbox3_Callback(hObject, eventdata, handles) +global right_q + +if get(hObject,'Value') + right_q =1; +else + right_q = 0; +end +% hObject handle to checkbox3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox3 + + +% --- Executes during object creation, after setting all properties. +function checkbox3_CreateFcn(hObject, eventdata, handles) +global right_q all_objects + +all_objects.right_q = hObject; + +if right_q + set(hObject,'Value',1) +else + set(hObject,'Value',0) +end + +% hObject handle to checkbox3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes on selection change in SelectProfileMonitor. +function SelectProfileMonitor_Callback(hObject, eventdata, handles) +global PROFILEMONITOR +% we can just take the instrument name from the string of this menu +contents = cellstr(get(hObject,'String')); +PROFILEMONITOR = contents{get(hObject,'Value')}; + + +function SelectStepSize_Callback(hObject, eventdata, handles) +global K_STEPS +K_STEPS = str2double(get(hObject,'String')); + +% --- Bogus functions +function SelectProfileMonitor_CreateFcn(hObject, eventdata, handles) +function SelectStepSize_CreateFcn(hObject, eventdata, handles) + + +% --- Executes on selection change in popupmenu3. +function popupmenu3_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +global background +background = get(hObject,'Value'); + +% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu3 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu3 + + +% --- Executes during object creation, after setting all properties. +function popupmenu3_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + +% --- Executes during object creation, after setting all properties. +function radiobutton1_CreateFcn(hObject, eventdata, handles) +% hObject handle to radiobutton1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes during object creation, after setting all properties. +function meas_type_CreateFcn(hObject, eventdata, handles) +% hObject handle to meas_type (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + + +function edit8_Callback(hObject, eventdata, handles) +global en_chirp +en_chirp = str2double(get(hObject,'String')); +% hObject handle to edit8 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: get(hObject,'String') returns contents of edit8 as text +% str2double(get(hObject,'String')) returns contents of edit8 as a double + + +% --- Executes during object creation, after setting all properties. +function edit8_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit8 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +global en_chirp all_objects +set(hObject,'String',en_chirp) + +all_objects.en_chirp = hObject; + + +% Hint: edit controls usually have a white background on Windows. +% See ISPC and COMPUTER. +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + +% --- Executes on button press in checkbox4. +function checkbox4_Callback(hObject, eventdata, handles) +global TDC_cal + +if get(hObject,'Value') + TDC_cal =1; +else + TDC_cal = 0; +end +% hObject handle to checkbox4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox4 + + +% --- Executes during object creation, after setting all properties. +function checkbox4_CreateFcn(hObject, eventdata, handles) +global TDC_cal all_objects + +all_objects.TDC_cal = hObject; + +if TDC_cal + set(hObject,'Value',1) +else + set(hObject,'Value',0) +end +% hObject handle to checkbox4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called diff --git a/script/fft.py b/script/fft.py new file mode 100755 index 0000000..d90439c --- /dev/null +++ b/script/fft.py @@ -0,0 +1,26 @@ +################################################################################################### +# Demonstrate the use of fft function in mathutils.py +################################################################################################### + +from mathutils import fft, get_modulus +import random + +#The signal is composed by 3 sinusoids (100Hz, 200Hz, 400Hz) and a background noise (a sin waveform is A.sin(2.pi.f.t)) +def signal_generator(t): + return math.sin(100*2*math.pi*t) + 0.5 * math.sin(200*2*math.pi*t) + 0.25 * math.sin(400*2*math.pi*t) + 0.5* random.random() + +sampling_frequency = 1024.0 +number_of_samples = 1024 + +time_vector = [x / sampling_frequency for x in frange(0, number_of_samples, 1)] +signal = [signal_generator(x) for x in time_vector] + +tranform = fft(signal) +two_side_spectrum = [x / number_of_samples for x in get_modulus(tranform)] +spectrum = [two_side_spectrum[0],] + [x * 2 for x in two_side_spectrum[1:len(two_side_spectrum)/2 + 1] ] + +number_of_samples = len(tranform) # Signal may have been padded to next power of two +freq_vector = [x * sampling_frequency / float(number_of_samples) for x in frange(0, len(spectrum) , 1)] + +plot([signal,spectrum], ["signal", "spectrum"],[time_vector, freq_vector]) + \ No newline at end of file diff --git a/script/fit_radius.py b/script/fit_radius.py new file mode 100755 index 0000000..ed7ea29 --- /dev/null +++ b/script/fit_radius.py @@ -0,0 +1,54 @@ +from mathutils import * + +#Fiting center of circle of radius 70 to observerd points +radius = 70.0 +x = [30.0, 50.0, 110.0, 35.0, 45.0] +y = [68.0, -6.0, -20.0, 15.0, 97.0] +p = plot(y, xdata=x)[0] +num_samples = len(x) +w = [ 1.0] * num_samples +w = [0.1, 0.1, 1.0, 0.1, 1.0] +#I = MatrixUtils.createRealIdentityMatrix(len(w)) +W = MatrixUtils.createRealDiagonalMatrix(w) + + + # the model function components are the distances to current estimated center, + # they should be as close as possible to the specified radius +class Model(MultivariateJacobianFunction): + def value(self, variables): + (cx,cy) = (variables.getEntry(0), variables.getEntry(1)) + value = ArrayRealVector(num_samples) + jacobian = Array2DRowRealMatrix(num_samples, 2) + for i in range(num_samples): + model = math.hypot(cx-x[i], cy-y[i]) + value.setEntry(i, model) + # derivative with respect to p0 = x center + jacobian.setEntry(i, 0, (cx - x[i]) / model) + # derivative with respect to p1 = y center + jacobian.setEntry(i, 1, (cy - y[i]) / model) + return Pair(value, jacobian) + +model = Model() + +# the target is to have all points at the specified radius from the center +target = [radius,] * num_samples + +#least squares problem to solve : modeled radius should be close to target radius +initial = [0.0, 0.0 ] +problem = LeastSquaresBuilder().start(initial).model(model).target(target).lazyEvaluation(False).maxEvaluations(1000).maxIterations(1000).weight(W).build() +optimizer = LevenbergMarquardtOptimizer() +optimum = optimizer.optimize(problem) +cx, cy = optimum.getPoint().getEntry(0), optimum.getPoint().getEntry(1) + +print "fitted center x: ", cx +print "fitted center y: ", cy +print "" +print "RMS: " , optimum.getRMS() +print "evaluations: " , optimum.getEvaluations() +print "iterations: " , optimum.getIterations() + +from plotutils import * + +plot_point(p, cx, cy, name="Fit Cente") +plot_circle(p, cx, cy, radius, name="Fit") + diff --git a/script/flux_diode.py b/script/flux_diode.py new file mode 100755 index 0000000..a6d3e05 --- /dev/null +++ b/script/flux_diode.py @@ -0,0 +1,86 @@ +# from Clemens' flux calc & Robin's paper [Owen et al, JSR 16, 2009, Silicon PIN diodes] +#--------- formula -------------------------------------------- +# flux = I_ph * eps_Si /e/E/( 1-exp(A_Si*rsi*t_Si ) ) +# with Al and air atten: +# flux= flux * exp(A_Al*ral*t_Al) * exp(A_air*rair*t_air) +# +# with A_ being the photoelectric cross sections of the materials + +#--------- parameters ----------------------------------------- +# density of Si +rsi = 2.33 # g/cm^3 +# density of Al +ral = 2.699 # g/cm^3 +# density of air +rair = 1.205e-3 # g/cm^3 + +eps_si = 3.62 # eV energy req. for charge separation in Si (generation of el/hole pairs) +e = 1.602e-19 # As , elementary charge + +t_si = 0.0012 # thickness of diode in cm (== 12 micron) ; [* 10000] +t_al = 0.002 # thickness of diode in cm ; (== 20 micron) + +#--------- input--------------------------------------------------- + +cur = float(get_string('Please enter the measured diode current [in mA]', 0.1)) +ep = float(get_string('Please enter the photon energy [in keV]', 12.4 )) +t_si= float(get_string('Please enter the thickness of the Si layer [in micron]', t_si)) +t_si = t_si/10000. # --> cm +t_al = float(get_string('Please enter the thickness of the Al layer [in micron, 0 if not available]', t_al)) +t_al = t_al/10000 +t_air = float(get_string('Please enter the pathway in air [in mm]', 165.+100.)) + + +#--------- calc---------------------------------------------------- +# energy deposit in Silicon + +polys=[4.158,- 2.238, - 0.477, 0.0789] + +hlp_si= poly(math.log10(ep), polys) +A_Si= 10.0 ** hlp_si +efact=math.exp(-A_Si*rsi*t_si) + +sifact=1.0-efact + +#help, cur, eps_si, ep + +fl0=cur* eps_si/1.602/ep/sifact *1.e13 + + +# Aluminium attenuation + +# ratio of photoelectric cross section to density for Aluminium +polyal= [4.106, - 2.349, - 0.413, 0.0638 ] +hlp_al= poly(math.log10(ep), polyal) +A_Al= 10.0 ** hlp_al + +# attenuation due to aluminium +alfact=math.exp(-A_Al*ral*t_al) + +# Air attenuation + +# ratio of photoelectric cross section to density for air +polyair= [3.153, - 1.026, - 2.348, 0.928] +hlp_air= poly(math.log10(ep), polyair) +A_air= 10.0 ** hlp_air + +# attenuation due to air +airfact=math.exp(-A_air*rair*t_air/10.) + +# total flux from photocurrent + +fl=fl0/alfact/airfact + +f = fl + +msg = ' Energy: ' + '%7.4f' % e + ' keV\n' +msg = msg+ ' Diodecurrent: ' + str(cur).strip() +' mA\n' +msg = msg+ '\n' +msg = msg+ ' Thickness of active Si layer: ' + str(t_si*10000.).strip() + ' micron\n' +msg = msg+ ' Thickness of Al layer in front of diode: ' + str(t_al*10000.).strip() + ' micron\n' +msg = msg+ ' Length of path in air in front of diode: ' + str(t_air).strip() + ' mm\n' +msg = msg+ '\n' +msg = msg+ ' ===> flux: %8.2E photons / s' % f + +print msg +show_message(msg, "flux_diode", False) diff --git a/script/hfit.py b/script/hfit.py new file mode 100755 index 0000000..ad48bdc --- /dev/null +++ b/script/hfit.py @@ -0,0 +1,55 @@ +from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list, Gaussian +from mathutils import fit_polynomial,fit_gaussian, fit_harmonic, calculate_peaks +from mathutils import PolynomialFunction, Gaussian, HarmonicOscillator, LaguerreSolver +import math + + + +def hfit(ydata, xdata = None): + if xdata is None: + xdata = frange(0, len(ydata), 1) + + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + + start,end = min(xdata), max(xdata) + (amplitude, angular_frequency, phase) = fit_harmonic(ydata, xdata) + fitted_harmonic_function = HarmonicOscillator(amplitude, angular_frequency, phase) + + print "amplitude = ", amplitude + print "angular frequency = ", angular_frequency + print "phase = ", phase + + f = angular_frequency/ (2* math.pi) + print "frequency = ", f + + resolution = 0.01 + fit_y = [] + for x in frange(start,end,resolution, True): + fit_y.append(fitted_harmonic_function.value(x)) + fit_x = frange(start, end+resolution, resolution) + + p = plot(ydata,"data", xdata, title="HFit")[0] + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + #m = (phase + math.pi)/ angular_frequency + m = -phase / angular_frequency + if (m 0) else 1.0 + offset = -minV + return rescale(image, scale,offset, inPlace) + + +class MyFilter2(Filter): + def process(self, image, data): + image = grayscale(image) + image = translate(image, 100, 200, True) + #image = rescale(image, 1.0, 200.0, False) + return image + + +#Setting the filter to a source +img.setFilter(MyFilter2()) diff --git a/script/image10.py b/script/image10.py new file mode 100755 index 0000000..326cf1c --- /dev/null +++ b/script/image10.py @@ -0,0 +1,148 @@ +################################################################################################### +# Example of using ImageJ functionalities through ijutils. +################################################################################################### + +from ijutils import * +import java.awt.Color as Color + +#Image Loading +ip = load_image("images/img2.png", title="Image2") + +#Basic image manipulation: creation, copying, padding, saving +resized = resize(ip, 300,300) +save_image(resized,get_context().setup.expandPath("{images}/resized.tiff") ,"tiff") +crop=sub_image(ip,10,20,50,30) +bin_im = binning(ip,2) +new_im = new_image(256, 256, "color") +copy_image_to(bin_im, new_im, 20, 20) +pad_im = pad_image(ip, 1, 2, 3, 4, Color.RED) +stack=create_stack([ip,resized,crop, bin_im, new_im, pad_im], title = "Basic Functions") +save_image(stack,get_context().setup.expandPath("{images}/stack.tiff") ,"tiff") +stack.show() + + +#Decomposing color channels + +create_stack([ get_channel(ip, "red"), + get_channel(ip, "green"), + get_channel(ip, "blue"), + get_channel(ip, "alpha"), + grayscale(get_channel(ip, "brightness"), False)], title = "Color Decomposition").show() + + +#Basic functions (in_place) +aux1 = ip.duplicate() +aux1.show() +grayscale(aux1) +gaussian_blur(aux1); aux1.repaintWindow() +invert(aux1); aux1.repaintWindow() +smooth(aux1); aux1.repaintWindow() +sharpen(aux1); aux1.repaintWindow() +noise(aux1, 100); aux1.repaintWindow() + + +#Changing LUT +aux = ip.duplicate() +aux = grayscale(aux, in_place=False) +r,g,b = [],[],[] +for i in range(256): + r.append(0) + g.append(0) + b.append(i) +set_lut(aux, r, g, b) +aux.show() + + +#Histogram +plot(get_histogram(ip)) + + +#Binarization and binary operations +aux = grayscale(ip, in_place = False) +bin = ip.duplicate() +ip_bin = auto_threshold(aux, in_place=False) +create_stack([ ip_bin, + binary_outline(ip_bin, in_place=False), + binary_dilate(ip_bin, in_place=False), + binary_erode(ip_bin, in_place=False), + binary_open(ip_bin, in_place=False), + binary_close(ip_bin, in_place=False), + binary_skeletonize(ip_bin, in_place=False), + binary_fill_holes(ip_bin, in_place=False), + binary_outline(ip_bin, in_place=False)], title = "Binarization").show() + + +#EDM, const & image operations +aux = grayscale(ip, in_place = False) +ip_bin = auto_threshold(aux, in_place=False) +binary_fill_holes(ip_bin) + +edm = edm(ip_bin, in_place=False) +ws = watershed(ip_bin, in_place=False) +up = ultimate_points(ip_bin, in_place=False) +vr = veronoi(ip_bin, in_place=False) +edm_disp = remap(edm, in_place=False) +ws_disp = grayscale(ws, False) +up_disp = enhance_contrast(up, in_place=False) +vr_disp = enhance_contrast(vr, in_place=False) +create_stack([edm_disp, aux, ip_bin, ws_disp, up_disp, vr_disp], title = "EDM Operations").show() +final = grayscale(ip_bin, in_place = False) +op_const(final,"add", -200) +op_image(final, vr_disp, 'or') +op_image(final, up_disp, 'or') +final.show() + +aux = grayscale(ip, in_place = False) + +create_stack([ aux, + subtract_background(aux, in_place=False), + smooth(aux, False), + sharpen(aux, False), + edges(aux, False), + bandpass_filter(aux,0, 5, in_place=False), + bandpass_filter(aux,5, 100, in_place=False), + op_const(aux,"and", 127, False), + convolve(aux, KERNEL_BLUR, False), + convolve(aux, KERNEL_SHARPEN, False), + convolve(aux, KERNEL_SHARPEN_2, False), + convolve(aux, KERNEL_LIGHT, False), + convolve(aux, KERNEL_DARK, False), + convolve(aux, KERNEL_EDGE_DETECT, False), + convolve(aux, KERNEL_EDGE_DETECT_2, False), + convolve(aux, KERNEL_DIFFERENTIAL_EDGE_DETECT, False), + convolve(aux, KERNEL_PREWITT, False), + convolve(aux, KERNEL_SOBEL, False) + ], title = "General Operations").show() + + +#Rank operators +rank_opers = [] +for op in "mean", "min", "max", "variance", "median", "close_maxima", "open_maxima", "remove_outliers", "remove_nan", "despeckle": + rank_opers.append(op_rank(aux,op, in_place=False, kernel_radius=1)) +create_stack(rank_opers, title = "Rank Operations").show() + + +#Reslicing +#orig = load_image("{data}/img/img2.png") +orig = resize(ip, 300,200) +grayscale(orig) +images=[] +for i in range (20): + images.append(orig.duplicate()) + op_const(orig, "multiply", 0.9) +stack=create_stack(images, title = "Original Stack") +#stack.show() +r1 = reslice(stack, start_at="Left", title="Reslice Horizontally") +r2 = reslice(stack, start_at="Top", title="Reslice Vertically") +r1.show() +r2.show() + + +#Particle Analysis +aux = grayscale(ip, in_place = False) +auto_threshold(aux) +#binary_fill_holes(aux) +#aux.show() +(results,output_img)=analyse_particles(aux, 100,1000, print_table=True) +output_img.show() + diff --git a/script/image11.py b/script/image11.py new file mode 100755 index 0000000..2499b3d --- /dev/null +++ b/script/image11.py @@ -0,0 +1,22 @@ +run("pip") + +orig = load_image("{data}/img/img2.png") + +#orig.show() + +#Resize +resized = resize(orig, 300,300) + +#Sub-image +crop=sub_image(orig,10,20,50,30) + +bin_im = bin_image(orig,2) +new_im = new_image(256, 256, "color") +pad_im = pad_image(orig, 1, 2, 3, 4, Color.RED) + + + +stack=create_stack([orig,resized,crop, bin_im, new_im, pad_im]) +save_image(stack,context.setup.expandPath("{data}/img/out.tiff") ,"tiff") +stack.show() + diff --git a/script/image12.py b/script/image12.py new file mode 100755 index 0000000..0252819 --- /dev/null +++ b/script/image12.py @@ -0,0 +1,25 @@ +run("pip") + +orig = load_image("{data}/img/img2.png") +orig = resize(orig, 300,200) +grayscale(orig) +images=[] + +for i in range (20): + images.append(orig.duplicate()) + op_const(orig, "multiply", 0.9) + + +stack=create_stack(images) +stack.show() + +r1 = reslice(stack, start_at="Left") +r2 = reslice(stack, start_at="Top") +r1.show() +r2.show() + + +#x=new_image(800, 600, image_type="byte") +#copy_image_to(orig, x, 100, 200) +#x.show() + diff --git a/script/image13.py b/script/image13.py new file mode 100755 index 0000000..9e07c14 --- /dev/null +++ b/script/image13.py @@ -0,0 +1,28 @@ +#run("pip") +from pip import * + +ip = load_image("{data}/img/img3.png") + +auto_threshold(ip) + +#binary_outline(ip) +#binary_fill_holes(ip) +ip.show() + + + +(results,output_img)=analyse_particles(ip, 100,1000, print_table=True) +output_img.show() + +""" + +""" + +#static int SHOW_MASKS +#static int SHOW_NONE +#static int SHOW_OUTLINES +#static int SHOW_OVERLAY_MASKS +#static int SHOW_OVERLAY_OUTLINES +#static int SHOW_PROGRESS +#static int SHOW_RESULTS +#static int SHOW_ROI_MASKS \ No newline at end of file diff --git a/script/image14.py b/script/image14.py new file mode 100755 index 0000000..f9ebcf6 --- /dev/null +++ b/script/image14.py @@ -0,0 +1,164 @@ +################################################################################################### +# Example of using ImageJ functionalities through ijutils. +################################################################################################### + +from ijutils import * +import java.awt.Color as Color + +#Image Loading +ip1 = load_image("images/img1.png", title="Image1") +ip2 = load_image("images/img2.png", title="Image2") +ip3 = load_image("images/img3.png", title="Grid") +ip4 = load_image("images/img4.png", title="Square") + + +#Basic operaions creation, copying, padding, saving +resized = resize(ip2, 300,300) +save_image(resized,get_context().setup.expandPath("~/resized.tiff") ,"tiff") +crop=sub_image(ip2,10,20,50,30) +bin_im = binning(ip2,2) +new_im = new_image(256, 256, "color") +copy_image_to(bin_im, new_im, 20, 20) +pad_im = pad_image(ip2, 1, 2, 3, 4, Color.RED) +stack=create_stack([ip2,resized,crop, bin_im, new_im, pad_im], title = "Basic Functions") +save_image(stack,get_context().setup.expandPath("~/stack.tiff") ,"tiff") +stack.show() + + +#Decomposing color channels +ip1.show() +create_stack([ get_channel(ip1, "red"), + get_channel(ip1, "green"), + get_channel(ip1, "blue"), + get_channel(ip1, "alpha"), + grayscale(get_channel(ip1, "brightness"), False)], title = "Color Decomposition").show() + + +#Histogram +plot(get_histogram(ip1)) + +#Changing LUT +ip = ip1.duplicate() +ip = grayscale(ip, in_place=False) +r,g,b = [],[],[] +for i in range(256): + r.append(0) + g.append(0) + b.append(i) +set_lut(ip, r, g, b) +ip.show() + + +#Basic functions (in_place) +ip = ip1.duplicate() +ip.show() +grayscale(ip) +gaussian_blur(ip) +invert(ip) +smooth(ip) +sharpen(ip) +#edge(ip) +#add(ip) +#noise(ip, 100) +ip.show() + + +#Binarization and binary operations +ip = grayscale(ip2, in_place = False) +bin = ip1.duplicate() +ip_bin = auto_threshold(ip, in_place=False) +create_stack([ ip_bin, + binary_outline(ip_bin, in_place=False), + binary_dilate(ip_bin, in_place=False), + binary_erode(ip_bin, in_place=False), + binary_open(ip_bin, in_place=False), + binary_close(ip_bin, in_place=False), + binary_skeletonize(ip_bin, in_place=False), + binary_fill_holes(ip_bin, in_place=False), + binary_outline(ip_bin, in_place=False)], title = "Binarization").show() + + +#EDM, const & image operations +ip = grayscale(ip2, in_place = False) +ip_bin = auto_threshold(ip, in_place=False) +binary_fill_holes(ip_bin) + +edm = edm(ip_bin, in_place=False) +ws = watershed(ip_bin, in_place=False) +up = ultimate_points(ip_bin, in_place=False) +vr = veronoi(ip_bin, in_place=False) +edm_disp = remap(edm, in_place=False) +ws_disp = grayscale(ws, False) +up_disp = enhance_contrast(up, in_place=False) +vr_disp = enhance_contrast(vr, in_place=False) +create_stack([edm_disp, ip, ip_bin, ws_disp, up_disp, vr_disp], title = "EDM Operations").show() +final = grayscale(ip_bin, in_place = False) +op_const(final,"add", -200) +op_image(final, vr_disp, 'or') +op_image(final, up_disp, 'or') +final.show() + + +#Correlate, convolve, deconvolve +grayscale(ip3) +grayscale(ip4) +cor = op_fft(ip3, ip4, "correlate", True) +con = op_fft(ip3, ip4, "convolve", True) +dec = op_fft(con, ip4, "deconvolve", True) + +create_stack([ip3,ip4, grayscale(cor,False),grayscale(con,False),grayscale(dec,False)], title = "Correlation").show() + +ip = grayscale(ip2, in_place = False) + +create_stack([ ip, + subtract_background(ip, in_place=False), + smooth(ip, False), + sharpen(ip, False), + edges(ip, False), + bandpass_filter(ip,0, 5, in_place=False), + bandpass_filter(ip,5, 100, in_place=False), + op_const(ip,"and", 127, False), + convolve(ip, KERNEL_BLUR, False), + convolve(ip, KERNEL_SHARPEN, False), + convolve(ip, KERNEL_SHARPEN_2, False), + convolve(ip, KERNEL_LIGHT, False), + convolve(ip, KERNEL_DARK, False), + convolve(ip, KERNEL_EDGE_DETECT, False), + convolve(ip, KERNEL_EDGE_DETECT_2, False), + convolve(ip, KERNEL_DIFFERENTIAL_EDGE_DETECT, False), + convolve(ip, KERNEL_PREWITT, False), + convolve(ip, KERNEL_SOBEL, False) + ], title = "General Operations").show() + + +#Rank operators +rank_opers = [] +for op in "mean", "min", "max", "variance", "median", "close_maxima", "open_maxima", "remove_outliers", "remove_nan", "despeckle": + rank_opers.append(op_rank(ip,op, in_place=False, kernel_radius=1)) +create_stack(rank_opers, title = "Rank Operations").show() + + +#Reslicing +#orig = load_image("{data}/img/img2.png") +orig = resize(ip2, 300,200) +grayscale(orig) +images=[] +for i in range (20): + images.append(orig.duplicate()) + op_const(orig, "multiply", 0.9) +stack=create_stack(images, title = "Original Stack") +#stack.show() +r1 = reslice(stack, start_at="Left", title="Reslice Horizontally") +r2 = reslice(stack, start_at="Top", title="Reslice Vertically") +r1.show() +r2.show() + + +#Particle Analysis +ip = grayscale(ip2, in_place = False) +auto_threshold(ip) +#binary_fill_holes(ip) +#ip.show() +(results,output_img)=analyse_particles(ip, 100,1000, print_table=True) +output_img.show() + diff --git a/script/image2.py b/script/image2.py new file mode 100755 index 0000000..270ddd1 --- /dev/null +++ b/script/image2.py @@ -0,0 +1,30 @@ +################################################################################################### +# Demonstrate creation of an image filters and new source based on filter. +# Also demonstrate creation of image histogram and use of overlays. +################################################################################################### + + +import ch.psi.pshell.imaging.Filter as Filter +from ch.psi.pshell.imaging.Utils import * +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Pen as Pen + +import net.imglib2.script.bufferedimage.BufferedImageImg as BufferedImageImg + + +class MyFilter(Filter): + def process(self, image, data): + im = BufferedImageImg(image) + global last + image = grayscale(image) + i=None + if last is not None: + i = sub(image,last, False) + i = rescale(i,100.0, 0, True) + i = add(i, last, True) + i = rescale(i,10.0, 0, True) + last = image + return i + +#Setting the filter to a source +img.setFilter(MyFilter()) diff --git a/script/image3.py b/script/image3.py new file mode 100755 index 0000000..0978dcd --- /dev/null +++ b/script/image3.py @@ -0,0 +1,27 @@ +import ch.psi.pshell.imaging.Filter as Filter +from ch.psi.pshell.imaging.Utils import * +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Pen as Pen + +import net.imglib2.script.bufferedimage.BufferedImageImg as BufferedImageImg +import net.imglib2.script.algorithm.FFT as FFT +import net.imglib2.img.display.imagej.ImageJFunctions as ImageJFunctions + +bi = None +fftimg = None + +class MyFilter(Filter): + def process(self, image, data): + #image = rescale(image, 1.0, -20, True) + image = grayscale(image) + global bi, fftimg + bi = image + im = BufferedImageImg(image) + fft = FFT(im) + fftimg = fft + ret = ImageJFunctions.wrap(fft.image(), "").getBufferedImage() + return ret + +#Setting the filter to a source +tst.setFilter(MyFilter()) +tst.initialize() \ No newline at end of file diff --git a/script/image4.py b/script/image4.py new file mode 100755 index 0000000..f124a33 --- /dev/null +++ b/script/image4.py @@ -0,0 +1,28 @@ +run("pip") + +img = BufferedImageImg(bi) +diamondShape = DiamondShape( 8 ); + + +ImageJFunctions.show( img, "Source" ) + + + +#ImageJFunctions.show( Erosion.erode( img, StructuringElements.diamond( 8, 2, True ), 1 ), "NewSourceDecomp" ) +#ImageJFunctions.show( Erosion.erode( img, StructuringElements.diamond( 8, 2, False ), 1 ), "NewSourceStraight" ) +#ImageJFunctions.show( Erosion.erode( img, diamondShape, 1 ), "NewSourceSingle" ) +#Full +#ImageJFunctions.show( Erosion.erodeFull( img, StructuringElements.diamond( 8, 2, True ), 1 ), "NewFullSourceDecomp" ) +#ImageJFunctions.show( Erosion.erodeFull( img, StructuringElements.diamond( 8, 2, False ), 1 ), "NewFullSourceStraight" ) +#ImageJFunctions.show( Erosion.erodeFull( img, diamondShape, 1 ), "NewFullSourceSingle" ) + + +strel = StructuringElements.disk( 6, 2, 4 ) +for shape in strel: + print shape + print MorphologyUtils.printNeighborhood( shape, 2 ) + +minVal = FloatType(0) +ImageJFunctions.show (Dilation.dilateFull( img, strel, minVal, 1 )) + + diff --git a/script/image5.py b/script/image5.py new file mode 100755 index 0000000..9dde32a --- /dev/null +++ b/script/image5.py @@ -0,0 +1,24 @@ +import ch.psi.pshell.imaging.Filter as Filter +from ch.psi.pshell.imaging.Utils import * +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Pen as Pen +run("pip") + + +renderer = show_panel(tst) +com_overlay = Crosshairs(Pen(java.awt.Color.WHITE), java.awt.Point(-1,-1), java.awt.Dimension(15,15)) +renderer.clearOverlays() +renderer.addOverlays([com_overlay,]) + +class MyFilter(Filter): + def process(self, image, data): + aux = rescale(image, 1.0, -20, False) + ip = ImagePlus("Img", aux) + stats = get_statistics(ip,Measurements.CENTER_OF_MASS | Measurements.CENTROID ) + (x,y) = (stats.xCenterOfMass, stats.yCenterOfMass) + print x,y + com_overlay.update(java.awt.Point(int(x),int(y))) + return image + +tst.setFilter(MyFilter()) +tst.refresh() diff --git a/script/image6.py b/script/image6.py new file mode 100755 index 0000000..c1f3168 --- /dev/null +++ b/script/image6.py @@ -0,0 +1,108 @@ +run("pip") + +ip1_orig = load_image("{data}/img/img1.png") +ip1 = ip1_orig.duplicate() +#Decomposing color channels +ip1.show() +create_stack([get_channel(ip1, "red"), get_channel(ip1, "green"), get_channel(ip1, "blue"), get_channel(ip1, "alpha"), grayscale(get_channel(ip1, "brightness"), False)]).show() + + + + +ip2 = ip1_orig.duplicate() +grayscale(ip2) +r,g,b = [],[],[] +for i in range(256): + r.append(0) + g.append(0) + b.append(i) +set_lut(ip2, r, g, b) +ip2.show() + +""" +#gaussian_blur(ip1) +#invert(ip1) +#smooth(ip1) +#sharpen(ip1) +#edge(ip1) +#add(ip1) +#noise(ip1, 100) + +plot(get_histogram(ip1)) +#plot(get_array(ip1)) +#plot(get_line(ip1, 0,0, 100,100)) +#plot(get_pixels(ip1)) +#plot (get_col(ip1,1)) + +print get_pixel_range(ip1) +print get_num_channels(ip1) +print get_pixel(ip1,0,0) +print get_pixel_array(ip1,0,0) +stats = get_statistics(ip1) +print stats + +s2 = get_statistics(ip1,Measurements.CENTER_OF_MASS | Measurements.CENTROID ) +print s2 +print s2.xCenterOfMass, s2.yCenterOfMass +print s2.xCentroid , s2.yCentroid + +#pr1.subtract(80) +#pr1.setMinAndMax(20,80) +#pr1.rotate(20) + +""" + + +ip1_orig = load_image("{data}/img/img1.png") +ip1_grayscale = ip1_orig.duplicate() +grayscale(ip1_grayscale) + +pr1 = ip1_grayscale.getProcessor() + + + +#ip1 = threshold(ip1, 150, 255) +#auto_threshold(ip1) +#pr1.dilate() +#pr1.erode() + +""" +#print pr1.getAutoThreshold() +pr1.resetBinaryThreshold() +pr1.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.NO_LUT_UPDATE) +#pr1.setAutoThreshold(AutoThresholder.getMethods()[0], True , ImageProcessor.NO_LUT_UPDATE); +minThreshold = pr1.getMinThreshold(); +maxThreshold = pr1.getMaxThreshold(); +pr1.resetThreshold() +#pr1.threshold(80) + +fcolor=255 +bcolor=0 +lut = [] +for i in range(256): + if minThreshold <= i <=maxThreshold: + lut.append(fcolor) + else: + lut.append(bcolor) +pr1.applyTable(lut); +#pr1.autoThreshold() +#pr1.setBinaryThreshold() +min_threshold, max_threshold = 50, 200 + +pr1.setThreshold(min_threshold, max_threshold, ImageProcessor.NO_LUT_UPDATE); +WindowManager.setTempCurrentImage(ip1); +thresholder=Thresholder(); +thresholder.run("mask"); +bp = WindowManager.getCurrentImage().getProcessor(); + +ip1 = ImagePlus(ip1.getTitle() + " binary", bp); +""" + + +#shadows(ip1_grayscale, "north") +#voronoi(ip1_grayscale) +#ip1_grayscale.show() + + + + diff --git a/script/image7.py b/script/image7.py new file mode 100755 index 0000000..9b3d1a3 --- /dev/null +++ b/script/image7.py @@ -0,0 +1,45 @@ +run("pip") + +ip1_orig = load_image("{data}/img/img2.png") + +grayscale(ip1_orig) + +bin = ip1_orig.duplicate() + +auto_threshold(bin) + +edm = edm(bin, in_place=False) + + +ws = bin.duplicate() +ws.setTitle("watershed") +watershed(ws) + + +up = bin.duplicate() +up.setTitle("ultimate points") +ultimate_points(up) + +vr = bin.duplicate() +vr.setTitle("veronoi") +veronoi(vr) + +edm_disp = remap(edm, in_place=False) +#edm.duplicate() +#edm_disp.getProcessor().setMinAndMax(0,get_statistics(edm,Measurements.MIN_MAX).max) + + +ws_disp = grayscale(ws, False) +up_disp = enhance_contrast(up, in_place=False) +vr_disp = enhance_contrast(vr, in_place=False) + + +create_stack([edm_disp, ip1_orig, bin, edm_disp, ws_disp, up_disp, vr_disp]).show() + +final = bin.duplicate() +grayscale(final) +op_const(final,"add", -200) +op_image(final, vr_disp, 'or') +op_image(final, up_disp, 'or') + +final.show() \ No newline at end of file diff --git a/script/image8.py b/script/image8.py new file mode 100755 index 0000000..8faf845 --- /dev/null +++ b/script/image8.py @@ -0,0 +1,47 @@ +run("pip") + +ip1_orig = load_image("{data}/img/img1.png") + +ip1_grayscale = ip1_orig.duplicate() +grayscale(ip1_grayscale) + +pr1 = ip1_grayscale.getProcessor() + +#ip1_grayscale.show() + + +ip1_max = find_maxima(ip1_grayscale, 50, output_type=MaximumFinder.SINGLE_POINTS) +#ip1_max.show() +(x,y) = get_maxima_points(ip1_grayscale,50) +p=plot(x, xdata=Convert.toDouble(y))[0] +p.getSeries(0).setPointSize(5) +p.getSeries(0).setLinesVisible(False) + +""" +f = image_fft(ip1_grayscale, False) +#f.getProcessor().fillOval(50,50, 50, 50) +#f.getProcessor().fillOval(250,250, 50, 50) +i = image_ffti(f, False) +#f.show() +#i.show() + +""" + + + +#bandpass_filter(ip1_grayscale,0, 5) +#ip1_grayscale.show() +#edges(ip1_grayscale) + +#bandpass_filter(ip1,20,40) +#ip1.show() +ip_bin = ip1_grayscale.duplicate() +threshold(ip_bin, 80, 255) +#binary_skeletonize(ip_bin) + + +#enhance_contrast(ip1_grayscale) +op_rank (ip1_grayscale, "max", kernel_radius = 1.0) + +ip1_grayscale.show() +ip_bin.show() \ No newline at end of file diff --git a/script/image9.py b/script/image9.py new file mode 100755 index 0000000..eda45e1 --- /dev/null +++ b/script/image9.py @@ -0,0 +1,15 @@ +run("pip") + +ip1 = load_image("{data}/img/grid.png", title="Grid") +ip2 = load_image("{data}/img/square.png", title="Square") + +grayscale(ip1) +grayscale(ip2) + + +cor = op_fft(ip1, ip2, "correlate", True) +con = op_fft(ip1, ip2, "convolve", True) +dec = op_fft(con, ip2, "deconvolve", True) + +create_stack([ip1,ip2,grayscale(cor,False),grayscale(con,False),grayscale(dec,False)]).show() + diff --git a/script/imagej.py b/script/imagej.py new file mode 100755 index 0000000..f2b1ec5 --- /dev/null +++ b/script/imagej.py @@ -0,0 +1,164 @@ +################################################################################################### +# Example of using ImageJ functionalities through ijutils. +################################################################################################### + +from ijutils import * +import java.awt.Color as Color + +#Image Loading +ip1 = load_image("{images}/img1.png", title="Image1") +ip2 = load_image("{images}/img2.png", title="Image2") +ip3 = load_image("{images}/img3.png", title="Grid") +ip4 = load_image("{images}/img4.png", title="Square") + + +#Basic operaions creation, copying, padding, saving +resized = resize(ip2, 300,300) +save_image(resized,context.setup.expandPath("~/resized.tiff") ,"tiff") +crop=sub_image(ip2,10,20,50,30) +bin_im = binning(ip2,2) +new_im = new_image(256, 256, "color") +copy_image_to(bin_im, new_im, 20, 20) +pad_im = pad_image(ip2, 1, 2, 3, 4, Color.RED) +stack=create_stack([ip2,resized,crop, bin_im, new_im, pad_im], title = "Basic Functions") +save_image(stack,context.setup.expandPath("~/stack.tiff") ,"tiff") +stack.show() + + +#Decomposing color channels +ip1.show() +create_stack([ get_channel(ip1, "red"), + get_channel(ip1, "green"), + get_channel(ip1, "blue"), + get_channel(ip1, "alpha"), + grayscale(get_channel(ip1, "brightness"), False)], title = "Color Decomposition").show() + + +#Histogram +plot(get_histogram(ip1)) + +#Changing LUT +ip = ip1.duplicate() +ip = grayscale(ip, in_place=False) +r,g,b = [],[],[] +for i in range(256): + r.append(0) + g.append(0) + b.append(i) +set_lut(ip, r, g, b) +ip.show() + + +#Basic functions (in_place) +ip = ip1.duplicate() +ip.show() +grayscale(ip) +gaussian_blur(ip) +invert(ip) +smooth(ip) +sharpen(ip) +#edge(ip) +#add(ip) +#noise(ip, 100) +ip.show() + + +#Binarization and binary operations +ip = grayscale(ip2, in_place = False) +bin = ip1.duplicate() +ip_bin = auto_threshold(ip, in_place=False) +create_stack([ ip_bin, + binary_outline(ip_bin, in_place=False), + binary_dilate(ip_bin, in_place=False), + binary_erode(ip_bin, in_place=False), + binary_open(ip_bin, in_place=False), + binary_close(ip_bin, in_place=False), + binary_skeletonize(ip_bin, in_place=False), + binary_fill_holes(ip_bin, in_place=False), + binary_outline(ip_bin, in_place=False)], title = "Binarization").show() + + +#EDM, const & image operations +ip = grayscale(ip2, in_place = False) +ip_bin = auto_threshold(ip, in_place=False) +binary_fill_holes(ip_bin) + +edm = edm(ip_bin, in_place=False) +ws = watershed(ip_bin, in_place=False) +up = ultimate_points(ip_bin, in_place=False) +vr = veronoi(ip_bin, in_place=False) +edm_disp = remap(edm, in_place=False) +ws_disp = grayscale(ws, False) +up_disp = enhance_contrast(up, in_place=False) +vr_disp = enhance_contrast(vr, in_place=False) +create_stack([edm_disp, ip, ip_bin, ws_disp, up_disp, vr_disp], title = "EDM Operations").show() +final = grayscale(ip_bin, in_place = False) +op_const(final,"add", -200) +op_image(final, vr_disp, 'or') +op_image(final, up_disp, 'or') +final.show() + + +#Correlate, convolve, deconvolve +grayscale(ip3) +grayscale(ip4) +cor = op_fft(ip3, ip4, "correlate", True) +con = op_fft(ip3, ip4, "convolve", True) +dec = op_fft(con, ip4, "deconvolve", True) + +create_stack([ip3,ip4, grayscale(cor,False),grayscale(con,False),grayscale(dec,False)], title = "Correlation").show() + +ip = grayscale(ip2, in_place = False) + +create_stack([ ip, + subtract_background(ip, in_place=False), + smooth(ip, False), + sharpen(ip, False), + edges(ip, False), + bandpass_filter(ip,0, 5, in_place=False), + bandpass_filter(ip,5, 100, in_place=False), + op_const(ip,"and", 127, False), + convolve(ip, KERNEL_BLUR, False), + convolve(ip, KERNEL_SHARPEN, False), + convolve(ip, KERNEL_SHARPEN_2, False), + convolve(ip, KERNEL_LIGHT, False), + convolve(ip, KERNEL_DARK, False), + convolve(ip, KERNEL_EDGE_DETECT, False), + convolve(ip, KERNEL_EDGE_DETECT_2, False), + convolve(ip, KERNEL_DIFFERENTIAL_EDGE_DETECT, False), + convolve(ip, KERNEL_PREWITT, False), + convolve(ip, KERNEL_SOBEL, False) + ], title = "General Operations").show() + + +#Rank operators +rank_opers = [] +for op in "mean", "min", "max", "variance", "median", "close_maxima", "open_maxima", "remove_outliers", "remove_nan", "despeckle": + rank_opers.append(op_rank(ip,op, in_place=False, kernel_radius=1)) +create_stack(rank_opers, title = "Rank Operations").show() + + +#Reslicing +#orig = load_image("{data}/img/img2.png") +orig = resize(ip2, 300,200) +grayscale(orig) +images=[] +for i in range (20): + images.append(orig.duplicate()) + op_const(orig, "multiply", 0.9) +stack=create_stack(images, title = "Original Stack") +#stack.show() +r1 = reslice(stack, start_at="Left", title="Reslice Horizontally") +r2 = reslice(stack, start_at="Top", title="Reslice Vertically") +r1.show() +r2.show() + + +#Particle Analysis +ip = grayscale(ip2, in_place = False) +auto_threshold(ip) +#binary_fill_holes(ip) +#ip.show() +(results,output_img)=analyse_particles(ip, 100,1000, print_table=True) +output_img.show() + diff --git a/script/import.py b/script/import.py new file mode 100755 index 0000000..38681a1 --- /dev/null +++ b/script/import.py @@ -0,0 +1,42 @@ +#Script imported from: test1.xml + +#Variables +var1 = 0.0 + +#TODO: Set the diplay names of positioners and detectors +scan = ManualScan(['id278043'], ['id348623', 'id367393'] , [0.0], [31.0], [31]) +scan.start() + +#Creating channels: dimension 1 +#LinearPositioner id278043 +id278043 = Channel('TESTIOC:TESTCALCOUT:Input', type = 'd') +#ScalarDetector id348623 +id348623 = Channel('TESTIOC:TESTCALCOUT:Output', type = 'd') +#ScalarDetector id367393 +id367393 = Channel('TESTIOC:TESTSINUS:SinCalc', type = 'd') + +#Dimension 1 +#LinearPositioner id278043 +for setpoint1 in frange(0.0, 31.0, 1.0, True): + if setpoint1 > 31.0 or setpoint1 < 0.0: + break + id278043.put(setpoint1, timeout=None) # TODO: Set appropriate timeout + readback1 = id278043.get() + if abs(readback1 - setpoint1) > 0.5 : # TODO: Check accuracy + raise Exception('Actor id278043 could not be set to the value ' + str(setpoint1)) + #Dimension Actions + #Script action + #TODO: Move, if needed, this import to the file header: import time + time.sleep(0.1) + #Detector id348623 + detector1 = id348623.get() + #Detector id367393 + detector2 = id367393.get() + scan.append ([setpoint1], [readback1], [detector1, detector2]) + +#Closing channels +id278043.close() +id348623.close() +id367393.close() + +scan.end() diff --git a/script/import2.py b/script/import2.py new file mode 100755 index 0000000..44769ee --- /dev/null +++ b/script/import2.py @@ -0,0 +1,55 @@ +#Script imported from: test2.xml + +#Variables +var1 = 0.0 + +#TODO: Set the diplay names of positioners and detectors +scan = ManualScan(['id643271', 'id278043'], ['id348623', 'id367393'] , [0.0, 0.0], [5.0, 31.0], [5, 31]) +scan.start() + +#Creating channels: dimension 1 +#LinearPositioner id643271 +id643271 = Channel('TESTIOC:TESTCALC:MyCalc', type = 'd') +#Creating channels: dimension 2 +#LinearPositioner id278043 +id278043 = Channel('TESTIOC:TESTCALCOUT:Input', type = 'd') +#ScalarDetector id348623 +id348623 = Channel('TESTIOC:TESTCALCOUT:Output', type = 'd') +#ScalarDetector id367393 +id367393 = Channel('TESTIOC:TESTSINUS:SinCalc', type = 'd') + +#Dimension 1 +#LinearPositioner id643271 +for setpoint1 in frange(0.0, 5.0, 1.0, True): + if setpoint1 > 5.0 or setpoint1 < 0.0: + break + id643271.put(setpoint1, timeout=None) # TODO: Set appropriate timeout + readback1 = id643271.get() + if abs(readback1 - setpoint1) > 0.5 : # TODO: Check accuracy + raise Exception('Actor id643271 could not be set to the value ' + str(setpoint1)) + #Dimension 2 + #LinearPositioner id278043 + for setpoint2 in frange(0.0, 31.0, 1.0, True): + if setpoint2 > 31.0 or setpoint2 < 0.0: + break + id278043.put(setpoint2, timeout=None) # TODO: Set appropriate timeout + readback2 = id278043.get() + if abs(readback2 - setpoint2) > 0.5 : # TODO: Check accuracy + raise Exception('Actor id278043 could not be set to the value ' + str(setpoint2)) + #Dimension Actions + #Script action + #TODO: Move, if needed, this import to the file header: import time + time.sleep(0.01) + #Detector id348623 + detector1 = id348623.get() + #Detector id367393 + detector2 = id367393.get() + scan.append ([setpoint1, setpoint2], [readback1, readback2], [detector1, detector2]) + +#Closing channels +id278043.close() +id348623.close() +id367393.close() +id643271.close() + +scan.end() diff --git a/script/import5.py b/script/import5.py new file mode 100755 index 0000000..85120a7 --- /dev/null +++ b/script/import5.py @@ -0,0 +1,31 @@ +#Script imported from: test5.xml + +set_exec_pars(flush=False) +#set_preference(Preference.PLOT_DISABLED,True) +set_preference(Preference.TABLE_DISABLED,True) + +#TODO: Set the diplay names of positioners and detectors +scan = ManualScan(['id236750', 'id226053'], ['id246209'] , [0.0, 0.0], [1000.0, 1000.0], [1000, 1000]) +scan.start() + +#Creating channels: dimension 1 +#PseudoPositioner id236750 +#Timestamp id246209 +#Creating channels: dimension 2 +#PseudoPositioner id226053 + +#Dimension 1 +#PseudoPositioner id236750 +for setpoint1 in range(0, 1000): + readback1 = setpoint1 + #Detector id246209 + detector1 = java.lang.System.currentTimeMillis() + #Dimension 2 + #PseudoPositioner id226053 + for setpoint2 in range(0, 1000): + readback2 = setpoint2 + scan.append ([setpoint1, setpoint2], [readback1, readback2], [detector1]) + +#Closing channels + +scan.end() diff --git a/script/import7.py b/script/import7.py new file mode 100755 index 0000000..d895186 --- /dev/null +++ b/script/import7.py @@ -0,0 +1,52 @@ +#Script imported from: test7.xml + +#Variables +var1 = 0.0 + +#TODO: Set the diplay names of positioners and detectors +scan = ManualScan(['id278043'], ['id348623', 'id367393', 'id192931', 'id173831'] , [0.0], [31.0], [31]) +scan.start() + +#Creating channels: dimension 1 +#LinearPositioner id278043 +id278043 = Channel('TESTIOC:TESTCALCOUT:Input', type = 'd') +#ScalarDetector id348623 +id348623 = Channel('TESTIOC:TESTCALCOUT:Output', type = 'd') +#ScalarDetector id367393 +id367393 = Channel('TESTIOC:TESTSINUS:SinCalc', type = 'd') +#Timestamp id192931 + +#Dimension 1 +#LinearPositioner id278043 +for setpoint1 in frange(0.0, 31.0, 1.0, True): + if setpoint1 > 31.0 or setpoint1 < 0.0: + break + id278043.put(setpoint1, timeout=None) # TODO: Set appropriate timeout + readback1 = id278043.get() + if abs(readback1 - setpoint1) > 0.5 : # TODO: Check accuracy + raise Exception('Actor id278043 could not be set to the value ' + str(setpoint1)) + #Dimension Actions + #Script action + #Variable Mappings + x = Channel('TESTIOC:TESTSINUS:SinCalc', type = 'd') + #TODO: Move, if needed, this import to the file header: import time + time.sleep(0.1) + #print "==>" + str(x.getValue()) + #Detector id348623 + detector1 = id348623.get() + #Detector id367393 + detector2 = id367393.get() + #Detector id192931 + detector3 = float(java.lang.System.currentTimeMillis()) + #Manipulation id173831 + #Variable Mappings + v = detector2 + id173831 = v+100.0 + scan.append ([setpoint1], [readback1], [detector1, detector2, detector3, id173831]) + +#Closing channels +id278043.close() +id348623.close() +id367393.close() + +scan.end() diff --git a/script/jep1.py b/script/jep1.py new file mode 100755 index 0000000..883f3ab --- /dev/null +++ b/script/jep1.py @@ -0,0 +1,6 @@ +a = call_jep("numpy", "ones", [(2,3)]) +print a.getDimensions(), a.getData() + + +b = call_jep("numpy", "transpose", [a,]) +print b.getDimensions(), b.getData() diff --git a/script/jepcall.py b/script/jepcall.py new file mode 100755 index 0000000..8c92112 --- /dev/null +++ b/script/jepcall.py @@ -0,0 +1,14 @@ + + +def call_cpython(module, function, args = []): + j=__getJep() + f = "function_" + j.hashCode() + eval_cpython("from " + module + " import " + function + " as " + f) + return j.invoke(f, args) + + + +call_cpython("numpy", "ones", [(2,3)]) + + + diff --git a/script/jepscript.py b/script/jepscript.py new file mode 100755 index 0000000..c5258eb --- /dev/null +++ b/script/jepscript.py @@ -0,0 +1,15 @@ +import numpy +from java.lang import System + +def transpose(x): + return numpy.transpose(x) + + +for I in range(10): + System.out.println(I) + +b = numpy.ones((2,4)) +print b + +#System.out.println(x) +b \ No newline at end of file diff --git a/script/jepscript2.py b/script/jepscript2.py new file mode 100755 index 0000000..39840ea --- /dev/null +++ b/script/jepscript2.py @@ -0,0 +1,47 @@ +import numpy as np +import matplotlib.pyplot as plt + +# example data + +x = np.arange(0.1, 4, 0.5) +y = np.exp(-x) + +# example variable error bar values +yerr = 0.1 + 0.2*np.sqrt(x) +xerr = 0.1 + yerr + +# First illustrate basic pyplot interface, using defaults where possible. +plt.figure() +plt.errorbar(x, y, xerr=0.2, yerr=0.4) +plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") + +# Now switch to a more OO interface to exercise more features. +fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) +ax = axs[0,0] +ax.errorbar(x, y, yerr=yerr, fmt='o') +ax.set_title('Vert. symmetric') + +# With 4 subplots, reduce the number of axis ticks to avoid crowding. +ax.locator_params(nbins=4) + +ax = axs[0,1] +ax.errorbar(x, y, xerr=xerr, fmt='o') +ax.set_title('Hor. symmetric') + +ax = axs[1,0] +ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o') +ax.set_title('H, V asymmetric') + +ax = axs[1,1] +ax.set_yscale('log') +# Here we have to be careful to keep all y values positive: +ylower = np.maximum(1e-2, y - yerr) +yerr_lower = y - ylower + +ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr, + fmt='o', ecolor='g', capthick=2) +ax.set_title('Mixed sym., log y') + +fig.suptitle('Variable errorbars') + +plt.show() \ No newline at end of file diff --git a/script/jepscript3.py b/script/jepscript3.py new file mode 100755 index 0000000..bacab30 --- /dev/null +++ b/script/jepscript3.py @@ -0,0 +1,45 @@ +import numpy as np +from scipy.fftpack import fft + +def plot(x,y, block = True): + import matplotlib.pyplot as plt + plt.figure() + plt.plot(x, y) + plt.grid() + #if show: + plt.show(block=block) + + +def get_f(N,T,F): + x = np.linspace(0.0, N*T, N) + y=0.0 + for (a,f) in F: + y = y + a*np.sin(f * 2.0*np.pi*x) + return (x,y) + +def get_fft(x,y,T): + N = len(x) + yf = fft(y) + xf = np.linspace(0.0, 1.0/(2.0*T), N / 2) + yfp = 2.0/N * np.abs(yf[0:N/2]) + return (xf,yf,yfp) + +def get_fft2(y): + T = 1.0 / 800.0 + N = len(y) + yf = fft(y) + return yf + xf = np.linspace(0.0, 1.0/(2.0*T), N/2) + yfp = 2.0/N * np.abs(yf[0:N/2]) + return (xf,yf,yfp) + + +if __name__ == '__main__': + N = 600 # Number of sample points + T = 1.0 / 800.0 # sample spacing + F = [(1.0,50.0), (0.5,80.0)] #Sinuoisids + (x,y) = get_f(N,T,F) + (xf,yf,yfp) = get_fft(x,y,T) + + plot(x,y, False) + plot(xf,yfp) \ No newline at end of file diff --git a/script/jepscript4.py b/script/jepscript4.py new file mode 100755 index 0000000..1162d41 --- /dev/null +++ b/script/jepscript4.py @@ -0,0 +1,27 @@ +#from jeputils import * + +eval_jep("import jepscript3") +eval_jep("reload(jepscript3)") + + +N = 600 # Number of sample points +T = 1.0 / 800.0 # sample spacing +F = [(1.0,50.0), (0.5,80.0)] #Sinuoisids +(x,y) = call_jep("jepscript3", "get_f", [N,T,F]) + + +ret = call_jep("jepscript3", "get_fft2", [y,]) +print "---" +print ret +print "---" + +""" +ret = call_jep("jepscript3", "get_fft", [x,y,T]) + + +print ret +(xf,yf,yfp) = ret + +plot(y, xdata = x) +plot(yfp, xdata = xf) +""" \ No newline at end of file diff --git a/script/jeptest.py b/script/jeptest.py new file mode 100755 index 0000000..dea321b --- /dev/null +++ b/script/jeptest.py @@ -0,0 +1,27 @@ +import jep.Jep as Jep + +#if "j" in globals().keys(): +# j.close() + +if not "j" in globals().keys(): + j = Jep(False) +j.eval("from java.lang import System") +j.eval("s = 'Hello World'") +j.eval("System.out.println(s)") +j.eval("print(s)") +j.eval("print(s[1:-1])") + + + + +j.eval("import numpy"); +j.eval("numpy.ones((1,2))") +ret = j.getValue("_") + + + +#j.close() +#res= lscan(inp, sin, 0, 40, 10, 0.1) + + + diff --git a/script/jeptest3.py b/script/jeptest3.py new file mode 100755 index 0000000..5503db9 --- /dev/null +++ b/script/jeptest3.py @@ -0,0 +1,12 @@ +from jeputils import * +import ch.psi.utils.Convert as Convert +a = call_jep("numpy", "ones", [[400,200],'d']) + +while(True): + b = call_jep("numpy", "ones", [[400,200],'d']) + a = call_jep("cpython", "add", [a,b]) + s = call_jep("cpython", "sum", [a,]) + print a.getData()[0], s + sleep(0.01) + + diff --git a/script/jeptest4.py b/script/jeptest4.py new file mode 100755 index 0000000..35dcb20 --- /dev/null +++ b/script/jeptest4.py @@ -0,0 +1,19 @@ +from jeputils import * + + +import javax.swing.SwingUtilities as SwingUtilities +import java.lang.Runnable as Runnable + +#class MyRunnable (Runnable): +# def run(self): +# print "Starting" +# run_jep("cpython6") +# print "Started" +#SwingUtilities.invokeLater(MyRunnable()) + +eval_jep("import matplotlib") +eval_jep("matplotlib.use('TkAgg')") + +#run_jep("cpython5") +run_jep("cpython6") +#exec_cpython("cpython6") \ No newline at end of file diff --git a/script/launcher.py b/script/launcher.py new file mode 100755 index 0000000..e17b1d5 --- /dev/null +++ b/script/launcher.py @@ -0,0 +1,25 @@ +import sys +import json + +script = sys.argv[1] +function = sys.argv[2] +jsonargs = sys.argv[3] + +args =json.loads(jsonargs) + +i = script.rfind('/') +if i<0: + i = script.rfind('\\') +module = script[i+1:-3] + +path = script[:i+1] +sys.path.insert(1,path) + +cmd = "from " + module + " import " + function + " as function" +exec cmd + +ret = function(*args) +jsonret = json.dumps(ret) + +print jsonret + diff --git a/script/listener.groovy b/script/listener.groovy new file mode 100755 index 0000000..e390fba --- /dev/null +++ b/script/listener.groovy @@ -0,0 +1,28 @@ + +class Listener implements ch.psi.pshell.device.DeviceListener{ + void onStateChanged(ch.psi.pshell.device.Device device, state, former){ + } + + void onValueChanged(ch.psi.pshell.device.Device device, value, former){ + println "Moved to: " + value.toString() + } + + + void onValueChanging(ch.psi.pshell.device.Device device, value, former){ + if (value > 20){ + + throw new Exception("Forbidden move to " + value.toString()); + } + println "Moving to: " + value.toString() + " ... " + } + +} + +listener = new Listener() +inp.addListener(listener) + +try{ + lscan(inp, (sin), 0, 40, 20, 0.01) +} finally { + inp.removeListener(listener) +} diff --git a/script/listener.js b/script/listener.js new file mode 100755 index 0000000..6be3f3f --- /dev/null +++ b/script/listener.js @@ -0,0 +1,29 @@ + + var listenerClass = Java.extend(Java.type("ch.psi.pshell.device.DeviceListener")) + var listener = new listenerClass() { + onStateChanged: function (device, state, former) { + }, + onValueChanged: function (device, value, former) { + print ("Moved to: " + value.toString()) + }, + onValueChanging: function (device, value, former) { + if (value > 20){ + throw ("Forbidden move to " + value.toString()); + } + print ("Moving to: " + value.toString() + " ... ") + }, + } + + + + + + + +inp.addListener(listener) + +try{ + lscan(inp, [sin,], 0, 40, 20, 0.01) +} finally { + inp.removeListener(listener) +} diff --git a/script/listener.py b/script/listener.py new file mode 100755 index 0000000..fc8822d --- /dev/null +++ b/script/listener.py @@ -0,0 +1,47 @@ +""" +Create a device listener to interrupt the scan +""" +import java.lang.InterruptedException + + +class ListenerAO (ch.psi.pshell.device.DeviceListener): + def onStateChanged(self, device, state, former): + pass + def onValueChanged(self, device, value, former): + pass + def onValueChanging(self, device, value, former): + pass + +#Create a listener to the sensor, verifying the readback values. +class ListenerAI (DeviceListener): + def onValueChanged(self, device, value, former): + if value > 1.02: + print "Value over limit-> aborting" + abort() +listenerAI = ListenerAI() +ai1.addListener(listenerAI) + + + +#Create a listener to the positioner checking the setpoint before each command is sent. +class ListenerAO (DeviceListener): + def onStateChanged(self, device, state, former): + pass + def onValueChanged(self, device, value, former): + print "Moved to: " + str(value) + def onValueChanging(self, device, value, former): + if value > 20: + #Vetoing the change will abort the scan + raise Exception("Forbidden move to " + str(value)) + print "Moving to: " + str(value) + " ... " , +listenerAO = ListenerAO() +ao1.addListener(listenerAO) + + +try: + lscan(ao1, (ai1), 0, 40, 200, 0.01) +except java.lang.InterruptedException: + print "Aborted" +finally: + ai1.removeListener(listenerAI) + ao1.removeListener(listenerAO) diff --git a/script/local.groovy b/script/local.groovy new file mode 100755 index 0000000..1c34bc1 --- /dev/null +++ b/script/local.groovy @@ -0,0 +1,18 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Deployment specific global definitions - executed after startup.groovy +/////////////////////////////////////////////////////////////////////////////////////////////////// +import ch.psi.pshell.scan.ScanRecord + +System.out.println("OK") + +before_readout = { double[] pos-> println (pos) } + +after_readout = { ScanRecord rec->println (rec) } + +def onBeforeReadout(double[]pos){ + println (pos) +} + +def onAfterReadout(ScanRecord rec){ + println (rec) +} \ No newline at end of file diff --git a/script/local.js b/script/local.js new file mode 100755 index 0000000..a7bb602 --- /dev/null +++ b/script/local.js @@ -0,0 +1,13 @@ + +function onBeforeReadout(pos){ + print (pos) +} + + +function onAfterReadout(rec){ + print (rec) +} + + + +run("SimulatedDEvices") \ No newline at end of file diff --git a/script/local.py b/script/local.py new file mode 100755 index 0000000..3ddd1ab --- /dev/null +++ b/script/local.py @@ -0,0 +1,738 @@ +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Overlay as Overlay +import ch.psi.pshell.imaging.Pen as Pen +import java.awt.Font as Font +import java.awt.Point as Point +import java.awt.Color as Color +import ch.psi.pshell.crlogic.CrlogicPositioner as CrlogicPositioner +import ch.psi.pshell.crlogic.CrlogicSensor as CrlogicSensor + + +crlogic_config = {} +crlogic_config["class"] = "ch.psi.pshell.crlogic.CrlogicScan" +crlogic_config["prefix"] = "MTEST-HW3-CRL" +crlogic_config["ioc"] = "MTEST-VME-HW3.psi.ch" +crlogic_config["integrationTime"] = 0.01 +crlogic_config["additionalBacklash"] = 0.0 + + +#LOCAL DEFINITIONS + + +""" +from ch.psi.pshell.imaging.Utils import * +from ch.psi.pshell.imaging.Overlays import * +import ch.psi.pshell.imaging.Pen as Pen +import java.awt.Font as Font +import java.awt.Point as Point +old = ov if globals().has_key("ov") else None +r = show_panel(img) +ov1 = Text(Pen(Color.ORANGE), "TEXT", Font("Verdana", Font.PLAIN, 12) , Point(20,20), ) +ov2 = Rect(Pen(Color.ORANGE),Point(50,50), Point(100,100), ) +ov3 = Rect(Pen(Color.RED),Point(150,150), Point(200,200), ) +ov4 = Rect(Pen(Color.GREEN),Point(250,250), Point(300,300), ) +ov5 = Text(Pen(Color.ORANGE), "TEXT 2", Font("Verdana", Font.PLAIN, 12) , Point(-50,-50), ) +ov5.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_BOTTOM_RIGHT) +ov5.setFixed(True) +ov1.setFixed(True) +ov2.setFixed(True) +ov2.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT) +ov2.setMovable(True) +ov2.setSolid(True) +ov3.setFixed(True) +ov3.setMovable(True) +ov3.setSolid(True) +ov4.setMovable(True) +ov4.setSolid(True) +ov=[ov1,ov2, ov3, ov4, ov5] +r.updateOverlays(ov, old) +""" + +#from jeputils import * + +#det.data.monitored=True +import random + +#State listener: cleanup can be made at end of execution +def onStateChange(state, former, script): + if state == State.Closing: + #print "Closing the app" + pass + elif script is not None: + if state.isProcessing(): + #print "Started script " + script + pass + elif former.isProcessing(): + #print "Finished script " + script + pass + + +class Listener(ContextListener): + def onContextStateChanged(self, state, former): + onStateChange(state, former, get_context().runningScriptName) + + +def scan_e(start, end, step, settling_time = 0, accumulation_time = None, name = None): + """ + """ + if name is not None: + set_exec_pars(name = name) + print get_exec_pars().path + lscan(inp,out, start, end, step,settling_time) + + +#Simulated Devices + +#run("tutorial/devices") +#run("src/main/assembly/help/Tutorial/devices") +#run("devices") + +class SimulatedOutput(Writable): + def write(self, value): + pass + + +class SimulatedInput(Readable): + def __init__(self): + self.x = 0.0 + + def read(self): + self.x = self.x + 0.1 + noise = (random.random() - 0.5) / 20.0 + return math.sin(self.x) + noise + + +sout = SimulatedOutput() +sinp = SimulatedInput() + + +#Controler Evenrt Listener + + + + +clistener = Listener() +get_context().addListener(clistener) + + + +def trig_scienta(): + time.sleep(1.0) + +energy = None +class SimulatedEnergy(Writable): + def write(self, value): + self.put(value) + + def put(self, value, timeout = None): + global energy + energy = value + + def close(self): + pass + + @staticmethod + def test (): + return "asd" + + +class SimulatedEnergyReadback(Readable): + def read(self): + global energy + return energy; + + def get(self): + return self.read() + + def close(self): + pass + +sim_energy = SimulatedEnergy() +sim_energy_readback = SimulatedEnergyReadback() + + + + +#Device utilities +def integrate_image(): + data = scienta.data.read() + #Integrate and plot + (width,height) = scienta.getImageSize().tolist() + integration = [] + for i in range(width): + p=0.0 + for j in range(height): + p=p+data[j*width+i] + integration.append(p) + return integration + +def trig_scienta(): + #scienta.start() + #scienta.waitReady(-1) + time.sleep(1.0) + pass + + +#Pseudo-Devices +class ImageIntegrator(ReadableArray): + def getSize(self): + (width,height) = scienta.getImageSize().tolist() + return width + + def read(self): + return to_array(integrate_image(),'d') + +integration = ImageIntegrator() + + +""" +class Interlock(DeviceAdapter): + def onValueChanging(self, device, value, former): + if value > 5.0: + raise Exception("Interlocked") + + + +motor.addListener(Interlock()) +""" + +#This procedude is used to emulate file names generated by FDA +""" +import ch.psi.pshell.data.LayoutTable +class Layout( ch.psi.pshell.data.LayoutTable): + def getLogFileName(self): + return time.strftime('%Y%m%d%H%M%S') + '_' + get_exec_pars().name + '_logs' + + def getDatasetName(self, scan): + return time.strftime('%Y%m%d%H%M%S') + '_' + get_exec_pars().name + '_' + str(get_exec_pars().index).zfill(4) + +get_context().dataManager.setLayout(Layout()) + +""" + +""" +import ch.psi.pshell.data.LayoutTable +class DataLayout( ch.psi.pshell.data.LayoutTable): + def getLogFileName(self): + return time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().script + '_logs' + + def getDatasetName(self, scan): + print get_exec_pars().count + data_file = time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().name + '_' + str(get_exec_pars().count).zfill(4) + print "Opened data file: " + get_exec_pars().path + "/" + data_file + return data_file +get_context().dataManager.setLayout(DataLayout()) +""" + +#Interlocks +""" +class MyInterlock1 (Interlock): +#Motor and Positioners + def __init__(self): + Interlock.__init__(self, (motor, pe)) + + def check(self, (m, p)): + if p>50.0 and (m<50 and m>40): + return False + return True + +interlock1 = MyInterlock1() +""" + +""" +#Motor group +class MyInterlock2(Interlock): + def __init__(self): + Interlock.__init__(self, (table, pe)) + + def check(self, ((m1,m2), p)): + if p<500 and (m1>4 and m2>4): + return False + return True + +interlock2 = MyInterlock2() + +""" + +""" +#Discrete Positioner +class MyInterlock3(Interlock): + def __init__(self): + Interlock.__init__(self, (tab, pe)) + + def check(self, (tab, p)): + if p<500 and tab=="Out": + return False + return True + +interlock3 = MyInterlock3() +""" +""" + +import ch.psi.pshell.data.LayoutTable +class DataLayout( ch.psi.pshell.data.LayoutTable): + def getLogFileName(self): + return time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().name + '_logs' + + def getDatasetName(self, scan): + print get_exec_pars().count + data_file = time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().name + '_' + str(get_exec_pars().count).zfill(4) + print "Opened data file: " + get_exec_pars().path + "/" + data_file + return data_file +get_context().dataManager.setLayout(DataLayout()) +""" + + +#run("CPython/wrapper") + +class SimulatedImage(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def __init__(self, size_x=1280, size_y=960, number_of_dead_pixels=100, noise=0.1, beam_size_x=100, beam_size_y=20): + self.size_x, self.size_y, self.number_of_dead_pixels, self.noise, self.beam_size_x, self.beam_size_y = \ + size_x, size_y, number_of_dead_pixels, noise, beam_size_x, beam_size_y + self.sc = None + + def doRead(self): + if self.sc is None: + self.sc = new_simulated_camera(self.size_x, self.size_y, self.number_of_dead_pixels, self.noise, self.beam_size_x, self.beam_size_y) + ret = get_image() + return Convert.reshape(ret,self.size_y, self.size_x) + + def getWidth(self): + return self.width + + def getHeight(self): + return self.height + +add_device(RegisterMatrixSource("sim", SimulatedImage()), True) +sim.polling = -250 + + + + +def get_next_fid(folder, prefix, ext): + try: + import glob + files = glob.glob(folder + prefix + '*_*.dat') + last = max(files) + index = int (last[last.rfind('_')+1 : last.rfind('.')]) + 1 + return index + except: + return 0 + +def wait_channel(name, value, timeout =None, type='s'): + print "Waiting " + str(name) + " = " + str(value) + cawait(name, value, timeout = timeout, type=type) + print "Done waiting" + +def convert_file(input_file_name, output_file_name, field = 0, pol = 0, keithley_3 = False): + sep = "\t" + line_sep = "\n" + with open(input_file_name) as inp: + lines = inp.readlines() + with open(output_file_name, "wb") as out: + out.write("Energy" + sep + "rbkenergy" + sep + "Mag" + sep + "Pol" + sep + "Io" + sep + "TEY" + sep + "Norm" + line_sep) + s = sep + " " #File format has a space before numeric values + for line in lines[1:]: + line = line.strip() + if line=="": break + try: + (Ecrbk,CADC1, CADC2, NORM, CADC3, CADC4, MCurr, cffrbk, ID1Erbk, ID2Erbk, vTime) = line.split(" ") + #out.write(Ecrbk + sep + Ecrbk + sep + str(field) + sep + str(pol) + sep + CADC1 + sep + CADC2 + sep + (CADC3 if keithley_3 else NORM) + line_sep) + out.write(" " + Ecrbk + s + Ecrbk + s + str(field) + s + str(pol) + s + CADC1 + s + CADC2 + s + (CADC3 if keithley_3 else NORM) + line_sep) + except: + traceback.print_exc() + +def plot_file(file, title = None): + """ + """ + table = Table.load(file, "\t", '#') + plots = plot(table, title = title) + + + + + +from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list, Gaussian,fit_harmonic,HarmonicOscillator +import java.awt.Color as Color + +def fit(ydata, xdata = None): + if xdata is None: + xdata = frange(0, len(ydata), 1) + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + print "Max index:" + str(index_max), + print " x:" + str(max_x), + print " y:" + str(max_y) + + gaussians = fit_gaussians(ydata, xdata, [index_max,]) + p = plot([ydata],["data"],[xdata], title="Fit" )[0] + + if gaussians[0] is None: #Fitting error + p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY) + print "Fitting error - using max value" + return (None, max_x, None) + + (norm, mean, sigma) = gaussians[0] + + fitted_gaussian_function = Gaussian(norm, mean, sigma) + scale_x = [float(min(xdata)), float(max(xdata)) ] + points = max((len(xdata)+1), 100) + resolution = (scale_x[1]-scale_x[0]) / points + fit_y = [] + fit_x = frange(scale_x[0],scale_x[1],resolution, True) + for x in fit_x: + fit_y.append(fitted_gaussian_function.value(x)) + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + if abs(mean - xdata[index_max]) < ((scale_x[0] + scale_x[1])/2): + print "Mean -> " + str(mean) + p.addMarker(mean, None, "Mean="+str(round(norm,2)), Color.MAGENTA.darker()) + return (norm, mean, sigma) + else: + p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY) + print "Invalid gaussian fit: " + str(mean) + " - using max value" + return (None, max_x, None) + +def hfit(ydata, xdata = None): + if xdata is None: + xdata = frange(0, len(ydata), 1) + + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + + start,end = min(xdata), max(xdata) + (amplitude, angular_frequency, phase) = fit_harmonic(ydata, xdata) + fitted_harmonic_function = HarmonicOscillator(amplitude, angular_frequency, phase) + + print "amplitude = ", amplitude + print "angular frequency = ", angular_frequency + print "phase = ", phase + + f = angular_frequency/ (2* math.pi) + print "frequency = ", f + + resolution = 0.01 + fit_y = [] + for x in frange(start,end,resolution, True): + fit_y.append(fitted_harmonic_function.value(x)) + fit_x = frange(start, end+resolution, resolution) + + p = plot(ydata,"data", xdata, title="HFit")[0] + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + #m = (phase + math.pi)/ angular_frequency + m = -phase / angular_frequency + if (m0: + plots[0].clear() + +def add_convex_hull_plot(title, x,y, name=None, clear = False, x_range = None, y_range = None): + plots = get_plots(title = title) + p = None + if len(plots)==0: + p = plot(None,name=name, title = title)[0] + if x_range is not None: + p.getAxis(p.AxisId.X).setRange(x_range[0], x_range[1]) + if y_range is not None: + p.getAxis(p.AxisId.Y).setRange(y_range[0], y_range[1]) + p.setLegendVisible(True) + else: + p = plots[0] + if clear: + p.clear() + p.addSeries(LinePlotSeries(name)) + s = p.getSeries(name) + s.setLinesVisible(False) + s.setPointSize(3) + x, y = to_array(x,'d') , to_array(y,'d') + s.setData(x, y) + + #Convex Hull + #In the first time the plot shows, it takes some time for the color to be assigned + timeout = 0 + while s.color is None and timeout<1000: + time.sleep(0.001) + timeout = timeout + 1 + hull = LinePlotSeries(name + "Hull", s.color) + p.addSeries(hull) + #Bounding box + #x1,x2,y1,y2 = min(x), max(x), min(y), max(y) + #(hx,hy) = ([x1,x2, x2, x1, x1], [y1, y1, y2, y2, y1]) + (hx,hy) = convex_hull(x=x, y=y) + hx.append(hx[0]); hy.append(hy[0]) + hull.setLineWidth(2) + hull.setData(to_array(hx,'d') , to_array(hy,'d')) + hull.setColor(s.color) + return [hx,hy] + + + + +class CamtoolValue(Readable): + def __init__(self, channel, alias = None): + self.channel=channel + set_device_alias(self, channel if (alias is None) else alias) + + def read(self): + return camtool.getValue(self.channel) + +class CamtoolArray(ReadableArray): + def __init__(self, channel, alias = None): + self.channel=channel + set_device_alias(self, channel if (alias is None) else alias) + + def read(self): + return camtool.getValue(self.channel) + + def getSize(self): + return len(camtool.getValue(self.channel)) + + + +class CamtoolImage(ReadableMatrix): + def __init__(self, alias = None): + set_device_alias(self, camtool.getCurrentCamera() + " image" if (alias is None) else alias) + + def read(self): + return camtool.getData().matrix + + def getWidth(self): + return camtool.getData().width + + def getHeight(self): + return camtool.getData().height + + +def wait_camtool_message(number_messages = 1, timeout = 10000): + for i in range (number_messages): + if not camtool.stream.waitCacheChange(timeout): raise Exception("Timeout receiving from Camtool") + + +def get_camtool_stats(number_images=1, async = True, interval=-1, good_region = False): + #return [CamtoolValue("gr_x_fit_mean"), CamtoolValue("gr_y_fit_mean"), CamtoolValue("gr_x_fit_standard_deviation"), CamtoolValue("gr_y_fit_standard_deviation")] + ret = [] + wait_camtool_message() + prefix = "gr_" if good_region else "" + for ident in [prefix+"x_fit_mean", prefix+"y_fit_mean", prefix+"x_fit_standard_deviation", prefix+"y_fit_standard_deviation"]: + child = camtool.stream.getChild(ident) + av = create_averager(child, number_images, interval) + av.monitored = async + ret.append(av) + return ret + + + +""" +import ch.psi.fda.LayoutFDA +class DataLayout( ch.psi.fda.LayoutFDA): + def getLogFileName(self): + return time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().name + '_logs' + + def getDatasetName(self, scan): + return time.strftime('%Y%m%d_%H%M') + '_' + get_exec_pars().name + '_' + str(get_exec_pars().count-1).zfill(4) +get_context().dataManager.setLayout(DataLayout()) + +""" + + +def is_panel(): + return get_exec_pars().source == CommandSource.plugin + +def is_ui(): + return get_exec_pars().source == CommandSource.ui + + +class AnalogOutput(RegisterBase): + def doRead(self): + return self.val if hasattr(self, 'val') else 0.0 + + def doWrite(self, val): + self.val = val + +class Sinusoid(ReadonlyRegisterBase): + def doRead(self): + noise = (random.random() - 0.5) * 0.15 + return round(math.sin(1.0*time.time()) + noise , 3) + +class Bpm(ReadonlyRegisterBase): + def doRead(self): + noise = (random.random() - 0.5) * 0.15 + return round(math.sin(0.5*math.radians(phase.read())) + noise , 3) + +class SinusoidWaveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + time.sleep(0.001) + ret = [] + x = random.random() + for i in range (20): + ret.append(math.sin(x)) + x = x + 0.1 + return ret + + def getSize(self): + return len(self.take(-1)) #only reads if cache is None + +class SinusoidImage(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def doRead(self): + time.sleep(0.001) + (width, height) = (200, 100) + ret = [] + x = random.random(); + base = [] + for i in range (width): + base.append( math.sin(x)) + x = x + 0.05 + for i in range (height): + noise = (random.random() - 0.5)/5.0 + ret.append([x+noise for x in base]) + return to_array(ret,'d') + def getWidth(self): + return len(self.take(-1)[0]) + + def getHeight(self): + return len(self.take(-1)) +""" + +add_device(Bpm("bpm_x"), True) +add_device(Sinusoid("amplitude"), True) +add_device(Sinusoid("power"), True) +add_device(SinusoidWaveform("waveform1"), True) +add_device(SinusoidImage("detector1"), True) +import ch.psi.pshell.imaging.RegisterMatrixSource as RegisterMatrixSource +add_device(RegisterMatrixSource("image1", detector1), True) + +bpm_x.setPolling(100) +waveform1.setPolling(1000) +image1.setPolling(-200) + +add_device(DummyPositioner("phase"),True) +""" \ No newline at end of file diff --git a/script/local_1.js b/script/local_1.js new file mode 100755 index 0000000..17db863 --- /dev/null +++ b/script/local_1.js @@ -0,0 +1,4 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Deployment specific global definitions - executed after startup.js +/////////////////////////////////////////////////////////////////////////////////////////////////// + diff --git a/script/lscov.py b/script/lscov.py new file mode 100755 index 0000000..a799942 --- /dev/null +++ b/script/lscov.py @@ -0,0 +1,66 @@ +import org.apache.commons.math3.geometry.euclidean.twod.Vector2D as Vector2D +import org.apache.commons.math3.linear.ArrayRealVector as ArrayRealVector +import org.apache.commons.math3.linear.Array2DRowRealMatrix as Array2DRowRealMatrix +import org.apache.commons.math3.linear.MatrixUtils as MatrixUtils +import org.apache.commons.math3.util.Pair as Pair +import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer as LevenbergMarquardtOptimizer +import org.apache.commons.math3.fitting.leastsquares.MultivariateJacobianFunction as MultivariateJacobianFunction +import org.apache.commons.math3.fitting.leastsquares.LeastSquaresBuilder as LeastSquaresBuilder +import org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer as LevenbergMarquardtOptimizer + + + +x = [12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0] +y = [30.0, 21.0, 17.0, 15.0, 16.0, 19.0, 22.0, 33.0] +v = [0.25, 0.5, 0.75, 0.33, 0.7. 0.35, 0.22, 0.35] + +num_samples = len(x) +w = [1.0/i for i in v] + +W = MatrixUtils.createRealDiagonalMatrix(w) + + + + +initial = [1.0, 1.0, 1.0] #a, b, c + + +class Model(MultivariateJacobianFunction): + def value(self, variables): + value = ArrayRealVector(num_samples) + jacobian = Array2DRowRealMatrix(num_samples, 3) + for i in range(num_samples): + (a,b,c) = (variables.getEntry(0), variables.getEntry(1), variables.getEntry(2)) + model = a*x[i]*x[i] + b*x[i] + c + value.setEntry(i, model) + + # derivative with respect to a + jacobian.setEntry(i, 0, x[i]*x[i]) + # derivative with respect to b + jacobian.setEntry(i, 1, x[i]) + # derivative with respect to c + jacobian.setEntry(i, 2, 1.0) + + return Pair(value, jacobian) + + +model = Model() + +# the target is to have all points at the specified radius from the center +target = [v for v in y] + +problem = LeastSquaresBuilder().start(initial).model(model).target(target).lazyEvaluation(False).maxEvaluations(1000).maxIterations(1000).weight(W).build() + +optimizer = LevenbergMarquardtOptimizer() +optimum = optimizer.optimize(problem) +optimalValues = optimum.getPoint() +a,b,c = optimum.getPoint().getEntry(0), optimum.getPoint().getEntry(1), optimum.getPoint().getEntry(2) + +print "A: ", a +print "B: ", b +print "C: ", c +print "" +print "RMS: " , optimum.getRMS() +print "evaluations: " , optimum.getEvaluations() +print "iterations: " , optimum.getIterations() + diff --git a/script/mathtests.py b/script/mathtests.py new file mode 100755 index 0000000..1e8d0df --- /dev/null +++ b/script/mathtests.py @@ -0,0 +1,50 @@ + +from mathutils import * + +""" +a = [1,2,3,4,7,10,50,4,3,2,1,2,1,1,2,3,4,7,10,50,4,3,2,1,1,2,1,2,3,4,7,10,50,4,3,2,1,2,1,2,3,4,7,10,50,4,3,2,1,1,2,1,2,3,4,7,10,50,4,3,2,1,2] +ft = fft(a) +it = ffti(ft) +plot([a,get_real(ft),get_imag(ft) ,get_real(it),get_imag(it)],("a", "real","img", "i real","i img")) + + + +data = [2,3,4,10,20,5,3,2,1] +print estimate_peak_indexes(data) +print estimate_peak_indexes(data, threshold =21.0) +print estimate_peak_indexes(data, positive=False) +print estimate_peak_indexes(data, threshold =1.0, positive=False) +print estimate_peak_indexes(data, threshold = None, min_peak_distance = 10.0 , positive=False) +xdata = [1,3,7,23,34,45,56,58, 61] +print estimate_peak_indexes(data, xdata, threshold = None, min_peak_distance = 10.0 , positive=False) + +""" + + + + +import random + +#A sin wave is: A.sin(2.pi.f.t) +#The signal is composed by 3 sinusoids (100Hz, 200Hz, 400Hz) and a background noise +def signal_generator(t): + return math.sin(100*2*math.pi*t) + 0.5 * math.sin(200*2*math.pi*t) + 0.25 * math.sin(400*2*math.pi*t) + 0.5* random.random() + +sampling_frequency = 1024.0 +number_of_samples = 1024 + +time_vector = [x / sampling_frequency for x in frange(0, number_of_samples, 1)] +signal = [signal_generator(x) for x in time_vector] + +tranform = fft(signal) +two_side_spectrum = [x / number_of_samples for x in get_modulus(tranform)] +spectrum = [two_side_spectrum[0],] + [x * 2 for x in two_side_spectrum[1:len(two_side_spectrum)/2 + 1] ] + + +number_of_samples = len(tranform) # Signal may have been padded to next power of two +freq_vector = [x * sampling_frequency / float(number_of_samples) for x in frange(0, len(spectrum) , 1)] + +#print f + +plot([signal,spectrum], ["signal", "spectrum"],[time_vector, freq_vector]) +#plot(p1, xdata = f) \ No newline at end of file diff --git a/script/mult.txt b/script/mult.txt new file mode 100755 index 0000000..59f4a22 --- /dev/null +++ b/script/mult.txt @@ -0,0 +1,2 @@ +scan E Fe.cfg +start \ No newline at end of file diff --git a/script/mxsc/Calibration1 b/script/mxsc/Calibration1 new file mode 100755 index 0000000..716f0e1 --- /dev/null +++ b/script/mxsc/Calibration1 @@ -0,0 +1,19 @@ +CAMERA = tst + + +r = show_panel(tst) + + +def get_point(name): + m = show_message("Click at point:" + name, title = "Calibration", blocking = False) + return r.waitClick(100000) + + + +p1 = get_point("p1") +p2 = get_point("p2") +p3 = get_point("p3") +p4 = get_point("p4") + + +print p1, p2, p3, p4 \ No newline at end of file diff --git a/script/np.py b/script/np.py new file mode 100755 index 0000000..50bfd6f --- /dev/null +++ b/script/np.py @@ -0,0 +1,31 @@ +import numpy as np +import sys + + +def add(a1, a2): + #raise Exception("Test") + x = np.array(a1, dtype=np.float64) + y = np.array(a2, dtype=np.float64) + return np.add(x, y).tolist() + + +if __name__ == "__main__": + print sys.argv + x = np.array([[1,2],[3,4]], dtype=np.float64) + y = np.array([[5,6],[7,8]], dtype=np.float64) + print "---------------" + print x + y + print np.add(x, y) + print np.add(x, y).tolist() + print "---------------" + print x - y + print np.subtract(x, y) + print "---------------" + print x * y + print np.multiply(x, y) + print "---------------" + print x / y + print np.divide(x, y) + print "---------------" + print np.sqrt(x) + print "---------------" diff --git a/script/parallel.groovy b/script/parallel.groovy new file mode 100755 index 0000000..2a4b955 --- /dev/null +++ b/script/parallel.groovy @@ -0,0 +1,39 @@ +import ch.psi.pshell.device.Device + +before_readout = { double[] pos-> println (pos) } +before_readout = { double[] pos-> println (pos) } +before_readout = { double[] pos-> println (pos) } + + +task1 = { + motor.moveRel(1.0) + return motor.getPosition() + } + +task2 = { + motor2.moveRel(1.0) + return motor2.getPosition() + } + +task3 = { + return sin.read() + } + +task4 = { ch.psi.pshell.device.Motor motor, double step -> + print ("Moving " + motor.getName() + " step = " + step) + motor.moveRel(step) + return motor.getPosition() +} + + +//ret = parallelize(task1, task2, task3) + +//ret = fork(task1, task2, task3) +//println (ret) +//ret = join(ret) + + +ret = parallelize(task4.rcurry(motor,1), task4.rcurry(motor2,1)) + + +println (ret) diff --git a/script/parallel.js b/script/parallel.js new file mode 100755 index 0000000..ba307a2 --- /dev/null +++ b/script/parallel.js @@ -0,0 +1,33 @@ +function task1() { + m1.moveRel(1.0) + return m1.getPosition() + } +function task2() { + m2.moveRel(1.0) + return m2.getPosition() + } + +function task3() { + return ai1.read() + } + +function moveRelative(args){ + var motor = args[0] + var step = args[1] + print ("Moving " + m1.getName() + " step = " + step) + m1.moveRel(step) + return m1.getPosition() +} + + +ret = parallelize(task1, task2, task3) + +//ret = fork(task1, task2, task3) +//print (ret) +//ret = join(ret) + + +//ret = parallelize([moveRelative,[motor,1]], [moveRelative,[motor2,1]]) + + +print (ret) diff --git a/script/parallel.py b/script/parallel.py new file mode 100755 index 0000000..8ac8a93 --- /dev/null +++ b/script/parallel.py @@ -0,0 +1,42 @@ + +#Simple parallization +def task1(): + return out.read() + +def task2(): + return inp.read() + +def task3(): + time.sleep(0.1) + return sin.read() + +ret = parallelize(task1, task2, task3) +print ret + + +#Fork amd join +ret = fork(task1, task2, task3) +time.sleep(0.1) +ret = join(ret) +print ret + + +#Functions with parameters +def devRead(dev, msg): + print msg + " -> " + dev.getName() + return dev.read() + +ret = parallelize((devRead,(out,"1")), (devRead,(inp,"2")), (devRead,(sin,"3"))) +print ret + + +#Exception in parallel task +def taskExcept(msg): + raise Exception ("Error in parallel task " + msg) + + +ret = parallelize((taskExcept,("1")), (taskExcept,(inp,"2")) ) +print ret + + + diff --git a/script/parscan.py b/script/parscan.py new file mode 100755 index 0000000..9849b9b --- /dev/null +++ b/script/parscan.py @@ -0,0 +1,11 @@ +#Scan parallization + +def scan1(): + print "scan1" + return lscan(inp, sin, 0, 40, 20, 0.1, title = "scan1") + +def scan2(): + print "scan2" + return lscan(sout, arr, 0, 40, 20, 0.1, title = "scan2") + +ret = parallelize(scan1, scan2) diff --git a/script/pip.py b/script/pip.py new file mode 100755 index 0000000..a7b0ba2 --- /dev/null +++ b/script/pip.py @@ -0,0 +1,688 @@ +#Image: https://imagej.nih.gov/ij/docs/guide/146-28.html#toc-Section-28 +#Process: https://imagej.nih.gov/ij/docs/guide/146-29.html#toc-Section-29 +#Analyze: https://imagej.nih.gov/ij/docs/guide/146-30.html#toc-Section-30 + +import ch.psi.pshell.imaging.Utils as Utils +import java.awt.image.BufferedImage as BufferedImage + +""" +import net.imglib2.FinalInterval as FinalInterval +import net.imglib2.Interval as Interval +import net.imglib2.algorithm.neighborhood.DiamondShape as DiamondShape +import net.imglib2.algorithm.neighborhood.Shape as Shape +import net.imglib2.img.Img as Img +import net.imglib2.img.array.ArrayImg as ArrayImg +import net.imglib2.img.array.ArrayImgs as ArrayImgs +import net.imglib2.img.array.ArrayRandomAccess as ArrayRandomAccess +import net.imglib2.img.basictypeaccess.array.ByteArray as ByteArray +import net.imglib2.img.basictypeaccess.array.FloatArray as FloatArray +import net.imglib2.img.basictypeaccess.array.LongArray as LongArray +import net.imglib2.type.logic.BitType as BitType +import net.imglib2.type.numeric.integer.UnsignedByteType as UnsignedByteType +import net.imglib2.type.numeric.real.FloatType as FloatType +import net.imglib2.view.IntervalView as IntervalView +import net.imglib2.view.Views as Views + +import net.imglib2.algorithm.morphology.Erosion as Erosion +import net.imglib2.algorithm.morphology.Dilation as Dilation +import net.imglib2.algorithm.morphology.StructuringElements as StructuringElements +import net.imglib2.algorithm.morphology.MorphologyUtils as MorphologyUtils +import net.imglib2.img.display.imagej.ImageJFunctions as ImageJFunctions + +import net.imglib2.script.bufferedimage.BufferedImageImg as BufferedImageImg +#import net.imglib2.script.algorithm.FFT as FFT +""" + +import ij.IJ as IJ +import ij.ImageJ as ImageJ +import ij.io.FileSaver as FileSaver +#import ij.gui.GenericDialog as GenericDialog +#import ij.macro.Interpreter as Interpreter + +import ij.WindowManager as WindowManager +import ij.ImagePlus as ImagePlus +import ij.Prefs as Prefs +import ij.process.ImageProcessor as ImageProcessor +import ij.process.ByteProcessor as ByteProcessor +import ij.process.ShortProcessor as ShortProcessor +import ij.process.ColorProcessor as ColorProcessor +import ij.process.FloatProcessor as FloatProcessor +import ij.process.ImageConverter as ImageConverter +import ij.process.AutoThresholder as AutoThresholder +import ij.process.LUT as LUT +import ij.measure.Measurements as Measurements +import ij.measure.ResultsTable as ResultsTable +import ij.plugin.filter.Analyzer as Analyzer +import ij.plugin.filter.GaussianBlur as GaussianBlur +import ij.plugin.filter.Filters as Filters +import ij.plugin.filter.Binary as Binary +import ij.plugin.filter.FFTFilter as FFTFilter +import ij.plugin.filter.BackgroundSubtracter as BackgroundSubtracter +import ij.plugin.filter.EDM as EDM +import ij.plugin.filter.Shadows as Shadows +import ij.plugin.filter.UnsharpMask as UnsharpMask +import ij.plugin.filter.MaximumFinder as MaximumFinder +import ij.plugin.filter.EDM as EDM +import ij.plugin.filter.Shadows as Shadows +import ij.plugin.filter.UnsharpMask as UnsharpMask +import ij.plugin.filter.RankFilters as RankFilters +import ij.plugin.filter.Convolver as Convolver +import ij.plugin.filter.ParticleAnalyzer as ParticleAnalyzer + +import ij.plugin.ContrastEnhancer as ContrastEnhancer +import ij.plugin.Thresholder as Thresholder +import ij.plugin.ImageCalculator as ImageCalculator +import ij.plugin.FFT as FFT +import ij.plugin.Concatenator as Concatenator + +#ImageJ customizations +import ij.plugin.FFTOper as FFTOper +import ij.plugin.filter.BandpassFilter as BandpassFilter +import ij.plugin.filter.BinaryFilterConfig as BinaryFilterConfig +import ij.plugin.StackSlicer as StackSlicer + + + +#This eliminates the error messages due to the bug on ij.gui.ImageWindow row 555 (ij is null) +if not "image_j" in globals().keys(): + image = ImageJ(None, ImageJ.NO_SHOW) + + +""" +def to_imagelib2(bi): + if bi.getType() not in [BufferedImage.TYPE_INT_RGB, BufferedImage.TYPE_INT_ARGB, + BufferedImage.TYPE_BYTE_GRAY, BufferedImage.TYPE_BYTE_INDEXED, + BufferedImage.TYPE_USHORT_GRAY]: + bi = Utils.copy(bi, BufferedImage.TYPE_INT_RGB, None) + return BufferedImageImg(bi) +""" + + +#Image creation & copying +def load_image(image, title = "img"): + """ + image: file name or BufferedImage + """ + if isinstance(image, str): + try: + from startup import context + image = context.setup.expandPath(image) + except: + pass + image = Utils.newImage(image) + return ImagePlus(title, image) + +def new_image(width, height, image_type="byte", title = "img", fill_color = None): + """ + type = "byte", "short", "color" or "float" + """ + if image_type == "byte": p=ByteProcessor(width, height) + elif image_type == "short": p=ShortProcessor(width, height) + elif image_type == "color": p=ColorProcessor(width, height) + elif image_type == "float": p=FloatProcessor(width, height) + else: raise Exception("Invalid image type " + str(image_type)) + ret = ImagePlus(title, p) + if fill_color is not None: + p.setColor(fill_color) + p.resetRoi() + p.fill() + return ret + +def sub_image(ip, x, y, width, height): + """ + Returns new ImagePlus + """ + orig.setRoi(x, y, width, height) + p=orig.getProcessor().crop() + return ImagePlus(ip.getTitle() + " subimage", p) + +def copy_image(ip): + return ip.duplicate() + +def copy_image_to(ip_source, ip_dest, x, y): + ip_source.deleteRoi() + ip_source.copy() + ip_dest.setRoi(x, y, ip_source.getWidth(), ip_source.getHeight()) + ip_dest.paste() + ip_dest.changes = False + ip_dest.deleteRoi() + +def pad_image(ip, left=0, right=0, top=0, bottom=0, fill_color = None): + p=ip.getProcessor() + width = p.getWidth() + left + right + height = p.getHeight() + top + bottom + image_type = get_image_type(ip) + ret = new_image(width, height, image_type, ip.getTitle() + " padded", fill_color) + ip.deleteRoi() + ip.copy() + ret.setRoi(left, top, p.getWidth(), p.getHeight()) + ret.paste() + ret.changes = False + ret.deleteRoi() + return ret + +def get_image_type(ip): + """ + Returns: "byte", "short", "color" or "float" + """ + p=ip.getProcessor() + if type(p) == ShortProcessor: return "short" + elif type(p) == ColorProcessor: return "color" + elif type(p) == FloatProcessor: return "float" + return "byte" + +#Type conversion +def grayscale(ip, in_place=True): + ip = ip if in_place else ip.duplicate() + ic = ImageConverter(ip) + ic.convertToGray8() + return ip + +def get_channel(ip, channel): + """ + Return a channel from a color image as a new ImagePlus. + channel: "red", "green","blue", "alpha", "brightness", + """ + proc = ip.getProcessor() + if channel == "red": ret = proc.getChannel(1, None) + elif channel == "green": ret = proc.getChannel(2, None) + elif channel == "blue": ret = proc.getChannel(3, None) + elif channel == "alpha": ret = proc.getChannel(4, None) + elif channel == "brightness": ret = proc.getBrightness() + else: raise Exception("Invalid channel " + str(channel)) + return ImagePlus(ip.getTitle() + " channel: " + channel, ret) + +#Thresholder +def threshold(ip, min_threshold, max_threshold, in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().setThreshold(min_threshold, max_threshold, ImageProcessor.NO_LUT_UPDATE) + WindowManager.setTempCurrentImage(ip) + Thresholder().run("mask") + return ip + +def auto_threshold(ip, dark_background = False, method = AutoThresholder.getMethods()[0], in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().setAutoThreshold(method, dark_background , ImageProcessor.NO_LUT_UPDATE) + WindowManager.setTempCurrentImage(ip) + thresholder=Thresholder().run("mask") + return ip + +#Binary functions + +def binary_op(ip, op, dark_background=False, iterations=1, count=1, in_place=True): + """ + op = "erode","dilate", "open","close", "erode", "outline", "fill holes", "skeletonize" + """ + ip = ip if in_place else ip.duplicate() + binary = Binary() + BinaryFilterConfig.setCount(count) + BinaryFilterConfig.setIterations(iterations) + Prefs.blackBackground=dark_background + binary.setup(op, ip) + binary.run(ip.getProcessor()) + return ip + +def binary_erode(ip, dark_background=False, iterations=1, count=1, in_place=True): + return binary_op(ip, "erode", dark_background, iterations, count, in_place) + +def binary_dilate(ip, dark_background=False, iterations=1, count=1, in_place=True): + return binary_op(ip, "dilate", dark_background, iterations, count, in_place) + +def binary_open(ip, dark_background=False, iterations=1, count=1, in_place=True): + return binary_op(ip, "open", dark_background, iterations, count, in_place) + +def binary_close(ip, dark_background=False, iterations=1, count=1, in_place=True): + return binary_op(ip, "close", dark_background, iterations, count) + +def binary_erode(ip, dark_background=False, iterations=1, count=1, in_place=True): + return binary_op(ip, "erode", dark_background, iterations, count, in_place) + +def binary_outline(ip, dark_background=False, in_place=True): + return binary_op(ip, "outline", dark_background, in_place=in_place) + +def binary_fill_holes(ip, dark_background=False, in_place=True): + return binary_op(ip, "fill holes", dark_background, in_place=in_place) + +def binary_skeletonize(ip, dark_background=False, in_place=True): + return binary_op(ip, "skeletonize", dark_background, in_place=in_place) + +def analyse_particles(ip, min_size, max_size, fill_holes = True, exclude_edges = True, extra_measurements = 0, \ + print_table = False, output_image = "outlines", minCirc = 0.0, maxCirc = 1.0): + """ + Returns: tuple (ResultsTable results_table, ImagePlus output_image) + output_image = "outlines", "overlay_outlines", "masks", "overlay_masks", "roi_masks" or None + extra_measurements = mask with Measurements.CENTROID, PERIMETER, RECT, MIN_MAX, ELLIPSE, CIRCULARITY, AREA_FRACTION, INTEGRATED_DENSITY, INVERT_Y, FERET, KURTOSIS, MEDIAN, MODE, SKEWNESS, STD_DEV + Measurements is a mask of flags: https://imagej.nih.gov/ij/developer/api/ij/measure/Measurements.html. + Returned ResultsTable hold public fields: https://imagej.nih.gov/ij/developer/api/ij/measure/ResultsTable.html + + """ + rt = ResultsTable() + show_summary = False + options = ParticleAnalyzer.SHOW_RESULTS | ParticleAnalyzer.CLEAR_WORKSHEET + """ + ParticleAnalyzer.SHOW_ROI_MASKS | \ + #ParticleAnalyzer.RECORD_STARTS | \ + #ParticleAnalyzer.ADD_TO_MANAGER | \ + #ParticleAnalyzer.FOUR_CONNECTED | \ + #ParticleAnalyzer.IN_SITU_SHOW | \ + #ParticleAnalyzer.SHOW_NONE | \ + """ + if show_summary: options = options | ParticleAnalyzer.DISPLAY_SUMMARY + if output_image == "outlines": options = options | ParticleAnalyzer.SHOW_OUTLINES + elif output_image == "overlay_outlines": options = options | ParticleAnalyzer.SHOW_OVERLAY_OUTLINES + elif output_image == "masks": options = options | ParticleAnalyzer.SHOW_MASKS + elif output_image == "overlay_masks": options = options | ParticleAnalyzer.SHOW_OVERLAY_MASKS + elif output_image == "roi_masks": options = options | ParticleAnalyzer.SHOW_ROI_MASKS + #ParticleAnalyzer.SHOW_ROI_MASKS + if exclude_edges: options = options | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES + if fill_holes: options = options | ParticleAnalyzer.INCLUDE_HOLES + measurements = Measurements.AREA | Measurements.MEAN | Measurements.CENTER_OF_MASS | Measurements.RECT + pa = ParticleAnalyzer(options, measurements, rt, min_size, max_size, minCirc, maxCirc) + pa.setHideOutputImage(True) + pa.setResultsTable(rt) + if pa.analyze(ip): + if print_table: + print rt.getColumnHeadings() + for row in range (rt.counter): + print rt.getRowAsString(row) + return (rt, pa.getOutputImage()) + +#Image operators +def op_image(ip1, ip2, op, float_result=False, in_place=True): + """ + op = "add","subtract", "multiply","divide", "and", "or", "xor", "min", "max", "average", "difference" or "copy" + """ + ip1 = ip1 if in_place else ip1.duplicate() + ic = ImageCalculator() + pars = op + if float_result: + op = op + " float" + ic.run(pars, ip1, ip2) + return ip1 + +def op_const(ip, op, val, in_place=True): + """ + op = "add","subtract", "multiply","divide", "and", "or", "xor", "min", "max", "gamma", "set" or "log", "exp", "sqr", "sqrt","abs" + """ + ip = ip if in_place else ip.duplicate() + pr = ip.getProcessor() + if op == 'add': pr.add(val) + elif op == 'sub': pr.subtract(val) + elif op == 'multiply': pr.multiply(val) + elif op == 'divide' and val!=0: pr.multiply(1.0/val) + elif op == 'and': pr.and(val) + elif op == 'or': pr.or(val) + elif op == 'xor': pr.xor(val) + elif op == 'min': pr.min(val);pr.resetMinAndMax() + elif op == 'max': pr.max(val);pr.resetMinAndMax() + elif op == 'gamma' and 0.05 < val < 5.0: pr.gamma(val) + elif op == 'set': pr.set(val) + elif op == 'log': pr.log() + elif op == 'exp': pr.exp() + elif op == 'sqr': pr.sqr() + elif op == 'sqrt': pr.sqrt() + elif op == 'abs': pr.abs();pr.resetMinAndMax() + else: raise Exception("Invalid operation " + str(op)) + return ip + +def op_fft(ip1, ip2, op, do_inverse = True) : + """ + Images must have same sizes, and multipe of 2 height and width. + op = "correlate", "convolve", "deconvolve" + """ + if op == "correlate": op_index = 0 + elif op == "convolve": op_index = 1 + elif op == "deconvolve": op_index = 2 + else: raise Exception("Invalid operation " + str(op)) + return FFTOper().doMath(ip1, ip2, op_index, do_inverse) + +#RankFilters +def op_rank(ip, op, kernel_radius =1 , dark_outliers = False ,threshold = 50, in_place=True): + """ + op = "mean", "min", "max", "variance", "median", "close_maxima", "open_maxima", "remove_outliers", "remove_nan", "despeckle" + """ + if op == "mean": filter_type = RankFilters.MEAN + elif op == "min": filter_type = RankFilters.MIN + elif op == "max": filter_type = RankFilters.MAX + elif op == "variance": filter_type = RankFilters.VARIANCE + elif op == "median": filter_type = RankFilters.MEDIAN + elif op == "close_maxima": filter_type = RankFilters.CLOSE + elif op == "open_maxima": filter_type = RankFilters.OPEN + elif op == "remove_outliers": filter_type = RankFilters.OUTLIERS + elif op == "remove_nan": filter_type = RankFilters.REMOVE_NAN + elif op == "despeckle": filter_type, kernel_radius = RankFilters.MEDIAN, 1 + else: raise Exception("Invalid operation " + str(op)) + ip = ip if in_place else ip.duplicate() + RankFilters().rank(ip.getProcessor(), kernel_radius, filter_type, RankFilters.DARK_OUTLIERS if dark_outliers else RankFilters.BRIGHT_OUTLIERS ,threshold) + return ip + +def op_edm(ip, op="edm", dark_background=False, in_place=True): + """ + Euclidian distance map & derived operations + op ="edm", "watershed","points", "voronoi" + """ + ip = ip if in_place else ip.duplicate() + pr = ip.getProcessor() + edm=EDM() + Prefs.blackBackground=dark_background + if op=="edm": + #pr.setPixels(0, edm.makeFloatEDM(pr, 0, False)); + #pr.resetMinAndMax(); + if dark_background: + pr.invert() + edm.toEDM(pr) + else: + edm.setup(op, ip) + edm.run(pr) + return ip + +def watershed(ip, dark_background=False, in_place=True): + return op_edm(ip, "watershed", dark_background, in_place) + +def ultimate_points(ip, dark_background=False, in_place=True): + return op_edm(ip, "points", dark_background, in_place) + +def veronoi(ip, dark_background=False, in_place=True): + return op_edm(ip, "voronoi", dark_background, in_place) + +def edm(ip, dark_background=False, in_place=True): + return op_edm(ip, "edm", dark_background, in_place) + + +def op_filter(ip, op, in_place=True): + """ + This is redundant as just calls processor methods. + op ="invert", "smooth", "sharpen", "edge", "add" + """ + ip = ip if in_place else ip.duplicate() + f = Filters() + f.setup(op, ip ) + f.run(ip.getProcessor()) + return ip + +#Other operations +def gaussian_blur(ip, sigma_x=3.0, sigma_y=3.0, accuracy = 0.01, in_place=True): + ip = ip if in_place else ip.duplicate() + GaussianBlur().blurGaussian(ip.getProcessor(), sigma_x, sigma_y, accuracy) + return ip + +def find_maxima(ip, tolerance=25, threshold = ImageProcessor.NO_THRESHOLD, output_type=MaximumFinder.IN_TOLERANCE, exclude_on_edges = False, is_edm = False): + """ + Returns new ImagePlus + tolerance: maxima are accepted only if protruding more than this value from the ridge to a higher maximum + threshhold: minimum height of a maximum (uncalibrated); + output_type = SINGLE_POINTS, IN_TOLERANCE or SEGMENTED. No output image is created for output types POINT_SELECTION, LIST and COUNT. + """ + byte_processor = MaximumFinder().findMaxima(ip.getProcessor(), tolerance, threshold, output_type, exclude_on_edges, is_edm) + return ImagePlus(ip.getTitle() + " maxima", byte_processor) + + +def get_maxima_points(ip, tolerance=25, exclude_on_edges = False): + polygon = MaximumFinder().getMaxima(ip.getProcessor(), tolerance, exclude_on_edges) + return (polygon.xpoints, polygon.ypoints) + +def enhance_contrast(ip, equalize_histo = True, saturated_pixels = 0.5, normalize = False, stack_histo = False, in_place=True): + ip = ip if in_place else ip.duplicate() + ce = ContrastEnhancer() + if equalize_histo: + ce.equalize(ip.getProcessor()); + else: + ce.stretchHistogram(ip.getProcessor(), saturated_pixels) + if normalize: + ip.getProcessor().setMinAndMax(0,1.0 if (ip.getProcessor().getBitDepth()==32) else ip.getProcessor().maxValue()) + return ip + +def shadows(ip, op, in_place=True): + """ + op ="north","northeast", "east", "southeast","south", "southwest", "west","northwest" + """ + ip = ip if in_place else ip.duplicate() + shadows= Shadows() + shadows.setup(op, ip) + shadows.run(ip.getProcessor()) + return ip + +def unsharp_mask(ip, sigma, weight, in_place=True): + """ + Float processor + """ + ip = ip if in_place else ip.duplicate() + ip.getProcessor().snapshot() + unsharp=UnsharpMask() + USmask.setup(" ", ip) + USmask.sharpenFloat( ip.getProcessor(),sigma, weight) + return ip + +def subtract_background(ip, radius = 50, create_background=False, dark_background=False, use_paraboloid =True, do_presmooth = True, correctCorners = True, rgb_brightness=False, in_place=True): + ip = ip if in_place else ip.duplicate() + if rgb_brightness: + BackgroundSubtracter().rollingBallBrightnessBackground(ip.getProcessor(), radius, create_background,not dark_background, use_paraboloid, do_presmooth, correctCorners) + else: + BackgroundSubtracter().rollingBallBackground(ip.getProcessor(), radius, create_background, not dark_background, use_paraboloid, do_presmooth, correctCorners) + return ip + +#FFT +def image_fft(ip, show = True): + WindowManager.setTempCurrentImage(ip) + fft = FFT() + fft.run("fft") + #TODO: how to avoid it to be created? + #ret = ImagePlus("FHT of " + ip.getTitle(), WindowManager.getCurrentImage().getProcessor()) + ret = WindowManager.getCurrentImage() + if not show: + WindowManager.getCurrentImage().hide() + return ret + + +def image_ffti(ip, show = True): + WindowManager.setTempCurrentImage(ip) + fft = FFT() + fft.run("inverse") + #WindowManager.getCurrentImage().hide() + #TODO: how to avoid it to be created? + #ret = WindowManager.getCurrentImage() + #WindowManager.getCurrentImage().hide() + #ret = ImagePlus(ip.getTitle() + " ffti", WindowManager.getCurrentImage().getProcessor()) + ret = WindowManager.getCurrentImage() + if not show: + WindowManager.getCurrentImage().hide() + + return ret + +def bandpass_filter(ip, small_dia_px, large_dia_px, suppress_stripes = 0, stripes_tolerance_direction = 5.0, autoscale_after_filtering = False, saturate_if_autoscale = False, display_filter = False, in_place=True): + """ + suppress_stripes = 0 for none, 1 for horizontal, 2 for vertical + """ + ip = ip if in_place else ip.duplicate() + filter= BandpassFilter(); + BandpassFilter.filterLargeDia = large_dia_px + BandpassFilter.filterSmallDia = small_dia_px + BandpassFilter.choiceIndex = suppress_stripes + BandpassFilter.toleranceDia = stripes_tolerance_direction + BandpassFilter.doScalingDia = autoscale_after_filtering + BandpassFilter.saturateDia = saturate_if_autoscale + BandpassFilter.displayFilter =display_filter + filter.setup(None, ip); + filter.run(ip.getProcessor()) + return ip + +KERNEL_BLUR = [[0.1111, 0.1111, 0.1111], [0.1111, 0.1111, 0.1111], [0.1111, 0.1111, 0.1111]] +KERNEL_SHARPEN = [[0.0, -0.75, 0.0], [-0.75, 4.0, -0.75], [0.0, -0.75, 0.0]] +KERNEL_SHARPEN_2 = [[-1.0, -1.0, -1.0], [-1.0, 9.0, -1.0], [-1.0, -1.0, -1.0]] +KERNEL_LIGHT = [[0.1, 0.1, 0.1], [0.1, 1.0, 0.1],[0.1, 0.1, 0.1]] +KERNEL_DARK = [[0.01, 0.01, 0.01],[0.01, 0.5, 0.01],[0.01, 0.01, 0.01]] +KERNEL_EDGE_DETECT = [[0.0, -0.75, 0.0], [-0.75, 3.0, -0.75], [0.0, -0.75, 0.0]] +KERNEL_EDGE_DETECT_2 = [[-0.5, -0.5, -0.5], [-0.5, 4.0, -0.5], [-0.5, -0.5, -0.5]] +KERNEL_DIFFERENTIAL_EDGE_DETECT = [[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]] +KERNEL_PREWITT = [[-2.0, -1.0, 0.0], [-1.0, 0.0, 1.0 ], [0.0, 1.0, 2.0]] +KERNEL_SOBEL = [[2.0, 2.0, 0.0], [2.0, 0.0, -2.0 ], [0.0, -2.0, -2.0]] + + +def convolve(ip, kernel, in_place=True): + """ + kernel: list of lists + """ + ip = ip if in_place else ip.duplicate() + kernel_width = len(kernel) + kernel_height= len(kernel[0]) + kernel = [item for row in kernel for item in row] + #Convolver().convolve(ip.getProcessor(), kernel, kernel_width, kernel_height) + ip.getProcessor().convolve(kernel, kernel_width, kernel_height) + return ip + + +#Processor methods +def invert(ip, in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().invert() + return ip + +def smooth(ip, in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().smooth() + return ip + +def sharpen(ip, in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().sharpen() + return ip + +def edges(ip, in_place=True): #Sobel + ip = ip if in_place else ip.duplicate() + ip.getProcessor().findEdges() + return ip + +def noise(ip, sigma = 25.0, in_place=True): + ip = ip if in_place else ip.duplicate() + ip.getProcessor().noise(sigma) + return ip + +def remap(ip, min=None, max=None, in_place=True): + ip = ip if in_place else ip.duplicate() + if min is None or max is None: + stats = get_statistics(ip, Measurements.MIN_MAX) + if min is None: min = stats.min + if max is None: max = stats.max + ip.getProcessor().setMinAndMax(min, max) + return ip + +def set_lut(ip, r, g, b): + """ + r,g and b are lists of 256 integers + """ + r = [x if x<128 else x-256 for x in r] + g = [x if x<128 else x-256 for x in g] + b = [x if x<128 else x-256 for x in b] + ip.setLut(LUT(to_array(r,'b'),to_array(g,'b'),to_array(b,'b'))) + +def resize(ip, width, height): + """ + Returns new ImagePlus + """ + p = ip.getProcessor().resize(width, height) + return ImagePlus(ip.getTitle() + " resized", p) + +def binning(ip, factor): + p=ip.getProcessor().bin(factor) + return ImagePlus(ip.getTitle() + " resized", p) + +def get_histogram(ip, hist_min = 0, hist_max = 0, hist_bins = 256, roi=None): + """ + hist_min, hist_max, hist_bins onlyu used onlu for float images (otherwise fixed to 0,255,256) + roi is list [x,y,w,h] + """ + if roi == None: ip.deleteRoi() + else: ip.setRoi(roi[0],roi[1],roi[2],roi[3]) + print (hist_min, hist_max) + image_statistics = ip.getStatistics(0, hist_bins, hist_min, hist_max) + return image_statistics.getHistogram() + + +def get_array(ip): + return ip.getProcessor().getIntArray() + +def get_line(ip, x1, y1, x2, y2): + return ip.getProcessor().getLine(x1, y1, x2, y2) + +def get_pixel_range(ip): + return (ip.getProcessor().getMin(), ip.getProcessor().getMax()) + +def get_num_channels(ip): + return ip.getProcessor().getNChannels() + +def is_binary(ip): + return ip.getProcessor().isBinary() + +def get_pixel(ip, x, y): + return ip.getProcessor().getPixel(x,y) + +def get_pixel_array(ip, x, y): + a = [0]*get_num_channels(ip) + return ip.getProcessor().getPixel(x,y,a) + +def get_pixels(ip): + return ip.getProcessor().getPixels() + +def get_width(ip): + return ip.getProcessor().getWidth() + +def get_height(ip): + return ip.getProcessor().getHeight() + +def get_row(ip, y): + a = [0]*get_width(ip) + array = to_array(a,'i') + ip.getProcessor().getRow(0, y, array, get_width(ip)) + return array + +def get_col(ip, x): + a = [0]*get_height(ip) + array = to_array(a,'i') + ip.getProcessor().getColumn(x, 0, array, get_height(ip)) + return array + +def get_statistics(ip, measurements = None): + """ + Measurements is a mask of flags: https://imagej.nih.gov/ij/developer/api/ij/measure/Measurements.html. + Statistics object hold public fields: https://imagej.nih.gov/ij/developer/api/ij/process/ImageStatistics.html + """ + if measurements is None: + return ip.getStatistics() + else: + return ip.getStatistics(measurements) + +#Stack functions +def create_stack(ip_list, keep=True): + return Concatenator().concatenate(ip_list, keep) + +def reslice(stack, start_at = "Top", vertically = True, flip = True, output_pixel_spacing=1.0, avoid_interpolation = True): + ss = StackSlicer() + ss.rotate = vertically + ss.startAt = start_at + ss.flip = flip + ss.nointerpolate = avoid_interpolation + ss.outputZSpacing = output_pixel_spacing + return ss.reslice(stack) + + +def save_image(ip, path=None, format = None): + """ + Saves image or stack + If parameters ommited, resaves image in same location, with same format. + """ + fs = FileSaver(ip) + if path == None: fs.save() + elif format == "bmp": fs.saveAsBmp(path) + elif format == "fits": fs.saveAsFits(path) + elif format == "gif": fs.saveAsGif(path) + elif format == "jpeg": fs.saveAsJpeg(path) + elif format == "lut": fs.saveAsLut(path) + elif format == "pgm": fs.saveAsPgm(path) + elif format == "png": fs.saveAsPng(path) + elif format == "raw" and ip.getImageStackSize()>1: fs.saveAsRawStack(path) + elif format == "raw": fs.saveAsRaw(path) + elif format == "txt": fs.saveAsText(path) + elif format == "tiff" and ip.getImageStackSize()>1: fs.saveAsTiffStack(path) + elif format == "tiff": fs.saveAsTiff(path) + elif format == "zip": fs.saveAsZip(path) + diff --git a/script/points_q_0.xml b/script/points_q_0.xml new file mode 100755 index 0000000..aeb2f7b --- /dev/null +++ b/script/points_q_0.xml @@ -0,0 +1,462 @@ + + + + + + + + + + + + + + + + + 1399.0 + 1399.50.4 + + + + 1400.0 + 1552.010.0 + + + + 1552.5 + 1580.00.3 + + + + 1581.0 + 1610.01.0 + + + + 1611.0 + 1700.02.0 + + + + 1705.0 + 1819.04.0 + + + + 1820.0 + 1850.06.0 + + + + 4.0321673086 + 11.00.05 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -20.1 + + + -19.0 + + + 1.4 + + + 1.35 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/script/pyt.py b/script/pyt.py new file mode 100755 index 0000000..ebf6475 --- /dev/null +++ b/script/pyt.py @@ -0,0 +1,68 @@ + + + +def cmd(c): + import subprocess + proc = subprocess.Popen(c, stdout=subprocess.PIPE, shell=True) + (ret, err) = proc.communicate() + if (err is not None) and err!="": + raise Exception(err) + return ret + + +def run_cpython(script_name, args = []): + script = get_context().scriptManager.library.resolveFile(script_name) + c = "python " + script + " " + for arg in args: + c = c + str(arg) + " " + return cmd(c) + +def call_cpython(script_name, method_name, args = []): + launcher = get_context().scriptManager.library.resolveFile("launcher") + + script = os.path.abspath(get_context().scriptManager.library.resolveFile(script_name)) + jsonargs = json.dumps(args) + + a = [] + a.append(script) + a.append(method_name) + a.append('"' + jsonargs + '"') + ret = run_cpython(launcher, a) + ret = ret[0:-2] + jsonret = ret[ret.rfind('\n')+1:] + return json.loads(jsonret) + + +def call_cpython(script_name, method_name, args = []): + script = os.path.abspath(get_context().scriptManager.library.resolveFile(script_name)) + jsonargs = json.dumps(args) + + launcher = "" + launcher = launcher + "script = '" +script + "'\n" + launcher = launcher + "function = '" +method_name + "'\n" + launcher = launcher + "jsonargs = '" +jsonargs + "'\n" + launcher = launcher + """import sys +import json +import os +args =json.loads(jsonargs) +i = script.rfind(os.sep) +module = script[i+1:-3] +sys.path.insert(1,script[:i+1]) +exec 'from ' + module + ' import ' + function + ' as function' +print json.dumps(function(*args)) +""" + launcher = launcher.replace('\n', ';') + launcher = launcher.replace('\\', '\\\\') + c = 'python -c "' + launcher + '"' + ret = cmd(c) + ret = ret[0:-2] + jsonret = ret[ret.rfind('\n')+1:] + return json.loads(jsonret) + + +print cmd("dir") +print "--------" +print run_cpython("np", ["asd", 2]) +print "--------" +ret = call_cpython("np","add", [[1,2,3,4,5], [3,3,3,3,3]]) +print ret \ No newline at end of file diff --git a/script/pytst.py b/script/pytst.py new file mode 100755 index 0000000..a25e52b --- /dev/null +++ b/script/pytst.py @@ -0,0 +1,21 @@ +""" +import sys +import json +script ='C:\\Users\\gobbo_a\\Dev\\pshell\\pshell\\home\\script\\np.py' +function = 'add' +jsonargs = '[[1, 2, 3, 4, 5], [3, 3, 3, 3, 3]]' +args =json.loads(jsonargs) +i = script.rfind('/') +if i<0: i = script.rfind('\\') +module = script[i+1:-3] +path = script[:i+1] +sys.path.insert(1,path) +cmd = 'from ' + module + ' import ' + function + ' as function' +print cmd +exec cmd +ret = function(*args) +jsonret = json.dumps(ret) +print jsonret +""" + +import sys;import json;script = 'C:\\Users\\gobbo_a\\Dev\\pshell\\pshell\\home\\script\\np.py';function = 'add';jsonargs = '[[1, 2, 3, 4, 5], [3, 3, 3, 3, 3]]';args =json.loads(jsonargs);i = script.rfind('\\');module = script[i+1:-3];path = script[:i+1];sys.path.insert(1,path);cmd = 'from ' + module + ' import ' + function + ' as function';exec cmd;ret = function(*args);jsonret = json.dumps(ret);print jsonret; \ No newline at end of file diff --git a/script/reinit.py b/script/reinit.py new file mode 100755 index 0000000..4a79add --- /dev/null +++ b/script/reinit.py @@ -0,0 +1,4 @@ +if get_context().state == State.Ready: + failures = reinit() + if len(failures) == 0: + stop_task("reinit", force = False) \ No newline at end of file diff --git a/script/renderer_plot.py b/script/renderer_plot.py new file mode 100755 index 0000000..c8aa45f --- /dev/null +++ b/script/renderer_plot.py @@ -0,0 +1,4 @@ +#setup_plotting(line_plots = (arr,)) + +set_preference(Preference.PLOT_TYPES, {arr:"ch.psi.pshell.plot.MatrixPlotRenderer"}) +tscan(arr, 10,0.1) \ No newline at end of file diff --git a/script/runAllTutorial.py b/script/runAllTutorial.py new file mode 100755 index 0000000..ccd132e --- /dev/null +++ b/script/runAllTutorial.py @@ -0,0 +1,28 @@ +tutorial_path = "src/main/assembly/help/Tutorial_py/" +run(tutorial_path+"SimulatedDevices") + +m1.setSpeed(10) +m2.setSpeed(10) + +start=10.0 +end=50.0 +step=40 + + +for d in os.listdir(tutorial_path): + p = tutorial_path + d + if os.path.isdir(p): + print p + for f in os.listdir(p): + try: + script = p + "/" + f + print "\n----------------------------------------------------------------------------------------------------" + print "Running " + script + print "----------------------------------------------------------------------------------------------------" + set_status("Running: " + script) + run(script) + print get_exec_pars().index, get_exec_pars().group + except: + print >> sys.stderr, sys.exc_info()[0] + + \ No newline at end of file diff --git a/script/sc.py b/script/sc.py new file mode 100755 index 0000000..a1dce91 --- /dev/null +++ b/script/sc.py @@ -0,0 +1,4 @@ +sc1.setOneShot() # s +#sc1.setAutoCount() +sc1.counters[0].setPreset(False) # +sc1.counters[0].setPresetValue(0) # \ No newline at end of file diff --git a/script/scan.py b/script/scan.py new file mode 100755 index 0000000..0006d1e --- /dev/null +++ b/script/scan.py @@ -0,0 +1,3 @@ +def calc(a): + return a*2 + diff --git a/script/scans/PhaseScan.py b/script/scans/PhaseScan.py new file mode 100755 index 0000000..434994b --- /dev/null +++ b/script/scans/PhaseScan.py @@ -0,0 +1,42 @@ +from mathutils import * +from plotutils import * + +if is_ui(): + start = 0.0 + end = 360.0 + step = 10.0 + plt = plot(None, title="Harmonic Fit")[0] + +#Plot setup +plt.clear() +plt.removeMarker(None) +plt.addSeries(LinePlotSeries("data", color = Color.RED)) +plt.setLegendVisible(True) +plt.getAxis(plt.AxisId.X).setRange(start, end) + +#Creating an averager of the BPM +avg = create_averager(bpm_x, 3, 0.100) + +#The scan command +def after(rec, scan): + plt.getSeries(0).appendData(rec.positions[0], rec.values[0].mean) + +r = lscan(phase, [avg], start, end, step, latency=0.2, after_read=after) + +#Fitting +rf_phase = r.getPositions(0) +energy = [val.mean for val in r.getReadable(0)] +(fit_ampl, fit_freq, fit_phase) = fit_harmonic(energy, rf_phase) +ph_crest = round(-fit_phase / fit_freq, 3) +function = HarmonicOscillator(fit_ampl, fit_freq, fit_phase) +x = frange(min(rf_phase), max(rf_phase), 4.0, True, True) +plot_function(plt, function, "fit", x, show_points=False, color=Color.BLUE) +plt.addMarker(ph_crest, None, "ph_crest="+str(ph_crest), Color.MAGENTA) + +#Return values +print "ph_crest = ", ph_crest +phase.write(ph_crest) +phase_offset = round(90.0 - ph_crest, 3) +amplitude_scale = round(fit_ampl / amplitude.read(), 3) +power_scale = round(power.read() / math.pow(fit_ampl,2), 3) +set_return([phase_offset, amplitude_scale,power_scale ]) diff --git a/script/script.groovy b/script/script.groovy new file mode 100755 index 0000000..08abd78 --- /dev/null +++ b/script/script.groovy @@ -0,0 +1,31 @@ + +def function(a){ + a*2 +} +//evaluate (new File("calc.groovy")) +//evaluate (new File("cls.groovy")) + +println "--------------" + +lib.load "calc" +cls = lib.load "cls" + + +//This is how to load a new class dinamically +// ClassLoader parent = lib.class.getClassLoader(); +// groovy.lang.GroovyClassLoader loader = new groovy.lang.GroovyClassLoader(parent); +// Class cls = loader.parseClass(new File("script\\cls.groovy")); + + +println dev.get() +println dev2.val +println calc(6) + + +//cls = Class.forName('cls') +//obj = new cls() +obj = cls.newInstance() +println obj.val +obj.exec() + + diff --git a/script/script.js b/script/script.js new file mode 100755 index 0000000..038ad41 --- /dev/null +++ b/script/script.js @@ -0,0 +1,33 @@ +function task1() { + motor.moveRel(1.0) + return motor.getPosition() + } +function task2() { + motor2.moveRel(1.0) + return motor2.getPosition() + } + +function task3() { + return sin.read() + } + + +//ret = parallelize(task1, task2, task3) + +//ret = fork(task1, task2, task3) +//print (ret) +//ret = join(ret) + + + + +function moveRelative(args){ + var motor = args[0] + var step = args[1] + print ("Moving " + motor.getName() + " step = " + step) + motor.moveRel(step) + return motor.getPosition() +} + +ret = parallelize([moveRelative,[motor,1]], [moveRelative,[motor2,1]]) +print (ret) diff --git a/script/sig_process.py b/script/sig_process.py new file mode 100755 index 0000000..ff1ef21 --- /dev/null +++ b/script/sig_process.py @@ -0,0 +1,227 @@ +# Signal processing functions +import copy +from mathutils import * + + +# Noise evaluation #### +def noise_evaluation(noise): + """ + Returns offset and standard deviation of the noise signal. + :param noise: noise signal + :return: Tuple of (noise_offset, noise_sigma)) + """ + + return mean(noise), stdev(noise) + + +# Processing of BLM signal #### +def blm_remove_spikes(x): + """ + Returns new array with removed 1 and 2 point spikes. + :param x: input array + :return: output array + """ + + x = copy.copy(x) + if x.size > 5: # Must have enough sample points + d_x = x[1:] - x[:-1] + maximum = x.max() - x.min() + + for i in range(x.size-3): + if d_x[i+1] > 0.5 * maximum and d_x[i+2] < -0.5 * maximum: + # 1 point spike + x[i+2] = (x[i:i+5].sum() - x[i+2])/4 + + if d_x[i+1] > 0.5 * maximum and d_x[i+2] >= -0.5 * maximum: + # 2 point spikes + x[i+2] = (x[i:i+2].sum() + x[i+4])/3 + x[i+3] = (x[i+1] + x[i+4:i+6].sum())/3 + + # Handle edge points + if d_x[-1] > 0.5 * maximum: + x[-1] = x[-3:-1].sum() / 2 + + if d_x[-2] > 0.5 * maximum: + x[-2] = (x[-1] + x[-4:-2].sum()) / 3 + if d_x[0] < -0.5 * maximum: + x[0] = x[1:3].sum() / 2 + if d_x[1] < -0.5*maximum: + x[1] = (x[0] + x[2:4].sum()) / 3 + return x + + +def blm_normalize(x, q): + """ + Returns normalized BLM signal using charge from the BPM + :param x: BLM signal + :param q: BPM charge + :return: output array (same instance as input array) + """ + x = copy.copy(x) + return x / q + + +# Processing of position data #### +def motor_to_wire_cs(pos, type: str = 'u', center_pos: float = 0.0): + """ + Map wire position from motor coordinates (encoder readout) to wire coordinates. center_pos should be motor position + when wire is in the middle of the pipe. + + :param pos: position in motor coordinates + :param type: type of wire 'x', 'y' or 'u' (under 45 degrees to the pipe horizon) + :param center_pos: wire position in motor coordinates when in the middle of the pipe + :return: position in wire coordinates + """ + + # u: normal positions, like GARAGE, POSITION, or any wires under 45 degrees to pipe horizon + # x: which crosses pipe vertically (scans in x coordinate) + # y: which crosses pipe horizontally (scans in y coordinate) + w_scale = {'u': 1, 'x': -math.sqrt(2).sqrt(2), 'y': math.sqrt(2).sqrt(2)} + + return (pos-center_pos)/w_scale[type] + + +def remove_beam_jitter(pos, bpm1, bpm2, d_b1_w=1, d_w_b2=1): + """ + This is a temporary solution which works only for first WSC on SwissFEL. + !!TODO: In future this method must implement correction using online model. + + :param pos: array of positions for 1 profile + :param bpm1: array of bpm in front of wsc readings (x or y) for 1 profile + :param bpm2: array of after wsc bpm readings (x or y) for 1 profile + :param d_b1_w: Distance between bpm1 and wsc + :param d_w_b2: Distance between wsc and bpm2 + :return: array of corrected positions + """ + + beam_position_at_wsc = (bpm1 * d_b1_w + bpm2 * d_w_b2) / (d_b1_w + d_w_b2) + + # Reference centroid position is mean value of all measured values + beam_jitter = beam_position_at_wsc - beam_position_at_wsc.mean(0) + + # Correct wire position for beam jitter + return pos + beam_jitter + + +# Profile statistics #### +def profile_gauss_stats(x, y, off=None, amp=None, com=None, sigma=None): + if off is None: + off = y.min() # good enough starting point for offset + + if com is None: + #com = x[y.argmax()] + com = x[y.index(max(y))] + + if amp is None: + amp = y.max() - off + + # For normalised gauss curve sigma=1/(amp*sqrt(2*pi)) + if sigma is None: + surface = integrate((y-off), xdata=x) + sigma = surface / (amp * math.sqrt(2 * math.pi)) + try: + #popt, pcov = scipy.optimize.curve_fit(gauss_fn, x, y, p0=[off, amp, com, sigma], method='lm') + #popt[3] = abs(popt[3]) # sigma should be returned as positive + pars = fit_gaussian(y, x, start_point = [amp, com, sigma]) + popt = [0.0, pars[0], pars[1], abs([pars[2])] + + + except Exception as e: + print("Gauss fitting not successful.\n" + str(e)) + popt = [off, amp, com, abs(sigma)] + + return popt + + +def gauss_fn(x, a, b, c, d): + return a + b * math.exp(-(math.pow((x - c), 2) / (2 * math.pow(d, 2)))) + + +def profile_rms_stats(x, y, noise_std=0, n_sigma=3.5): + """ + Does the center of mass and RMS calculation on given profile. + + :param x: data of x axis (wire position) + :param y: data of y axis (blm current) + :param noise_std: standard deviation of noise + :param n_sigma: multiplication of window size (n_sigma*sigma) where sigma is first estimation of sigma + :return: rms of signal + """ + + if x.shape == y.shape: + # Windowing the signal + # 1. All points bellow +sigma are treated as noise and ignored + # 2. If point is higher than +sigma and neighbour points are noise, then it is also treated as noise and ignored + # 3. All sets of multiple non noise points in a row are treated as signal_candidates + signal_flag = False + signal_start = 0 + signal_candidates = list() + for i in range(y.size): + if y[i] < noise_std: + # Not part of the signal. Check if this is the end of signal candidate. + if signal_flag and i-signal_start > 1: + signal_candidates.append((signal_start, i-1)) + signal_flag = False + + elif not signal_flag: + # Start of potential new signal candidate + signal_flag = True + signal_start = i + + # Take care of last signal candidate if last point is higher than noise (signal_flag is still True) + if signal_flag and (y.size - signal_start - 1) > 1: + signal_candidates.append((signal_start, y.size-1)) + + if len(signal_candidates) == 0: + # Only noise, no signal. Cannot calculate rms + print("RMS calculation not successful. No signal detected.\n") + return None, None + + # Evaluate candidates + candidates_val = [y[s[0]:s[1]].sum() for s in signal_candidates] + signal_boundaries = signal_candidates[candidates_val.index(max(candidates_val))] + + # Calculate RMS values (at this point they are underestimated, but sigma is then used to extend the signal + # region of interest which gives a better result (biggest surface) + com_estimate, rms_estimate = com_rms(x[signal_boundaries[0]:signal_boundaries[1]], + y[signal_boundaries[0]:signal_boundaries[1]]) + + # Indexes of useful signal (-1 is here because original algorithm calculates this a bit different and + # because it does the floor() of calculated function + + # Define direction of scan + if x[0] < x[-1]: # increasing position + low_boundary = np.argmax(x >= com_estimate - n_sigma * rms_estimate)-1 + high_boundary = np.argmax(x >= com_estimate + n_sigma * rms_estimate)-1 + + else: # decreasing position + high_boundary = np.argmax(x <= com_estimate - n_sigma * rms_estimate)-1 + low_boundary = np.argmax(x <= com_estimate + n_sigma * rms_estimate)-1 + + if high_boundary <= 0: + high_boundary = x.size + + if low_boundary < 0: + low_boundary = 0 + + if (high_boundary-low_boundary) < 4: + print("RMS calculation not successful. Resolution to low.\n") + return None, None + + # Calculate final RMS and centroid on ROI data + if high_boundary == x.size: + com, rms = com_rms(x[low_boundary:], y[low_boundary:]) + else: + com, rms = com_rms(x[low_boundary:high_boundary], y[low_boundary:high_boundary]) + + return com, rms + else: + return None, None + + +def com_rms(x, y): + # Centre of mass and rms + com = sum([a*b for a,b in zip(x,y)]) / sum(y) + com2 = sum([a*a*b for a,b in zip(x,y)]) / sum(y) + rms = math.sqrt(math.abs(com2 - com * com)) + return com, rms \ No newline at end of file diff --git a/script/sig_process_new.py b/script/sig_process_new.py new file mode 100755 index 0000000..ff1ef21 --- /dev/null +++ b/script/sig_process_new.py @@ -0,0 +1,227 @@ +# Signal processing functions +import copy +from mathutils import * + + +# Noise evaluation #### +def noise_evaluation(noise): + """ + Returns offset and standard deviation of the noise signal. + :param noise: noise signal + :return: Tuple of (noise_offset, noise_sigma)) + """ + + return mean(noise), stdev(noise) + + +# Processing of BLM signal #### +def blm_remove_spikes(x): + """ + Returns new array with removed 1 and 2 point spikes. + :param x: input array + :return: output array + """ + + x = copy.copy(x) + if x.size > 5: # Must have enough sample points + d_x = x[1:] - x[:-1] + maximum = x.max() - x.min() + + for i in range(x.size-3): + if d_x[i+1] > 0.5 * maximum and d_x[i+2] < -0.5 * maximum: + # 1 point spike + x[i+2] = (x[i:i+5].sum() - x[i+2])/4 + + if d_x[i+1] > 0.5 * maximum and d_x[i+2] >= -0.5 * maximum: + # 2 point spikes + x[i+2] = (x[i:i+2].sum() + x[i+4])/3 + x[i+3] = (x[i+1] + x[i+4:i+6].sum())/3 + + # Handle edge points + if d_x[-1] > 0.5 * maximum: + x[-1] = x[-3:-1].sum() / 2 + + if d_x[-2] > 0.5 * maximum: + x[-2] = (x[-1] + x[-4:-2].sum()) / 3 + if d_x[0] < -0.5 * maximum: + x[0] = x[1:3].sum() / 2 + if d_x[1] < -0.5*maximum: + x[1] = (x[0] + x[2:4].sum()) / 3 + return x + + +def blm_normalize(x, q): + """ + Returns normalized BLM signal using charge from the BPM + :param x: BLM signal + :param q: BPM charge + :return: output array (same instance as input array) + """ + x = copy.copy(x) + return x / q + + +# Processing of position data #### +def motor_to_wire_cs(pos, type: str = 'u', center_pos: float = 0.0): + """ + Map wire position from motor coordinates (encoder readout) to wire coordinates. center_pos should be motor position + when wire is in the middle of the pipe. + + :param pos: position in motor coordinates + :param type: type of wire 'x', 'y' or 'u' (under 45 degrees to the pipe horizon) + :param center_pos: wire position in motor coordinates when in the middle of the pipe + :return: position in wire coordinates + """ + + # u: normal positions, like GARAGE, POSITION, or any wires under 45 degrees to pipe horizon + # x: which crosses pipe vertically (scans in x coordinate) + # y: which crosses pipe horizontally (scans in y coordinate) + w_scale = {'u': 1, 'x': -math.sqrt(2).sqrt(2), 'y': math.sqrt(2).sqrt(2)} + + return (pos-center_pos)/w_scale[type] + + +def remove_beam_jitter(pos, bpm1, bpm2, d_b1_w=1, d_w_b2=1): + """ + This is a temporary solution which works only for first WSC on SwissFEL. + !!TODO: In future this method must implement correction using online model. + + :param pos: array of positions for 1 profile + :param bpm1: array of bpm in front of wsc readings (x or y) for 1 profile + :param bpm2: array of after wsc bpm readings (x or y) for 1 profile + :param d_b1_w: Distance between bpm1 and wsc + :param d_w_b2: Distance between wsc and bpm2 + :return: array of corrected positions + """ + + beam_position_at_wsc = (bpm1 * d_b1_w + bpm2 * d_w_b2) / (d_b1_w + d_w_b2) + + # Reference centroid position is mean value of all measured values + beam_jitter = beam_position_at_wsc - beam_position_at_wsc.mean(0) + + # Correct wire position for beam jitter + return pos + beam_jitter + + +# Profile statistics #### +def profile_gauss_stats(x, y, off=None, amp=None, com=None, sigma=None): + if off is None: + off = y.min() # good enough starting point for offset + + if com is None: + #com = x[y.argmax()] + com = x[y.index(max(y))] + + if amp is None: + amp = y.max() - off + + # For normalised gauss curve sigma=1/(amp*sqrt(2*pi)) + if sigma is None: + surface = integrate((y-off), xdata=x) + sigma = surface / (amp * math.sqrt(2 * math.pi)) + try: + #popt, pcov = scipy.optimize.curve_fit(gauss_fn, x, y, p0=[off, amp, com, sigma], method='lm') + #popt[3] = abs(popt[3]) # sigma should be returned as positive + pars = fit_gaussian(y, x, start_point = [amp, com, sigma]) + popt = [0.0, pars[0], pars[1], abs([pars[2])] + + + except Exception as e: + print("Gauss fitting not successful.\n" + str(e)) + popt = [off, amp, com, abs(sigma)] + + return popt + + +def gauss_fn(x, a, b, c, d): + return a + b * math.exp(-(math.pow((x - c), 2) / (2 * math.pow(d, 2)))) + + +def profile_rms_stats(x, y, noise_std=0, n_sigma=3.5): + """ + Does the center of mass and RMS calculation on given profile. + + :param x: data of x axis (wire position) + :param y: data of y axis (blm current) + :param noise_std: standard deviation of noise + :param n_sigma: multiplication of window size (n_sigma*sigma) where sigma is first estimation of sigma + :return: rms of signal + """ + + if x.shape == y.shape: + # Windowing the signal + # 1. All points bellow +sigma are treated as noise and ignored + # 2. If point is higher than +sigma and neighbour points are noise, then it is also treated as noise and ignored + # 3. All sets of multiple non noise points in a row are treated as signal_candidates + signal_flag = False + signal_start = 0 + signal_candidates = list() + for i in range(y.size): + if y[i] < noise_std: + # Not part of the signal. Check if this is the end of signal candidate. + if signal_flag and i-signal_start > 1: + signal_candidates.append((signal_start, i-1)) + signal_flag = False + + elif not signal_flag: + # Start of potential new signal candidate + signal_flag = True + signal_start = i + + # Take care of last signal candidate if last point is higher than noise (signal_flag is still True) + if signal_flag and (y.size - signal_start - 1) > 1: + signal_candidates.append((signal_start, y.size-1)) + + if len(signal_candidates) == 0: + # Only noise, no signal. Cannot calculate rms + print("RMS calculation not successful. No signal detected.\n") + return None, None + + # Evaluate candidates + candidates_val = [y[s[0]:s[1]].sum() for s in signal_candidates] + signal_boundaries = signal_candidates[candidates_val.index(max(candidates_val))] + + # Calculate RMS values (at this point they are underestimated, but sigma is then used to extend the signal + # region of interest which gives a better result (biggest surface) + com_estimate, rms_estimate = com_rms(x[signal_boundaries[0]:signal_boundaries[1]], + y[signal_boundaries[0]:signal_boundaries[1]]) + + # Indexes of useful signal (-1 is here because original algorithm calculates this a bit different and + # because it does the floor() of calculated function + + # Define direction of scan + if x[0] < x[-1]: # increasing position + low_boundary = np.argmax(x >= com_estimate - n_sigma * rms_estimate)-1 + high_boundary = np.argmax(x >= com_estimate + n_sigma * rms_estimate)-1 + + else: # decreasing position + high_boundary = np.argmax(x <= com_estimate - n_sigma * rms_estimate)-1 + low_boundary = np.argmax(x <= com_estimate + n_sigma * rms_estimate)-1 + + if high_boundary <= 0: + high_boundary = x.size + + if low_boundary < 0: + low_boundary = 0 + + if (high_boundary-low_boundary) < 4: + print("RMS calculation not successful. Resolution to low.\n") + return None, None + + # Calculate final RMS and centroid on ROI data + if high_boundary == x.size: + com, rms = com_rms(x[low_boundary:], y[low_boundary:]) + else: + com, rms = com_rms(x[low_boundary:high_boundary], y[low_boundary:high_boundary]) + + return com, rms + else: + return None, None + + +def com_rms(x, y): + # Centre of mass and rms + com = sum([a*b for a,b in zip(x,y)]) / sum(y) + com2 = sum([a*a*b for a,b in zip(x,y)]) / sum(y) + rms = math.sqrt(math.abs(com2 - com * com)) + return com, rms \ No newline at end of file diff --git a/script/spectrum b/script/spectrum new file mode 100755 index 0000000..7b69f98 --- /dev/null +++ b/script/spectrum @@ -0,0 +1,30 @@ + +from mathutils import fft, get_modulus +import random + +def plot_spectrum(signal, sampling_frequency, plots = None): + number_of_samples = len(signal) + time_vector = [x / sampling_frequency for x in frange(0, number_of_samples, 1)] + tranform = fft(signal) + two_side_spectrum = [x / number_of_samples for x in get_modulus(tranform)] + spectrum = [two_side_spectrum[0],] + [x * 2 for x in two_side_spectrum[1:len(two_side_spectrum)/2 + 1] ] + number_of_samples = len(tranform) # Signal may have been padded to next power of two + freq_vector = [x * sampling_frequency / float(number_of_samples) for x in frange(0, len(spectrum) , 1)] + if plots is None: + plots = plot([signal,spectrum], ["signal", "spectrum"],[time_vector, freq_vector], context = "Spectrum") + else: + plots[0].getSeries(0).setData(time_vector,signal) + plots[1].getSeries(0).setData(freq_vector,spectrum) + return plots + +def get_sample(samples, sampling_freq): + return map(lambda t:math.sin(100*2*math.pi*t/sampling_freq) + random.random(), frange(0,samples,1)) + + + +plots = None +while(True): + signal = get_sample(1024, 1024.0) + plots = plot_spectrum(signal,sampling_freq, plots) + time.sleep(0.1) + diff --git a/script/spectrum.py b/script/spectrum.py new file mode 100755 index 0000000..7fec967 --- /dev/null +++ b/script/spectrum.py @@ -0,0 +1,10 @@ +set_exec_pars(persist=False) +set_preference(Preference.PLOT_DISABLED, True) + +plots = None +samples = 20; sampling_freq = 10 +while(True): + signal = tscan(sin, samples, 1/sampling_freq).getReadable(0) + plots = plot_spectrum(signal, sampling_freq, plots) + time.sleep(0.1) + diff --git a/script/sr.py b/script/sr.py new file mode 100755 index 0000000..662ea58 --- /dev/null +++ b/script/sr.py @@ -0,0 +1,29 @@ + + +#print args + +""" +scan_pos.set([]) +scan_val.set([]) +def after(rec): + scan_val.append(rec.values[0]) + scan_pos.append(rec.positions[0]) +""" + +#TODO: this is workaround to CAS not supporting dynamic arrays +def after(rec): + global arrpos,arrval + print rec.index + arrval = scan_val.take().tolist() + arrpos = scan_pos.take().tolist() + arrval[rec.index] = rec.values[0] + arrpos[rec.index] = rec.positions[0] + arrval[rec.index:] = [rec.values[0]] * (len(arrval) -rec.index) + arrpos[rec.index:] = [rec.positions[0]] * (len(arrpos) -rec.index) + scan_val.set(arrval) + scan_pos.set(arrpos) + + +res = lscan(inp, (sin,out), scan_start.read(), scan_stop.read(), scan_step.read(), 0.1, after_read = after) + +set_return(res.print()) \ No newline at end of file diff --git a/script/task1.py b/script/task1.py new file mode 100755 index 0000000..0ca1002 --- /dev/null +++ b/script/task1.py @@ -0,0 +1,8 @@ + + +print "Start 1" + +try: + sleep(2) +finally: + print "Quit 1" \ No newline at end of file diff --git a/script/task2.py b/script/task2.py new file mode 100755 index 0000000..0110c2e --- /dev/null +++ b/script/task2.py @@ -0,0 +1,7 @@ + +print "Start 2" + +try: + sleep(10) +finally: + print "Quit 2" \ No newline at end of file diff --git a/script/test.groovy b/script/test.groovy new file mode 100755 index 0000000..f5d958b --- /dev/null +++ b/script/test.groovy @@ -0,0 +1,35 @@ + +set_exec_pars(["name":"newtest"]) + +tscan(sin, 10, 0.100) + + +st1 = new ch.psi.pshell.bs.Stream("st1", dispatcher) + +/* +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 10, 0) +s2=st1.addScalar("Float64Scalar", "Float64Scalar", 10, 0) +w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 10, 0) +mt1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) +st1.initialize() +bscan (st1, 10) +*/ + + +r1 = rscan(inp,[sin,inp] , [[0,5,5], [10,15,20], [20,25,5]] , 0.01, false, passes = 1) + +lscan ([inp,motor], [sin,dev], [0,0], [10,1], 10,0.1,false) + + + +//1D vector scan, plot to 1D Vector tab +vector = [ 1, 3, 5, 10, 25, 40, 45, 47, 49] +vscan(inp,[sin,dev],vector, false, 0.5) + +//2D vector scan, plot to 2D Vector tab +vector = [ [1,1] , [1,2] , [1,3] , [1,4] , + [1.5,2.5] , + [2,1] , [2,2] , [2,3] , [2,4] , + [2.5,2.5] , + [3,1] , [3,2] , [3,3] , [3,4] ] +a= vscan([inp,motor],[sin,dev],vector,false, 0.1) \ No newline at end of file diff --git a/script/test.js b/script/test.js new file mode 100755 index 0000000..5f82abe --- /dev/null +++ b/script/test.js @@ -0,0 +1,109 @@ +/* +var st1 = new Stream("st1", dispatcher) +s1=st1.addScalar("Int8Scalar", "Int8Scalar", 10, 0) +s2=st1.addScalar("Float64Scalar", "Float64Scalar", 10, 0) +w1=st1.addWaveform("Int32Waveform", "Int32Waveform", 10, 0) +mt1=st1.addMatrix("Int16Waveform", "Int16Waveform", 10, 0, 64, 32) +st1.initialize() +bscan (st1, 10) +*/ + + +r1 = rscan(inp,[sin,inp] , [[0,5,5], [10,15,20], [20,25,5]] , 0.01, false, passes = 1) + + +lscan(inp, [sin,], 0, 40, 20, 0.01) + + + + +load("nashorn:mozilla_compat.js") +importClass(java.util.concurrent.FutureTask) + + +print ("a") + +function _getCallable(func, args){ + var callable = new java.util.concurrent.Callable() { + call: function() { + print ("HAHA") + //print (func) + print (args) + return func(args) + } + } + return callable +} + + +function fork(){ + print ("FORK") + print (arguments.length) + print (typeof arguments[0]) + var callables = [] + for(i =0; i0){ + print("X") + print (m.length) + //print (m[0]) + print (m[1]) + callables.push(_getCallable(m[0], m[1])) + } + else + callables.push(_getCallable(m)) + + } + return Threading.fork(callables) +} + + +function join(futures){ + try{ + return Threading.join(futures) + } catch(err){ + throw err.getCause() + } +} + + +function parallelize() { + futures = fork.apply(this, arguments) + return join(futures) +} + +function task1() { + print("On 1") + motor.moveRel(1.0) + return motor.getPosition() + } +function task2() { + print("On 2") + motor2.moveRel(1.0) + return motor2.getPosition() + } + +function task3() { + print("On 3") + return sin.read() + } + + + + +function moveRelative(args){ + motor = args[0] + step = args[1] + print ("Moving " + motor.getName() + " step = " + step) + motor.moveRel(step) + return motor.getPosition() +} + +ret = parallelize([moveRelative,[motor,-2]], [moveRelative,[motor2,-2]]) +//ret = fork([moveRelative,[motor,-2]], [moveRelative,[motor2,-2]]) +//ret = parallelize(task1,task2) +//ret = fork(task1,task2) +//ret = join(ret) +print (ret) + diff --git a/script/test.py b/script/test.py new file mode 100755 index 0000000..30aa5fa --- /dev/null +++ b/script/test.py @@ -0,0 +1,5 @@ +#set_exec_pars(name = "test1") +set_exec_pars(group = "g1") +a= lscan(inp, (sin,out,arr), 0, 40, 20, 0.1, group = "g2") +#set_exec_pars(name = "test2", open = False) +a= lscan(inp, (sin,out,arr), 0, 40, 20, 0.1) diff --git a/script/test/BugSetCache.py b/script/test/BugSetCache.py new file mode 100755 index 0000000..02b15ff --- /dev/null +++ b/script/test/BugSetCache.py @@ -0,0 +1,15 @@ + +class ScalarDevice(RegisterBase): + def doRead(self): + return self.val if hasattr(self, 'val') else 0.0 + + def doWrite(self, val): + self.val = val + + def test(self): + self.setCache(1.0, None) + + +add_device(ScalarDevice("scan_start"), True) + +scan_start.test() \ No newline at end of file diff --git a/script/test/CamtoolCheckProfile.py b/script/test/CamtoolCheckProfile.py new file mode 100755 index 0000000..1471cd7 --- /dev/null +++ b/script/test/CamtoolCheckProfile.py @@ -0,0 +1,22 @@ +import ch.psi.pshell.imaging.Data as Data + +path = "2017_06/20170619/20170619_153743_snapshot.h5|/data" + +d = load_data(path) +atts = get_attributes(path) +data = Data(d) +iv = data.integrateVertically(False) +ih = data.integrateHorizontally(False) +xp = atts["x_profile"] +yp = atts["y_profile"] +p1, p2 = plot([xp, yp], ["X profile", "Y profile"]) +p1.addSeries(LinePlotSeries("data X")) +p2.addSeries(LinePlotSeries("data Y")) +p1.getSeries(1).setData(iv) +p2.getSeries(1).setData(ih) + + +p1.addSeries(LinePlotSeries("error X", None, 2)) +p2.addSeries(LinePlotSeries("error Y", None, 2)) +p1.getSeries(2).setData(arrsub(xp,iv)) +p2.getSeries(2).setData(arrsub(yp,ih)) \ No newline at end of file diff --git a/script/test/DeviceChannel.py b/script/test/DeviceChannel.py new file mode 100755 index 0000000..98d3e0e --- /dev/null +++ b/script/test/DeviceChannel.py @@ -0,0 +1,119 @@ +class Channel(java.beans.PropertyChangeListener, Writable, Readable, DeviceBase): + def __init__(self, channel_name, type = None, size = None, callback=None, alias = None): + """ Create an object that encapsulates an Epics PV connection. + Args: + name(str): value to be written + type(str, optional): type of PV. By default gets the PV standard field type. + Scalar values: 'b', 'i', 'l', 'd', 's'. + Array: values: '[b', '[i,', '[l', '[d', '[s'. + size(int, optional): the size of the channel + callback(function, optional): The monitor callback. + alias(str): name to be used on scans. + """ + DeviceBase.__init__(self, channel_name if (alias is None) else alias) + self.channel = create_channel(channel_name, type, size) + self.callback = callback + if alias is not None: + set_device_alias(self, alias) + else: + set_device_alias(self, channel_name) + self.initialize() + + def get_name(self): + """Return the name of the channel. + """ + return self.channel.name + + def get_size(self): + """Return the size of the channel. + """ + return self.channel.size + + def set_size(self, size): + """Set the size of the channel. + """ + self.channel.size = size + + def is_connected(self): + """Return True if channel is connected. + """ + return self.channel.connected + + def is_monitored(self): + """Return True if channel is monitored + """ + return self.channel.monitored + + def set_monitored(self, value): + """Set a channel monitor to trigger the callback function defined in the constructor. + """ + self.monitored = value + + def doSetMonitored(self, value): + self.channel.monitored = value + if (value): + self.channel.addPropertyChangeListener(self) + else: + self.channel.removePropertyChangeListener(self) + + def propertyChange(self, pce): + if pce.getPropertyName() == "value": + val = pce.getNewValue() + self.setCache(val, None) + if self.callback is not None: + self.callback(val) + + def put(self, value, timeout=None): + """Write to channel and wait value change. In the case of a timeout throws a TimeoutException. + Args: + value(obj): value to be written + timeout(float, optional): timeout in seconds. If none waits forever. + """ + if (timeout==None): + self.channel.setValue(value) + else: + self.channel.setValueAsync(value).get(int(timeout*1000), java.util.concurrent.TimeUnit.MILLISECONDS); + + def putq(self, value): + """Write to channel and don't wait. + """ + self.channel.setValueNoWait(value) + + def get(self, force = False): + """Get channel value. + """ + val = self.channel.getValue(force) + self.setCache(val, None) + return val + + def wait_for_value(self, value, timeout=None, comparator=None): + """Wait channel to reach a value, using a given comparator. In the case of a timeout throws a TimeoutException. + Args: + value(obj): value to be verified. + timeout(float, optional): timeout in seconds. If None waits forever. + comparator (java.util.Comparator, optional). If None, uses Object.equals. + """ + if comparator is None: + if timeout is None: + self.channel.waitForValue(value) + else: + self.channel.waitForValue(value, int(timeout*1000)) + else: + if timeout is None: + self.channel.waitForValue(value, comparator) + else: + self.channel.waitForValue(value, comparator, int(timeout*1000)) + + def close(self): + """Close the channel. + """ + self.channel.destroy() + DeviceBase.close(self) + + #Writable interface + def write(self, value): + self.put(value) + + #Readable interface + def read(self): + return self.get() diff --git a/script/test/Robot.py b/script/test/Robot.py new file mode 100755 index 0000000..3350ca0 --- /dev/null +++ b/script/test/Robot.py @@ -0,0 +1,716 @@ +from ch.psi.pshell.serial import TcpDevice + +import threading + +FRAME_DEFAULT = "world" + + + +import ch.psi.pshell.device.PositionerConfig as PositionerConfig + + + +ROBOT_MOTORS = ["x" , "y", "z", "rx", "ry", "rz"] + + +class RobotCartesianMotor (PositionerBase): + def __init__(self, robot, index): + PositionerBase.__init__(self, robot.name + "_" + ROBOT_MOTORS[index], PositionerConfig()) + self.index = index + self.robot = robot + + #ATTENTION: Always initialize cartesian motors before scanning (or call robot.set_motors_enabled(True)) + def doInitialize(self): + self.setCache(None, None) + self.setCache(self.doRead(), None) + + def doRead(self): + return float("nan") if self.robot.cartesian_destination is None else float(robot.cartesian_destination[self.index]) + + def doWrite(self, value): + if self.robot.cartesian_destination is not None: + print "Move " + ROBOT_MOTORS[self.index] + " to " + str(value) + self.robot.updating = True + try: + robot.cartesian_destination[self.index] = float(value) + self.robot.set_pnt(robot.cartesian_destination , "tcp_p") + self.robot.movel("tcp_p", self.robot.tool , DESC_SCAN) + except: + self.robot.updating = False + + def doReadReadback(self): + #return float(self.robot.get_cartesian_pos(self._get_tool(),self.frame)[self.index]) + return float("nan") if self.robot.cartesian_pos is None else float(self.robot.cartesian_pos[self.index]) + + + + +ROBOT_JOINT_MOTORS = ["j1" , "j2", "j3", "j4", "j5", "j6"] + + +class RobotJointMotor (PositionerBase): + def __init__(self, robot, index): + PositionerBase.__init__(self, robot.name + "_" + ROBOT_JOINT_MOTORS[index], PositionerConfig()) + self.index = index + self.robot = robot + + def doInitialize(self): + self.setpoint = self.doReadReadback() + self.setCache(self.doRead(), None) + + def doRead(self): + return self.setpoint + + def doWrite(self, value): + print "Move " + ROBOT_JOINT_MOTORS[self.index] + " to " + str(value) + self.setpoint = value + joint = self.robot.herej() + joint[self.index] = value + self.robot.updating = True + try: + self.robot.set_jnt(joint, name="tcp_j") + self.robot.movej("tcp_j", self.robot.tool , DESC_SCAN) + finally: + self.robot.updating = False + + + def doReadReadback(self): + return self.robot.herej()[self.index] if self.robot.joint_pos is None else float(self.robot.joint_pos[self.index]) + + + +class RobotTCP(TcpDevice, Stoppable): + def __init__(self, name, server, timeout = 1000, retries = 1): + TcpDevice.__init__(self, name, server) + self.timeout = timeout + self.retries = retries + self.header = None + self.trailer = "\n" + self.array_separator = '|' + self.cmd_separator = ' ' + self.msg_id = 0 + self.working_mode = "invalid" + self.status = "invalid" + self.powered = None + self.settled = None + self.empty = None + self.working_mode = None + self.status = None + self.lock = threading.Lock() + self.joint_forces = None + self.current_task = None + self.high_level_tasks = [] + self.cartesian_destination = None + self.cartesian_pos = None + self.joint_pos = None + self.cartesian_motors_enabled = False + self.cartesian_motors = [] + self.joint_motors_enabled = False + self.joint_motors = [] + self.tool = None + self.frame = FRAME_DEFAULT + self.updating = False + + + def doInitialize(self): + super(RobotTCP, self).doInitialize() + self.reset = True + + + def set_tool(self,tool): + self.tool = tool + if self.cartesian_motors_enabled: + self.cartesian_pos = self.get_cartesian_pos() + for m in self.cartesian_motors: + m.initialize() + m.update() + + + def get_tool(self): + return self.tool + + + def _sendReceive(self, msg_id, msg = "", timeout = None): + tx = self.header if (self.header != None) else "" + tx = tx + msg_id + " " + msg + if (len(tx)>127): + raise Exception("Exceeded maximum message size") + self.getLogger().finer("TX = '" + str(tx)+ "'") + if (self.trailer != None): tx = tx + self.trailer + rx = self.sendReceive(tx, msg_id, self.trailer , 0, self.timeout if timeout is None else timeout, self.retries) + rx=rx[:-1] #Remove 0A + self.getLogger().finer("RX = '" + str(rx) + "'") + if rx[:3] != msg_id: + if (time.time()-start) >= timeout: + raise Exception("Received invalid message id: " + str(rx[:3]) + " - expecting:" + msg_id ) + if len(rx)<4: + raise Exception("Invalid message size: " + str(len(rx)) ) + if rx[3] == "*": + raise Exception(rx[4:]) + return rx[4:] + + def call(self, msg, timeout = None): + self.lock.acquire() + try: + id = "%03d" % self.msg_id + self.msg_id = (self.msg_id+1)%1000 + return self._sendReceive(id, msg, timeout) + finally: + self.lock.release() + + def execute(self, command, *args, **kwargs): + timeout = None if (kwargs is None) or (not kwargs.has_key("timeout")) else kwargs["timeout"] + msg = str(command) + if len(args)>10: + raise Exception("Exceeded maximum number of parameters") + for i in range(len(args)): + msg += (self.cmd_separator if (i==0) else self.array_separator) + str(args[i]) + rx = self.call(msg, timeout) + if rx.count(self.array_separator)>0: + return rx.split(self.array_separator) + return rx + + def evaluate(self, cmd, timeout=None): + ret = self.execute('eval', cmd, timeout=timeout) + if type(ret) is str: + if ret.strip() != "": raise Exception(ret) + + def get_var(self, name): + return self.execute('get_var', name) + + #Makes app crash + #def get_str(self, name='s'): + # return self.execute('get_str', name) + + def get_arr(self, name, size): + return self.execute('get_arr', name, size) + + def get_bool(self, name = "tcp_b"): + return True if (self.execute('get_bool', name).strip() == '1') else False + + def get_int(self, name ="tcp_n"): + return int(self.get_var(name)) + + def get_float(self, name ="tcp_n"): + return float(self.get_var(name)) + + def get_int_arr(self, size, name="tcp_a"): + # not working. A Jython bug in PyUnicaode? + #return [int(x) for x in self.get_arr("tcp_a", size)] + ret = [] + a=self.get_arr(name, size) + for i in range(size): + ret.append(int(a[i])) + return ret + + def get_float_arr(self, size, name="tcp_a"): + #return [float(x) for x in self.get_arr("tcp_a", size)] + a=self.get_arr(name, size) + ret = []; + for i in range(size): ret.append(float(a[i])); + return ret + + def get_trsf(self, name="tcp_t"): + a = self.execute('get_trf', name) + ret = [] + for i in range(6): ret.append(float(a[i])) + return ret + + def set_trsf(self, l, name="tcp_t"): + self.evaluate(name + "={" + str(l[0]) + ","+ str(l[1]) + ","+ str(l[2]) + ","+ str(l[3]) + ","+ str(l[4]) + ","+ str(l[5]) + "}") + + def get_jnt(self, name="tcp_j"): + a = self.execute('get_jnt', name) + ret = [] + for i in range(6): ret.append(float(a[i])) + return ret + + def set_jnt(self, l, name="tcp_j"): + self.evaluate(name + "={" + str(l[0]) + ","+ str(l[1]) + ","+ str(l[2]) + ","+ str(l[3]) + ","+ str(l[4]) + ","+ str(l[5]) + "}") + + def get_pnt(self, name="tcp_p"): + #a = self.execute('get_pnt', name) + #ret = [] + #for i in range(6): ret.append(float(a[i])) + #return ret + return self.get_trsf(name+".trsf") + + #trsf = (x,y,z,rx,ry,rz) + #TODO: config = (shoulder, elbow, wrist) + def set_pnt(self, trsf, name="tcp_p", config=None): + self.set_trsf(trsf, name+".trsf") + + def get_tool_trsf(self, name=None): + if name is None: + name = self.tool + return self.get_trsf(name+".trsf") + + def set_tool_trsf(self, trsf, name=None): + if name is None: + name = self.tool + self.set_trsf(trsf, name+".trsf") + + def eval_int(self, cmd): + self.evaluate("tcp_n=" + cmd) + return self.get_int() + + def eval_float(self, cmd): + self.evaluate("tcp_n=" + cmd) + return self.get_float() + + def eval_bool(self, cmd): + self.evaluate("tcp_b=" + cmd) + return self.get_bool() + + #def eval_str(self, cmd): + # self.evaluate("s=" + cmd) + # return self.get_str() + + def eval_jnt(self, cmd): + self.evaluate("tcp_j=" + cmd) + return self.get_jnt() + + def eval_trf(self, cmd): + self.evaluate("tcp_t=" + cmd) + return self.get_trsf() + + def eval_pnt(self, cmd): + self.evaluate("tcp_p=" + cmd) + return self.get_pnt() + + + #Robot control + def is_powered(self): + self.powered = self.eval_bool("isPowered()") + return self.powered + + def enable(self): + if not self.is_powered(): + self.evaluate("enablePower()") + time.sleep(1.0) + if not self.is_powered(): + raise Exception("Cannot enable power") + + #waits for power to be actually cut off + def disable(self): + self.evaluate("disablePower()", timeout=5000) + + def get_monitor_speed(self): + self.speed = self.eval_int("getMonitorSpeed()") + return self.speed + + def set_monitor_speed(self, speed): + ret = self.eval_int("setMonitorSpeed(" + str(speed) + ")") + if (ret==-1): raise Exception("The robot is not in remote working mode") + if (ret==-2): raise Exception("The monitor speed is under the control of the operator") + if (ret==-3): raise Exception("The specified speed is not supported") + + def is_calibrated(self): + return self.eval_bool("isCalibrated()") + + def save_program(self): + ret = self.execute('save', timeout=5000) + if str(ret) != "0": raise Exception("Error saving program: " + str(ret)) + + def _update_working_mode(self, mode, status): + if mode==1: + self.working_mode = "manual" + self.status = "hold" if status==6 else "move" + elif mode==2: + self.working_mode = "test" + self.status = "hold" if status==3 else "move" + elif mode==3: + self.working_mode = "local" + self.status = "hold" if status==2 else "move" + elif mode==4: + self.working_mode = "remote" + self.status = "hold" if status==2 else "move" + else: + self.working_mode = "invalid" + self.status = "invalid" + + def read_working_mode(self): + try: + mode = self.eval_int("workingMode(tcp_a)") + status = int(self.get_var("tcp_a[0]")) + self._update_working_mode(mode, status) + self._update_state() + except: + self.working_mode = "invalid" + self.status = "invalid" + return self.working_mode + + def get_emergency_stop_sts(self): + st = self.eval_int("esStatus()") + if (st== 1): return "active" + if (st== 2): return "activated" + return "off" + + def get_safety_fault_signal(self): + fault = self.eval_bool("safetyFault(s)") + #if (fault): + # return get_str() + return fault + + #Motion control + def stop(self): + self.evaluate("stopMove()") + + def resume(self): + self.evaluate("restartMove()") + + def reset_motion(self, joint=None): + self.evaluate("resetMotion()" if (joint is None) else ("resetMotion(" + joint + ")")) + + def is_empty(self): + self.empty = self.eval_bool("isEmpty()") + self._update_state() + return self.empty + + def is_settled(self): + self.settled = self.eval_bool("isSettled()") + self._update_state() + return self.settled + + def get_move_id(self): + return self.eval_int("getMoveId()") + + def set_move_id(self, id): + return self.evaluate("setMoveId(" + str(id) + " )") + + def get_joint_forces(self): + try: + self.evaluate("getJointForce(tcp_a)") + self.joint_forces = self.get_float_arr(6) + return self.joint_forces + except: + self.joint_forces = None + raise + + def movej(self, joint_or_point, tool, desc): + return self.eval_int("movej(" + joint_or_point + ", " + tool + ", " + desc +")") + + def movel(self, point, tool, desc): + return self.eval_int("movel(" + point + ", " + tool + ", " + desc +")") + + def movec(self, point_interm, point_target, tool, desc): + return self.eval_int("movec(" + point_interm + ", " + point_target + ", " + tool + ", " + desc +")") + + + #Tool + #This function can timeout since it synchronizes move. + #Better check state before otherwise it can freeze the communication + def open_tool(self, tool): + return self.evaluate("open(" + tool + " )", timeout=3000) + + #This function can timeout since it synchronizes move. Better check state before + #Better check state before otherwise it can freeze the communication + def close_tool(self, tool): + return self.evaluate("close(" + tool + " )", timeout=3000) + + #Arm position + def herej(self): + return self.eval_jnt("herej()") + + def distance_t(self, trsf1, trsf2): + return self.eval_float("distance(" + trsf1 + ", " + trsf2 + ")") + + def distance_p(self, pnt1, pnt2): + return self.eval_float("distance(" + pnt1 + ", " + pnt2 + ")") + + def compose(self, pnt, frame, trsf): + return self.eval_pnt("compose(" + pnt + ", " + frame + ", " + trsf + ")") + + def here(self, tool, frame): + return self.eval_pnt("here(" + tool + ", " + frame + ")") + + def joint_to_point(self, tool, frame, joint="tcp_j"): + return self.eval_pnt("jointToPoint(" + tool + ", " + frame + ", " + joint +")") + + def point_to_joint(self, tool, initial_joint="tcp_j", point="tcp_p"): + if self.eval_bool("pointToJoint(" + tool + ", " + initial_joint + ", " + point +", j)"): + return self.get_jnt() + + def position(self, point, frame): + return self.eval_trf("position(" + point + ", " + frame + ")") + + #Profile + def get_profile(self): + return self.execute('get_profile', timeout=2000) + + def set_profile(self, name, pwd = ""): + self.execute('set_profile', str(name), str(pwd), timeout=5000) + + + #Task control + def task_create(self, program, *args, **kwargs): + program = str(program) + priority = 10 if (kwargs is None) or (not kwargs.has_key("priority")) else kwargs["priority"] + name = str(program if (kwargs is None) or (not kwargs.has_key("name")) else kwargs["name"]) + + if self.get_task_status(name)[0] != -1: + raise Exception("Task already exists: " + name) + + #taskCreate "t1", 10, read(sMessage) + cmd = 'taskCreate "' + name + '", ' + str(priority) + ', ' + program + '(' + for i in range(len(args)): + cmd += str(args[i]) + (',' if (i<(len(args)-1)) else '') + cmd+=')' + self.evaluate(cmd) + + def task_suspend(self, name): + self.evaluate('taskSuspend("' + str(name)+ '")') + + #waits until the task is ready for restart + def task_resume(self, name): + self.evaluate('taskResume("' + str(name)+ '",0)', timeout = 2000) + + #waits for the task to be actually killed + def task_kill(self, name): + #self.evaluate('taskKill("' + str(name)+ '")', timeout = 5000) + self.execute('kill', str(name), timeout=5000) + + def get_task_status(self, name): + code = self.eval_int('taskStatus("' + str(name)+ '")') + #TODO: String assignments in $exec causes application to freeze + #status = self + if code== -1: status = "Stopped" + elif code== 0: status = "Paused" + elif code== 1: status = "Running" + #else: status = self.execute('get_help', code) + else: status = "Error" + return (code,status) + + def _update_state(self): + #self.setState(State.Busy if self.status=="move" else State.Ready) + if self.state==State.Offline: + print "Communication resumed" + if self.reset or (self.state==State.Offline): + self.get_task() + if self.current_task is not None: + print "Ongoing task: " + self.current_task + + if (not self.settled) or (self.current_task is not None): self.setState(State.Busy) + elif not self.empty: self.setState(State.Paused) + else: self.setState(State.Ready) + + def doUpdate(self): + try: + start = time.time() + #sts = self._sendReceive("EVT").strip().split(self.array_separator) + sts = self.execute("get_status", self.current_task) + self._update_working_mode(int(sts[0]), int(sts[1])) + self.powered = sts[2] == "1" + self.speed = int(sts[3]) + self.empty = sts[4] == "1" + self.settled = sts[5] == "1" + ev = sts[7] if len(sts)>7 else "" + if len(ev.strip()) >0: + self.getLogger().info(ev) + self.on_event(ev) + #if (self.current_task is not None) and (self.get_task_status(self.current_task)[0]<0): + if int(sts[6]) < 0: + self.current_task = None + self._update_state() + self.reset = False + self.setCache({"powered": self.powered, + "speed": self.speed, + "empty": self.empty, + "settled": self.settled, + "task": self.current_task, + "mode": self.working_mode, + "status": self.status + }, None) + if not self.updating: + if self.cartesian_motors_enabled: + self.cartesian_pos = self.get_cartesian_pos() + for m in self.cartesian_motors: + #m.update() + m.readback.update() + else: + self.cartesian_pos = None + if self.joint_motors_enabled: + self.joint_pos = self.herej() + for m in self.joint_motors: + m.readback.update() + except: + if self.state != State.Offline: + print >> sys.stderr, "Update error: " + str(sys.exc_info()[1]) + self.setState(State.Offline) + + #Cartesian space + + def get_cartesian_pos(self): + return self.eval_pnt("jointToPoint(" + self.tool + ", " + self.frame + ", herej())") + #self.set_jnt(self.herej()) + #return self.joint_to_point(tool, frame) + + def get_cartesian_destination(self): + return self.here(self.tool, self.frame) + + def get_distance_to_pnt(self, name): + #self.here(self.tool, self.frame) #??? + self.get_cartesian_pos() + return self.distance_p("tcp_p", name) + + #Cartesian peudo-motors + def set_motors_enabled(self, value): + if value !=self.cartesian_motors_enabled: + self.cartesian_motors_enabled = value + if value: + for i in range(6): + self.cartesian_motors.append(RobotCartesianMotor(self, i)) + add_device(self.cartesian_motors[i], True) + self.cartesian_destination = self.get_cartesian_destination() + else: + for m in self.cartesian_motors: + remove_device(m) + self.cartesian_motors = [] + self.cartesian_destination = None + else: + if value: + self.cartesian_destination = self.get_cartesian_destination() + for m in self.cartesian_motors: + m.initialize() + + + #Cartesian peudo-motors + def set_joint_motors_enabled(self, value): + if value !=self.joint_motors_enabled: + self.joint_motors_enabled = value + if value: + for i in range(6): + self.joint_motors.append(RobotJointMotor(self, i)) + add_device(self.joint_motors[i], True) + else: + for m in self.joint_motors: + remove_device(m) + self.joint_motors = [] + self.joint_destination = None + else: + if value: + self.joint_destination = self.get_joint_destination() + for m in self.joint_motors: + m.initialize() + + + #High-level, exclusive motion task. + def start_task(self, program, *args, **kwargs): + tasks = [t for t in self.high_level_tasks] + if (self.current_task is not None) and (not self.current_task in tasks): + tasks.append(pro) + if not program in tasks: + tasks.append(pro) + for task in tasks: + if self.get_task_status(task)[0]>=0: + raise Exception("Ongoing high-level task: " + task) + self.task_create(program, *args, **kwargs) + start = time.time() + while self.get_task_status(program)[0] < 0: + if time.time() - start > 5000: + raise Exception("Cannot start task " + task) + time.sleep(0.1) + self.update() + self.current_task = program + self._update_state() + + def stop_task(self): + tasks = [t for t in self.high_level_tasks] + if (self.current_task is not None) and (not self.current_task in tasks): + tasks.append(self.current_task) + for task in tasks: + #if self.get_task_status(task)[0]>=0: + self.task_kill(task) + + def get_task(self): + if self.current_task is not None: + return self.current_task + for task in self.high_level_tasks: + if self.get_task_status(task)[0]>=0: + self.current_task = task + return task + return None + + + def on_event(self,ev): + pass + + + +TOOL_CALIBRATION = "tCalib" +TOOL_SUNA= "tSuna" +TOOL_DEFAULT= TOOL_SUNA + +DESC_FAST = "mFast" +DESC_SLOW = "mSlow" +DESC_SCAN = "mScan" +DESC_DEFAULT = DESC_FAST + + + + +simulation = True +joint_forces = False + + +class RobotSC(RobotTCP): + def __init__(self, name, server, timeout = 1000, retries = 1): + RobotTCP.__init__(self, name, server, timeout, retries) + self.tool = TOOL_CALIBRATION + + def mount(self, puck, sample): + return self.execute('mount',segment, puck, sample) + + def firstmount(self, puck, sample): + return self.execute('firstmount', segment, puck, sample) + + def unmount(self, puck, sample): + return self.execute('unmount',segment, puck, sample) + + def on_event(self,ev): + #print "EVT: " + ev + pass + + def doUpdate(self): + #start = time.time() + RobotTCP.doUpdate(self) + global simulation + if not simulation: + if joint_forces: + if self.state != State.Offline: + self.get_joint_forces() + for dev in [jf1, jf2, jf3, jf4,jf5, jf6, jfc]: + dev.update() + #print time.time() -start + + def start_task(self, program, *args, **kwargs): + #TODO: Check safe position + RobotTCP.start_task(self, program, *args, **kwargs) + + def stop_task(self): + RobotTCP.stop_task(self) + #TODO: Restore safe position + + def set_remote_mode(self): + robot.set_profile("remote") + + def set_local(self): + robot.set_profile("default") + + def set_tool(self,tool): + if tool != self.tool: + self.tool = tool + for dev in (robot_x, robot_y, robot_z, robot_rx, robot_ry, robot_rz): + dev.initialize() + dev.update() + + + +if simulation: + #add_device(RobotSC("robot","129.129.126.92:1000"),force = True) + add_device(RobotSC("robot","129.129.110.99:1000"),force = True) +else: + add_device(RobotSC("robot", "129.129.110.100:1000"), force = True) + +robot.high_level_tasks = ["mount", "firstmount"] +robot.setPolling(500) \ No newline at end of file diff --git a/script/test/Save3d.py b/script/test/Save3d.py new file mode 100755 index 0000000..6b5dc9d --- /dev/null +++ b/script/test/Save3d.py @@ -0,0 +1,15 @@ + +#Creating a 3D dataset from an array +data3d = [ [ [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]], [ [3,2,3,4,5], [4,3,4,5,6], [5,4,5,6,7]]] +path="group/data1" +save_dataset(path, data3d) +#Reading it back +read =load_data(path,0) +print read.tolist() +read =load_data(path,1) +print read.tolist() + + +set_exec_pars(depth_dim=2) + +save_dataset("group/data2", data3d) diff --git a/script/test/TEstPars.py b/script/test/TEstPars.py new file mode 100755 index 0000000..d6d3dc2 --- /dev/null +++ b/script/test/TEstPars.py @@ -0,0 +1,5 @@ +#set_exec_pars(persist=False, plot_disabled=True, table_disabled=True) +#set_exec_pars(persist=False, plot_disabled=True, table_disabled=True) + +tscan((sin,arr), 10, 0.100, enabled_plots= [arr,], persist=False, table_disabled=False, status = "Status") +tscan(sin, 10, 0.100) \ No newline at end of file diff --git a/script/test/Test3dDataset.py b/script/test/Test3dDataset.py new file mode 100755 index 0000000..8aa05ff --- /dev/null +++ b/script/test/Test3dDataset.py @@ -0,0 +1,15 @@ +width = cam_server.data.width +height = cam_server.data.height + +print + +print width, height +images = 4 + +path = "/image" + +create_dataset(path, 'd', dimensions = [height, width, images]) + + +for i in range(images): + append_dataset(path, cam_server.data.matrix) \ No newline at end of file diff --git a/script/test/TestBack.py b/script/test/TestBack.py new file mode 100755 index 0000000..488c539 --- /dev/null +++ b/script/test/TestBack.py @@ -0,0 +1,8 @@ +camtool.setBackgroundEnabled(False) + +camtool.start("simulation") +camtool.setBackground(camtool.getData()) +camtool.setBackgroundEnabled(True) +camtool.saveBackground(None) +camtool.setBackground(None) +camtool.loadBackground(None) \ No newline at end of file diff --git a/script/test/TestBack2.py b/script/test/TestBack2.py new file mode 100755 index 0000000..3e97876 --- /dev/null +++ b/script/test/TestBack2.py @@ -0,0 +1,8 @@ +tst2.setBackgroundEnabled(False) + +tst2.setBackground(tst2.getImage()) +tst2.setBackgroundEnabled(True) +tst2.refresh() +tst2.saveBackground(None) +tst2.setBackground(None) +tst2.loadBackground(None) \ No newline at end of file diff --git a/script/test/TestBsget.py b/script/test/TestBsget.py new file mode 100755 index 0000000..b9e42d0 --- /dev/null +++ b/script/test/TestBsget.py @@ -0,0 +1,24 @@ +def bsget(channel): + """Reads an values a bsread stream, using the default provider. + + Args: + channel(str or list of str): channel name(s) + Returns: + PV value + + """ + channels = to_list(channel) + st = Stream(None, None) + try: + for c in channels: + st.addScalar(c, c, 1,0) + st.initialize() + st.start() + st.waitValueNot(None, 5000) + if type(channel) is str: + return st.getValue(channel) + return st.values + finally: + st.close() + +bsget("Int32Scalar") \ No newline at end of file diff --git a/script/test/TestCom.py b/script/test/TestCom.py new file mode 100755 index 0000000..f57db21 --- /dev/null +++ b/script/test/TestCom.py @@ -0,0 +1,17 @@ + +data = camtool.getValue("x_profile") +x = camtool.getValue("x_axis") +y=data + +back = [3160000 if i>3340000 else i for i in y] + +y = arroff(y, "min") +#y=arrsub(y, back) + +p=plot(y, xdata = x)[0] +#print y +com,rms = center_of_mass(y, x) +print com,rms +p.addMarker(com, None, str(com), Color.GREEN) +p.addMarker(com-rms, None, "", Color.GREEN) +p.addMarker(com+rms, None, "", Color.GREEN) diff --git a/script/test/TestErrorAxis2.py b/script/test/TestErrorAxis2.py new file mode 100755 index 0000000..778f08d --- /dev/null +++ b/script/test/TestErrorAxis2.py @@ -0,0 +1,9 @@ +plt = plot(None)[0] +plt.clear() +plt.getAxis(plt.AxisId.Y).setLabel("Axis 1") +plt.getAxis(plt.AxisId.Y2).setLabel("Axis 2") +plt.setStyle(plt.Style.ErrorY) +plt.addSeries(LinePlotErrorSeries("S1")) +plt.addSeries(LinePlotErrorSeries("S2", None, 2)) +plt.getSeries(0).appendData(1.0, 3.0 , 1.0) +plt.getSeries(1).appendData(3.0, 2.0 , 2.0) \ No newline at end of file diff --git a/script/test/TestGaussFit.py b/script/test/TestGaussFit.py new file mode 100755 index 0000000..2bf0dfe --- /dev/null +++ b/script/test/TestGaussFit.py @@ -0,0 +1,16 @@ +run("cpython/GaussFit_wrapper") + + +x=[-200.30429237268825, -200.2650700434188, -200.22115208318002, -199.9457671375377, -199.86345548879072, -199.85213073174933, -199.35687977133284, -199.13811861090275, -197.97304970346386, -197.2952215624348, -195.09076092936948, -192.92276048970703, -191.96871876227698, -189.49577852322938, -187.9652790409825, -183.63756456925222, -180.04899765472996, -178.43839623242422, -174.07311671294445, -172.0410133577918, -165.90824309893102, -160.99771795989466, -159.30176653939253, -154.27688897558514, -152.0854103810786, -145.75652847587313, -140.80843828908465, -139.23982133191495, -134.27073891256106, -132.12649284133064, -125.95947209775511, -121.00309550337462, -119.26736932643232, -114.2706655484383, -112.07393889578914, -105.72295990367157, -100.8088439880125, -99.2034906238494, -94.30042325164636, -92.15010048151461, -85.92203653534293, -81.03913275494665, -79.27412793784428, -74.33487658582118, -72.06274362408762, -65.76562628131825, -60.91255356825276, -59.20334389560392, -54.33286972659312, -52.19387171350535, -45.94978737932291, -41.03014719193582, -39.301602568238906, -34.35572209014114, -32.04464301272608, -25.8221033382824, -20.922074315528747, -19.21590299233186, -14.31090212502093, -12.217203140101386, -5.9283722049240435, -0.9863587170369246, 0.7408048387279834, 5.71126832601389, 7.972628957879352, 14.204559894256546, 19.11839959633025, 20.8218087836657, 25.678748486941828, 27.822718344586864, 34.062659474970715, 38.9745656819391, 40.77409719734158, 45.72080631619803, 47.974156754056835, 54.23453768983539, 59.12020360609568, 60.77306570712026, 65.70734521458867, 67.8344660434617, 74.03187028154134, 78.96532114824849, 80.76070945985495, 85.74802197591286, 87.9140889204674, 94.18082276873524, 99.25790470037091, 100.68454787413205, 105.7213026221542, 107.79483801526698, 113.99555681638138, 119.0707052529143, 120.72715813056156, 125.77551384921307, 127.91257836719551, 134.2011330887875, 139.23043006997628, 140.71673537840158, 145.76288138835983, 147.80216629676042, 154.06420451405637, 159.0846626604798, 160.76183155710717, 165.73699067536242, 167.9265357747636, 173.96705069576544, 178.2522282751915, 179.9042617354548, 183.54586165856657, 185.23269803071796, 189.41678143751972, 191.87149157986588, 192.8741468985015, 195.0241934550453, 195.966634211846, 197.9821647518146, 198.99006812859284, 199.33202054855676, 199.91897441965887, 200.11536227958896, 200.22280936469997, 200.25181179127208] +y=[11.0, 6.0, 8.0, 5.0, 11.0, 7.0, 18.0, 11.0, 12.0, 10.0, 8.0, 6.0, 16.0, 4.0, 12.0, 9.0, 15.0, 14.0, 8.0, 20.0, 15.0, 8.0, 9.0, 11.0, 13.0, 12.0, 13.0, 15.0, 13.0, 20.0, 10.0, 7.0, 17.0, 11.0, 20.0, 13.0, 13.0, 23.0, 14.0, 10.0, 17.0, 15.0, 20.0, 16.0, 14.0, 13.0, 18.0, 22.0, 9.0, 20.0, 12.0, 14.0, 17.0, 19.0, 14.0, 14.0, 23.0, 19.0, 15.0, 20.0, 20.0, 21.0, 20.0, 23.0, 22.0, 15.0, 10.0, 17.0, 21.0, 15.0, 23.0, 23.0, 25.0, 18.0, 16.0, 21.0, 22.0, 16.0, 16.0, 14.0, 19.0, 20.0, 18.0, 20.0, 23.0, 13.0, 16.0, 20.0, 25.0, 15.0, 15.0, 17.0, 22.0, 26.0, 19.0, 30.0, 25.0, 17.0, 17.0, 23.0, 16.0, 27.0, 21.0, 21.0, 26.0, 27.0, 21.0, 17.0, 20.0, 20.0, 21.0, 19.0, 25.0, 19.0, 13.0, 23.0, 20.0, 20.0, 18.0, 20.0, 19.0, 25.0] + +[off, amp, com, sigma] = profile_gauss_stats(x, y, off=None, amp=None, com=None, sigma=None) +print "Gauss: ", [off, amp, com, sigma] +from mathutils import Gaussian + +#Plotting results +from mathutils import Gaussian +g = Gaussian(amp, com, sigma) +fit = [g.value(i)+off for i in x] + +plot([y, fit], ["data", "fit"], xdata = x) diff --git a/script/test/TestJson.py b/script/test/TestJson.py new file mode 100755 index 0000000..e680521 --- /dev/null +++ b/script/test/TestJson.py @@ -0,0 +1,25 @@ +import requests +import json + + +url = 'http://MPC1900:8080/run' + + +#Text mode +#resp = requests.get(url=url+"/test5(steps_x=3, steps_y=5)&") +#if resp.status_code != 200: raise Exception(resp.text) +#print resp.text + + +resp = requests.put(url=url, json={"script":'test5', "pars":{"steps_x":3, "steps_y":5}, "background":True }) +#resp = requests.put(url=url, json={"script":'test5', "pars":[8,10], "background":True }) +if resp.status_code != 200: raise Exception(resp.text) +data = json.loads(resp.text) +print data + + + + + + + diff --git a/script/test/TestLayout.py b/script/test/TestLayout.py new file mode 100755 index 0000000..c9dec89 --- /dev/null +++ b/script/test/TestLayout.py @@ -0,0 +1,39 @@ +tutorial_path = "src/main/assembly/help/Tutorial_py/" +run(tutorial_path+"SimulatedDevices") + + +import ch.psi.pshell.data.LayoutDefault +class LayoutParallelScan(ch.psi.pshell.data.LayoutDefault): + def getDefaultGroup(self, scan): + return scan.readables[0].name + + +#get_context().pluginManager.addDynamicClass(LayoutParallel().getClass()) + + +#Does not work +#lay = LayoutParallelScan().getClass() +##print lay +#cls = Class.forName(lay.getCanonicalName(), True, lay.getClassLoader()) +#3print cls +#set_exec_pars(layout = "org.python.proxies.__main__$LayoutParallelScan$25") + + + +#Must restore the layout +#get_context().dataManager.setLayout(LayoutParallelScan()) + +set_exec_pars(layout = "Table") + + + +def scan1(): + print "scan1" + return lscan(ao1, ai1, 0, 40, 20, 0.1, title = "scan1") + +def scan2(): + print "scan2" + return lscan(ao2, ai2, 0, 40, 20, 0.1, title = "scan2") + + +parallelize(scan1, scan2) diff --git a/script/test/TestPlot.py b/script/test/TestPlot.py new file mode 100755 index 0000000..80a42db --- /dev/null +++ b/script/test/TestPlot.py @@ -0,0 +1,3 @@ +plot([1,2,3,4,5,4,3,2,1], "test") +attachments = get_plot_snapshots() +print attachments diff --git a/script/test/TestProsilica.py b/script/test/TestProsilica.py new file mode 100755 index 0000000..ba7acfe --- /dev/null +++ b/script/test/TestProsilica.py @@ -0,0 +1,7 @@ + + +while (True): + prosilica.stop() + time.sleep(0.1) + prosilica.start() + time.sleep(0.5) \ No newline at end of file diff --git a/script/test/TestPyArray.py b/script/test/TestPyArray.py new file mode 100755 index 0000000..283696d --- /dev/null +++ b/script/test/TestPyArray.py @@ -0,0 +1,55 @@ +def lscan(writables, readables, start, end, steps, latency=0.0, relative=False, passes=1, zigzag=False, before_read=None, after_read=None, title=None): + """Line Scan: positioners change together, linearly from start to end positions. + + Args: + writables(list of Writable): Positioners set on each step. + readables(list of Readable): Sensors to be sampled on each step. + start(list of float): start positions of writables. + end(list of float): final positions of writables. + steps(int or float or list of float): number of scan steps (int) or step size (float). + relative (bool, optional): if true, start and end positions are relative to + current at start of the scan + latency(float, optional): settling time for each step before readout, defaults to 0.0. + passes(int, optional): number of passes + zigzag(bool, optional): if true writables invert direction on each pass. + before_read (function, optional): callback on each step, before each readout. Callback may have as + optional parameters list of positions. + after_read (function, optional): callback on each step, after each readout. Callback may have as + optional parameters a ScanRecord object. + title(str, optional): plotting window name. + + Returns: + ScanResult object. + + """ + latency_ms=int(latency*1000) + writables=to_list(string_to_obj(writables)) + readables=to_list(string_to_obj(readables)) + start=to_list(start) + end=to_list(end) + if type(steps) is float or is_list(steps): + steps = to_list(steps) + scan = LineScan(writables,readables, start, end , steps, relative, latency_ms, passes, zigzag) + scan.before_read=before_read + scan.after_read=after_read + scan.setPlotTitle(title) + scan.start() + ret = scan.getResult() + return ret + + +a= lscan(inp, (sin,out), 0, 4, 10, 0.1) + +x = a.getPositions(0) +y= a.getReadable(0) + + + +plt = plot(None,name="data")[0] +plt.addSeries(LinePlotSeries("1")) +plt.addSeries(LinePlotSeries("2")) +plt.getSeries(0).setData(x,y) +plt.getSeries(1).setData(list(x), list(y)) +plt.getSeries(2).setData(to_array(x,'d'), to_array(y,'d')) + + diff --git a/script/test/TestPyObj.py b/script/test/TestPyObj.py new file mode 100755 index 0000000..c240076 --- /dev/null +++ b/script/test/TestPyObj.py @@ -0,0 +1,67 @@ +class TestClass: + def __init__(self): + self.data = 10 + + def f1(self, p1 = 3, p2 = 4.0, p3 = False): + pass + + def f2(self, p1 = "asd", *argv, **kw): + pass + + def f3(self, p1 = [1,2,3], **kw): + pass + + def f4(self, p1 = {"v1":2.3}, *argv): + pass + +obj = TestClass() +print obj.data + + + +class TestClassDev (DeviceBase): + def __init__(self): + self.data = 10 + + def doInitialize(self): + pass + + def update(self): + pass + + def f1(self, p1 = 3, p2 = 4.0, p3 = False): + pass + + def f2(self, p1 = "asd", *argv, **kw): + pass + + def f3(self, p1 = [1,2,3], **kw): + pass + + def f4(self, p1 = {"v1":2.3}, *argv): + pass + +o2 = TestClassDev() + + + +class TestClassRead (Readable): + def __init__(self): + self.data = 10 + + def f1(self, p1 = 3, p2 = 4.0, p3 = False): + pass + + def f2(self, p1 = "asd", *argv, **kw): + pass + + def f3(self, p1 = [1,2,3], **kw): + pass + + def f4(self, p1 = {"v1":2.3}, *argv): + pass + + def read(self): + return 1 + +o3 = TestClassRead() \ No newline at end of file diff --git a/script/test/TestRotation.py b/script/test/TestRotation.py new file mode 100755 index 0000000..02d8d21 --- /dev/null +++ b/script/test/TestRotation.py @@ -0,0 +1,28 @@ +import ch.psi.pshell.epics.Positioner as Positioner + + +class Readback(ReadonlyRegisterBase): + def doRead(self): + return caget("TESTIOC:TESTCALCOUT:Output",'d') + 360.0 + +readback = Readback() +readback.initialize() +readback.setPolling(2000) + +p = Positioner("rot", "TESTIOC:TESTCALCOUT:Input", None, readback) + +#p = Positioner("RotationPositioner", "TESTIOC:TESTCALCOUT:Input", "TESTIOC:TESTCALCOUT:Output") +p.monitored=True +p.config.minValue = -360.0 +p.config.maxValue = 360.0 +p.config.precision = 3 +p.config.rotation = True +p.config.resolution = 0.01 +p.config.save() +p.initialize() + + +add_device(p, True) + + +print readback.read() \ No newline at end of file diff --git a/script/test/TestScan.py b/script/test/TestScan.py new file mode 100755 index 0000000..1102789 --- /dev/null +++ b/script/test/TestScan.py @@ -0,0 +1,17 @@ +print args + +if get_exec_pars().source == CommandSource.ui: + msg = None + start = 0 + end = 10.0 + steps = 10 +else: + msg = args[0] + start = float(args[1]) + end = float(args[2]) + steps = int(args[3]) + + +print msg +r = lscan (out, sin, start, end, steps, 0.2) + diff --git a/script/test/TestUndulatorScan.py b/script/test/TestUndulatorScan.py new file mode 100755 index 0000000..3df1a72 --- /dev/null +++ b/script/test/TestUndulatorScan.py @@ -0,0 +1,75 @@ +import ch.psi.pshell.epics.ControlledVariable as ControlledVariable +import ch.psi.pshell.epics.ChannelSettlingCondition as ChannelSettlingCondition +import ch.psi.pshell.device.SettlingCondition as SettlingCondition + +#cam_server.start("SAROP21-PSRD103_sp1", True) +pip.start("simulation_sp") +pip.stream.waitCacheChange(-1) +i = pip.stream.getChild("intensity") +iavg = create_averager(i, 2, interval = -1) + +x=0 + + +""" +class DCM(RegisterBase): + def doWrite(self, value): + print "Putting " , value + caput ("TESTIOC:TESTCALCOUT:Output", value) + print "Waiting " , value + cawait('TESTIOC:TESTCALCOUT:Output', value, timeout = 3600.0) + print "Done " + #if abs(value - self.read()) > IN_POSITION_BAND : + # raise Exception("Cannot set mono") + def doRead(self): + global x + x=x+1 + return caget ("TESTIOC:TESTCALCOUT:Input") + x + + #return caget("SARUN03-UIND030:FELPHOTENE.VAL") + +undulator = DCM() +undulator.initialize() +""" + +""" +class DCM(Readable, Writable): + def write(self, value): + print "Putting " , value + caput ("TESTIOC:TESTCALCOUT:Output", value) + print "Waiting " , value + cawait('TESTIOC:TESTCALCOUT:Output', value, timeout = 3600.0) + print "Done " + #if abs(value - self.read()) > IN_POSITION_BAND : + # raise Exception("Cannot set mono") + def read(self): + global x + x=x+1 + return caget ("TESTIOC:TESTCALCOUT:Input") + x + + #return caget("SARUN03-UIND030:FELPHOTENE.VAL") + +undulator = DCM() +""" + + +class MySettlingCondition(SettlingCondition): + def waitSettled(self): + time.sleep(100) + cawait('TESTIOC:TESTCALCOUT:Input', value, timeout = 3600.0) + + + + #return caget("SARUN03-UIND030:FELPHOTENE.VAL") + +undulator = ControlledVariable("undulator", "TESTIOC:TESTCALCOUT:Output", "TESTIOC:TESTSINUS:SinCalc") +undulator.config.resolution = float('inf') +undulator.initialize() +undulator.setSettlingCondition(ChannelSettlingCondition("TESTIOC:TESTCALCOUT:Input", 0, None, 'i', None)) + +undulator.settlingCondition.latency = 100 + + +lscan(undulator, [iavg], 1.0100, 1.18, 0.005 , latency= 0.2, range="auto") + + diff --git a/script/test/averager.py b/script/test/averager.py new file mode 100755 index 0000000..82039e6 --- /dev/null +++ b/script/test/averager.py @@ -0,0 +1,16 @@ +#diode = Channel("TESTIOC:TESTSINUS:SinCalc") + +#diode = create_channel_device("TESTIOC:TESTSINUS:SinCalc") +#diode.monitored = True +#iavg = create_averager(diode, 3, interval = -1) + + + +#iavg = create_averager("ca://TESTIOC:TESTSINUS:SinCalc", 3, interval = -1) +iavg = create_averager("bs://Int8Scalar", 3, interval = 0.1) + + +tscan (iavg, 10, 0.5) + + +#$iavg.close() \ No newline at end of file diff --git a/script/test/back.py b/script/test/back.py new file mode 100755 index 0000000..98aa191 --- /dev/null +++ b/script/test/back.py @@ -0,0 +1,6 @@ +import java.util.logging.Logger as Logger +logger = Logger.getLogger("back") + +logger.info("Started") + + diff --git a/script/test/calc.groovy b/script/test/calc.groovy new file mode 100755 index 0000000..0034558 --- /dev/null +++ b/script/test/calc.groovy @@ -0,0 +1,6 @@ + + +def calc(a){ + a*2 +} + diff --git a/script/test/calc.js b/script/test/calc.js new file mode 100755 index 0000000..65c0271 --- /dev/null +++ b/script/test/calc.js @@ -0,0 +1,5 @@ + + +function calc(a) { + return a * 5; + } \ No newline at end of file diff --git a/script/test/calc.py b/script/test/calc.py new file mode 100755 index 0000000..7d85119 --- /dev/null +++ b/script/test/calc.py @@ -0,0 +1,3 @@ +def calc(a): + return a*4 + diff --git a/script/test/cls.groovy b/script/test/cls.groovy new file mode 100755 index 0000000..071cd03 --- /dev/null +++ b/script/test/cls.groovy @@ -0,0 +1,7 @@ +package script +class cls { + double val = 1.0 + void exec(){ + println "Exec" + } +} \ No newline at end of file diff --git a/script/test/cls.py b/script/test/cls.py new file mode 100755 index 0000000..d1cdbcc --- /dev/null +++ b/script/test/cls.py @@ -0,0 +1,4 @@ +class cls: + def execute(self): + print "Execute" + diff --git a/script/test/script.groovy b/script/test/script.groovy new file mode 100755 index 0000000..08abd78 --- /dev/null +++ b/script/test/script.groovy @@ -0,0 +1,31 @@ + +def function(a){ + a*2 +} +//evaluate (new File("calc.groovy")) +//evaluate (new File("cls.groovy")) + +println "--------------" + +lib.load "calc" +cls = lib.load "cls" + + +//This is how to load a new class dinamically +// ClassLoader parent = lib.class.getClassLoader(); +// groovy.lang.GroovyClassLoader loader = new groovy.lang.GroovyClassLoader(parent); +// Class cls = loader.parseClass(new File("script\\cls.groovy")); + + +println dev.get() +println dev2.val +println calc(6) + + +//cls = Class.forName('cls') +//obj = new cls() +obj = cls.newInstance() +println obj.val +obj.exec() + + diff --git a/script/test/script.js b/script/test/script.js new file mode 100755 index 0000000..b205d9b --- /dev/null +++ b/script/test/script.js @@ -0,0 +1,13 @@ +function calcx(a) { + return a * 5; + } + +print('Hello, World') +lib.load ("calc") + + +a=3 +a +print (dev.get()) +print (dev2.val) +print (calc(5)) diff --git a/script/test/startup.groovy b/script/test/startup.groovy new file mode 100755 index 0000000..ff7e6da --- /dev/null +++ b/script/test/startup.groovy @@ -0,0 +1,53 @@ +import ch.psi.pshell.scan.LineScan; +import ch.psi.pshell.scan.AreaScan; + + +def sleep(millis){ + Thread.sleep(millis); +} + +def toArray(obj){ + /* if (!obj.getClass().isArray()){ + arr = java.lang.reflect.Array.newInstance(obj.getClass(), 1); + arr[0]= obj; + obj=arr + }*/ + return obj +} + + +def scan(writables, readables, start, end, steps, latency_ms=0, plot=null){ + writables=toList(writables) + readables=toList(readables) + start=toList(start) + end=toList(end) + scan = LineScan(writables,readables, start, end , steps,latency_ms, controller) + scan.setPlotName(plot) + scan.start() + return scan.getResult() +} + +def tscan(readables, points, interval_ms, plot=null){ + writables=[] + //readables=toList(readables) + readables=[readables,] + start=[0] + + end=[points] + steps=points + scan = LineScan(writables,readables, start, end , steps,interval_ms, controller) + scan.setPlotName(plot) + scan.start() + return scan.getResult() +} + +def ascan(writables, readables, start, end, steps, latency_ms0, plot=null){ + writables=toList(writables) + readables=toList(readables) + start=toList(start) + end=toList(end) + scan = AreaScan(writables,readables, start, end , steps,latency_ms, controller) + scan.setPlotName(plot) + scan.start() + return scan.getResult() +} \ No newline at end of file diff --git a/script/test/swing.py b/script/test/swing.py new file mode 100755 index 0000000..508b9b4 --- /dev/null +++ b/script/test/swing.py @@ -0,0 +1,2 @@ +from javax.swing import * +a=JPanel() \ No newline at end of file diff --git a/script/test/test.py b/script/test/test.py new file mode 100755 index 0000000..7ef0f67 --- /dev/null +++ b/script/test/test.py @@ -0,0 +1,2 @@ +def test(): + print dev.read() \ No newline at end of file diff --git a/script/test0.py b/script/test0.py new file mode 100755 index 0000000..db2b740 --- /dev/null +++ b/script/test0.py @@ -0,0 +1,69 @@ +import sys +import time + +#To add library folders from within the script +#sys.path.append("./site-packages") + + +import requests +r = requests.get('https://api.github.com', auth=('user', 'pass')) +print r.status_code +print r.headers['content-type'] +r.close() + + +def calc2(a): + return a*2 +time.sleep(0.1) +#import os +#print os.environ +#import calc + + +lib.load("calc") +lib.load("cls") +time.sleep(0.1) +for x in range(3): + print x + while(True): + print x*2 + break +time.sleep(2) +x=cls() +x.execute() +print dev.take() +#print dev2.val +time.sleep(1) +print calc(4) + + + +data = [1,2,3,4,5] +path="group/data" + + +save_dataset(path, data) +read =load_data(path) + +print read.tolist() + +#plot(read) + + +data = [ [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]] +path="group/data2" + + +save_dataset(path, data) +read =load_data(path) + +print read.tolist() + +plot(read) + + + + +""" +It lives!!!! +""" \ No newline at end of file diff --git a/script/test1.py b/script/test1.py new file mode 100755 index 0000000..d93a78a --- /dev/null +++ b/script/test1.py @@ -0,0 +1,34 @@ +''' +Line Scan +''' +#setup_plotting(plot_list = (sin,out)) +#x = 2/0 +print get_exec_pars().path + + +#a= lscan(inp, (sin,out,arr), 0, 40, 10, 0.2) + +ret= tscan(sin, 10, 0.1) +p = get_exec_pars() +print p.getPath() + +print p.getScanPath() + + +path = get_exec_pars().group +#save_dataset(path + "data", a.getReadable(0) ) +#set_attribute(path + "data", "Temp", 39.0) +set_attribute(path, "AttrString", "Value") +set_attribute(path, "AttrInteger", 1) +set_attribute(path, "AttrDouble", 2.0) +set_attribute(path, "AttrBoolean", True) +set_attribute(path, "AttrArr", [1,2,3]) + +set_attribute(path + "sin", "Temp", 39.0) + + +#set_return([1.0, 3, [1,2,3,4]]) + +#set_return("T\"es\"t") +#set_return([3.0,2]) +set_return(ret) \ No newline at end of file diff --git a/script/test1.xml b/script/test1.xml new file mode 100755 index 0000000..0d59451 --- /dev/null +++ b/script/test1.xml @@ -0,0 +1,26 @@ + + + + alexandre.gobbo@psi.ch + + + My first test a + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + diff --git a/script/test10.py b/script/test10.py new file mode 100755 index 0000000..5134466 --- /dev/null +++ b/script/test10.py @@ -0,0 +1,41 @@ +""" +Multi-peak search +""" + +from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list + +start = 0 +end = 30 +step_size = 0.2 + +result= lscan(sout,sinp,start,end,[step_size,],0.01) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +threshold = (min(readable) + max(readable))/2 +min_peak_distance = 5.0 + +peaks = estimate_peak_indexes(readable, positions, threshold, min_peak_distance) +print "Peak indexes: " + str(peaks) +print "Peak x: " + str(map(lambda x:positions[x], peaks)) +print "Peak y: " + str(map(lambda x:readable[x], peaks)) + + + +gaussians = fit_gaussians(readable, positions, peaks) + + +plots = plot([readable],["sin"],[positions], title="Data" ) +for i in range(len(peaks)): + peak = peaks[i] + (norm, mean, sigma) = gaussians[i] + if abs(mean - positions[peak]) < min_peak_distance: + print "Peak -> " + str(mean) + plots[0].addMarker(mean, None, "N="+str(round(norm,2)), None) + else: + print "Invalid gaussian fit: " + str(mean) + + + + diff --git a/script/test11-Guard.xml b/script/test11-Guard.xml new file mode 100755 index 0000000..0cd8635 --- /dev/null +++ b/script/test11-Guard.xml @@ -0,0 +1,29 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + + diff --git a/script/test11.py b/script/test11.py new file mode 100755 index 0000000..dd27bcd --- /dev/null +++ b/script/test11.py @@ -0,0 +1,10 @@ +""" +Injecting parameters + +Parameters: start(float), end(float), step(int) + +Execute: run ("test11", {"start":10.0, "end":50.0, "step":40}) +""" +a= lscan(inp, sin, start, end, step, 0.1) + + diff --git a/script/test12-region.xml b/script/test12-region.xml new file mode 100755 index 0000000..633d648 --- /dev/null +++ b/script/test12-region.xml @@ -0,0 +1,38 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + + + + + + + + diff --git a/script/test12.py b/script/test12.py new file mode 100755 index 0000000..b20102b --- /dev/null +++ b/script/test12.py @@ -0,0 +1,8 @@ +""" +Relative Scan +""" + +a= lscan(inp, (sin,out,arr), -2, 2, 20, 0.1, True) + + + diff --git a/script/test13.py b/script/test13.py new file mode 100755 index 0000000..b20102b --- /dev/null +++ b/script/test13.py @@ -0,0 +1,8 @@ +""" +Relative Scan +""" + +a= lscan(inp, (sin,out,arr), -2, 2, 20, 0.1, True) + + + diff --git a/script/test13.xml b/script/test13.xml new file mode 100755 index 0000000..96b92d8 --- /dev/null +++ b/script/test13.xml @@ -0,0 +1,54 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + + + + + 0.0 + 30.0 + 5.0 + + + + + + 50.0 + 70.0 + 2.0 + + + + + + 70.0 + 75.0 + 1.0 + + + + + + + + + + + + diff --git a/script/test14.py b/script/test14.py new file mode 100755 index 0000000..3d3eaaa --- /dev/null +++ b/script/test14.py @@ -0,0 +1,21 @@ +RANGE_1 = (0.0, 80.0) +SETPOINTS_2 = (1.0, 2.0, 3.0) +motor.setSpeed(100.0) + +#set_preference(Preference.ENABLED_PLOTS, [sin,]) +set_preference(Preference.PLOT_TYPES, {sin:1,sinp:1}) + + + +scan = ManualScan([motor.getName(), out.getName()], [sin.getName(), sinp.getName()] , [-1, SETPOINTS_2[0]], [-1, SETPOINTS_2[-1]], [-1, len(SETPOINTS_2)-1]) +#scan = ManualScan([motor.getName(), out.getName()], [sin.getName(), sinp.getName()] , [RANGE_1[0], SETPOINTS_2[0]], [RANGE_1[-1], SETPOINTS_2[-1]], [int(RANGE_1[1]-RANGE_1[0]), len(SETPOINTS_2)-1]) +scan.start() +for setpoint1 in frange(RANGE_1[0], RANGE_1[1], 1.0, True): + motor.move(setpoint1) + for setpoint2 in SETPOINTS_2: + out.put(setpoint2) + scan.append ([setpoint1, setpoint2], [motor.read(), out.read()], [sin.read(), sinp.read()]) + + + +scan.end() diff --git a/script/test14.xml b/script/test14.xml new file mode 100755 index 0000000..db1f4ec --- /dev/null +++ b/script/test14.xml @@ -0,0 +1,26 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 20.0 + 1.0 + + + + + + + + + + + diff --git a/script/test15.py b/script/test15.py new file mode 100755 index 0000000..22af96f --- /dev/null +++ b/script/test15.py @@ -0,0 +1,15 @@ +""" +Area Scan with custom 1D plot +""" +set_preference(Preference.PLOT_TYPES, {'sin':1}) + + + +p = plot(None, title="1d")[0] +def AfterReadout(record, scan): + if record.setpoints[1] == scan.getStart()[1]: + p.addSeries(LinePlotSeries(str(record.positions[0]))) + p.getSeries(p.numberOfSeries-1).appendData(record.positions[1], record.values[0]) + + +ascan((dev,out), (sin,arr), (0,10), (20,30), (20,20), 0.2, after_read=AfterReadout) \ No newline at end of file diff --git a/script/test15.xml b/script/test15.xml new file mode 100755 index 0000000..f7cc16c --- /dev/null +++ b/script/test15.xml @@ -0,0 +1,34 @@ + + + + alexandre.gobbo@psi.ch + + + My second test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + 0.0 + 5.0 + 1.0 + + + + + + diff --git a/script/test16.py b/script/test16.py new file mode 100755 index 0000000..385e086 --- /dev/null +++ b/script/test16.py @@ -0,0 +1,12 @@ + + +#A single motor at current speed +a= cscan(m1, (ai1,ai2), -2, 2 , steps=100, relative=True) + + +#A single motor in a given time +a= cscan(m1, (ai1,ai2), -2.0, 3.0, steps=100 ,time = 4.0, relative=True) + +#Multiple motors in a given time +a= cscan((m1, m2), (ai1,ai2), (-2.0, -3), (3.0, 5.0), steps=100,time = 4.0, relative=True) + diff --git a/script/test16.xml b/script/test16.xml new file mode 100755 index 0000000..f7cc16c --- /dev/null +++ b/script/test16.xml @@ -0,0 +1,34 @@ + + + + alexandre.gobbo@psi.ch + + + My second test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + 0.0 + 5.0 + 1.0 + + + + + + diff --git a/script/test17.py b/script/test17.py new file mode 100755 index 0000000..1c3ca69 --- /dev/null +++ b/script/test17.py @@ -0,0 +1,23 @@ +""" +Line Scan with 2 writables and triggering +""" + +index=0 + +x=0 +def AfterReadout(rec): + global x + print rec.getIndex() , + print " - ", + print rec.values + + + if rec.index==10 and x==0: + x=1 + time.sleep(3.0) + rec.invalidate() + + + + +a= lscan((inp), (sin,out,arr), (0,), (40,), 20, 0.1, after_read=AfterReadout) \ No newline at end of file diff --git a/script/test17.xml b/script/test17.xml new file mode 100755 index 0000000..60b4e2f --- /dev/null +++ b/script/test17.xml @@ -0,0 +1,21 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 31.0 + 0.01 + + + + + + + diff --git a/script/test18.py b/script/test18.py new file mode 100755 index 0000000..8f37b6a --- /dev/null +++ b/script/test18.py @@ -0,0 +1,30 @@ +""" +Line Scan +""" + +attrs_dataset = None +attrs_names = ["TESTIOC:TESTCALCOUT:Input", + "TESTIOC:TESTCALCOUT:Output", + "TESTIOC:TESTSINUS:SinCalc", + "TESTIOC:TESTWF2:MyWF"] +attrs_types = ["d", "d", "d", "[d"] +attrs_lenghts = [0,0,0,10] + + +def AfterReadout(rec): + global attrs_dataset, attrs_names, attrs_type, attrs_lenghts + if attrs_dataset is None: + attrs_dataset = get_exec_pars().group() + "attributes" + create_table(attrs_dataset, attrs_names, attrs_types, attrs_lenghts) + record = [] + for i in range(len(attrs_names)): + record.append(caget(attrs_names[i], attrs_types[i])) + print record + append_table(attrs_dataset, record) + +a = lscan(m1, (ai1, ai2), 0, 0.1, 20, 0.01, after_read=AfterReadout) + + + + + diff --git a/script/test18.xml b/script/test18.xml new file mode 100755 index 0000000..03a6ff5 --- /dev/null +++ b/script/test18.xml @@ -0,0 +1,22 @@ + + + + + + + 4 + + + + + 4 + + + + + + + + + diff --git a/script/test19.py b/script/test19.py new file mode 100755 index 0000000..56ab4ec --- /dev/null +++ b/script/test19.py @@ -0,0 +1,44 @@ +import ch.psi.pshell.device.ReadonlyRegisterBase as ReadonlyRegisterBase +import ch.psi.pshell.device.ReadonlyRegister.ReadonlyRegisterArray as ReadonlyRegisterArray + +class Mean(Readable): + def __init__(self, dev): + self.dev =dev + + def read(self): + return mean(self.dev.take()) + +class Variance(Readable): + def __init__(self, dev): + self.dev =dev + + def read(self): + return variance(self.dev.take()) + +class Measures(ReadonlyRegisterBase, ReadonlyRegisterArray): + def __init__(self, dev, count, interval=0): + self.dev = dev + self.count = count + self.interval = interval + self.initialize() + + def getSize(self): + return self.count + + def doRead(self): + measures = [] + for i in range(self.count): + measures.append(self.dev.read()) + if self.interval>0 and i<(self.count-1): + time.sleep(self.interval) + return measures + + +def average(dev, count, interval=0.0): + #av = Measures(dev, count, interval) + #return [av, Mean(av), Variance(av)] + av = Averager(dev, count, int(interval*1000)) + av.initialize() + return [av, av.samples, av.variance] + +res= lscan(inp, average(sin,5,0.1), 0, 40, 20, 0.1) diff --git a/script/test2.js b/script/test2.js new file mode 100755 index 0000000..e20cc9d --- /dev/null +++ b/script/test2.js @@ -0,0 +1,9 @@ +function multiply(a, b) { + a = (typeof a !== 'undefined') ? a : 3; + b = (typeof b !== 'undefined') ? b : 1; + return a * b; +} + +print (multiply(5, 2)) +print (multiply(5, 1)) +print (multiply(2)) \ No newline at end of file diff --git a/script/test2.py b/script/test2.py new file mode 100755 index 0000000..789bb1e --- /dev/null +++ b/script/test2.py @@ -0,0 +1,17 @@ +""" +Line Scan with 2 writables and triggering +""" + +index=0 + +def BeforeReadout(): + global index +# print "Frame = " + str(index) + index=index+1 + #log("trigger " + index) + caput("TESTIOC:TESTBO:MyBO","On") + caput("TESTIOC:TESTBO:MyBO","Off") + + +a= lscan((m1,inp), (sin,out,arr), (0,0), (4,40), 20, 0.1, before_read=BeforeReadout) + \ No newline at end of file diff --git a/script/test2.xml b/script/test2.xml new file mode 100755 index 0000000..04e6b94 --- /dev/null +++ b/script/test2.xml @@ -0,0 +1,34 @@ + + + + alexandre.gobbo@psi.ch + + + My second test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + 0.0 + 5.0 + 1.0 + + + + + + diff --git a/script/test20.py b/script/test20.py new file mode 100755 index 0000000..b2e4673 --- /dev/null +++ b/script/test20.py @@ -0,0 +1,29 @@ +from mathutils import deriv, interpolate, fit_polynomial, PolynomialFunction, get_values + + +start = 0 +end = 10 +step_size = 0.1 + +result= lscan(out,sin,start,end,[step_size,],0.01) +readable = result.getReadable(0) +positions = result.getPositions(0) + +pars_polynomial = (a0, a1, a2, a3, a4, a5, a6) = fit_polynomial(readable, positions, 6) +fitted_polynomial_function = PolynomialFunction(pars_polynomial) + +resolution = step_size/100 +fit_polinomial = [] +for x in frange(start,end,resolution, True): + fit_polinomial.append(fitted_polynomial_function.value(x)) +x = frange(start, end+resolution, resolution) + +d = deriv(fitted_polynomial_function,x) + +d2 = deriv(readable,positions) +f = interpolate(readable,positions) +f2 = interpolate(readable,positions, "cubic") + + +plot([get_values(f,frange(0,10,0.01)), get_values(f2,frange(0,10,0.01))], ["f", "f2"], title = "aux") +plots = plot([readable, fit_polinomial, d, d2] , ["data", "polinomial", "deriv", "d2"], xdata = [positions,x,x, positions], title="Data") diff --git a/script/test21.py b/script/test21.py new file mode 100755 index 0000000..db38674 --- /dev/null +++ b/script/test21.py @@ -0,0 +1,37 @@ +from mathutils import * + +#interpolation +y = [0, 1, 4,10,50,25,12, 5, 3, 0] +x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +types = "linear", "cubic", "akima", "loess", "neville", "newton" +functions = [interpolate(y,x,t) for t in types] + +plot_x = frange (0,9,0.01) +values = [get_values(f,plot_x) for f in functions] +plots=plot(values,types,plot_x) + +#derivative +for i in range(len(types)): + try: + d = deriv(functions[i]) + plots[i].addSeries(LinePlotSeries("Derivative")) + plots[i].getSeries(1).setData(plot_x, get_values(d,plot_x)) + except: + #not differentiable + pass + +#integration +for i in range(len(types)): + s = integrate(functions[i],x) + plots[i].addMarker(x[-1], None, "Integral=" + str(round(s,4)), java.awt.Color.DARK_GRAY) + + + + +#Direct calculation on arrays: + +print "Deriv (linear interpolation): ", deriv(y,x) +print "Deriv (cubic interpolation): ", deriv(y, x, "cubic") +print "Integral (linear interpolation): ", integrate(y, None, x, "cubic") +print "Integral (cubic interpolation): ", integrate(y, None, x, "cubic") +print "Integral (linear interpolation in range [1,5]): ", integrate(y, [1,5], x) \ No newline at end of file diff --git a/script/test22.py b/script/test22.py new file mode 100755 index 0000000..2d56b52 --- /dev/null +++ b/script/test22.py @@ -0,0 +1,34 @@ +tutorial_path = "src/main/assembly/help/Tutorial/" +run(tutorial_path+"00_Devices") + + + +import ch.psi.pshell.epics.CAS as CAS + +cas = [] + +#CAS.setServerPort(5062) + +CAS("TESTCAS:c1", ai1, 'double') +cas1 = CAS("TESTCAS:c2", ai1, 'int') +cas2 = CAS("TESTCAS:c3", ai1, 'string') +cas3 = CAS("TESTCAS:c4", ao1, 'double') +cas4 = CAS("TESTCAS:c5", dp1, 'string') +cas5 = CAS("TESTCAS:c6", wf1, 'double') +cas6 = CAS("TESTCAS:c7", wf1, 'int') +cas7 = CAS("TESTCAS:c8", wf1, 'string') + +print caget("TESTCAS:c1") +print caget("TESTCAS:c2") +print caget("TESTCAS:c3") +print caget("TESTCAS:c4") +print caget("TESTCAS:c5") +print caget("TESTCAS:c6").tolist() +print caget("TESTCAS:c7").tolist() +print caget("TESTCAS:c8","[s").tolist() + + + + + + \ No newline at end of file diff --git a/script/test23.py b/script/test23.py new file mode 100755 index 0000000..230c03d --- /dev/null +++ b/script/test23.py @@ -0,0 +1,32 @@ + +type = '[s' +name = 'TESTCAS:c4' + + +import java.beans.PropertyChangeListener as PropertyChangeListener +#import java.beans.PropertyChangeEvent as PropertyChangeEvent + +scalar = not type.startswith('[') +#val = lambda x: x if scalar else x.tolist() +val = lambda x: x +class MonitorListener(PropertyChangeListener): + def propertyChange(self, pce): + print val(pce.getNewValue()) + + + + +channel = create_channel(name, type = type) + +print val(channel.getValue()) +channel.setMonitored(True) +changeListener = MonitorListener() +channel.addPropertyChangeListener(changeListener) + +try: + time.sleep(sys.maxint) +finally: + channel.removePropertyChangeListener(changeListener) + Epics.closeChannel(channel) + print "ok" + \ No newline at end of file diff --git a/script/test24.py b/script/test24.py new file mode 100755 index 0000000..6cde89b --- /dev/null +++ b/script/test24.py @@ -0,0 +1,16 @@ + +plots = None +def plot_hist(data): + global plots + (h,x) = histogram(data) #(h,x) = histogram(data, 0, 255) is more efficient: no neet to calculate min & max + if plots is None: + plots = plot(h, xdata = x, title = "Histo") + else: + plots[0].getSeries(0).setData(x,h) + +while(True): + data = img.getData().getRectSelection(0,0,500,250) + plot_hist(data) + if plots[0].displayable == False: + break + time.sleep(0.250) diff --git a/script/test25.py b/script/test25.py new file mode 100755 index 0000000..6555b7a --- /dev/null +++ b/script/test25.py @@ -0,0 +1,6 @@ +x = [10,20,30,40,50,60] +p = plot(None,name="Data 1")[0] +p.addSeries(LinePlotSeries("Data2")) +p.getSeries(0).setData(x, [1,2,3,4,5,6]) +p.getSeries(1).setData(x, [6,5,4,3,2,1]) +p.addMarker(35.0, None, "This is the answer", None) \ No newline at end of file diff --git a/script/test26.py b/script/test26.py new file mode 100755 index 0000000..9250c5a --- /dev/null +++ b/script/test26.py @@ -0,0 +1,14 @@ +################################################################################################### +# Multipass and zigzag scans +################################################################################################### + + +#Linear with 2 passes +a= lscan(m1, (ai1,wf1), -0.2, 0.2, 20, relative = True, passes = 4) + +#Linear with 4 passes and zigzag +a= lscan(m1, (ai1,wf1), -0.2, 0.2, 20, relative = True, passes = 4, zigzag = True) + + +#Multi-dimentional zigzag +x = ascan ([m1,m2], ai1, [0,0], [1, 1], [0.25,0.25], latency=0.01, zigzag=True) diff --git a/script/test27.py b/script/test27.py new file mode 100755 index 0000000..717c954 --- /dev/null +++ b/script/test27.py @@ -0,0 +1,48 @@ +import ch.psi.pshell.device.ArrayCalibration as ArrayCalibration +import ch.psi.pshell.device.MatrixCalibration as MatrixCalibration + +class Scalar(Readable): + def read(self): + return 1.0 + +class Array(ReadableArray): + def read(self): + return range(self.getSize()) + + def getSize(self): + return 10 + +class Matrix(ReadableMatrix): + def read(self): + return [range(self.getWidth()),] * self.getHeight() + + def getWidth(self): + return 20 + + def getHeight(self): + return 5 + +class ArrayCalibrated(Array, Readable.ReadableCalibratedArray): + def getCalibration(self): + return ArrayCalibration(5,1000) + +class ArrayCalibrated1d(Array, Readable.ReadableCalibratedArray): + def getCalibration(self): + return ArrayCalibration(5,1000) + +class MatrixCalibrated(Matrix, Readable.ReadableCalibratedMatrix): + def getCalibration(self): + return MatrixCalibration(2,4,100,200) + +scalar = Scalar() +array = Array() +matrix = Matrix() +arrayCalibrated = ArrayCalibrated() +arrayCalibrated1d = ArrayCalibrated1d() +matrixCalibrated = MatrixCalibrated() + + +set_preference(Preference.PLOT_TYPES, {arrayCalibrated1d:1}) + + +a= lscan(out, [scalar, array, arrayCalibrated, arrayCalibrated1d, matrix, matrixCalibrated], 0, 40, 200) \ No newline at end of file diff --git a/script/test28.py b/script/test28.py new file mode 100755 index 0000000..b952c78 --- /dev/null +++ b/script/test28.py @@ -0,0 +1,48 @@ +import ch.psi.pshell.epics.CAS as CAS + + + +class ScanDevice(ReadonlyAsyncRegisterBase, ReadonlyRegisterArray): + def getSize(self): + global scan_result + return len(self.take()) + + def append(self, value): + c = self.take() + c.append(value) + self.set(c) + + def set(self, value): + self.onReadout(to_array(value, 'd')) + + + +if get_device("scan_pos") is None: + add_device(ScanDevice("scan_pos"), True) + add_device(ScanDevice("scan_val"), True) + scan_pos.set([]) + scan_val.set([]) + + cas1 = CAS("PSHELL:scanpos",scan_pos, "double") + cas2 = CAS("PSHELL:scanval",scan_val, "double") + cas3 = CAS("PSHELL:var",ai1) + + scan_pos.set([]) + scan_val.set([]) + + + +scan_pos.set([]) +scan_val.set([]) + +def after(rec): + scan_pos.append(rec.positions[0]) + scan_val.append(rec.values[0]) + +res = lscan(ao1, ai1, 0, 40, 40, 0.1, after_read = after) +#scan_pos.set(res.getPositions(0)) +#scan_val.set(res.getReadable(0)) + +set_return(res.print()) + + diff --git a/script/test29.py b/script/test29.py new file mode 100755 index 0000000..8045532 --- /dev/null +++ b/script/test29.py @@ -0,0 +1,16 @@ +[py, px, pxy]=plot([None,None,None],["y","x", "xy"]) + + + + +#XY error plot +pxy.setStyle(pxy.Style.ErrorXY) +pxy.setLegendVisible(True) +sxy = LinePlotErrorSeries("F4") +pxy.addSeries(sxy) +#sxy.appendData(1.0,0.5,1.5, 10.0, 9.0, 11.0) +#sxy.appendData(10.0,9.0, 11.0, 6.1, 4.34, 7.54) +#sxy.appendData(17.8, 17.0, 18.0, 4.5, 3.1, 5.8) + + +sxy.setData([1,2,3,4,5],[4,6,3,2,1]) diff --git a/script/test3.js b/script/test3.js new file mode 100755 index 0000000..70592d6 --- /dev/null +++ b/script/test3.js @@ -0,0 +1,5 @@ + +run("jeputils") +//Running a modole +run_jep("cpython") + diff --git a/script/test3.py b/script/test3.py new file mode 100755 index 0000000..bdd192a --- /dev/null +++ b/script/test3.py @@ -0,0 +1,21 @@ +""" +Processing and plotting scan data +""" + +inp.write(0.0) +scan1= lscan(inp, (sin,out,arr), 0, 40, 20, 0.1, False, "Scan 1") +scan2= lscan(inp, (sin,out,arr), 0, 40, 20, 0.1, False, "Scan 2") + + +from operator import add +result = map(add, scan1.getReadable(0), scan2.getReadable(0)) + +#Alternative: +#result=[] +#for i in range(len(scan1.records)): +# result.append(scan1.records[i].values[0]+scan2.records[i].values[0]) + + +plot(result) +print result + diff --git a/script/test3.xml b/script/test3.xml new file mode 100755 index 0000000..962e239 --- /dev/null +++ b/script/test3.xml @@ -0,0 +1,35 @@ + + + + alexandre.gobbo@psi.ch + + + My third test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + + + + + diff --git a/script/test30.py b/script/test30.py new file mode 100755 index 0000000..0a99b6f --- /dev/null +++ b/script/test30.py @@ -0,0 +1,98 @@ +################################################################################################### +# Example of least squares optimization +# http://commons.apache.org/proper/commons-math/userguide/leastsquares.html +################################################################################################### + + +from mathutils import * +from plotutils import * + +[p1,p2] = plot([None, None], [None, None]) + +################################################################################################### +#Fitting the quadratic function f(x) = a x2 + b x + c +################################################################################################### +x = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] +y = [36.0, 66.0, 121.0, 183.0, 263.0, 365.0, 473.0, 603.0, 753.0, 917.0] +num_samples = len(x) +weigths = [ 1.0] * num_samples + +p1.getSeries(0).setData(x, y) +p1.getSeries(0) + +class Model(MultivariateJacobianFunction): + def value(self, variables): + value = ArrayRealVector(num_samples) + jacobian = Array2DRowRealMatrix(num_samples, 3) + for i in range(num_samples): + (a,b,c) = (variables.getEntry(0), variables.getEntry(1), variables.getEntry(2)) + model = a*x[i]*x[i] + b*x[i] + c + value.setEntry(i, model) + jacobian.setEntry(i, 0, x[i]*x[i]) # derivative with respect to p0 = a + jacobian.setEntry(i, 1, x[i]) # derivative with respect to p1 = b + jacobian.setEntry(i, 2, 1.0) # derivative with respect to p2 = c + return Pair(value, jacobian) + +model = Model() +initial = [1.0, 1.0, 1.0] #parameters = a, b, c +target = [v for v in y] #the target is to have all points at the positios + +(parameters, residuals, rms, evals, iters) = optimize_least_squares(model, target, initial, weigths) + +(a,b,c) = parameters + +print "A: ", a , " B: ", b, " C: ", c +print "RMS: " , rms, " evals: " , evals, " iters: " , iters +for i in range (num_samples): + print x[i], y[i], poly(x[i], [c,b,a]) + +plot_function(p1, PolynomialFunction((c,b,a)), "Fit", x) +print "----------------------------------------------------------------------------\n" + + +################################################################################################### +#Fiting center of circle of known radius to observerd points +################################################################################################### + + +#Fiting center of circle of radius 70 to observerd points +radius = 70.0 +x = [30.0, 50.0, 110.0, 35.0, 45.0] +y = [68.0, -6.0, -20.0, 15.0, 97.0] +num_samples = len(x) +weigths = [ 1.0] * num_samples +weigths = [0.1, 0.1, 1.0, 0.1, 1.0] + +p2.getSeries(0).setData(x, y) +p2.getSeries(0).setLinesVisible(False) +p2.getSeries(0).setPointSize(4) + +# the model function components are the distances to current estimated center, +# they should be as close as possible to the specified radius +class Model(MultivariateJacobianFunction): + def value(self, variables): + (cx,cy) = (variables.getEntry(0), variables.getEntry(1)) + value = ArrayRealVector(num_samples) + jacobian = Array2DRowRealMatrix(num_samples, 2) + for i in range(num_samples): + model = math.hypot(cx-x[i], cy-y[i]) + value.setEntry(i, model) + jacobian.setEntry(i, 0, (cx - x[i]) / model) # derivative with respect to p0 = x center + jacobian.setEntry(i, 1, (cy - y[i]) / model) # derivative with respect to p1 = y center + return Pair(value, jacobian) + +model = Model() #modeled radius should be close to target radius +initial = [mean(x), mean(y)] #parameters = cx, cy +target = [radius,] * num_samples #the target is to have all points at the specified radius from the center + +(parameters, residuals, rms, evals, iters) = optimize_least_squares(model, target, initial, weigths) + +(cx, cy) = parameters + +print "CX: ", cx , " CY: ", cy +print "RMS: " , rms, " evals: " , evals, " iters: " , iters + + +from plotutils import * +plot_point(p2, cx, cy, name="Fit Cente") +plot_circle(p2, cx, cy, radius, name="Fit") diff --git a/script/test31.py b/script/test31.py new file mode 100755 index 0000000..0567e99 --- /dev/null +++ b/script/test31.py @@ -0,0 +1,13 @@ +tutorial_path = "src/main/assembly/help/Tutorial/" +run(tutorial_path+"00_devices") + + + +def after(rec): + if rec.index==1: + (p1,p2) = get_plots("Jitter Scan") + p1.setScale(0.0, 2.0) + p2.setScale(0.0, 1.0) + +ascan((m1,m2), (ai1,ai2), (0.0,0.0), (0.5,0.5), (5,5), after_read=after, title = "Jitter Scan") + diff --git a/script/test32.py b/script/test32.py new file mode 100755 index 0000000..a16b6e8 --- /dev/null +++ b/script/test32.py @@ -0,0 +1,29 @@ +from mathutils import * +from plotutils import * + + +x = [ 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0,18.0] +y = [ 30.0, 22.0, 12.0, 10.0, 11.0, 14.0, 21.0, 32.0] +v = [ 0.3, 0.8, 0.4, 0.3, 0.5, 0.4, 0.3, 0.2] + +w = [ 1/ max(i,0.1) for i in v] + + + +p=plot(None)[0] +p.setStyle(p.Style.ErrorY) +p.setLegendVisible(True) +s1 = LinePlotErrorSeries("Observed Data") +p.addSeries(s1) +for i in range(len(x)):\ + s1.appendData(x[i], y[i], v[i]) + + +pars_polynomial= fit_polynomial(y, x, 2, None, w) +function = PolynomialFunction(pars_polynomial) +plot_function(p, function, "Fit" , frange (min(x), max(x), 0.1), False) + +print "(a0,a1,a2) = " , pars_polynomial + +for xp in x: + print xp, poly(xp, pars_polynomial) diff --git a/script/test33.py b/script/test33.py new file mode 100755 index 0000000..c2423fa --- /dev/null +++ b/script/test33.py @@ -0,0 +1,50 @@ +start = time.time() + +#setup_plotting( enable_table=False) +#set_exec_pars(accumulate = False, persist = False) +#set_preference(Preference.PLOT_TYPES, {det.getDataMatrix():"ch.psi.pshell.plot.MatrixPlotRenderer"}) +#tscan(det.getDataMatrix(), 1000,0.00) + + + +#for i in range(100000): +# det.getDataMatrix().read() + +arr = [1.0] * 1000 +arr = [arr,] * 1000 + +p = plot(arr)[0] +print time.time() - start, +print " ", +start = time.time() + + +#for i in range(100): +# p.getSeries(0).setData(arr) +#0.103999853134 10.1759998798 CPU=52 +#0.118000030518 9.76999998093 CPU=42 + +#p.setScale(0,500000) +#for i in range(500000): +# x = i % 1000 +# y = i % 1000 + i/1000 +# p.getSeries(0).appendData(x,y,i) +#p.update(True); +#0.115999937057 1.13800001144 CPU=52 +#0.101000070572 1.10399985313 CPU=22 +#Fixed range + +#0.0950000286102 1.1289999485 CPU = 50 +#0.0909998416901 1.09500002861 + + +#p.setScale(0,500000) +for i in range(1000): + for j in range(1000): + p.getSeries(0).appendData(i,j,i*1000+j) + p.update(True); + +#0.0999999046326 1.61400008202 CPU = 60 +#0.101000070572 1.72300004959 +print time.time() - start + diff --git a/script/test34.py b/script/test34.py new file mode 100755 index 0000000..a6012b9 --- /dev/null +++ b/script/test34.py @@ -0,0 +1,35 @@ + +class FitnessFunction(ReadonlyRegisterBase): + def doRead(self): + return 1000.0 - (math.pow(inp.take()-18, 2) + math.pow(out.take()-6, 2) + test.take()) + +add_device(FitnessFunction("fitness"), True) + +inp.read();out.read();test.read() + + +#Fitness Function +r = ascan([inp, out], fitness, [0.0,0.0], [21.0,26.0], [1.1,1.1], title = "Fitness") + + +#Binary Search +strategy = "Normal" # or "Boundary" or "FullNeighborhood" +r = bsearch([inp, out], fitness, [0.0,0.0], [21.0,26.0], [0.1, 0.1], maximum=True, strategy = strategy, latency = 0.01, title = "Binary Search") +#Relative search: +#inp.write(10.5);out.write(13.0) +#r = bsearch([inp, out], fitness, [-10.5,-13.0], [10.5,13.0], [0.1, 0.1],relative = True, maximum=True, strategy = "Normal", title = "Binary Search") + +print "--------------- Binary Search -----------------" +print r +print r.print() +print len(r.getRecords()) + + + +inp.write(10.5) +out.write(13.0) +r = hsearch([inp, out], fitness,[0.0,0.0], [21.0,26.0], [1.0, 1.0], [0.1, 0.1], 1, relative = False, maximum=True, latency = 0.01, title = "Hill Climbing") +print "--------------- Hill Climbing Search -----------------" +print r +print r.print() +print len(r.getRecords()) \ No newline at end of file diff --git a/script/test35.py b/script/test35.py new file mode 100755 index 0000000..0313cce --- /dev/null +++ b/script/test35.py @@ -0,0 +1,14 @@ +tutorial_path = "src/main/assembly/help/Tutorial/" +run(tutorial_path+"00_devices") + +class FitnessFunction(ReadonlyRegisterBase): + def doRead(self): + return 1000.0 - (math.pow(ao1.take()-18, 2) + math.pow(ao2.take()-6, 2)) + +add_device(FitnessFunction("fitness"), True) + +#a= lscan(ao1, (wf1), 5, 0, 0.1) +#a= lscan(ao1, (wf1), 0, 5, 0.1) +r = ascan([ao1, ao2], fitness, [0.0,0.0], [21.0,21.0], [1.1, 1.1], title = "Fitness") +s= 1.1 +r = ascan([ao1, ao2], fitness, [0.0,0.0], [4.0,4.0], [s, s], title = "Fitness") diff --git a/script/test36.py b/script/test36.py new file mode 100755 index 0000000..574357c --- /dev/null +++ b/script/test36.py @@ -0,0 +1,86 @@ +################################################################################################### +# Calibrating array and matrix pseudo-devices +################################################################################################### + + + +class Waveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + + def getSize(self): + return len(self.take(-1)) #only reads if cache is None + +class Image(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + + def getWidth(self): + return len(self.take(-1)[0]) + + def getHeight(self): + return len(self.take(-1)) + + + +class SinusoidWaveform(Waveform): + def calc(self): + ret = [] + x = random.random() + for i in range (20): + ret.append(math.sin(x)) + x = x + 0.1 + return ret + +class SinusoidImage(Image): + def calc(self): + (width, height) = (200, 100) + ret = [] + x = random.random(); + base = [] + for i in range (width): + base.append( math.sin(x)) + x = x + 0.05 + for i in range (height): + noise = (random.random() - 0.5)/5.0 + ret.append([x+noise for x in base]) + return ret + +add_device(SinusoidWaveform("wf1"), True) +add_device(SinusoidImage("im1"), True) + + +class ArrayCalibrated(ReadonlyRegisterBase, ReadonlyRegisterArray, ReadableCalibratedArray): + def doRead(self): + return wf1.read() + + def getSize(self): + return wf1.size + + def getCalibration(self): + return ArrayCalibration(5,1000) + + +class MatrixCalibrated(ReadonlyRegisterBase, ReadonlyRegisterMatrix, ReadableCalibratedMatrix): + def doRead(self): + return im1.read() + + def getWidth(self): + return im1.width + + def getHeight(self): + return im1.height + + def getCalibration(self): + return MatrixCalibration(2,4,100,200) + +add_device(ArrayCalibrated() , True) +add_device( MatrixCalibrated() , True) +ArrayCalibrated.polling=100 +MatrixCalibrated.polling=250 + + \ No newline at end of file diff --git a/script/test37.py b/script/test37.py new file mode 100755 index 0000000..ce01b45 --- /dev/null +++ b/script/test37.py @@ -0,0 +1,21 @@ +tutorial_path = "src/main/assembly/help/Tutorial/" +run(tutorial_path+"00_devices") + + + +class ArrayCalibrated(ReadableArray, ReadableCalibratedArray): + def read(self): + return wf1.read() + + def getSize(self): + return wf1.size + + def getCalibration(self): + return ArrayCalibration(5,1000) + +ac1 = ArrayCalibrated() + +#The data window never displays 3d data, but the 3d data can be accesses during the scan in the Data tab. +ascan((m1,m2), (ac1, wf1), (0.0,0.0), (2.0,1.0), (19,19)) + + diff --git a/script/test38.py b/script/test38.py new file mode 100755 index 0000000..e96a428 --- /dev/null +++ b/script/test38.py @@ -0,0 +1,23 @@ +from ijutils import * +import java.awt.Color as Color + + +ip2 = load_image("images/img2.png", title="Image2") + +ip3 = new_image(256, 256, "color", fill_color = Color.WHITE) +ip4 = new_image(256, 256, "color", fill_color =Color.WHITE) + +copy_image_to(ip2, ip3, 25, 25) +copy_image_to(sub_image(ip2, 11, 33, 24,24), ip4, 123, 123) + + +#Correlate, convolve, deconvolve +grayscale(ip3) +grayscale(ip4) + +cor = op_fft(ip3, ip4, "correlate", True) +con = op_fft(ip3, ip4, "convolve", True) +dec = op_fft(con, ip4, "deconvolve", True) + +create_stack([ip3,ip4, grayscale(cor,False),grayscale(con,False),grayscale(dec,False)], title = "Correlation").show() + diff --git a/script/test39.py b/script/test39.py new file mode 100755 index 0000000..b781a99 --- /dev/null +++ b/script/test39.py @@ -0,0 +1,167 @@ +x = to_array([0,1,2,3,4,5,6,7,8,9,10],'i') +y = to_array([1,2,3,4,5,10, 50, 11, 4,3,1],'i') + + + + +def to_array(obj, type = 'o'): + """Convert Python list to Java array. + + Args: + obj(list): Original data. + type(str): array type 'b' = byte, 'h' = short, 'i' = int, 'l' = long, 'f' = float, 'd' = double, + 'c' = char, 'z' = boolean, 's' = String, 'o' = Object + Returns: + Java array. + + """ + if type[0] == '[': + type = type[1:] + arrayType = class_types.get("["+type) + + if obj is None: + return None + if isinstance(obj,java.util.List): + obj = obj.toArray(java.lang.reflect.Array.newInstance(Class.forName(class_types.get(type)),0)) + if type != 'o': + obj = Convert.toPrimitiveArray(obj) + if isinstance(obj,PyArray): + if obj.typecode != type: + print "DIF", obj.typecode, type + ret = java.lang.reflect.Array.newInstance(Class.forName(class_types.get(type)),len(obj)) + if type == 's': + for i in range(len(obj)): ret[i] = str(obj[i]) + elif type == 'c': + for i in range(len(obj)): ret[i] = chr(obj[i]) + else: + for i in range(len(obj)): ret[i] = obj[i] + obj = ret + if type not in ['o', 's']: + obj = Convert.toPrimitiveArray(obj) + return obj + if is_list(obj): + if type=='o' or type== 's': + ret = java.lang.reflect.Array.newInstance(Class.forName(class_types.get(type)),len(obj)) + for i in range (len(obj)): + if is_list(obj): + ret[i] = to_array(obj[i],type) + elif type == 's': + ret[i] = str(obj[i]) + else: + ret[i] = obj[i] + return ret + + if len(obj)>0 and is_list(obj[0]): + if len(obj[0])>0 and is_list(obj[0][0]): + ret = java.lang.reflect.Array.newInstance(Class.forName(arrayType),len(obj),len(obj[0])) + for i in range(len(obj)): + ret[i]=to_array(obj[i], type) + return ret + else: + ret = java.lang.reflect.Array.newInstance(Class.forName(arrayType),len(obj)) + for i in range(len(obj)): + ret[i]=to_array(obj[i], type) + return ret + return jarray.array(obj,type) + return obj + + +def plot(data, name = None, xdata = None, ydata=None, title=None): + """Request one or multiple plots of user data (1d, 2d or 3d) + + Args: + data: array or list of values. For multiple plots, array of arrays or lists of values. + name(str or list of str, optional): plot name or list of names (if multiple plots). + xdata: array or list of values. For multiple plots, array of arrays or lists of values. + ydata: array or list of values. For multiple plots, array of arrays or lists of values. + title(str, optional): plotting context name. + + Returns: + ArrayList of Plot objects. + + """ + if isinstance(data, ch.psi.pshell.data.Table): + if is_list(xdata): + xdata = to_array(xdata, 'd') + return get_context().plot(data,xdata,name,title) + if isinstance(data, ch.psi.pshell.scan.ScanResult): + return get_context().plot(data,title) + + + if (name is not None) and is_list(name): + if len(name)==0: + name=None; + else: + if (data==None): + data = [] + for n in name: + data.append([]) + plots = java.lang.reflect.Array.newInstance(Class.forName("ch.psi.pshell.data.PlotDescriptor"), len(data)) + for i in range (len(data)): + plotName = None if (name is None) else name[i] + x = xdata + if is_list(x) and len(x)>0 and (is_list(x[i]) or isinstance(x[i] , java.util.List) or isinstance(x[i],PyArray)): + x = x[i] + y = ydata + if is_list(y) and len(y)>0 and (is_list(y[i]) or isinstance(y[i] , java.util.List) or isinstance(y[i],PyArray)): + y = y[i] + plots[i] = PlotDescriptor(plotName , to_array(data[i], 'd'), to_array(x, 'd'), to_array(y, 'd')) + return get_context().plot(plots,title) + else: + plot = PlotDescriptor(name, to_array(data, 'd'), to_array(xdata, 'd'), to_array(ydata, 'd')) + return get_context().plot(plot,title) + + + + +from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list, Gaussian,fit_harmonic,HarmonicOscillator +import java.awt.Color as Color + +def fit(ydata, xdata = None): + if xdata is None: + xdata = frange(0, len(ydata), 1) + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + print "Max index:" + str(index_max), + print " x:" + str(max_x), + print " y:" + str(max_y) + + gaussians = fit_gaussians(ydata, xdata, [index_max,]) + + print "PLOT" + + ydata =to_array(ydata,'d') + xdata= to_array(xdata,'d') + + p = plot([ydata],["data"],[xdata], title="Fit" )[0] + print "OK" + + if gaussians[0] is None: #Fitting error + p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY) + print "Fitting error - using max value" + return (None, max_x, None) + + (norm, mean, sigma) = gaussians[0] + + fitted_gaussian_function = Gaussian(norm, mean, sigma) + scale_x = [float(min(xdata)), float(max(xdata)) ] + points = max((len(xdata)+1), 100) + resolution = (scale_x[1]-scale_x[0]) / points + fit_y = [] + fit_x = frange(scale_x[0],scale_x[1],resolution, True) + for x in fit_x: + fit_y.append(fitted_gaussian_function.value(x)) + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + if abs(mean - xdata[index_max]) < ((scale_x[0] + scale_x[1])/2): + print "Mean -> " + str(mean) + p.addMarker(mean, None, "Mean="+str(round(norm,2)), Color.MAGENTA.darker()) + return (norm, mean, sigma) + else: + p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY) + print "Invalid gaussian fit: " + str(mean) + " - using max value" + return (None, max_x, None) + +fit(y,x) \ No newline at end of file diff --git a/script/test4.py b/script/test4.py new file mode 100755 index 0000000..efe0d99 --- /dev/null +++ b/script/test4.py @@ -0,0 +1,11 @@ +""" +Vector Scan +""" + +vector = [ [1,1] , [1,2] , [1,3] , [1,4] , + [1.5,2.5] , + [2,1] , [2,2] , [2,3] , [2,4] , + [2.5,2.5] , + [3,1] , [3,2] , [3,3] , [3,4] ] + +a= vscan((dev,inp),(sin,out),vector,False, 0.1) diff --git a/script/test4.xml b/script/test4.xml new file mode 100755 index 0000000..e1303fc --- /dev/null +++ b/script/test4.xml @@ -0,0 +1,21 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 100.0 + 0.01 + + + + + + + diff --git a/script/test40.py b/script/test40.py new file mode 100755 index 0000000..26594d7 --- /dev/null +++ b/script/test40.py @@ -0,0 +1,14 @@ +d=[ [0.010115384124219418, 0.008994088508188725, 0.010135136544704437]\ + [0.008685849606990814, 0.008604667149484158, 0.00958736427128315],\ + [0.010523559525609016, 0.008842745795845985, 0.008996413089334965],\ + [0.008908904157578945, 0.008445623330771923, 0.00871073268353939], \ + [0.008137226104736328, 0.00887210387736559, 0.00992573145776987], \ + [0.009319707751274109, 0.008513474836945534, 0.008966488763689995],\ + [0.00849974900484085, 0.00978073664009571, 0.008474956266582012]] + + +#0.008880565874278545, 0.010073209181427956, 0.009464358910918236, 0.010007734410464764, 0.00896169152110815, 0.00939770694822073, 0.009098240174353123, 0.009016894735395908, 0.008204123005270958, 0.009538586251437664, 0.008587008342146873, 0.0090327812358737, 0.01018200907856226, 0.008627708069980145, 0.008711149916052818, 0.009136876091361046, 0.008454966358840466, 0.009547500871121883, 0.009467598050832748, 0.00944132823497057, 0.008682359009981155, 0.008898311294615269, 0.009043870493769646, 0.00917191430926323, 0.009349015541374683, 0.008379173465073109, 0.009255114942789078, 0.009638028219342232, 0.00803715642541647, 0.008327572606503963, 0.007925431244075298, 0.00836490560323, 0.0070711043663322926, 0.00892611127346754, 0.010059300810098648, 0.008099151775240898, 0.009483003988862038, 0.008056368678808212, 0.008146187290549278, 0.010088167153298855, 0.0087339011952281, 0.009172079153358936, 0.009541817009449005, 0.009471668861806393, 0.008852284401655197, 0.00895639881491661, 0.009029458276927471, 0.008999759331345558, 0.00917622447013855, 0.008334473706781864, 0.008492929860949516, 0.008791427128016949, 0.007880245335400105, 0.008959128521382809, 0.008498640730977058, 0.009287312626838684, 0.00871323887258768, 0.00967397727072239, 0.00906734075397253, 0.008927318267524242, 0.009405833669006824, 0.008497903123497963, 0.008872325532138348, 0.007997157983481884, 0.008270026184618473, 0.009704588912427425, 0.007636429276317358, 0.009596660733222961, 0.008883758448064327, 0.009258335456252098, 0.00722940219566226, 0.00922910962253809, 0.009039347060024738, 0.008623686619102955, 0.007883899845182896, 0.008536171168088913, 0.009343329817056656, 0.008692772127687931, 0.009148652665317059, 0.009541308507323265, 0.008102779276669025, 0.007187945302575827, 0.009440058842301369, 0.009035518392920494, 0.00855229515582323, 0.007711557671427727, 0.008781946264207363] + + + +plot(d) \ No newline at end of file diff --git a/script/test41.py b/script/test41.py new file mode 100755 index 0000000..d1cc968 --- /dev/null +++ b/script/test41.py @@ -0,0 +1,18 @@ + +p = plot([1,2,3,4,5], title="x")[0] + +text = p.addText(1.5, 3.6, "Test") + +#Changing color +text.paint = Color.GREEN + +#Changing font +import java.awt.Font as Font +text.font = Font("Verdana", Font.PLAIN, 12) + +#Rotation +import math +text.rotationAngle = math.radians(90.0) + +#Removing +p.removeText(text) \ No newline at end of file diff --git a/script/test42.py b/script/test42.py new file mode 100755 index 0000000..1038feb --- /dev/null +++ b/script/test42.py @@ -0,0 +1,17 @@ +av = create_averager(sin, 2, 0.1) +add_device(av,True) +av.setMonitored(True) +#set_preference(Preference.PLOT_TYPES, {av.name:'minmax'}) +#res= tscan((sin, av, av.samples), 10, 0.1) + +#while True: +# print sin.read() +# time.sleep(0.1) + + +#p = plot([1,2,3,5])[0] +#y1=p.getAxis(p.AxisId.Y) + +#y1.setRange(-10, 10) + +#set_return (4) \ No newline at end of file diff --git a/script/test43.py b/script/test43.py new file mode 100755 index 0000000..5f75f5c --- /dev/null +++ b/script/test43.py @@ -0,0 +1,22 @@ + +ranges = [ [0,10], [20,30], [50,70]] + +for range in ranges: + run_fda("test1.xml", {"id278043.start":range[0], "id278043.end":range[1]}) + + + + +#ProcessorFDA().execute("test1.xml", {"var1":2.0, "id278043.end":10.0}) + + +""" +p = ProcessorFDA() +p.configuration.appendSuffix = False +set_exec_pars(name = "test1_0001") +p.execute("test1.xml", None); + +set_exec_pars(name = "test1_0002") +p.execute("test1.xml", None); + +""" diff --git a/script/test44.py b/script/test44.py new file mode 100755 index 0000000..eac6d46 --- /dev/null +++ b/script/test44.py @@ -0,0 +1,5 @@ +print "a=", a +print "b=", b +print "c=", c +print "d=", d +print "e=", e \ No newline at end of file diff --git a/script/test45.py b/script/test45.py new file mode 100755 index 0000000..b37a26b --- /dev/null +++ b/script/test45.py @@ -0,0 +1,27 @@ + + +import org.jfree.chart.axis.NumberAxis as NumberAxis + + + +p = plot([1,2,3,4,5])[0] +jf = p.chart.plot + +xAxis2 = NumberAxis("Secondary X Axis") +xAxis2.setRange(50, 75) +jf.setDomainAxis(1, xAxis2 ) +jf.getDomainAxis(0).setRange(0, 5) +#This is just for formatting the new axis fonts and colors, equals to the first axis +jf.getDomainAxis(1).labelPaint = jf.getDomainAxis(0).labelPaint +jf.getDomainAxis(1).labelFont = jf.getDomainAxis(0).labelFont +jf.getDomainAxis(1).tickLabelPaint = jf.getDomainAxis(0).tickLabelPaint +jf.getDomainAxis(1).tickLabelFont = jf.getDomainAxis(0).tickLabelFont + + + +#import org.jfree.chart.axis.LogarithmicAxis as LogarithmicAxis +#xAxis3 = LogarithmicAxis("Thurd X Axis") +#xAxis3.setRange(20,2000) +#jf.setDomainAxis(2, xAxis3 ) + + diff --git a/script/test46.py b/script/test46.py new file mode 100755 index 0000000..49025a9 --- /dev/null +++ b/script/test46.py @@ -0,0 +1,18 @@ + +p = plot([10,500,1000,5000,1000], xdata = [0.1,1,10,100,1000, 10000], title = "Logarithmic")[0] + +#import org.jfree.chart.axis.NumberAxis as NumberAxis +#import org.jfree.chart.axis.LogarithmicAxis as LogarithmicAxis +#jf = p.chart.plot +#logAxis = LogarithmicAxis("") +#logAxis.setRange(0.01,100) +#jf.setDomainAxis(0, logAxis ) + + +#p.getAxis(p.AxisId.X).setRange(0.01, 100000) +p.getAxis(p.AxisId.X).logarithmic = True +p.getAxis(p.AxisId.Y).setRange(1, 100000) +p.getAxis(p.AxisId.Y).logarithmic = True + + + diff --git a/script/test47.py b/script/test47.py new file mode 100755 index 0000000..989bbf9 --- /dev/null +++ b/script/test47.py @@ -0,0 +1,11 @@ +################################################################################################### +# Executing CPython in external process. +################################################################################################### + +#Calling a method: return values must be JSON serializable +ret = exec_cpython("cpython", [], "test_pandas") +print ret + +#Executing a module +ret = exec_cpython("cpython", []) +print ret diff --git a/script/test48.py b/script/test48.py new file mode 100755 index 0000000..fd106e4 --- /dev/null +++ b/script/test48.py @@ -0,0 +1,29 @@ +################################################################################################### +#Data Manipulation: Boolean datasets +################################################################################################### + +#Boolean datasets +path="group/data1" +data1d = [True, False, True] +save_dataset(path, data1d, '[z') + +path="group/data2" +create_dataset(path, 'z') +append_dataset(path, True) +append_dataset(path, False) +append_dataset(path, True) +append_dataset(path, False) +append_dataset(path, True) + + + +path="group/data3" +data2d = to_array ( [[True, False, True], [True, True, True], [False, False, True]], '[z') +save_dataset(path, data2d) + + + +path="group/data4" +create_dataset(path, 'z', dimensions = [2, 3]) +append_dataset(path, to_array([True, False, True], '[z'), type='[z') +append_dataset(path, to_array([True, True, True], '[z'), type='[z') diff --git a/script/test49.py b/script/test49.py new file mode 100755 index 0000000..88e4f5c --- /dev/null +++ b/script/test49.py @@ -0,0 +1,11 @@ +set_exec_pars(preserve = True) + +c = Channel("TESTIOC:TESTSINUS:SinCalc", 'i', alias = "C") +s= Channel("TESTIOC:TESTSINUS:SinCalc", 's', alias = "S") +#a = Channel("TESTIOC:TESTWF2:MyWF", '[i', size = 10,alias = "A") +o = Channel("TESTIOC:TESTCALCOUT:Output", 'd', alias = "O") + + +lscan (o, [c, arr, matrix], 0, 1, 10) +#lscan (o, [c, matrix], 0, 1, 10) +#tscan ([c,s], 10, 0.1) \ No newline at end of file diff --git a/script/test5.py b/script/test5.py new file mode 100755 index 0000000..58cf565 --- /dev/null +++ b/script/test5.py @@ -0,0 +1,20 @@ +""" +Area Scan +""" + +#steps_x = args[0] +#steps_y = args[1] + +ret = ascan((dev,out), (sin, arr), (0,10), (20,30), (steps_x,steps_x), 0.02) + +#p = get_exec_pars() +#set_return(ret) +#set_return(ret.getData(0)) +#set_return([p.getPath()+"|"+get_exec_pars().group+"sin"]) +#set_return(p.getPath()+"|"+get_exec_pars().group+"sin") + + +#set_return([ret.path + "sin", ret.path + "arr"]) +av = mean(ret.getReadable(0)) +set_return([av, ret.path + sin.name]) + diff --git a/script/test5.xml b/script/test5.xml new file mode 100755 index 0000000..81a3091 --- /dev/null +++ b/script/test5.xml @@ -0,0 +1,22 @@ + + + + + + + + 0.0 + 10.0 + 1.0 + + + 40.0 + 50.0 + 1.0 + + + + + + + diff --git a/script/test50.py b/script/test50.py new file mode 100755 index 0000000..4963d7b --- /dev/null +++ b/script/test50.py @@ -0,0 +1,21 @@ +class Waveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + time.sleep(0.001) + #self.val = to_array(self.calc(), 'd') + return self.calc() + + def getSize(self): + return len(self.take(-1)) #only reads if cache is None + +class SinusoidWaveform(Waveform): + def calc(self): + ret = [] + x = random.random() + for i in range (20): + ret.append(math.sin(x)) + x = x + 0.1 + return ret + +add_device(SinusoidWaveform("wf1"), True) + +r3 = lscan(out, (wf1,), 0.0,1.0, 4, 0.01) diff --git a/script/test51.py b/script/test51.py new file mode 100755 index 0000000..2862dec --- /dev/null +++ b/script/test51.py @@ -0,0 +1,30 @@ +################################################################################################### +# Demonstrate the use of Region Scan: one positioner move linearly in multiple regions. +################################################################################################### + + +passes = 2 +zigzag = True + +#Execute the scan: 3 regions with different number of steps +r1 = rscan(out, (sin,inp) , [(0,5,5), (10,15,20), (20,25,5)] , 0.01, passes = passes, zigzag = zigzag) + +#Execute the scan: 3 regions with different step size +r2 = rscan(out, (sin,inp) , [(0,5,1.0), (10,15,0.2), (20,25,1.0)] , 0.01, passes = passes, zigzag = zigzag) + + +vector = [ 1, 3, 5, 10, 25, 40, 45, 47, 49] + + +r1 = vscan(out,(sin,inp),vector,False, 0.123, passes = passes, zigzag = zigzag) + + + +#2D vector scan, plot to 2D Vector tab +vector = [ [1,1] , [1,2] , [1,3] , [1,4] , + [1.5,2.5] , + [2,1] , [2,2] , [2,3] , [2,4] , + [2.5,2.5] , + [3,1] , [3,2] , [3,3] , [3,4] ] + +r2 = vscan((out,testd),(sin,inp),vector,False, 0.123, passes = passes, zigzag = zigzag) diff --git a/script/test52.py b/script/test52.py new file mode 100755 index 0000000..9c65769 --- /dev/null +++ b/script/test52.py @@ -0,0 +1,9 @@ + +set_exec_pars(name = "Test1") + +r = lscan (out, sin, 0, 10, 10, 0.2) + + +set_exec_pars(open = False, reset=True, defaults = True) + +r = lscan (out, sin, 0, 10, 10, 0.2) diff --git a/script/test53.py b/script/test53.py new file mode 100755 index 0000000..2adf5e0 --- /dev/null +++ b/script/test53.py @@ -0,0 +1,35 @@ + + +caput("TESTIOC:TESTCALCOUT:Input", 2.0) + +time.sleep(0.0) + +caput("TESTIOC:TESTCALCOUT:Input", 5.0) + +try: + #write_logs() + + waiting = True + def plot_task(): + global waiting + while waiting: + if count.take() != pos: + time.sleep(2.0) + + ret = fork(plot_task) + try: + #Post-actions + wait_channel("TESTIOC:TESTCALCOUT:Output", "3.0", type = 's') + time.sleep(2.0) + print "Finished Energy scan" + finally: + waiting = False + join(ret) + + #plot_file(newName) + print("Success") + +except: + while caget('TESTIOC:TESTCALCOUT:Output') != 3.0: + print("Aborting...") + caput("TESTIOC:TESTCALCOUT:Input", 3.0) \ No newline at end of file diff --git a/script/test54.py b/script/test54.py new file mode 100755 index 0000000..24d06f6 --- /dev/null +++ b/script/test54.py @@ -0,0 +1,44 @@ +''' +Line Scan +''' + + +#setup_plotting(plot_list = (sin,out)) + +#set_preference(Preference.MANUAL_RANGE, [0, 80]) + +setup_plotting(range = [-20,100]) + +#a= lscan(inp, (sin,out,arr), 0, 40, 10, 0.2) + +#setup_plotting(range = "none") +#a= ascan((inp,out), (sin,out,arr), (0,0), (40,40), (10,10), 0.01) +#a= ascan((inp,ao1, ao2), (sin,out,arr), (0,0,0), (40,40, 40), (4.0,4.0,4.0), 0.01) +#a= ascan((inp,ao1, ao2), (sin), (0,0,0), (40,40, 40), (5,6,7), 0.01) + + + + + +data_1d = [10.0, 20.0, 30.0, 40.0, 50.0] +data_2d = [ data_1d, data_1d, data_1d, data_1d, data_1d] +data_3d = [ data_2d, data_2d , data_2d, data_2d, data_2d] +data_x = [1.0, 2.0, 3.0, 4.0, 5.0] +data_y = [2.0, 4.0, 6.0, 8.0, 10.0] + + +setup_plotting(range = [-20,100]) +#1d-plot with optional xdata +plot(data_1d, title = "1d", xdata = data_x) + + +setup_plotting(defaults=True) +#2d-plot with optional xdata and ydata +plot(data_2d, title = "2d", xdata = data_x, ydata = data_y) + +#3d-plot +plot(data_3d, title = "3d") + +#3 plots in the save panel +plot([data_1d, data_2d, data_3d], ["1d", "2d", "3d"]) + diff --git a/script/test55.py b/script/test55.py new file mode 100755 index 0000000..eff559f --- /dev/null +++ b/script/test55.py @@ -0,0 +1,23 @@ +#setup_plotting(range = [0,20], domain = "Index") +#setup_plotting(range = [0,100], line_plots = [arr], domain = "Clock") +#setup_plotting( range = [0,20], domain = "Index") +#setup_plotting( domain = "Index", range = "auto") +#setup_plotting( domain = "Clock") +setup_plotting( domain = "Clock", range = [0,100,1.0]) + +#setup_plotting(range = [0,200]) + +#setup_plotting(range = "auto") + +class Clock(Readable): + def read(self): + return time.clock() + +clock=Clock() + + +a= lscan(inp, (sin,out,arr, clock), 50, 90, 10, 0.2) + + + +#a= ascan((ao1,inp), (sin,out,arr, clock), (0,0), (20,10), (10,5), 0.001) diff --git a/script/test56.py b/script/test56.py new file mode 100755 index 0000000..85b55c4 --- /dev/null +++ b/script/test56.py @@ -0,0 +1,11 @@ +''' +Testing Line Scan +''' + + +a= lscan(motor, (ai1,wf1), 0.0, 2.0, 10, 0.1) + + +a= lscan(motor, (ai2,im1), 0.0, 2.0, 10, 0.1) + + diff --git a/script/test6.py b/script/test6.py new file mode 100755 index 0000000..e580ac7 --- /dev/null +++ b/script/test6.py @@ -0,0 +1,32 @@ +""" +Creating pseudo-devices +""" +import time + +sin_val=None + +class Sensor(Readable): + def read(self): + global sin_val + return sin_val + time.clock() + +class Positioner(Writable): + def write(self,pos): + print pos + +class Listener (DeviceListener): + def onStateChanged(self, device, state, former): + pass + def onValueChanged(self, device, value, former): + global sin_val + sin_val=value + +sensor=Sensor() +positioner=Positioner() +listener = Listener() + +sin.addListener(listener) +try: + a= lscan((inp,positioner),(sin,sensor),(0,0),(40,10),20,0.1) +finally: + sin.removeListener(listener) \ No newline at end of file diff --git a/script/test6.xml b/script/test6.xml new file mode 100755 index 0000000..d16a1ef --- /dev/null +++ b/script/test6.xml @@ -0,0 +1,25 @@ + + + + + + + 100 + + + + + 100 + + + + + + + + + + + + diff --git a/script/test7.py b/script/test7.py new file mode 100755 index 0000000..171ee0b --- /dev/null +++ b/script/test7.py @@ -0,0 +1,114 @@ +""" +Function fitting and peak search directly with org.apache.commons.math3 +""" + +import org.apache.commons.math3.util.FastMath as FastMath + +import org.apache.commons.math3.stat.regression.SimpleRegression as SimpleRegression + +import org.apache.commons.math3.analysis.polynomials.PolynomialFunction as PolynomialFunction +import org.apache.commons.math3.analysis.function.Gaussian as Gaussian +import org.apache.commons.math3.analysis.function.HarmonicOscillator as HarmonicOscillator +import org.apache.commons.math3.analysis.solvers.LaguerreSolver as LaguerreSolver + +import org.apache.commons.math3.fitting.GaussianCurveFitter as GaussianCurveFitter +import org.apache.commons.math3.fitting.PolynomialCurveFitter as PolynomialCurveFitter +import org.apache.commons.math3.fitting.HarmonicCurveFitter as HarmonicCurveFitter +import org.apache.commons.math3.fitting.WeightedObservedPoint as WeightedObservedPoint + +import org.apache.commons.math3.analysis.differentiation.FiniteDifferencesDifferentiator as FiniteDifferencesDifferentiator +import org.apache.commons.math3.analysis.differentiation.DerivativeStructure as DerivativeStructure + + +start = -0 +end = 2 +step_size = 0.1 + +result= lscan(inp,(sin,out),start,end,[step_size,],0.1) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +simple_regression= SimpleRegression() + +values = [] +for record in result.records: + simple_regression.addData(record.positions[0], record.values[0]) + values.append(WeightedObservedPoint(1, record.positions[0], record.values[0])) + +order = 6 +#polynomial_fitter = PolynomialCurveFitter.create(0).withStartPoint([ 5.0, 5.0, 5.0]) +polynomial_fitter = PolynomialCurveFitter.create(order) +gaussian_fitter = GaussianCurveFitter.create(); +#harmonic_fitter = HarmonicCurveFitter.create(); + + +best = polynomial_fitter.fit(values) +fitted_polynomial_function = PolynomialFunction(best) + + +(normalization, mean, sigma) = gaussian_fitter.fit(values) +print (normalization, mean, sigma) +fitted_gaussian_function = Gaussian(normalization, mean, sigma) +print "Mean: " + str(mean) + +#(amplitude, angular_frequency, phase) = harmonic_fitter.fit(values) +#print (amplitude, angular_frequency, phase) +#fitted_harmonic_function = HarmonicOscillator(amplitude, angular_frequency, phase) + + +#differentiator = FiniteDifferencesDifferentiator(order+2, 0.25) #points, step size +#derivative = differentiator.differentiate(fitted_polynomial) +derivative = fitted_polynomial_function.derivative() +print fitted_polynomial_function.coefficients +print derivative.coefficients + + +regression = [] +fit_polinomial = [] +fit_gaussian = [] +#fit_harmonic = [] +fit_polinomial_derivative = [] +resolution = step_size/100 +for x in frange(start,end,resolution, True): + regression.append(simple_regression.predict(x)) + fit_polinomial.append(fitted_polynomial_function.value(x)) + fit_gaussian.append(fitted_gaussian_function.value(x)) + #fit_harmonic.append(fitted_harmonic_function.value(x)) + fit_polinomial_derivative.append(derivative.value(x)) +x = frange(start, end+resolution, resolution) + + + + +def calculate_peaks(function, start_value, end_value , positive=True): + derivative = function.derivative() + derivative2 = derivative.derivative() + ret = [] + solver = LaguerreSolver() + for complex in solver.solveAllComplex(derivative.coefficients, start_value): + r = complex.real + if start_value < r < end_value: + if (positive and (derivative2.value(r) < 0)) or ( (not positive) and (derivative2.value(r) > 0)): + ret.append(r) + return ret + +peaks = calculate_peaks(fitted_polynomial_function, start, end) + + +plots = plot([readable, regression, fit_polinomial, fit_gaussian, fit_polinomial_derivative] , + ["sin", "regression", "fit polinomial", "fit gaussian", "fit harmonic ", "fit polinomial derivative"], + xdata = [positions,x,x,x,x,x], title="Data" ) + + +for p in peaks: + print "Max: " + str(p) + plots[0].addMarker(p, None, "Max", None) + +#plots[0].addMarker(mean, None, "Gaussian Mean", None) + + + +print result + + diff --git a/script/test7.xml b/script/test7.xml new file mode 100755 index 0000000..962e239 --- /dev/null +++ b/script/test7.xml @@ -0,0 +1,35 @@ + + + + alexandre.gobbo@psi.ch + + + My third test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + + + + + diff --git a/script/test8.py b/script/test8.py new file mode 100755 index 0000000..6a54198 --- /dev/null +++ b/script/test8.py @@ -0,0 +1,36 @@ +""" +Multi-peak search +""" + +from mathutils import estimate_peak_indexes, fit_gaussians + +start = 0 +end = 5 +step_size = 0.1 + +result= lscan(inp,sin,start,end,[step_size,],0.1) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +threshold = (min(readable) + max(readable))/2 +min_peak_distance = 0.5 + +peaks = estimate_peak_indexes(readable, positions, threshold, min_peak_distance) +print peaks + +gaussians = fit_gaussians(readable, positions, peaks) + +plots = plot([readable],["sin"],[positions] , title="Data") +for i in range(len(peaks)): + peak = peaks[i] + (norm, mean, sigma) = gaussians[i] + if abs(mean - positions[peak]) < min_peak_distance: + print "Peak -> " + str(mean) + plots[0].addMarker(mean, None, "N="+str(round(norm,2)), None) + else: + print "Invalid gaussian fit: " + str(mean) + + + + diff --git a/script/test8.xml b/script/test8.xml new file mode 100755 index 0000000..b45e95c --- /dev/null +++ b/script/test8.xml @@ -0,0 +1,29 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + + diff --git a/script/test9.py b/script/test9.py new file mode 100755 index 0000000..0667d71 --- /dev/null +++ b/script/test9.py @@ -0,0 +1,58 @@ +""" +Function fitting and peak search with mathutils facade +""" +from mathutils import fit_polynomial,fit_gaussian, fit_harmonic, calculate_peaks +from mathutils import PolynomialFunction, Gaussian, HarmonicOscillator +import math + + +start = 0 +end = 10 +step_size = 0.1 + +result= lscan(sout,sinp,start,end,[step_size,],0.01) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +def get_function_data(function, start, end, resolution): + ret = [] + for x in frange(start, end, resolution, True): + fit_polinomial.append(function.value(x)) + + +pars_polynomial = (a0, a1, a2, a3, a4, a5, a6) = fit_polynomial(readable, positions, 6) +fitted_polynomial_function = PolynomialFunction(pars_polynomial) +print pars_polynomial + +(normalization, mean, sigma) = fit_gaussian(readable, positions) +fitted_gaussian_function = Gaussian(normalization, mean, sigma) +print (normalization, mean, sigma) + +(amplitude, angular_frequency, phase) = fit_harmonic(readable, positions) +fitted_harmonic_function = HarmonicOscillator(amplitude, angular_frequency, phase) +print (amplitude, angular_frequency, phase) + + +resolution = step_size/100 +fit_polinomial = [] +fit_gaussian = [] +fit_harmonic = [] +for x in frange(start,end,resolution, True): + fit_polinomial.append(fitted_polynomial_function.value(x)) + fit_gaussian.append(fitted_gaussian_function.value(x)) + fit_harmonic.append(fitted_harmonic_function.value(x)) +x = frange(start, end+resolution, resolution) + + +peaks = calculate_peaks(fitted_polynomial_function, start, end) + +plots = plot([readable, fit_polinomial, fit_gaussian, fit_harmonic] , + ["data", "polinomial", "gaussian", "harmonic"], xdata = [positions,x,x,x], title="Data") + +for p in peaks: + print "Max: " + str(p) + plots[0].addMarker(p, None, "Max=" + str(round(p,2)), None) +import java.awt.Color +plots[0].addMarker(mean, None, "Mean=" + str(round(mean,2)), java.awt.Color.LIGHT_GRAY) + diff --git a/script/test9.xml b/script/test9.xml new file mode 100755 index 0000000..cf97860 --- /dev/null +++ b/script/test9.xml @@ -0,0 +1,28 @@ + + + + alexandre.gobbo@psi.ch + + + My third test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + + + diff --git a/script/test_region.xml b/script/test_region.xml new file mode 100755 index 0000000..fc70de8 --- /dev/null +++ b/script/test_region.xml @@ -0,0 +1,33 @@ + + + + alexandre.gobbo@psi.ch + + + My first test a + + + + + + 0.0 + 10.0 + 1.0 + + + 30.0 + 35.0 + 0.5 + + + + + + + + + + + diff --git a/script/testall.py b/script/testall.py new file mode 100755 index 0000000..2b309ff --- /dev/null +++ b/script/testall.py @@ -0,0 +1,6 @@ +scripts = ["test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "import", "import2", "import7", "test0","data"] + +for script in scripts: + print "------------------------ " + "Running: " + script + " ------------------------ " + set_status("Running: " + script) + run(script) \ No newline at end of file diff --git a/script/testb.py b/script/testb.py new file mode 100755 index 0000000..0534561 --- /dev/null +++ b/script/testb.py @@ -0,0 +1,17 @@ +from startup import * +#inject() + +#globals().update(get_context().scriptManager.injections) + +print "LOADED" + +#def inject(): +# globals().update(get_context().scriptManager.injections) + +def test(): + #globals().update(get_context().scriptManager.injections) + ##dev = None + #inject() + stop() + inject() + print 2* dev.read() \ No newline at end of file diff --git a/script/testc.py b/script/testc.py new file mode 100755 index 0000000..df8d217 --- /dev/null +++ b/script/testc.py @@ -0,0 +1,17 @@ +print get_option("Opt", "YesNo") +print get_string("Enter:", password = True) +print get_string("Enter:","default",["default","alt"]) + +print get_string("Enter:","default") + + + +print get_option("Opt", "OkCancel") +print get_option("Opt", "YesNoCancel") +print get_option("Opt", "YesNo") + + +show_message("test") +show_message("test2","tit") + + diff --git a/script/teste.py b/script/teste.py new file mode 100755 index 0000000..0534561 --- /dev/null +++ b/script/teste.py @@ -0,0 +1,17 @@ +from startup import * +#inject() + +#globals().update(get_context().scriptManager.injections) + +print "LOADED" + +#def inject(): +# globals().update(get_context().scriptManager.injections) + +def test(): + #globals().update(get_context().scriptManager.injections) + ##dev = None + #inject() + stop() + inject() + print 2* dev.read() \ No newline at end of file diff --git a/script/testf.py b/script/testf.py new file mode 100755 index 0000000..d165396 --- /dev/null +++ b/script/testf.py @@ -0,0 +1,15 @@ +print get_string("Enter:", password = True) +print get_string("Enter:","default",["default","alt"]) + +print get_string("Enter:","default") + + + +print get_option("Opt", "OkCancel") +print get_option("Opt", "YesNoCancel") +print get_option("Opt", "YesNo") + + +show_message("test") +show_message("test2","tit") + diff --git a/script/testmodule.py b/script/testmodule.py new file mode 100755 index 0000000..369351f --- /dev/null +++ b/script/testmodule.py @@ -0,0 +1,22 @@ +""" +def a(): + print "a" + + +def do_scan(positioner, sensor): + global a() + return lscan(positioner, sensor, 0, 5, 20, 0.1, title = str(positioner)) + + + +ret = do_scan(positioner, sensor) +set_return(ret) +""" + + +def a(): + print "a" + +a() +ret = lscan(positioner, sensor, 0, 5, 20, 0.1, title = str(positioner)) +set_return(ret) diff --git a/script/testx.xml b/script/testx.xml new file mode 100755 index 0000000..09d6938 --- /dev/null +++ b/script/testx.xml @@ -0,0 +1,26 @@ + + + + alexandre.gobbo@psi.ch + + + My first test + + + + + 0.0 + 31.0 + 1.0 + + + + + + + + + + diff --git a/script/tomography-scan.py b/script/tomography-scan.py new file mode 100755 index 0000000..79f301c --- /dev/null +++ b/script/tomography-scan.py @@ -0,0 +1,2174 @@ +#! /usr/bin/env python +# Federica Marone, July 2, 2014 + +import time +import sys +import math +import os +import ca +import CaChannel +import xml.etree.ElementTree as ET + +sys.path.append("/work/sls/bin") + +from epicsPV import epicsPV +from epicsMotor import epicsMotor +from channelDefinition import * + +CaChannel.CaChannel.ca_timeout = 3 +# ------------------------ Functions ------------------------------------- +def show_help(): + print "Tomography macro" + print "" + print "USAGE" + print "Input parameters" + print " $0 = scanType" + print " tomography-scan.py " + print "" + print "ARGUMENTS" + print " scanType Scan type" + print " 2 - Fast Scan Mode" + print " 5 - Fast Scan DPC Mode" + print " 6 - Snap&Snap Mode" + print " 7 - Snap&Step DPC Mode" + sys.exit() + +def standardChannelDefinition(operationMode): + + global chStorage,chFilePrefix, chUserID + global chServer,chEndstation + global chGo, chPause, chExperimentStatus, chCameraStatus + global chScanInterruption, chComputeSinograms + global chActualRotation, chScanTimeToGo + global chRoi, chExposure, chRotyMin, chRotyMax, chRotationAxisPosition + global chNumberOfDarks, chNumberOfFlats, chNumberOfProjections + global chXLinIn, chXLinOut, chTriggerDelay + + if operationMode!=2: + chStorage=epicsPV('X02DA-SCAN-CAM1:STORAGE') + chFilePrefix=epicsPV('X02DA-SCAN-CAM1:FILPRE') + chServer=epicsPV("X02DA-ES1-CAM1:SERV_SEL") + chEndstation=epicsPV("X02DA-ES1-CAM1:ENDST_SEL") + chGo=epicsPV("X02DA-SCAN-SCN1:GO") + chPause=epicsPV("X02DA-SCAN-SCN1:PAUSE") + chExperimentStatus=epicsPV("X02DA-SCAN-SCN1:STATUS") + chCameraStatus=epicsPV("X02DA-SCAN-CAM1:STATUS") + chScanInterruption=epicsPV("X02DA-SCAN-SCN1:INTR") + chComputeSinograms=epicsPV("X02DA-SCAN-SCN1:SINO") + chUserID=epicsPV("X02DA-SCAN-SCN1:USERID") + chActualRotation=epicsPV("X02DA-SCAN-SCN1:ACTROT") + chScanTimeToGo=epicsPV("X02DA-SCAN-SCN1:SCNFINTME") + chRoi=epicsPV("X02DA-SCAN-CAM1:ROI") + chExposure=epicsPV("X02DA-SCAN-CAM1:EXPTME") + chRotyMin=epicsPV("X02DA-SCAN-SCN1:ROTSTA") + chRotyMax=epicsPV("X02DA-SCAN-SCN1:ROTSTO") + chRotationAxisPosition=epicsPV("X02DA-SCAN-SCN1:STITCH") + chNumberOfDarks=epicsPV("X02DA-SCAN-SCN1:NPPDRK") + chNumberOfFlats=epicsPV("X02DA-SCAN-SCN1:NPPFLT") + chNumberOfProjections=epicsPV("X02DA-SCAN-SCN1:NPRJ") + chXLinIn=epicsPV("X02DA-SCAN-SCN1:SMPIN") + chXLinOut=epicsPV("X02DA-SCAN-SCN1:SMPOUT") + chTriggerDelay=epicsPV("X02DA-SCAN-SCN1:TRIDEL") + else: + channelPrefix="X02DA-SOFTTEST-TEST" + chStorage=epicsPV(channelPrefix+":STORAGE") + chFilePrefix=epicsPV(channelPrefix+":FILPRE") + chServer=epicsPV(channelPrefix+":SERV_SEL") + chEndstation=epicsPV(channelPrefix+":ENDST_SEL") + chGo=epicsPV(channelPrefix+":GO") + chPause=epicsPV(channelPrefix+":PAUSE") + chExperimentStatus=epicsPV(channelPrefix+":STATUS") + chCameraStatus=epicsPV(channelPrefix+":STATUS") + chScanInterruption=epicsPV(channelPrefix+":INTR") + chComputeSinograms=epicsPV(channelPrefix+":SINO") + chUserID=epicsPV(channelPrefix+":USERID") + chActualRotation=epicsPV(channelPrefix+":ACTROT") + chScanTimeToGo=epicsPV(channelPrefix+":SCNFINTME") + chRoi=epicsPV(channelPrefix+":ROI") + chExposure=epicsPV(channelPrefix+":EXPTME") + chRotyMin=epicsPV(channelPrefix+":ROTSTA") + chRotyMax=epicsPV(channelPrefix+":ROTSTO") + chRotationAxisPosition=epicsPV(channelPrefix+":STITCH") + chNumberOfDarks=epicsPV(channelPrefix+":NPPDRK") + chNumberOfFlats=epicsPV(channelPrefix+":NPPFLT") + chNumberOfProjections=epicsPV(channelPrefix+":NPRJ") + chXLinIn=epicsPV(channelPrefix+":SMPIN") + chXLinOut=epicsPV(channelPrefix+":SMPOUT") + + chGo.setMonitor() + chPause.setMonitor() + + +def cameraChannelDefinition(beamline,server): + + global chCCDCAM_SET_PARAM + global chCCDCAM_RECMODE + global chCCDCAM_STOREMODE + global chCCDCAM_DELAY + global chCCDCAM_FILENR + global chCCDCAM_SAVESTOP + global chCCDCAM_SAVESTART + global chCCDCAM_CLEARMEM + global chCCDCAM_STATUSCODE + global chCCDCAM_CAMERA + global chCCDCAM_COCTIME + global chCCDCAM_TRIGGER + global chCCDCAM_ACQMODE + global chCCDCAM_FILEFORMAT + global chCCDCAM_EXPOSURE + global chCCDCAM_FILESAVEBUSY + global chCCDCAM_CAMPROGRESS + global chCCDCAM_FTRANSFER + global chCCDCAM_FTRANSFERSEVR + global chCCDCAM_FILEPATH + global chCCDCAM_FILEPATHSEVR + global chCCDCAM_FILEPATHSTAT + global chCCDCAM_FILENAME + global chCCDCAM_REGIONX_START + global chCCDCAM_REGIONX_END + global chCCDCAM_REGIONY_START + global chCCDCAM_REGIONY_END + global chCCDCAM_CCDTEMP + global chCCDCAM_HEIGHT + global chCCDCAM_WIDTH + global chCCDCAM_PIC_MAX + global chCCDCAM_PIC_BUFFER + global chCCDCAM_CAMRATE + global chCCDCAM_INIT + global chCCDCAM_HSSPEED + global chCCDCAM_TRANSFER + global chCCDCAM_FILERATE + global chCCDCAM_HWFILENR + global chCCDCAM_POWERTEMP + global chCCDCAM_ERRCODE + global chCCDCAM_WARNCODE + global chCCDCAM_CAMTEMP + global chCCDCAM_BUSY + + chCCDCAM_SET_PARAM = epicsPV(beamline+"-"+server+":SET_PARAM") + chCCDCAM_RECMODE = epicsPV(beamline+"-"+server+":RECMODE") + chCCDCAM_STOREMODE = epicsPV(beamline+"-"+server+":STOREMODE") + chCCDCAM_DELAY = epicsPV(beamline+"-"+server+":DELAY") + chCCDCAM_FILENR = epicsPV(beamline+"-"+server+":FILENR") + chCCDCAM_SAVESTOP = epicsPV(beamline+"-"+server+":SAVESTOP") + chCCDCAM_SAVESTART = epicsPV(beamline+"-"+server+":SAVESTART") + chCCDCAM_CLEARMEM = epicsPV(beamline+"-"+server+":CLEARMEM") + chCCDCAM_CAMERA = epicsPV(beamline+"-"+server+":CAMERA") + chCCDCAM_COCTIME = epicsPV(beamline+"-"+server+":COCTIME") + chCCDCAM_TRIGGER = epicsPV(beamline+"-"+server+":TRIGGER") + chCCDCAM_ACQMODE = epicsPV(beamline+"-"+server+":ACQMODE") + chCCDCAM_FILEFORMAT = epicsPV(beamline+"-"+server+":FILEFORMAT") + chCCDCAM_EXPOSURE = epicsPV(beamline+"-"+server+":EXPOSURE") + # chCCDCAM_FILESAVEBUSY = epicsPV(beamline+"-"+server+":FILESAVEBUSY.RVAL") + chCCDCAM_FILESAVEBUSY = epicsPV(beamline+"-"+server+":FILESAVEBUSY") + chCCDCAM_CAMPROGRESS = epicsPV(beamline+"-"+server+":CAMPROGRESS") + chCCDCAM_FTRANSFER = epicsPV(beamline+"-"+server+":FTRANSFER") + chCCDCAM_FTRANSFERSEVR = epicsPV(beamline+"-"+server+":FTRANSFER.SEVR") + chCCDCAM_FILEPATH = epicsPV(beamline+"-"+server+":FILEPATH") + chCCDCAM_FILEPATHSEVR = epicsPV(beamline+"-"+server+":FILEPATH.SEVR") + chCCDCAM_FILEPATHSTAT = epicsPV(beamline+"-"+server+":FILEPATH.STAT") + chCCDCAM_FILENAME = epicsPV(beamline+"-"+server+":FILENAME") + chCCDCAM_REGIONX_START = epicsPV(beamline+"-"+server+":REGIONX_START") + chCCDCAM_REGIONX_END = epicsPV(beamline+"-"+server+":REGIONX_END") + chCCDCAM_REGIONY_START = epicsPV(beamline+"-"+server+":REGIONY_START") + chCCDCAM_REGIONY_END = epicsPV(beamline+"-"+server+":REGIONY_END") + + # The following variables are not used for the moment but are listed for completeness + + chCCDCAM_STATUSCODE = epicsPV(beamline+"-"+server+":STATUSCODE") + chCCDCAM_CCDTEMP = epicsPV(beamline+"-"+server+":CCDTEMP") + chCCDCAM_HEIGHT = epicsPV(beamline+"-"+server+":HEIGHT") + chCCDCAM_WIDTH = epicsPV(beamline+"-"+server+":WIDTH") + chCCDCAM_PIC_MAX = epicsPV(beamline+"-"+server+":PIC_MAX") + chCCDCAM_PIC_BUFFER = epicsPV(beamline+"-"+server+":PIC_BUFFER") + chCCDCAM_CAMRATE = epicsPV(beamline+"-"+server+":CAMRATE") + chCCDCAM_INIT = epicsPV(beamline+"-"+server+":INIT") + chCCDCAM_HSSPEED = epicsPV(beamline+"-"+server+":HSSPEED") + chCCDCAM_TRANSFER = epicsPV(beamline+"-"+server+":TRANSFER") + chCCDCAM_FILERATE = epicsPV(beamline+"-"+server+":FILERATE") + chCCDCAM_HWFILENR = epicsPV(beamline+"-"+server+":HWFILENR") + chCCDCAM_POWERTEMP = epicsPV(beamline+"-"+server+":POWERTEMP") + chCCDCAM_ERRCODE = epicsPV(beamline+"-"+server+":ERRCODE") + chCCDCAM_WARNCODE = epicsPV(beamline+"-"+server+":WARNCODE") + chCCDCAM_CAMTEMP = epicsPV(beamline+"-"+server+":CAMTEMP") + chCCDCAM_BUSY = epicsPV(beamline+"-"+server+":BUSY") + + # Set monitors + + chCCDCAM_FILESAVEBUSY.setMonitor() + chCCDCAM_CAMPROGRESS.setMonitor() + +def rotationStageDefinition(rotationStage,endstationPrefix,beamline): + + global chROT_SET_ABS, chROT_GET_POS, chROT_SVEL, chROT_GVEL, chROT_STOP, chROT_TWEAK, chROT_GACC + global chROT_SNAP_START, chROT_SNAP_OFFSET, chROT_DIRECT_MODE, chROT_STAB_TIME, chROT_REPETIONS + global chROT_PULSE_WIDTH, chROT_COUNTER, chROT_SNAP_READY, chROT_START, chROT_MOVE + global chSampleX, chSampleY, chSampleZ, chSampleXX, chSampleZZ, chMicroscopeX, chMicroscopeY, chMicroscopeZ + + if rotationStage!="Aerotech" and rotationStage!="Micos": + print "The " + rotationStage + " rotation stage has not been implemented yet" + + + chROT_SET_ABS = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYUSETP") + chROT_GET_POS = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYUGETP") + chROT_GET_POS.setMonitor() + chROT_SVEL = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYSETVE") + chROT_MOVE = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYASTAT") + + if rotationStage=="Aerotech": + + chROT_STOP = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYESTOP.PROC") + chROT_SNAP_START = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYMSTART") + chROT_SNAP_OFFSET = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYMOFFS") + chROT_DIRECT_MODE = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTY-DMODE") + chROT_STAB_TIME = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYMTRIGDLY") + chROT_TWEAK = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYMDIST") + chROT_REPETIONS = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYMREP") + chROT_PULSE_WIDTH = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:#ROTYPULSEON") + chROT_COUNTER = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYSCNT") + chROT_SNAP_READY = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTY-M2READY.PROC") + chROT_START = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTY-M2START.PROC") + chROT_GVEL = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYSETVE") + chROT_GACC = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYSETAC") + + chSampleX=epicsMotor("X02DA-ES1-SMP1:TRX") + chSampleY=epicsPV("X02DA-ES1-SMP1:TRY-VAL") + chSampleZ=epicsMotor("X02DA-ES1-SMP1:TRZ") + chSampleXX=epicsMotor("X02DA-ES1-SMP1:TRXX") + chSampleZZ=epicsMotor("X02DA-ES1-SMP1:TRZZ") + chMicroscopeX=epicsMotor("X02DA-ES1-MS1:TRX") + chMicroscopeY=epicsMotor("X02DA-ES1-MS1:TRY") + chMicroscopeZ=epicsMotor("X02DA-ES1-MS1:TRZ") + + elif rotationStage=="Micos": + + chROT_STOP = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYSTOP.PROC") + chROT_TWEAK = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYTWEAK") + chROT_GVEL = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYGETVE") + chROT_GACC = epicsPV(beamline+"-"+endstationPrefix+"-SMP1:ROTYGETAC") + + chSampleX=epicsMotor("X02DA-ES2-SMP1:TRX") + chSampleY=epicsPV("X02DA-ES2-SMP1:TRY-VAL") + chSampleZ=epicsMotor("X02DA-ES2-SMP1:TRZ") + chSampleXX=epicsMotor("X02DA-ES2-SMP1:TRXX") + chSampleZZ=epicsMotor("X02DA-ES2-SMP1:TRZZ") + chMicroscopeX=epicsMotor("X02DA-ES2-DET1:TRX") + chMicroscopeY=epicsMotor("X02DA-ES2-DET1:TRY") + chMicroscopeZ=epicsMotor("X02DA-ES2-DET1:TRZ") + +def moveRotationWait(value): + + poll=1 + + chROT_SET_ABS.putWait(value) + # To be sure that the rotation starts before I pull + time.sleep(1) + + while (1): + movementDone = chROT_MOVE.getw(req_type=ca.DBF_STRING) + if movementDone!="MOVING" and movementDone!="1": + break + time.sleep(poll) + +def checkpausestop_fast(): + + global scanInterruption, logFile + + scanStatus=chGo.getw() + + if scanStatus!=1: + + FILE = open(logFile,"a") + FILE.write("SCAN HAS BEEN INTERRUPTED!!!!!\n") + FILE.close() + print "SCAN HAS BEEN INTERRUPTED!!!!!" + chCCDCAM_SAVESTOP.putWait(0) + chCameraStatus.putWait(0) + + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + while cameraSaveBusy==1: + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + time.sleep(0.5) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chROT_STOP.putWait(0) + + scanInterruption=1 + chScanTimeToGo.putWait(0) + +def checkpausestop_fast_dpc(): + + global scanInterruption + global scanPause + global logFile + + # Abort scan if stop button is pressed! + + scanStatus=chGo.getw() + + if scanStatus!=1: + FILE = open(logFile,"a") + FILE.write("SCAN HAS BEEN INTERRUPTED!!!!!\n") + FILE.close() + print "SCAN HAS BEEN INTERRUPTED!!!!!" + chCCDCAM_SAVESTOP.putWait(0) + chCameraStatus.putWait(0) + + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + while cameraSaveBusy==1: + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + time.sleep(0.5) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chROT_STOP.putWait(0) + + scanInterruption=1 + return + + # Check if scan has been paused + + pauseStatus=chPause.getw() + if pauseStatus!=0: + FILE = open(logFile,"a") + FILE.write("SCAN HAS BEEN PAUSED!!!!!\n") + FILE.close() + print "SCAN HAS BEEN PAUSED!!!" + chCCDCAM_SAVESTOP.putWait(0) + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + while cameraSaveBusy==1: + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + time.sleep(0.5) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chROT_STOP.putWait(0) + scanPause=1 + + while pauseStatus!=0 and scanStatus==1: + time.sleep(0.1) + pauseStatus=chPause.getw() + scanStatus=chGo.getw() + +def snap_fifo(): + + global totalScanTime, logFile + + # Let perform some checks for beam status + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + # Interrupt the scan if there is a beam dump, an optics interlock or the absorber has been closed + + if ringCurrentStatus <= ringCurrentStart-0.05*ringCurrentStart: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because of a beam dump!\n") + FILE.close() + print "Scan is going to be interrupted because of a beam dump!" + chGo.putWait(0) + if interlockStatus==1: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because of an optics interlock!\n") + FILE.close() + print "Scan is going to be interrupted because of an optics interlock!" + chGo.putWait(0) + if absorberStatus==0: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because the absorber has been closed!\n") + FILE.close() + print "Scan is going to be interrupted because the absorber has been closed!" + chGo.putWait(0) + + # Start the camera + cameraStatus=chCCDCAM_CAMERA.getw(req_type=ca.DBF_STRING) + if cameraStatus=="OFF": + print "Starting the camera" + chCCDCAM_CAMERA.putWait("RUNNING",req_type=ca.DBF_STRING) + time.sleep(5) + chCCDCAM_FTRANSFER.putWait(1) + + cameraProgress=chCCDCAM_CAMPROGRESS.getw() + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + + while cameraSaveBusy==1: + + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + # Interrupt the scan if there is a beam dump, an optics interlock or the absorber has been closed + + if ringCurrentStatus <= ringCurrentStart-0.05*ringCurrentStart: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because of a beam dump!\n") + FILE.close() + print "Scan is going to be interrupted because of a beam dump!" + chGo.putWait(0) + if interlockStatus==1: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because of an optics interlock!\n") + FILE.close() + print "Scan is going to be interrupted because of an optics interlock!" + chGo.putWait(0) + if absorberStatus==0: + FILE = open(logFile,"a") + FILE.write("Scan is going to be interrupted because the absorber has been closed!\n") + FILE.close() + print "Scan is going to be interrupted because the absorber has been closed!" + chGo.putWait(0) + + checkpausestop_fast() + + cameraProgress=chCCDCAM_CAMPROGRESS.getw() + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + print "Acquiring projections ... %2.2f" % cameraProgress + "% ... done" + + if rotyMax!=rotyMin: + currentAngle=chROT_GET_POS.getw() + timeToGo=totalScanTime*(1-((currentAngle-rotyMin)/(rotyMax-rotyMin))) + currentRotation=((currentAngle-rotyMin)/(rotyMax-rotyMin)) + if currentRotation>=0: + chActualRotation.putWait(currentRotation) + else: + chActualRotation.putWait(0) + if math.fabs(currentAngle-rotyMin)>1e-4: + chScanTimeToGo.putWait(timeToGo) + + time.sleep(2) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chCameraStatus.putWait("Idle") + +def snap_dpc(): + + global scanPause + global totalScanTime + global NSteps, iPhase + + beamDump=0 + # Let perform some checks for beam status + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + # Check for a beam dump, an optics interlock or a closed absorber + + scanStatus=chGo.getw() + + while (ringCurrentStatus <= ringCurrentStart-0.05*ringCurrentStart or interlockStatus==1 or absorberStatus==0) and scanStatus==1: + + if scanPause!=1: + scanPause=1 + chPause.putWait(1) + + chCCDCAM_SAVESTOP.putWait(0) + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + while cameraSaveBusy==1: + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + time.sleep(0.5) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chROT_STOP.putWait(0) + + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + beamDump=1 + scanStatus=chGo.getw() + + + if ringCurrentStatus >= ringCurrentStart-0.05*ringCurrentStart and interlockStatus==0 and absorberStatus==0: + + FILE = open(logFile,"a") + FILE.write("The absorber has been closed by the interlock!!!\n") + FILE.close() + print "The absorber has been closed by the interlock!!!" + chAbsorberStatus.putWait(1) + FILE = open(logFile,"a") + FILE.write("Waiting for 10s for thermal compenstaion after the absorber has been opened ...\n") + FILE.close() + print "Waiting for 10s for thermal compenstaion after the absorber has been opened ..." + time.sleep(10) + + if beamDump==1: + chPause.putWait(0) + beamDump=0 + + checkpausestop_fast_dpc() + + if scanPause!=1: + + # Start the camera + cameraStatus=chCCDCAM_CAMERA.getw(req_type=ca.DBF_STRING) + if cameraStatus=="OFF": + print "Starting the camera" + chCCDCAM_CAMERA.putWait("RUNNING",req_type=ca.DBF_STRING) + chCCDCAM_FTRANSFER.putWait(1) + + cameraProgress=chCCDCAM_CAMPROGRESS.getw() + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + + while cameraSaveBusy==1: + + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + # Check for a beam dump, an optics interlock or a closed absorber + + scanStatus=chGo.getw() + + while (ringCurrentStatus <= ringCurrentStart-0.05*ringCurrentStart or interlockStatus==1 or absorberStatus==0) and scanStatus==1: + + if scanPause!=1: + scanPause=1 + chPause.putWait(1) + chCCDCAM_SAVESTOP.putWait(0) + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + while cameraSaveBusy==1: + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + time.sleep(0.5) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chROT_STOP.putWait(0) + + if operationMode==0: + ringCurrentStatus=chRingCurrentStatus.getw() + interlockStatus=chInterlockStatus.getw() + absorberStatus=chAbsorberStatus.getw() + else: + ringCurrentStatus=chRingCurrentStartFake.getw() + interlockStatus=0 + absorberStatus=1 + + beamDump=1 + scanStatus=chGo.getw() + + + if ringCurrentStatus >= ringCurrentStart-0.05*ringCurrentStart and interlockStatus==0 and absorberStatus==0: + + FILE = open(logFile,"a") + FILE.write("The absorber has been closed by the interlock!!!\n") + FILE.close() + print "The absorber has been closed by the interlock!!!" + chAbsorberStatus.putWait(1) + FILE = open(logFile,"a") + FILE.write("Waiting for 10s for thermal compenstaion after the absorber has been opened ...\n") + FILE.close() + print "Waiting for 10s for thermal compenstaion after the absorber has been opened ..." + time.sleep(10) + + if beamDump==1: + chPause.putWait(0) + beamDump=0 + + checkpausestop_fast_dpc() + + cameraProgress=chCCDCAM_CAMPROGRESS.getw() + cameraSaveBusy=chCCDCAM_FILESAVEBUSY.getw() + print "Acquiring projections ... %2.2f" % cameraProgress + "% ... done" + + if rotyMax!=rotyMin: + currentAngle=chROT_GET_POS.getw() + timeToGo=totalScanTime*(1-((currentAngle-rotyMin)/(rotyMax-rotyMin)))+totalScanTime*(NSteps-iPhase-1) + chScanTimeToGo.putWait(timeToGo) + + time.sleep(2) + + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chCameraStatus.putWait("Idle") + +def fasttomoscan(rotyMin,rotyMax,numberOfProjections,exposure,xLinIn,xLinOut,numberOfDarks,numberOfFlats,crystal1Pitch,scanType,millisecondShutter,rotationStage): + + global scanInterruption + global totalScanTime + global logFile,sampleTifPath,logPath,databaseFile + + scanInterruption=0 + + # Set the scan status flag to running + chExperimentStatus.putWait("Running") + print "TOMOGRAPHIC SCAN STARTED!!!" + FILE = open(logFile,"a") + FILE.write("TOMOGRAPHIC SCAN STARTED!!!\n") + FILE.close() + + # Set scan type to continuous mode (just in case) + if rotationStage=="Micos": + chScanType.putWait(0) + + # Setting file format + chCCDCAM_FILEFORMAT.putWait("TIFF") + + baseRotySpeed=chROT_GVEL.getw() + + # Select FIFO mode + chCCDCAM_STOREMODE.putWait("FIFO Buffer") + print "Fifo mode ON" + chCCDCAM_RECMODE.putWait("Sequence") + chCCDCAM_ACQMODE.putWait("Auto") + chCCDCAM_TRIGGER.putWait("auto trigger") + if scanType=="6": + chCCDCAM_DELAY.putWait(0) + chCCDCAM_SET_PARAM.putWait("SET") + + # This is to make the camera run with the correct settings + # TODO do I need this??? Maybe for the COCTIME??? + #chCCDCAM_CLEARMEM.putWait("CLEAR") + #chCCDCAM_CAMERA.putWait("RUNNING",req_type=ca.DBF_STRING) + #time.sleep(1) + #chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chCCDCAM_CLEARMEM.putWait("CLEAR") + + ccdFrameTime=chCCDCAM_COCTIME.getw() + + # Angular increment + deltaRot=rotyMax-rotyMin + if numberOfProjections!=0: + angularIncrement=deltaRot/(numberOfProjections-1) + else: + angularIncrement=0 + + if scanType=="6": + chROT_TWEAK.putWait(angularIncrement) + if rotationStage=="Micos": + systemOffset=chSystemOffset.getw() + systemTime=systemOffset+(rotyMax-rotyMin)*1000/((numberOfProjections-1)*baseRotySpeed) + systemTimeForFlats=systemOffset + delay=systemTime+exposure-ccdFrameTime + delayForFlats=systemTimeForFlats+exposure-ccdFrameTime + totalScanTime=numberOfProjections*(exposure+systemTime)/1000 + else: + stabilizationTime=chROT_STAB_TIME.getw() + print "Stabilization time " + str(stabilizationTime) + " ms" + totalScanTime=numberOfProjections*(ccdFrameTime+stabilizationTime)/1000 + elif scanType=="2": + totalScanTime=numberOfProjections*ccdFrameTime/1000 + else: + print "This scan type has not been implemented yet!" + sys.exit() + + print "Total scan time " + str(totalScanTime) + " s" + + if deltaRot!=0 and scanType=="2": + rotySpeed=deltaRot/((numberOfProjections-1)*ccdFrameTime)*1000 + else: + rotySpeed=baseRotySpeed + + rotationAcceleration=chROT_GACC.getw() + print "Acceleration " + str(rotationAcceleration) + accelerationAngle=rotySpeed*rotySpeed/rotationAcceleration + waitingTime=math.fabs(rotySpeed)/rotationAcceleration + if waitingTime <= 0.2999: + waitingTime=0.3 + + if deltaRot!=0: + if scanType=="2": + rotationStart=rotyMin-rotySpeed*waitingTime-accelerationAngle + rotationStop=rotationStart+deltaRot+2*(rotySpeed*waitingTime+accelerationAngle) + elif scanType=="6": + rotationStart=rotyMin-angularIncrement + rotationStop=rotyMax + else: + print "This scan type has not been implemented yet!" + sys.exit() + + else: + rotationStart=rotyMin + rotationStop=rotyMax + + print "Expected frame time " + str(ccdFrameTime) + " ms" + print "Angular scan: " + str(deltaRot) + " degrees" + print "Rotation speed (angle/s): " + str(math.fabs(rotySpeed)) + print "Base rotation speed (angle/s): " + str(baseRotySpeed) + print "Start position: " + str(rotationStart) + print "Acceleration angle: " + str(accelerationAngle) + print "End position: " + str(rotationStop) + + if numberOfDarks>0: + ###################### Acquire dark images ################################# + + print "\033[1m" ## bold + print "Acquiring dark images" + print "\033[0m" ## back to normal + + print "Move to start position" + print "Move rotation axis to: " + str(rotationStart) + chROT_SVEL.putWait(baseRotySpeed) + moveRotationWait(rotationStart) + + # Closing filter for dark acquisition + if operationMode!=2: + if crystal1Pitch>-100: + print "Dump the beam by moving OP-FILTER 4 at -22.0 mm ..." + chOPFilter4.move(-22) + else: + print "Dump the beam by moving OP-FILTER 4 at -12.0 mm ..." + chOPFilter4.move(-12) + chOPFilter4.wait(poll=1) + else: + if crystal1Pitch>-100: + print "Dump the beam by moving OP-FILTER 4 at -22.0 mm ..." + else: + print "Dump the beam by moving OP-FILTER 4 at -12.0 mm ..." + + print "Wait for afterglow ..." + print "Done!" + + # Set the channel of the tomography panel + chCameraStatus.putWait("Acquiring") + + # Clear buffer + chCCDCAM_CLEARMEM.putWait("CLEAR") + + print "Saving dark images 1-" + str(int(numberOfDarks)) + chCCDCAM_FILENR.putWait(1) + chCCDCAM_SAVESTART.putWait(1) + chCCDCAM_SAVESTOP.putWait(int(numberOfDarks)) + + # Triggering the CCD acquisition sequence + print "Send trigger to the camera" + snap_fifo() + + chCameraStatus.putWait("Idle") + print "Darks acquisition done!" + + if numberOfFlats>0: + #################### Acquire pre flats ######################################## + + if scanInterruption==0: + + print "\033[1m" ## bold + print "Acquiring pre-flat images" + print "\033[0m" ## back to normal + + print "Moving the sample out of beam ..." + chSampleX.move(xLinOut) + chSampleX.wait(poll=1) + + # Opening the shutter + if operationMode!=2: + chOPFilter4.move(0);chOPFilter4.wait(poll=1) + print "Moving up the filter OP-FILTER 4 at 0.0 mm ..." + time.sleep(3) + + moveRotationWait(rotationStart) + + if scanType=="6": + if millisecondShutter=="Cam-Ctrl": + if rotationStage=="Micos": + chCCDCAM_DELAY.putWait(delayForFlats) + else: + chCCDCAM_DELAY.putWait(stabilizationTime) + chCCDCAM_SET_PARAM.putWait("SET") + + # Set the channel of the tomography panel + chCameraStatus.putWait("Acquiring") + + # Clear buffer + chCCDCAM_CLEARMEM.putWait("CLEAR") + + print "Saving pre flats images " + str(int(numberOfDarks+1)) + "-" + str(int(numberOfDarks+numberOfFlats)) + chCCDCAM_FILENR.putWait(numberOfDarks+1) + chCCDCAM_SAVESTART.putWait(1) + chCCDCAM_SAVESTOP.putWait(numberOfFlats) + + # Triggering the CCD acquisition sequence + print "Send trigger to the camera" + snap_fifo() + + chCameraStatus.putWait("Idle") + print "Pre flats acquisition done!" + + if scanType=="6": + if millisecondShutter=="Cam-Ctrl": + chCCDCAM_DELAY.putWait(0) + chCCDCAM_SET_PARAM.putWait("SET") + + ################## Acquire projection images ######################################## + + if scanInterruption==0: + + print "\033[1m" ## bold + print "Acquiring projections" + print "\033[0m" ## back to normal + + if numberOfFlats==0: + + if operationMode!=2: + # Opening the shutter + chOPFilter4.move(0);chOPFilter4.wait(poll=1) + print "Moving up the filter OP-FILTER 4 at 0.0 mm ..." + time.sleep(3) + + print "Saving projection images " + str(int(numberOfDarks+numberOfFlats+1)) + "-" + str(int(numberOfDarks+numberOfFlats+numberOfProjections)) + chCCDCAM_FILENR.putWait(numberOfDarks+numberOfFlats+1) + chCCDCAM_SAVESTART.putWait(1) + chCCDCAM_SAVESTOP.putWait(numberOfProjections) + + print "Moving the sample in the beam ..." + chSampleX.move(xLinIn);chSampleX.wait(poll=1) + + if scanType=="2": + print "Set the speed to: " + str(math.fabs(rotySpeed)) + if rotationStage=="Aerotech": + chROT_STOP.putWait(0) + chROT_SVEL.putWait(math.fabs(rotySpeed)) + + # Clear buffer + chCCDCAM_CLEARMEM.putWait("CLEAR") + + if scanType=="6": + if rotationStage=="Micos": + chScanType.putWait(1) + chCCDCAM_DELAY.putWait(delay) + chCCDCAM_SET_PARAM.putWait("SET") + else: + chBoxModeSelection.putWait("Snap\'n\'Step") + chROT_GACC.putWait(500) + chROT_TWEAK.putWait(angularIncrement) + chROT_SNAP_START.putWait(rotationStart) + chROT_REPETIONS.putWait(numberOfProjections) + chROT_PULSE_WIDTH.putWait(1000) + chROT_SNAP_READY.putWait(1) + chROT_COUNTER.putWait(0) + chCCDCAM_TRIGGER.putWait("ext.exp sfttrg") + chCCDCAM_SET_PARAM.putWait("SET") + time.sleep(1) + chCCDCAM_CAMERA.putWait("RUNNING") + + # Set the channel of the tomography panel + chCameraStatus.putWait("Acquiring") + + print "Rotation starts" + if scanType=="2": + chROT_SET_ABS.putWait(rotationStop) + else: + if rotationStage=="Aerotech": + chROT_START.putWait(1) + + print "Send trigger to the camera" + snap_fifo() + + chCameraStatus.putWait("Idle") + + if scanType=="6" and rotationStage=="Aerotech": + + chBoxModeSelection.putWait("Custom") + chROT_GACC.putWait(rotationAcceleration) + chROT_DIRECT_MODE.putWait(1) + chCCDCAM_TRIGGER.putWait("auto trigger") + chCCDCAM_SET_PARAM.putWait("SET") + + if scanInterruption==0: + print "Projection acquisition done!" + + if numberOfFlats>0: + ##################### Acquire post flats ############################################# + + if scanInterruption==0: + + chROT_STOP.putWait(0) + chROT_SVEL.putWait(baseRotySpeed) + + if rotationStage=="Micos": + chScanType.putWait(0) + print "Move Rotation to " + str(rotyMin) + moveRotationWait(rotyMin) + + print "\033[1m" ## bold + print "Acquiring post-flat images" + print "\033[0m" ## back to normal + + print "Moving the sample out of beam ..." + chSampleX.move(xLinOut) + chSampleX.wait(poll=1) + + if scanType=="6": + if rotationStage=="Micos": + chScanType.putWait(0) + chCCDCAM_DELAY.putWait(delayForFlats) + else: + if millisecondShutter=="Cam-Ctrl": + chCCDCAM_DELAY.putWait(stabilizationTime) + chCCDCAM_SET_PARAM.putWait("SET") + + print "Saving post flat images " + str(int(numberOfDarks+numberOfFlats+numberOfProjections+1)) + "-" + str(int(numberOfDarks+2*numberOfFlats+numberOfProjections)) + chCCDCAM_FILENR.putWait(numberOfDarks+numberOfFlats+numberOfProjections+1) + chCCDCAM_SAVESTART.putWait(1) + chCCDCAM_SAVESTOP.putWait(numberOfFlats) + + # Clear buffer + chCCDCAM_CLEARMEM.putWait("CLEAR") + + # Set the channel of the tomography panel + chCameraStatus.putWait("Acquiring") + + print "Send trigger to the camera" + snap_fifo() + + chCameraStatus.putWait("Idle") + print "Post flats acquisition done!" + + if scanType=="6": + if millisecondShutter=="Cam-Ctrl": + chCCDCAM_DELAY.putWait(0) + chCCDCAM_SET_PARAM.putWait("SET") + + print "Moving back to initial conditions ..." + + if scanInterruption==0: + chComputeSinograms.putWait(1) + + # Close the shutter and put sample back! + + if operationMode!=2: + if crystal1Pitch>-100: + print "Dump the beam by moving OP_FILTER 4 to -22.0 mm ..." + chOPFilter4.move(-22);chOPFilter4.wait(poll=1) + else: + print "Dump the beam by moving OP_FILTER 4 to -12.0 mm ..." + chOPFilter4.move(-12);chOPFilter4.wait(poll=1) + else: + if crystal1Pitch>-100: + print "Dump the beam by moving OP_FILTER 4 to -22.0 mm ..." + else: + print "Dump the beam by moving OP_FILTER 4 to -12.0 mm ..." + + + print "Set rotation speed back to " + str(baseRotySpeed) + #if rotationStage=="Aerotech": + chROT_STOP.putWait(0) + chROT_SVEL.putWait(baseRotySpeed) + + if rotationStage=="Micos": + chScanType.putWait(0) + print "Move Rotation to " + str(rotyMin) + moveRotationWait(rotyMin) + if numberOfFlats>0: + print "Moving the sample out of beam ..." + chSampleX.move(xLinOut);chSampleX.wait(poll=1) + + chScanTimeToGo.putWait(0) + + if scanType=="6" and rotationStage=="Aerotech": + chBoxModeSelection.putWait("Custom") + chROT_GACC.putWait(rotationAcceleration) + chROT_DIRECT_MODE.putWait(1) + chCCDCAM_TRIGGER.putWait("auto trigger") + chROT_COUNTER.putWait(0) + + FILE = open(logFile,"a") + FILE.write("TOMOGRAPHIC SCAN FINISHED at " + str(time.asctime(time.localtime(time.time())))+"\n") + FILE.close() + + # Logging + tree = ET.parse(databaseFile) + sample = tree.getroot() + scan = sample.find("./pointOfInterest/scan") + endDate=ET.Element("endDate") + endDate.text=str(time.asctime(time.localtime(time.time()))) + scan.append(endDate) + tree.write(databaseFile) + + command = "cp " + logFile + " " + sampleTifPath + os.system(command) + command = "ln " + sampleTifPath + "/" + filePrefix + ".log " + logPath + os.system(command) + command = "rm " + logFile + os.system(command) + + if scanInterruption==0: + command = "curl -X PUT -H \"Content-Type: application/xml\" -d @\"" + databaseFile + "\" http://x02da-www-1:8080/ch.psi.epms.web/rs/epms/upload" + os.system(command) + command = "cp " + databaseFile + " " + sampleTifPath + os.system(command) + command = "ln " + sampleTifPath + "/" + filePrefix + ".xml " + logPath + os.system(command) + command = "rm " + databaseFile + os.system(command) + else: + chScanInterruption.putWait(1) + + print "Set STOREMODE and RECMODE back to Recorder and Ring Buffer (for preview purposes)" + chCCDCAM_STOREMODE.putWait("Recorder") + chCCDCAM_RECMODE.putWait("Ring Buffer") + chCCDCAM_SET_PARAM.putWait("SET") + print "Fifo mode OFF" + + # Set the scan status flag to Idle + chExperimentStatus.putWait("Idle") + +def fastdpcscan(rotyMin,rotyMax,numberOfProjections,exposure,xLinIn,xLinOut,numberOfDarks,numberOfFlats,gridStart,gridEnd,gridNSteps,crystal1Pitch,scanType,millisecondShutter,rotationStage): + + global scanPause + global scanInterruption + global totalScanTime + global NSteps, iPhase + global logFile,sampleTifPath,logPath,databaseFile + + scanInterruption=0 + scanPause=0 + + # Set the scan status flag to running + chExperimentStatus.putWait("Running") + print "DPC-TOMOGRAPHIC SCAN STARTED!!!" + FILE = open(logFile,"a") + FILE.write("DPC-TOMOGRAPHIC SCAN STARTED!!!\n") + FILE.close() + + # Set scan type to continuous mode (just in case) + if rotationStage=="Micos": + chScanType.putWait(0) + + # Setting file format + chCCDCAM_FILEFORMAT.putWait("TIFF") + + baseRotySpeed=chROT_GVEL.getw() + + # Select FIFO mode + chCCDCAM_STOREMODE.putWait("FIFO Buffer") + print "Fifo mode ON" + chCCDCAM_RECMODE.putWait("Sequence") + chCCDCAM_ACQMODE.putWait("Auto") + chCCDCAM_TRIGGER.putWait("auto trigger") + if scanType=="7": + chCCDCAM_DELAY.putWait(0) + chCCDCAM_SET_PARAM.putWait("SET") + + # This is to make the camera run with the correct settings + # TODO do I need this??? Maybe for the COCTIME??? + #chCCDCAM_CLEARMEM.putWait("CLEAR") + #chCCDCAM_CAMERA.putWait("RUNNING",req_type=ca.DBF_STRING) + #time.sleep(1) + #chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + chCCDCAM_CLEARMEM.putWait("CLEAR") + + # Grid increment + gridStepSize=(gridEnd-gridStart)/gridNSteps + NSteps=gridNSteps+1 + + # Total number of projections + totalNumberOfProjections=numberOfDarks+numberOfFlats*2*NSteps+numberOfProjections*NSteps + + ccdFrameTime=chCCDCAM_COCTIME.getw() + + # Angular increment + deltaRot=rotyMax-rotyMin + if numberOfProjections!=0: + angularIncrement=deltaRot/(numberOfProjections-1) + else: + angularIncrement=0 + + if scanType=="7": + chROT_TWEAK.putWait(angularIncrement) + if rotationStage=="Micos": + systemOffset=chSystemOffset.getw() + systemTime=systemOffset+(rotyMax-rotyMin)*1000/((numberOfProjections-1)*baseRotySpeed) + systemTimeForFlats=systemOffset + delay=systemTime+exposure-ccdFrameTime + delayForFlats=systemTimeForFlats+exposure-ccdFrameTime + totalScanTime=numberOfProjections*(exposure+systemTime)/1000 + else: + stabilizationTime=chROT_STAB_TIME.getw() + print "Stabilization time " + str(stabilizationTime) + " ms" + totalScanTime=numberOfProjections*(ccdFrameTime+stabilizationTime)/1000 + elif scanType=="5": + totalScanTime=numberOfProjections*ccdFrameTime/1000 + else: + print "This scan type has not been implemented yet!" + sys.exit() + + if deltaRot!=0 and scanType=="5": + rotySpeed=deltaRot/((numberOfProjections-1)*ccdFrameTime)*1000 + else: + rotySpeed=baseRotySpeed + + rotationAcceleration=chROT_GACC.getw() + print "Acceleration " + str(rotationAcceleration) + accelerationAngle=rotySpeed*rotySpeed/rotationAcceleration + waitingTime=math.fabs(rotySpeed)/rotationAcceleration + if waitingTime <= 0.2999: + waitingTime=0.3 + + if deltaRot!=0: + if scanType=="5": + rotationStart=rotyMin-rotySpeed*waitingTime-accelerationAngle + rotationStop=rotationStart+deltaRot+2*(rotySpeed*waitingTime+accelerationAngle) + elif scanType=="7": + rotationStart=rotyMin-angularIncrement + rotationStop=rotyMax + else: + print "This scan type has not been implemented yet!" + sys.exit() + + else: + rotationStart=rotyMin + rotationStop=rotationStart + + print "Expected frame time " + str(ccdFrameTime) + " ms" + print "Angular scan: " + str(deltaRot) + " degrees" + print "Rotation speed (angle/s): " + str(math.fabs(rotySpeed)) + print "Base rotation speed (angle/s): " + str(baseRotySpeed) + print "Start position: " + str(rotationStart) + print "Acceleration angle: " + str(accelerationAngle) + print "End position: " + str(rotationStop) + + + ###################### Acquire dark images ################################# + + print "\033[1m" ## bold + print "Acquiring dark images" + print "\033[0m" ## back to normal + + print "Move to start position" + print "Move rotation axis to: " + str(rotationStart) + chROT_SVEL.putWait(baseRotySpeed) + moveRotationWait(rotationStart) + + # Closing filter for dark acquisition + if operationMode!=2: + if crystal1Pitch>-100: + print "Dump the beam by moving OP-FILTER 4 at -22.0 mm ..." + chOPFilter4.move(-22) + else: + print "Dump the beam by moving OP-FILTER 4 at -12.0 mm ..." + chOPFilter4.move(-12) + chOPFilter4.wait(poll=1) + else: + if crystal1Pitch>-100: + print "Dump the beam by moving OP-FILTER 4 at -22.0 mm ..." + else: + print "Dump the beam by moving OP-FILTER 4 at -12.0 mm ..." + + print "Wait for afterglow ..." + time.sleep(5) + print "Done!" + + # Set the channel of the tomography panel + chCameraStatus.putWait("Acquiring") + + # Clear buffer + chCCDCAM_CLEARMEM.putWait("CLEAR") + + print "Saving dark images 1-" + str(int(numberOfDarks)) + chCCDCAM_FILENR.putWait(1) + chCCDCAM_SAVESTART.putWait(1) + chCCDCAM_SAVESTOP.putWait(int(numberOfDarks)) + + # Triggering the CCD acquisition sequence + print "Send trigger to the camera" + snap_fifo() + + chCameraStatus.putWait("Idle") + print "Darks acquisition done!" + + print "Moving the sample out of beam ..." + chSampleX.move(xLinOut) + chSampleX.wait(poll=1) + + ##################### Start step scans ####################################### + + print "\033[1m" ## bold + print "Starting grating stepping" + print "\033[0m" ## back to normal + + # Opening the shutter + print "Moving up the filter OP-FILTER 4 at 0.0 mm ..." + if operationMode!=2: + chOPFilter4.move(0);chOPFilter4.wait(poll=1) + time.sleep(3) + + # Defining a loop to take a block of flats and a tomograph for each grating step + + iPhase=0 + while iPhase-100: + print "Dump the beam by moving OP_FILTER 4 to -22.0 mm ..." + chOPFilter4.move(-22);chOPFilter4.wait(poll=1) + else: + print "Dump the beam by moving OP_FILTER 4 to -12.0 mm ..." + chOPFilter4.move(-12);chOPFilter4.wait(poll=1) + else: + if crystal1Pitch>-100: + print "Dump the beam by moving OP_FILTER 4 to -22.0 mm ..." + else: + print "Dump the beam by moving OP_FILTER 4 to -12.0 mm ..." + + print "Set rotation speed back to " + str(baseRotySpeed) + #if rotationStage=="Aerotech": + chROT_STOP.putWait(0) + chROT_SVEL.putWait(baseRotySpeed) + + if rotationStage=="Micos": + chScanType.putWait(0) + print "Move Rotation to " + str(rotyMin) + moveRotationWait(rotyMin) + print "Moving the sample out of beam ..." + chSampleX.move(xLinOut);chSampleX.wait(poll=1) + + if operationMode==0: + chPiezo.move(gridStart) + chPiezo.wait(poll=1) + print "Moving grating to " + str(gridStart) + + chScanTimeToGo.putWait(0) + + if scanType=="7" and rotationStage=="Aerotech": + chBoxModeSelection.putWait("Custom") + chROT_GACC.putWait(rotationAcceleration) + chROT_DIRECT_MODE.putWait(1) + chCCDCAM_TRIGGER.putWait("auto trigger") + chROT_COUNTER.putWait(0) + + FILE = open(logFile,"a") + FILE.write("DPC-TOMOGRAPHIC SCAN FINISHED at " + str(time.asctime(time.localtime(time.time())))+"\n") + FILE.close() + + # Logging + tree = ET.parse(databaseFile) + sample = tree.getroot() + scan = sample.find("./pointOfInterest/scan") + endDate=ET.Element("endDate") + endDate.text=str(time.asctime(time.localtime(time.time()))) + scan.append(endDate) + tree.write(databaseFile) + + command = "cp " + logFile + " " + sampleTifPath + os.system(command) + command = "ln " + sampleTifPath + "/" + filePrefix + ".log " + logPath + os.system(command) + command = "rm " + logFile + os.system(command) + + if scanInterruption==0: + command = "curl -X PUT -H \"Content-Type: application/xml\" -d @\"" + databaseFile + "\" http://x02da-www-1:8080/ch.psi.epms.web/rs/epms/upload" + os.system(command) + command = "cp " + databaseFile + " " + sampleTifPath + os.system(command) + command = "ln " + sampleTifPath + "/" + filePrefix + ".xml " + logPath + os.system(command) + command = "rm " + databaseFile + os.system(command) + else: + chScanInterruption.putWait(1) + + print "Set STOREMODE and RECMODE back to Recorder and Ring Buffer (for preview purposes)" + chCCDCAM_STOREMODE.putWait("Recorder") + chCCDCAM_RECMODE.putWait("Ring Buffer") + chCCDCAM_SET_PARAM.putWait("SET") + print "Fifo mode OFF" + + # Set the scan status flag to Idle + chExperimentStatus.putWait("Idle") + chPause.putWait(0) + + +# ---------------------------------- Main --------------------------------------------- +global logFile,sampleTifPath,logPath,databaseFile,operationMode + +beamline="X02DA" + +''' +operationMode=0 Production mode +operationMode=1 Production mode during machine/shutdown +operationMode=2 Testing on second endstation during operation +''' + +operationMode=0 +standardChannelDefinition(operationMode) + +# Camera channel definition +usedServer=chServer.getw() +if usedServer==0: + cameraPrefix="CCDCAM" + SERVERNR="1" +elif usedServer==1: + cameraPrefix="CCDCAM2" + SERVERNR="2" +else: + print "Server " + str(usedServer) + " has not been implemented yet!" + sys.exit(0) +print "Used server: " + SERVERNR +cameraChannelDefinition(beamline,cameraPrefix) + +# Endstation definition +usedEndstation=chEndstation.getw() +if usedEndstation==0: + endstationPrefix="ES1" + rotationStage="Aerotech" +elif usedEndstation==1: + endstationPrefix="ES2" + rotationStage="Micos" +else: + print "Endstation " + str(usedEndstation) + " has not been implemented yet!" + sys.exit(0) +print "Used endstation: " + endstationPrefix +rotationStageDefinition(rotationStage,endstationPrefix,beamline) + +# Initialize +chGo.putWait(0) +chPause.putWait(0) +chExperimentStatus.putWait("Idle",req_type=ca.DBF_STRING) +chCameraStatus.putWait("Idle",req_type=ca.DBF_STRING) + +oldSamplename="Null" + +while (1): + + # Scan type + scanType=sys.argv[1] + + scango=chGo.getw() + + if scanType == "2": + print "\033[1m" ## bold + print "Fast Mode ON" + print "Waiting for your toggle on the panel to start the scan" + print "\033[0m" ## back to normal + elif scanType == "5": + print "\033[1m" ## bold + print "DPC Fast Mode ON" + print "Waiting for your toggle on the panel to start the scan" + print "\033[0m" ## back to normal + elif scanType == "6": + print "\033[1m" ## bold + print "Snap&Step Mode On" + print "Waiting for your toggle on the panel to start the scan" + print "\033[0m" ## back to normal + elif scanType == "7": + print "\033[1m" ## bold + print "DPC Snap&Step Mode On" + print "Waiting for your toggle on the panel to start the scan" + print "\033[0m" ## back to normal + elif scanType == "-h": + show_help() + else: + show_help() + + while scango!=1: + time.sleep(0.1) + scango=chGo.getw() + + # Stop camera if running and reset rotation stage features + chCCDCAM_CAMERA.putWait("OFF",req_type=ca.DBF_STRING) + if rotationStage=="Aerotech": + chBoxModeSelection.putWait("Custom") + chROT_SNAP_START.putWait(0) + chROT_SNAP_OFFSET.putWait(0) + chROT_DIRECT_MODE.putWait(1) + + # Scan interruption flag + chScanInterruption.putWait(0) + chComputeSinograms.putWait(0) + + # Filename prefix for ccd images + filePrefix=chFilePrefix.getw() + baseName=filePrefix + + # Sample ROI (for robot operation and stacked scans) + roi=chRoi.getw() + if roi=="": + roi="P1" # For database + filePrefix=baseName + else: + filePrefix=baseName+"_"+roi + + if filePrefix==oldSamplename: + print "\033[1m" ## bold + print "" + print "Current samplename is the same as the one of the previous scan!" + print "Please change the samplename and start the scan again." + print "" + print "\033[0m" ## back to normal + scanType="10" + oldSamplename=filePrefix + + # Check for empty spaces in the samplename + filePrefixList=filePrefix.split(" ") + if len(filePrefixList)>1: + print "\033[1m" ## bold + print "" + print "The samplename must not contain spaces!!!" + print "" + print "\033[0m" ## back to normal + scanType="10" + + chFilePrefix.putWait(filePrefix) + + # Exposure time (in s) + exposure=chExposure.getw() + chCCDCAM_EXPOSURE.putWait(exposure) + chCCDCAM_SET_PARAM.putWait("SET") + # Delay time (in s) + delayStart=chCCDCAM_DELAY.getw() + # Rotation scan values + rotyMin=chRotyMin.getw() + rotyMax=chRotyMax.getw() + rotationAxisPosition=chRotationAxisPosition.getw(ca.DBF_STRING) + + # Region of interest + ccdXStart=chCCDCAM_REGIONX_START.getw() + ccdXEnd=chCCDCAM_REGIONX_END.getw() + ccdYStart=chCCDCAM_REGIONY_START.getw() + ccdYEnd=chCCDCAM_REGIONY_END.getw() + + # Values for in and out of beam position + xLinIn=chXLinIn.getw() + xLinOut=chXLinOut.getw() + + # Number of darks + numberOfDarks=chNumberOfDarks.getw() + # Number of flats + numberOfFlats=chNumberOfFlats.getw() + # Number of projections + numberOfProjections=chNumberOfProjections.getw() + + if math.fabs(rotyMax-rotyMin)==360: + if numberOfProjections%2==0 and rotationAxisPosition!="Standard": + print "\033[1m" ## bold + print "" + print "360 degrees stiched scan: an odd number of projections is required" + print "The number of projections has been incremented by 1" + print "" + print "\033[0m" ## back to normal + numberOfProjections=numberOfProjections+1 + print "Number of projections " + str(numberOfProjections) + chNumberOfProjections.putWait(numberOfProjections) + if numberOfProjections%2!=0 and rotationAxisPosition=="Standard": + print "\033[1m" ## bold + print "" + print "360 degrees standard scan: an even number of projections is required" + print "The number of projections has been incremented by 1" + print "" + print "\033[0m" ## back to normal + numberOfProjections=numberOfProjections+1 + print "Number of projections " + str(numberOfProjections) + chNumberOfProjections.putWait(numberOfProjections) + + # Sample coordinatesLog + sampleX=chSampleX.get_position(dial=1) + sampleY=chSampleY.getw() + sampleZ=chSampleZ.get_position(dial=1) + sampleXX=chSampleXX.get_position(dial=1) + sampleZZ=chSampleZZ.get_position(dial=1) + + # Microscope coordinates + microscopeX=chMicroscopeX.get_position(dial=1) + microscopeY=chMicroscopeY.get_position(dial=1) + microscopeZ=chMicroscopeZ.get_position(dial=1) + + # For DPC + if scanType=="5" or scanType=="7": + piezoOffset=50 + piezoCalibration=1.0 + # Grid start point + gridStartRaw=chGridStartRaw.getw() + gridEndRaw=chGridEndRaw.getw() + gridStart=(gridStartRaw*piezoCalibration)+piezoOffset + gridEnd=(gridEndRaw-gridStartRaw)*piezoCalibration+gridStart + gridNSteps=chGridNSteps.getw() + gridNPeriods=chGridNPeriods.getw() + + if scanType=="6" or scanType=="7": + triggerDelay=chTriggerDelay.getw() + if rotationStage=="Aerotech": + chROT_STAB_TIME.putWait(triggerDelay) + elif rotationStage=="Micos": + chSystemOffset.putWait(triggerDelay) + + millisecondShutter=chMillisecondShutter.getw(req_type=ca.DBF_STRING) + + # Read user id + userID=chUserID.getw() + + # Read machine and beamline parameters + if operationMode==0: + ringCurrentStart=chRingCurrentStatus.getw() + else: + ringCurrentStart=chRingCurrentStartFake.getw() + if ringCurrentStart<10: + print "\033[1m" ## bold + print "" + print "Ring current is too low to start a scan!!" + print "" + print "\033[0m" ## back to normal + chGo.putWait(0) + scanType="10" + + # Energy + crystal1Pitch=chCrystal1Pitch.get_position() + if crystal1Pitch>-100: + beamEnergy="Polychromatic radiation" + else: + beamEnergy=chBeamEnergy.getw() + stripe=chStripe.getw(req_type=ca.DBF_STRING) + + # Filters + FEFilter=chFEFilter.getw(req_type=ca.DBF_STRING) + OPFilter1=chOPFilter1.getw(req_type=ca.DBF_STRING) + OPFilter2=chOPFilter2.getw(req_type=ca.DBF_STRING) + OPFilter3=chOPFilter3.getw(req_type=ca.DBF_STRING) + + # Read detector parameters + camera=chCamera.getw(req_type=ca.DBF_STRING) + microscope=chMicroscope.getw(req_type=ca.DBF_STRING) + magnification=chMagnification.getw() + scintillator=chScintillator.getw() + pixelSize=chPixelSize.getw() + + # Path variables + storage=chStorage.getw() + + # Define the temporary path for logging + loggingBasePath="/sls/X02DA/data/e" + userID + "/public/" + logFile=loggingBasePath + filePrefix + ".log" + databaseFile=loggingBasePath + filePrefix + ".xml" + + # Sample path + sampleBasePath="/sls/X02DA/data/e" + userID + "/" + storage + "/" + filePrefix + "/" + sampleTifPath=sampleBasePath + "tif" + + # Log path + logPath="/sls/X02DA/data/e" + userID + "/" + storage + "/log" + + # Folder name for Camera Server X:// is hardcoded!!! + folderName="X:/" + storage + "/" + filePrefix + "/tif/\0" + if len(folderName)>255: + print "\033[1m" ## bold + print "" + print "The samplename is too long!!" + print "" + print "\033[0m" ## back to normal + scanType="10" + + if scanType!="10": + if os.path.isdir(logPath): + pass + else: + os.mkdir(logPath) + if os.path.isdir(sampleBasePath): + print "\033[1m" ## bold + print "" + print "The samplename " + filePrefix + " already exist!!" + print "" + print "\033[0m" ## back to normal + scanType="10" + else: + os.mkdir(sampleBasePath) + if os.path.isdir(sampleTifPath): + pass + else: + os.mkdir(sampleTifPath) + + if scanType!="10": + + print "User ID : e" + str(userID) + if scanType=="2": + print "FAST-TOMO scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + elif scanType=="5" or scanType=="7": + print "DPC scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + else: + print "SNAP&STEP-TOMO scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + + print "--------------------Beamline Settings-------------------------" + print "Ring current [mA] : %3.3f" % ringCurrentStart + if crystal1Pitch>-100: + print "Beam energy : " + str(beamEnergy) + else: + print "Beam energy [keV] : %2.3f" % beamEnergy + print "Monostripe : " + str(stripe) + print "FE-Filter : " + str(FEFilter) + print "OP-Filter 1 : " + str(OPFilter1) + print "OP-Filter 2 : " + str(OPFilter2) + print "OP-Filter 3 : " + str(OPFilter3) + print "--------------------Detector Settings-------------------------" + print "Camera : " + str(camera) + print "Microscope : " + str(microscope) + print "Magnification : " + str(magnification) + print "Scintillator : " + str(scintillator) + print "Exposure time [ms] : " + str(exposure) + if scanType=="2" or scanType=="5": + print "Delay time [ms] : " + str(delayStart) + if (scanType=="6" or scanType=="7") and rotationStage=="Aerotech": + stabilizationTime=chROT_STAB_TIME.getw() + print "Stabilization time [ms] : " + str(stabilizationTime) + + if millisecondShutter=="IOC-Ctrl": + print "Millisecond shutter : not used" + else: + print "Millisecond shutter : used" + print "X-ROI : " + str(int(ccdXStart)) + " - " +str(int(ccdXEnd)) + print "Y-ROI : " + str(int(ccdYStart)) + " - " +str(int(ccdYEnd)) + print "Actual pixel size [um] : " + str(pixelSize) + print "------------------------Scan Settings-------------------------" + print "Sample folder : " + str(sampleBasePath) + print "File Prefix : " + str(filePrefix) + print "Number of projections : " + str(int(numberOfProjections)) + print "Number of darks : " + str(int(numberOfDarks)) + print "Number of flats : " + str(int(numberOfFlats)) + print "Number of inter-flats : 0" + print "Flat frequency : 0" + print "Rot Y min position [deg] : " + str(rotyMin) + print "Rot Y max position [deg] : " + str(rotyMax) + print "Rotation axis position : " + str(rotationAxisPosition) + if numberOfProjections!=0: + print "Angular step [deg] : " + str((rotyMax-rotyMin)/(numberOfProjections-1)) + else: + print "Angular step [deg] : 0" + print "Sample In [um] : " + str(xLinIn) + print "Sample Out [um] : " + str(xLinOut) + print "-----------------------Sample coordinates---------------------" + print "X-coordinate : " + str(sampleX) + print "Y-coordinate : " + str(sampleY) + print "Z-coordinate : " + str(sampleZ) + print "XX-coordinate : " + str(sampleXX) + print "ZZ-coordinate : " + str(sampleZZ) + print "-----------------------Microscope coordinates---------------------" + print "X-coordinate : " + str(microscopeX) + print "Y-coordinate : " + str(microscopeY) + print "Z-coordinate : " + str(microscopeZ) + if scanType=="5" or scanType=="7": + print "--------------------Interferometer Settings-------------------" + print "Grid start position [um] : " + str(gridStartRaw) + print "Grid end position [um] : " + str(gridEndRaw) + print "Grid step : " + str(gridNSteps) + print "Grid period : " + str(gridNPeriods) + print "--------------------------------------------------------------" + + + FILE = open(logFile,"a") + FILE.write("User ID : e" + userID + "\n") + if scanType=="2": + FILE.write("FAST-TOMO scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + "\n") + elif scanType=="5" or scanType=="7": + FILE.write("DPC-TOMO scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + "\n") + else: + FILE.write("SNAP&STEP-TOMO scan of sample " + filePrefix + " started on " + str(time.asctime(time.localtime(time.time()))) + "\n") + FILE.write("--------------------Beamline Settings-------------------------\n") + FILE.write("Ring current [mA] : %3.3f\n" % ringCurrentStart) + if crystal1Pitch>-100: + FILE.write("Beam energy : " + beamEnergy + "\n") + else: + FILE.write("Beam energy [keV] : %2.3f\n" % beamEnergy) + FILE.write("Monostripe : " + str(stripe) + "\n") + FILE.write("FE-Filter : " + str(FEFilter) + "\n") + FILE.write("OP-Filter 1 : " + str(OPFilter1) + "\n") + FILE.write("OP-Filter 2 : " + str(OPFilter2) + "\n") + FILE.write("OP-Filter 3 : " + str(OPFilter3) + "\n") + FILE.write("--------------------Detector Settings-------------------------\n") + FILE.write("Camera : " + str(camera) + "\n") + FILE.write("Microscope : " + str(microscope) + "\n") + FILE.write("Magnification : " + str(magnification) + "\n") + FILE.write("Scintillator : " + str(scintillator) + "\n") + FILE.write("Exposure time [ms] : " + str(exposure) + "\n") + if scanType=="2" or scanType=="5": + FILE.write("Delay time [ms] : " + str(delayStart) + "\n") + if (scanType=="6" or scanType=="7") and rotationStage=="Aerotech": + FILE.write("Stabilization time [ms] : " + str(stabilizationTime) + "\n") + if millisecondShutter=="IOC-Ctrl": + FILE.write("Millisecond shutter [ms] : not used\n") + else: + FILE.write("Millisecond shutter [ms] : used\n") + FILE.write("X-ROI : " + str(int(ccdXStart)) + " - " + str(int(ccdXEnd)) + "\n") + FILE.write("Y-ROI : " + str(int(ccdYStart)) + " - " + str(int(ccdYEnd)) + "\n") + FILE.write("Actual pixel size [um] : " + str(pixelSize) + "\n") + FILE.write("------------------------Scan Settings-------------------------\n") + FILE.write("Sample folder : " + sampleBasePath + "\n") + FILE.write("File Prefix : " + str(filePrefix) + "\n") + FILE.write("Number of projections : " + str(int(numberOfProjections)) + "\n") + FILE.write("Number of darks : " + str(int(numberOfDarks)) + "\n") + FILE.write("Number of flats : " + str(int(numberOfFlats)) + "\n") + FILE.write("Number of inter-flats : 0\n") + FILE.write("Flat frequency : 0\n") + FILE.write("Rot Y min position [deg] : " + str(rotyMin) + "\n") + FILE.write("Rot Y max position [deg] : " + str(rotyMax) + "\n") + FILE.write("Rotation axis position : " + str(rotationAxisPosition) + "\n") + if numberOfProjections!=0: + FILE.write("Angular step [deg] : %3.3f\n" % ((rotyMax-rotyMin)/(numberOfProjections-1))) + else: + FILE.write("Angular step [deg] : 0") + FILE.write("Sample In [um] : %5.0f\n" % xLinIn) + FILE.write("Sample Out [um] : %5.0f\n" % xLinOut) + FILE.write("-----------------------Sample coordinates---------------------\n") + FILE.write("X-coordinate : %5.2f\n" % sampleX) + FILE.write("Y-coordinate : %5.2f\n" % sampleY) + FILE.write("Z-coordinate : %5.2f\n" % sampleZ) + FILE.write("XX-coordinate : %5.2f\n" % sampleXX) + FILE.write("ZZ-coordinate : %5.2f\n" % sampleZZ) + FILE.write("-----------------------Microscope coordinates---------------------\n") + FILE.write("X-coordinate : %5.2f\n" % microscopeX) + FILE.write("Y-coordinate : %5.2f\n" % microscopeY) + FILE.write("Z-coordinate : %5.2f\n" % microscopeZ) + if scanType=="5" or scanType=="7": + FILE.write("--------------------Interferometer Settings-------------------\n") + FILE.write("Grid start position [um] : " + str(gridStartRaw) + "\n") + FILE.write("Grid end position [um] : " + str(gridEndRaw) + "\n") + FILE.write("Grid step : " + str(int(gridNSteps)) + "\n") + FILE.write("Grid period : " + str(int(gridNPeriods)) + "\n") + FILE.write("--------------------------------------------------------------\n") + FILE.close() + + # Write xml file + sample=ET.Element("sample") + name=ET.SubElement(sample,"name") + name.text=baseName + userid=ET.SubElement(sample,"userid") + userid.text="e" + str(userID) + pointOfInterest=ET.SubElement(sample,"pointOfInterest") + name1=ET.SubElement(pointOfInterest,"name") + name1.text=roi + coordinates=ET.SubElement(pointOfInterest,"coordinates") + x=ET.SubElement(coordinates,"x") + x.text=str('{0:.2f}'.format(sampleX)) + y=ET.SubElement(coordinates,"y") + y.text=str('{0:.2f}'.format(sampleY)) + z=ET.SubElement(coordinates,"z") + z.text=str('{0:.2f}'.format(sampleZ)) + xx=ET.SubElement(coordinates,"xx") + xx.text=str('{0:.2f}'.format(sampleXX)) + zz=ET.SubElement(coordinates,"zz") + zz.text=str('{0:.2f}'.format(sampleZZ)) + coordinateSystem=ET.SubElement(coordinates,"coordinateSystem") + coordinateSystem.text="beamline" + scan=ET.SubElement(pointOfInterest,"scan") + scanTYPE=ET.SubElement(scan,"scanType") + if scanType=="2": + scanTYPE.text="FAST-TOMO" + elif scanType=="6": + scanTYPE.text="SNAP-AND-STEP-TOMO" + else: + scanTYPE.text="DPC-TOMO" + startDate=ET.SubElement(scan,"startDate") + startDate.text=str(time.asctime(time.localtime(time.time()))) + beamlineParameters=ET.SubElement(scan,"beamlineParameters") + parameter=ET.SubElement(beamlineParameters,"parameter") + parameter.text=str('{0:.3f}'.format(ringCurrentStart)) + parameter.set('name','Ring current') + parameter.set('unit','mA') + parameter1=ET.SubElement(beamlineParameters,"parameter") + if crystal1Pitch>-100: + parameter1.text=beamEnergy + parameter1.set('name','Beam energy') + else: + parameter1.text=str('{0:.3f}'.format(beamEnergy)) + parameter1.set('name','Beam energy') + parameter1.set('unit','keV') + parameter2=ET.SubElement(beamlineParameters,"parameter") + parameter2.text=stripe + parameter2.set('name','Monostripe') + parameter3=ET.SubElement(beamlineParameters,"parameter") + parameter3.text=FEFilter + parameter3.set('name','FE-Filter') + parameter4=ET.SubElement(beamlineParameters,"parameter") + parameter4.text=OPFilter1 + parameter4.set('name','OP-Filter1') + parameter5=ET.SubElement(beamlineParameters,"parameter") + parameter5.text=OPFilter2 + parameter5.set('name','OP-Filter2') + parameter6=ET.SubElement(beamlineParameters,"parameter") + parameter6.text=OPFilter3 + parameter6.set('name','OP-Filter3') + detectorParameters=ET.SubElement(scan,"detectorParameters") + parameter7=ET.SubElement(detectorParameters,"parameter") + parameter7.text=camera + parameter7.set('name','Camera') + parameter8=ET.SubElement(detectorParameters,"parameter") + parameter8.text=microscope + parameter8.set('name','Microscope') + parameter9=ET.SubElement(detectorParameters,"parameter") + parameter9.text=str(magnification) + parameter9.set('name','Objective') + parameter10=ET.SubElement(detectorParameters,"parameter") + parameter10.text=scintillator + parameter10.set('name','Scintillator') + parameter11=ET.SubElement(detectorParameters,"parameter") + parameter11.text=str(int(exposure)) + parameter11.set('name','Exposure time') + parameter11.set('unit','ms') + if scanType=="2" or scanType=="5": + parameter12=ET.SubElement(detectorParameters,"parameter") + parameter12.text=str(int(delayStart)) + parameter12.set('name','Delay time') + parameter12.set('unit','ms') + if (scanType=="6" or scanType=="7") and rotationStage=="Aerotech": + parameter12a=ET.SubElement(detectorParameters,"parameter") + parameter12a.text=str(int(stabilizationTime)) + parameter12a.set('name','Stabilization time') + parameter12a.set('unit','ms') + if millisecondShutter=="IOC-Ctrl": + parameter13=ET.SubElement(detectorParameters,"parameter") + parameter13.text="not used" + parameter13.set('name','Millisecond shutter') + else: + parameter13=ET.SubElement(detectorParameters,"parameter") + parameter13.text="used" + parameter13.set('name','Millisecond shutter') + parameter14=ET.SubElement(detectorParameters,"parameter") + parameter14.text=str(int(ccdXStart)) + parameter14.set('name','X-ROI Start') + parameter15=ET.SubElement(detectorParameters,"parameter") + parameter15.text=str(int(ccdXEnd)) + parameter15.set('name','X-ROI End') + parameter16=ET.SubElement(detectorParameters,"parameter") + parameter16.text=str(int(ccdYStart)) + parameter16.set('name','Y-ROI Start') + parameter17=ET.SubElement(detectorParameters,"parameter") + parameter17.text=str(int(ccdYEnd)) + parameter17.set('name','Y-ROI End') + parameter18=ET.SubElement(detectorParameters,"parameter") + parameter18.text=str('{0:.2f}'.format(pixelSize)) + parameter18.set('name','Actual pixel size') + parameter18.set('unit','um') + parameter18a=ET.SubElement(detectorParameters,"parameter") + parameter18a.text=str('{0:.2f}'.format(microscopeX)) + parameter18a.set('name','Microscope x position') + parameter18a.set('unit','mm') + parameter18b=ET.SubElement(detectorParameters,"parameter") + parameter18b.text=str('{0:.2f}'.format(microscopeY)) + parameter18b.set('name','Microscope y position') + parameter18b.set('unit','mm') + parameter18b=ET.SubElement(detectorParameters,"parameter") + parameter18b.text=str('{0:.2f}'.format(microscopeZ)) + parameter18b.set('name','Microscope z position') + parameter18b.set('unit','mm') + scanParameters=ET.SubElement(scan,"scanParameters") + parameter19=ET.SubElement(scanParameters,"parameter") + parameter19.text=sampleBasePath + parameter19.set('name','Sample folder') + parameter20=ET.SubElement(scanParameters,"parameter") + parameter20.text=filePrefix + parameter20.set('name','File Prefix') + parameter21=ET.SubElement(scanParameters,"parameter") + parameter21.text=str(int(numberOfProjections)) + parameter21.set('name','Number of projections') + parameter22=ET.SubElement(scanParameters,"parameter") + parameter22.text=str(int(numberOfDarks)) + parameter22.set('name','Number of darks') + parameter23=ET.SubElement(scanParameters,"parameter") + parameter23.text=str(int(numberOfFlats)) + parameter23.set('name','Number of flats') + parameter24=ET.SubElement(scanParameters,"parameter") + parameter24.text="0" + parameter24.set('name','Number of inter-flats') + parameter24=ET.SubElement(scanParameters,"parameter") + parameter24.text="0" + parameter24.set('name','Flat frequency') + parameter18=ET.SubElement(scanParameters,"parameter") + parameter18.text=str('{0:.3f}'.format(rotyMin)) + parameter18.set('name','Rot Y min position') + parameter18.set('unit','deg') + parameter19=ET.SubElement(scanParameters,"parameter") + parameter19.text=str('{0:.3f}'.format(rotyMax)) + parameter19.set('name','Rot Y max position') + parameter19a=ET.SubElement(scanParameters,"parameter") + parameter19a.text=str(rotationAxisPosition) + parameter19a.set('name','Rotation axis position') + if numberOfProjections!=0: + parameter20=ET.SubElement(scanParameters,"parameter") + parameter20.text=str('{0:.3f}'.format((rotyMax-rotyMin)/(numberOfProjections-1))) + parameter20.set('name','Angular step') + parameter20.set('unit','deg') + else: + parameter20=ET.SubElement(scanParameters,"parameter") + parameter20.text="0" + parameter20.set('name','Angular step') + parameter20.set('unit','deg') + parameter21=ET.SubElement(scanParameters,"parameter") + parameter21.text=str(int(xLinIn)) + parameter21.set('name','Sample In') + parameter21.set('unit','um') + parameter22=ET.SubElement(scanParameters,"parameter") + parameter22.text=str(int(xLinOut)) + parameter22.set('name','Sample Out') + parameter22.set('unit','um') + if scanType=="5" or scanType=="7": + parameter23=ET.SubElement(scanParameters,"parameter") + parameter23.text=str('{0:.3f}'.format(gridStartRaw)) + parameter23.set('name','Grid start position') + parameter23.set('unit','um') + parameter24=ET.SubElement(scanParameters,"parameter") + parameter24.text=str('{0:.3f}'.format(gridEndRaw)) + parameter24.set('name','Grid end position') + parameter24.set('unit','um') + parameter25=ET.SubElement(scanParameters,"parameter") + parameter25.text=str(int(gridNSteps)) + parameter25.set('name','Grid step') + parameter26=ET.SubElement(scanParameters,"parameter") + parameter26.text=str(int(gridNPeriods)) + parameter26.set('name','Grid period') + + # Wrap it in an ElementTree instance, and save as XML + tree=ET.ElementTree(sample) + tree.write(databaseFile) + chCCDCAM_FILENAME.putWait(filePrefix + "\0",req_type=ca.DBF_CHAR) + chCCDCAM_FILEPATH.putWait(folderName,req_type=ca.DBF_CHAR) + filepathSevr=chCCDCAM_FILEPATHSEVR.getw() + filepathStat=chCCDCAM_FILEPATHSTAT.getw() + while filepathSevr!=0 or filepathStat!=0: + print "I am setting the filepath again" + print filepathSevr + print filepathStat + chCCDCAM_FILEPATH.putWait(folderName,req_type=ca.DBF_CHAR) + filepathSevr=chCCDCAM_FILEPATHSEVR.getw() + filepathStat=chCCDCAM_FILEPATHSTAT.getw() + + # Make the scan + if scanType=="2" or scanType=="6": + fasttomoscan(rotyMin,rotyMax,numberOfProjections,exposure,xLinIn,xLinOut,numberOfDarks,numberOfFlats,crystal1Pitch,scanType,millisecondShutter,rotationStage) + else: + fastdpcscan(rotyMin,rotyMax,numberOfProjections,exposure,xLinIn,xLinOut,numberOfDarks,numberOfFlats,gridStart,gridEnd,gridNSteps,crystal1Pitch,scanType,millisecondShutter,rotationStage) + + # Set the scan start button to Stop + chGo.putWait(0) + chFilePrefix.putWait(baseName) + chCCDCAM_DELAY.putWait(delayStart) diff --git a/script/tools/save_snapshot_mult.py b/script/tools/save_snapshot_mult.py new file mode 100755 index 0000000..59c38cf --- /dev/null +++ b/script/tools/save_snapshot_mult.py @@ -0,0 +1,137 @@ +import ch.psi.pshell.imaging.ImageBuffer as ImageBuffer +import java.math.BigInteger as BigInteger +import org.python.core.PyLong as PyLong +import org.python.core.PyFloat as PyFloat +import json +import traceback +import datetime + +PARALLELIZE = True + +if get_exec_pars().source == CommandSource.ui: + camera_name = "simulation_sp" + shared = False + images = 10 + interval = -1 + roi = "" #"[540, 200, 430,100]" +else: + camera_name = args[0] + shared = args[1].lower() == "true" + images = int(args[2]) + interval = int(args[3]) + roi = args[4] + + +set_exec_pars(name="camera_snapshot") +path_image = "/image" +path_pid = "/pulse_id" +path_timestamp_str = "/timestamp_str" +snapshotFile = None + + +cam_server.start(camera_name, shared) + + + +if roi is not None and len(roi.strip())>0: + roi = json.loads(roi) + cam_server.setRoi(roi[0], roi[2], roi[1], roi[3]) + while True: + cam_server.waitNext(10000) + r = json.loads(cam_server.stream.take()["processing_parameters"]) + if roi == r["image_region_of_interest"]: + break; +else: + cam_server.waitNext(10000) + +width = cam_server.data.width +height = cam_server.data.height +type_image = 'f' + +def create_tables(stream_value): + global width, height, type_image + create_dataset(path_image, type_image, dimensions = [images, height, width]) + create_dataset(path_pid, 'l', dimensions = [images]) + create_dataset(path_timestamp_str, 's', dimensions = [images]) + for id in stream_value.identifiers: + val = stream_value.getValue(id) + if id == "image": + pass + elif id == "processing_parameters": + val = json.loads(val) + for key in val.keys(): + set_attribute(path_image, key, "" if val[key] is None else val[key] ) + elif isinstance(val, PyArray): + create_dataset("/"+id, 'd', dimensions = [images, len(val)]) + elif isinstance(val, PyLong): + create_dataset("/"+id, 'l', dimensions = [images]) + elif isinstance(val, PyFloat): + create_dataset("/"+id, 'd', dimensions = [images]) + else: + print "Unmanaged stream type: ", val, type(val) + pass + + +def append_frame(data, stream_value, index): + global path_image, width, height, type_image + print "Saving frame :", index + #append_dataset(path_image, data, index, type = type_image) + append_dataset(path_image, stream_value.getValue("image"),[index,0,0], type = type_image, shape=[1, height, width]) + append_dataset(path_pid, stream_value.getPulseId(), index) + append_dataset(path_timestamp_str, datetime.datetime.fromtimestamp(stream_value.timestampNanos/1e9).strftime('%Y-%m-%d %H:%M:%S'), index) + + for id in stream_value.identifiers: + try: + val = stream_value.getValue(id) + if id == "image": + pass + elif isinstance(val, PyArray): + append_dataset("/"+id, val, index) + elif isinstance(val, PyLong): + append_dataset("/"+id, int(val), index) + elif isinstance(val, PyFloat): + append_dataset("/"+id, float(val), index) + else: + pass + except: + print id, val + traceback.print_exc() + + print "Saved frame :", index + + +tasks = [] +cam_server.paused = True + +try: + for i in range(images): + if i==0: + create_tables(cam_server.stream.take()) + + start = time.time() + stream_value = cam_server.stream.take() + if PARALLELIZE: + tasks.extend( fork((append_frame,(cam_server.data.matrix,stream_value, i)),) ) + else: + append_frame(cam_server.data.matrix, stream_value, i) + + if i< (images-1): + if interval<=0: + cam_server.stream.waitCacheChange(10000) + else: + sleep_time = float(interval)/1000.0 - (time.time()-start) + time.sleep(max(sleep_time,0)) +finally: + cam_server.paused = False + pass + +print "Waiting finish persisting..." +join(tasks) +print "Done" + + +#Enforce the same timestamp to data & image files. +set_exec_pars(open = False) +data_file = get_exec_pars().path + +set_return(data_file) \ No newline at end of file diff --git a/script/tst3.js b/script/tst3.js new file mode 100755 index 0000000..57116ca --- /dev/null +++ b/script/tst3.js @@ -0,0 +1,36 @@ + +function is_java_array(obj){ + return !Array.isArray(obj) && obj.class.isArray() +} + +function is_java_list(obj){ + return obj instanceof java.util.List +} + + + +print(is_java_array(v)) +print(is_java_array(a)) +print(is_java_array(r)) + +function flatten(arr) { + var ret = []; + if (is_java_list(arr)){ + arr = to_array(arr) + } else if (is_java_array(arr)) { + arr = Java.from(arr); + } + + for(var i = 0; i < arr.length; i++) { + if((is_java_list(arr[i])) || (is_java_array(arr[i]))) { + ret = ret.concat(flatten(arr[i])); + } else { + ret.push(arr[i]); + } + } + return ret; +} + + + +r = flatten(a) \ No newline at end of file diff --git a/script/tst3.py b/script/tst3.py new file mode 100755 index 0000000..092beb5 --- /dev/null +++ b/script/tst3.py @@ -0,0 +1,37 @@ + +function is_java_array(obj){ + return !Array.isArray(obj) && obj.class.isArray() +} + +function is_java_list(obj){ + return obj instanceof java.util.List +} + + +v=2 + +print(is_java_array(v)) +print(is_java_array(a)) +print(is_java_array(r)) + +function flatten(arr) { + var ret = []; + if (is_java_list(arr)){ + arr = to_array(arr) + } else if (is_java_array(arr)) { + arr = Java.from(arr); + } + + for(var i = 0; i < arr.length; i++) { + if((is_java_list(arr[i])) || (is_java_array(arr[i]))) { + ret = ret.concat(flatten(arr[i])); + } else { + ret.push(arr[i]); + } + } + return ret; +} + + + +r = flatten(a) \ No newline at end of file diff --git a/script/tst4.js b/script/tst4.js new file mode 100755 index 0000000..c293e75 --- /dev/null +++ b/script/tst4.js @@ -0,0 +1,79 @@ + +function histogram(data, range_min, range_max, bin){ + + /* + Creates histogram on data. + + Args: + data (tuple, array, ArrayList or Array): input data can be multi-dimensional or nested. + range_min (int, optional): minimum histogram value. Default is floor(min(data)) + range_max (int, optional): maximul histogram value. Default is ceil(max(data)) + bin(int or float, optional): if int means number of bins. If float means bin size. Default = 1.0. + Returns: + tuple: (ydata, xdata) + + */ + flat = flatten(data) + if (!is_defined(range_min)) range_max = null + if (!is_defined(range_max)) range_max = null + if (!is_defined(bin)) bin = 1.0 + if (range_min == null) range_min = Math.floor(Math.min.apply(null,flat)) + if (range_max == null) range_max = Math.ceil(Math.max.apply(null,flat)) + + print("Min "+ range_min) + print("Max "+ range_max) + if (is_float(bin)){ + + bin_size = bin + n_bin = Math.ceil((range_max - range_min)/bin_size) + print(bin_size) + print( n_bin) + } + else{ + n_bin = bin + bin_size = (range_max - range_min)/bin + } + + print("n_bin" + n_bin)// + print("bin_size" + bin_size) + + result = []; size=n_bin; while(size--) result.push(0) + + for (d in flat){ + b = Math.floor( (flat[d] - range_min) / bin_size) + if ((b >=0) && (b < n_bin)){ + result[b] = result[b] + 1 + } + } + + result_x = []; size=result.length; p=range_min; while(size--) {result_x.push(p); p+=bin_size } + + return [result,result_x] +} + + + h = histogram(data=im1.read(), undefined, undefined, bin=0.1) + hd=h[0]; xd = h[1] + /* + image = Utils.grayscale(src1.getOutput()) + data = Convert.toUnsigned(image.getData().getDataBuffer().getData()) + h = histogram(data, range_min=0, range_max=255) + hi=h[0]; xi = h[1] + + if (plots == null){ + plots = plot((hd,hi), ("Data", "Image"), (xd, xi), title = "Histo") + } else{ + plots[0].getSeries(0).setData(xd,hd) + plots[1].getSeries(0).setData(xi,hi) + } + if (plots[0].displayable == false){ + abort() + } + + ov_cross.update(new Point((ov_cross.position.x+1) % size.width ,(ov_cross.position.y+1) % size.height)) + + sleep(0.1) +*/ + +print (hd.length) +print (xd.length) \ No newline at end of file diff --git a/script/tst_convolve.js b/script/tst_convolve.js new file mode 100755 index 0000000..3171f7d --- /dev/null +++ b/script/tst_convolve.js @@ -0,0 +1,22 @@ + +run("ijutils") + +//Image Loading +ip = load_image("images/img.png", title="Image") + +aux = grayscale(ip, in_place = false) + +create_stack([ aux, + + convolve(aux, KERNEL_BLUR, false), + convolve(aux, KERNEL_SHARPEN, false), + convolve(aux, KERNEL_SHARPEN_2, false), + + convolve(aux, KERNEL_LIGHT, false), + convolve(aux, KERNEL_DARK, false), + convolve(aux, KERNEL_EDGE_DETECT, false), + convolve(aux, KERNEL_EDGE_DETECT_2, false), + convolve(aux, KERNEL_DIFFERENTIAL_EDGE_DETECT, false), + convolve(aux, KERNEL_PREWITT, false), + convolve(aux, KERNEL_SOBEL, false) + ], undefined, title = "General Operations").show() diff --git a/script/tstabort.js b/script/tstabort.js new file mode 100755 index 0000000..2409ba9 --- /dev/null +++ b/script/tstabort.js @@ -0,0 +1,16 @@ +run("ijutils") + +//Image Loading +ip = load_image("images/img.png", title="Image") + +//Basic image manipulation: creation, copying, padding, saving +resized = resize(ip, 300,300) +save_image(resized, get_context().setup.expandPath("{images}/resized.tiff") ,"tiff") +crop=sub_image(ip,10,20,50,30) +bin_im = binning(ip,2) +new_im = new_image(256, 256, "color") +copy_image_to(bin_im, new_im, 20, 20) +pad_im = pad_image(ip, 1, 2, 3, 4, Color.RED) +stack=create_stack([ip,resized,crop, bin_im, new_im, pad_im], undefined, title = "Basic Functions") +save_image(stack, get_context().setup.expandPath("{images}/stack.tiff") ,"tiff") +stack.show() diff --git a/script/tstdebug.js b/script/tstdebug.js new file mode 100755 index 0000000..480d9e2 --- /dev/null +++ b/script/tstdebug.js @@ -0,0 +1,9 @@ + +var filter = new MyFilter() { + process: function (image, data) { + return image + }, + } + +//Setting the filter to a source +src2.setFilter(filter) \ No newline at end of file diff --git a/script/tstplot.js b/script/tstplot.js new file mode 100755 index 0000000..64f4990 --- /dev/null +++ b/script/tstplot.js @@ -0,0 +1,67 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Function fitting and peak search with mathutils.py +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +run("mathutils") + + +start = 0 +end = 10 +step_size = 0.1 + +result= lscan(ao1,ai1,start,end,[step_size,],0.01) + +readable = result.getReadable(0) +positions = result.getPositions(0) + +function get_function_data(func, start, end, resolution){ + ret = [] + for (var x=start; x<=end; x+=resolution){ + fit_polinomial.push(func.value(x)) + } +} + + +pars_polynomial = fit_polynomial(readable, positions, 6) + //(a0, a1, a2, a3, a4, a5, a6) +fitted_polynomial_function = new PolynomialFunction(pars_polynomial) +print (pars_polynomial) + +pars_gaussian = fit_gaussian(readable, positions) +normalization = pars_gaussian[0] +mean_val = pars_gaussian[1] +sigma = pars_gaussian [2] +fitted_gaussian_function = new Gaussian(normalization, mean_val, sigma) +print (normalization + " " + mean_val + " " + sigma) + +pars_harmonic= fit_harmonic(readable, positions) +amplitude = pars_harmonic[0] +angular_frequency = pars_harmonic[1] +phase = pars_harmonic[2] +fitted_harmonic_function = new HarmonicOscillator(amplitude, angular_frequency, phase) +print (amplitude+ " " + angular_frequency+ " " + phase) + + +resolution = step_size/100 +fit_polinomial = [] +fit_gaussian = [] +fit_harmonic = [] +for (var x=start; x<=end; x+=resolution){ + fit_polinomial.push(fitted_polynomial_function.value(x)) + fit_gaussian.push(fitted_gaussian_function.value(x)) + fit_harmonic.push(fitted_harmonic_function.value(x)) +} +fx = range(start, end+resolution, resolution) + +peaks = calculate_peaks(fitted_polynomial_function, start, end) + +plots = plot([readable, fit_polinomial, fit_gaussian, fit_harmonic] , + ["data", "polinomial", "gaussian", "harmonic"], xdata = [positions,fx,fx,fx], ydata=undefined, title="Data") + +for (var p in peaks){ + print ("Max: " + p) + plots[0].addMarker(p, null, "Max=" + Math.round(p,2), Color.LIGHT_GRAY) +} + +plots[0].addMarker(mean_val, null, "Mean=" + Math.round(mean_val,2), Color.LIGHT_GRAY) \ No newline at end of file diff --git a/script/tstrun.js b/script/tstrun.js new file mode 100755 index 0000000..dc5d6e9 --- /dev/null +++ b/script/tstrun.js @@ -0,0 +1,31 @@ + + + + +function run(script_name, args) { + /* + Run script: can be absolute path, relative, or short name to be search in the path. + Args: + args(Dict ot Array): gobal variables set to the script(if dict), or argv varialble (if array). + + Returns: + The script return value + */ + var script = get_context().scriptManager.library.resolveFile(script_name) + var file = script!=null ? new File(script) : null + if ((file == null) || ( ! file.exists())) throw "Invalid script: " + script_name + get_context().startScriptExecution(args) + + if (is_defined(args) && (args!=null)){ + if (is_array(args)){ + argv = args + } else { + for (var key in args) { + eval(key+"="+args[key]) + } + } + } + //eval(new String(Files.readAllBytes(file.toPath()))) + //get_context().scriptManager.interpreter.evalFile(script); + load(script) +} diff --git a/script/ttt.xml b/script/ttt.xml new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/ttt.xml @@ -0,0 +1,4 @@ + + + + diff --git a/script/tutorial.lnk b/script/tutorial.lnk new file mode 100755 index 0000000..7eab569 Binary files /dev/null and b/script/tutorial.lnk differ diff --git a/script/weighted_least_square_opt.py b/script/weighted_least_square_opt.py new file mode 100755 index 0000000..b56335c --- /dev/null +++ b/script/weighted_least_square_opt.py @@ -0,0 +1,58 @@ +from mathutils import * +from plotutils import * + +#Fitting the quadratic function f(x) = a x2 + b x + c +#Data created with [a = 8, b = 10, c = 16] and 0 + + + diff --git a/script/x11.py b/script/x11.py new file mode 100755 index 0000000..352cc61 --- /dev/null +++ b/script/x11.py @@ -0,0 +1,39 @@ +import traceback +sep = "\t" +line_sep = "\r\n" + +def plot_file(file): + table = Table.load(file, sep, '#') + plots = plot(table) + +def convert_file(input_file_name, output_file_name, field = 0, pol = 0, keithley_3 = False): + with open(input_file_name) as inp: + lines = inp.readlines() + with open(output_file_name, "wb") as out: + out.write("Energy" + sep + "rbkenergy" + sep + "Mag" + sep + "Pol" + sep + "Io" + sep + "TEY" + sep + "Norm" + line_sep) + s = sep + " " #File format has a space before numeric values + for line in lines[1:]: + line = line.strip() + if line=="": break + try: + (Ecrbk,CADC1, CADC2, NORM, CADC3, CADC4, MCurr, cffrbk, ID1Erbk, ID2Erbk, vTime) = line.split(" ") + #out.write(Ecrbk + sep + Ecrbk + sep + str(field) + sep + str(pol) + sep + CADC1 + sep + CADC2 + sep + (CADC3 if keithley_3 else NORM) + line_sep) + out.write(" " + Ecrbk + s + Ecrbk + s + str(field) + s + str(pol) + s + CADC1 + s + CADC2 + s + (CADC3 if keithley_3 else NORM) + line_sep) + except: + traceback.print_exc() + + + + +input = get_context().setup.getDataPath()+"/o151027_016.dat" +#output = get_context().setup.getDataPath()+"/os151027_016.dat" +output = get_context().setup.getDataPath()+"/out.dat" + + +convert_file(input, output) + +import filecmp +print filecmp.cmp(input, output) + + +plot_file(output) \ No newline at end of file diff --git a/script/xxx.xml b/script/xxx.xml new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/xxx.xml @@ -0,0 +1,4 @@ + + + + diff --git a/script/yyy.xml b/script/yyy.xml new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/yyy.xml @@ -0,0 +1,4 @@ + + + + diff --git a/script/zmq1.py b/script/zmq1.py new file mode 100755 index 0000000..a385feb --- /dev/null +++ b/script/zmq1.py @@ -0,0 +1,16 @@ +import org.zeromq.ZMQ as ZMQ +import org.zeromq.ZMQ.Socket as Socket + +context = ZMQ.context(1) + +socket = context.socket(ZMQ.SUB) +socket.connect("tcp://gfa-lc6-64:9999") +socket.subscribe("") + +try: + data = socket.recv() +finally: + socket.close() + context.term() + +print data \ No newline at end of file diff --git a/script/zmq2.py b/script/zmq2.py new file mode 100755 index 0000000..cd958f6 --- /dev/null +++ b/script/zmq2.py @@ -0,0 +1,20 @@ +import org.zeromq.ZMQ as ZMQ +import ch.psi.bsread.Receiver as Receiver +import ch.psi.bsread.ReceiverConfig as ReceiverConfig +import ch.psi.bsread.configuration.Channel as ReceiverChannel + + + +c1 = ReceiverChannel("min_value", 1) +config = ReceiverConfig("tcp://gfa-lc6-64:9999") +config.setSocketType( ZMQ.SUB); +receiver = Receiver(config) +receiver.connect() + +message = None + +message = receiver.receive() +for channel in message.getValues().keys(): + print channel , " = " , message.getValues()[channel].getValue().array().tolist() + +receiver.close() \ No newline at end of file diff --git a/script/zzz b/script/zzz new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/zzz @@ -0,0 +1,4 @@ + + + + diff --git a/script/zzz.xml b/script/zzz.xml new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/zzz.xml @@ -0,0 +1,4 @@ + + + + diff --git a/script/zzzxml b/script/zzzxml new file mode 100755 index 0000000..ee504d4 --- /dev/null +++ b/script/zzzxml @@ -0,0 +1,4 @@ + + + +