Welcome to Py4Syn’s documentation!¶
Contents:
Py4Syn Overview¶
Py4Syn is a python package which provides high-level abstraction for devices manipulation, scan routines, real-time plots and more. This package was created with the aim to provide a simple and powerful tool to allow scientists and user to develop their own scripts for data acquisition.
You will find here the documentation about available resources of elaborated softwares and scripts to provide you a set of engines to help you access information, control and manage the most common devices in use at LNLS. Such documentation informs classes and methods, as well as types, formats, etc., of input parameters and expected results.
Citation¶
To cite Py4Syn in publications use
Slepicka, H. H., Canova, H. F., Beniz, D. B., & Piton, J. R. (2015). Py4Syn: Python for synchrotrons. Journal of Synchrotron Radiation, 22(5), 1182–1189. https://doi.org/10.1107/S1600577515013715
A BibTeX entry for LaTeX users is
@article{Slepicka2015,
abstract = {{\textless}p{\textgreater} In this report, {\textless}italic{\textgreater}Py4Syn{\textless}/italic{\textgreater} , an open-source Python-based library for data acquisition, device manipulation, scan routines and other helper functions, is presented. Driven by easy-to-use and scalability ideals, {\textless}italic{\textgreater}Py4Syn{\textless}/italic{\textgreater} offers control system agnostic solution and high customization level for scans and data output, covering distinct techniques and facilities. Here, most of the library functionalities are described, examples of use are shown and ideas for future implementations are presented. {\textless}/p{\textgreater}},
author = {Slepicka, H. H. and Canova, H. F. and Beniz, D. B. and Piton, J. R.},
doi = {10.1107/S1600577515013715},
issn = {1600-5775},
journal = {Journal of Synchrotron Radiation},
keywords = {data acquisition,py4syn,python},
number = {5},
pages = {1182--1189},
title = {Py4Syn: Python for synchrotrons},
url = {http://scripts.iucr.org/cgi-bin/paper?S1600577515013715},
volume = {22},
year = {2015}
}
Py4Syn is ISC licensed, so you are free to use it whatever you like, be it academic, commercial, creating forks or derivatives (see the LICENSE file for details). That said, although not required by the Py4Syn license, if it is convenient for you, please cite Py4Syn when using it in your work and also consider contributing all your changes back, so that we can incorporate it and all of us will benefit in the end.
Environment Setup¶
In order to use Py4Syn there are some prerequisites. Here are the list and a basic guide to help you to setup the environment to run you scripts using Py4Syn.
To execute the next steps be sure to have a login with administrator rights in your machine.
This assumes you’re running Red Hat Enterprise Linux in your machine, for other distributions please check the correct/equivalent packages to install.
First of all let’s switch to super user:
sudo su
Python 3.x Installation¶
In order to install Python there are some required packages that will be installed with the following commands:
yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel xz libpng-devel
Now we need to add a line at the end of ld.so.conf file and run ldconfig:
echo "/usr/local/lib" >> /etc/ld.so.conf
/sbin/ldconfig
Download the lastest Python version, in this case it’s Python 3.4.1, using this link (Python 3.4.1 Download).
Extract the downloaded file with:
tar xf Python-3.4.1.tar.xz
Enter the extracted folder and run the following commands:
cd Python-3.4.1
./configure
make && make altinstall
After the installation finish include the new Python in the root user path with:
export PATH=$PATH:/usr/local/bin
Freetype2 Installation¶
To install most of the Python libraries Freetype2 is needed. Follow the next steps to correctly install Freetype2 in your computer.
Download the lastest version, using this link (Freetype 2.4.0).
Extract the downloaded file with:
tar -xzvf freetype-2.4.0.tar.gz
Enter the extracted folder and run the commands bellow to install:
cd freetype-2.4.0
./configure
make
make install
SetupTools and Pip Installation¶
SetupTools and Pip are the most used Python tools to install packages and libraries.
Download the ez_setup script from this link or use this internal link.
Run the script to install easy_install:
python3.4 ez_setup.py
And finally install pip:
easy_install-3.4 pip
Enabling the EPEL Repository¶
In order to install some of the packages below you will need to enable the EPEL repository.
Installing in Red Hat Enterprise Linux 6 - 64 Bits:
## RHEL/CentOS 6 64-Bit ##
wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
Installing in Red Hat Enterprise Linux 6 - 32 Bits:
## RHEL/CentOS 6 32-Bit ##
wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
Numpy Installation¶
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install numpy
Matplotlib Installation¶
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install matplotlib
PyEpics Installation¶
ATENTION, PyEpics requires that Epics Base to be correctly installed at your computer and that the environment variable PYEPICS_LIBCA is pointing to the correct place. For informations regarding to Epics Base installation please check LNLS Wiki - Epics Installation
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install pyepics
H5PY Installation¶
Prior to install H5PY some requirements must be filled, please install the required packages with:
yum install hdf5
yum install hdf5-devel
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install cython
pip3.4 install h5py
Pillow Installation¶
Pillow is the substitute for PIL (Python Image Library).
To correctly install the lastest version in your Python3.4 environment do:
easy_install-3.4 Pillow
Scipy Installation¶
Prior to install Scipy some requirements must be filled, please install the required packages with:
yum install gcc-gfortran
yum install openblas-devel
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install scipy
After install all the dependencies proceed to the installation guide
LMFIT Installation¶
Lmfit provides a high-level interface to non-linear optimization and curve fitting problems for Python.
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install lmfit
iPython Installation¶
Lmfit provides a high-level interface to non-linear optimization and curve fitting problems for Python.
To correctly install the lastest version in your Python3.4 environment do:
pip3.4 install ipython
Installation¶
After follow the setup you are now able to successfully install Py4Syn library in your computer.
Obtaining the Package¶
The version of Py4Syn is 0+untagged.128.ga7b5996.dirty. You can download this version by clicking on the proper link below.
Download Type | Python Version | Location |
---|---|---|
Source tarball | 3.x or Higher | Py4Syn 0+untagged.128.ga7b5996.dirty |
Development | 3.x or Higher | Py4Syn GitHub Repo |
Installing¶
To install from source do:
python3.x setup.py build
python3.x setup.py install
Or using Python Setup Tools:
easy_install-3.x -U py4syn
Getting Help¶
For questions, bug reports, feature request, please consider using the following methods:
- Create an Issue for Py4Syn on GitHub.
- If you’re sure you’ve found a bug in existing code, or have some code you think would be useful to add to Py4Syn create a pull request on GitHub.
License¶
This software is distributed under the following ISC license:
Copyright (c) 2015 BRAZILIAN SYNCHROTRON LIGHT SOURCE <sol@lnls.br>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Acknowledgments¶
Py4Syn was written and is maintained by the LNLS SOL group. The library started as an idea to promote basic scripts and functions to LNLS beam line members. Thanks to all who contributed to this idea.
EPICS module¶
Available entities at py4syn.epics library:
Devices¶
Available devices:
Countable PV¶
This is the basic Python class to help in the use of simple pvs as counters.
Using EPICS-Countable PV class¶
Usage of Python Class
-
class
py4syn.epics.CountablePVClass.
CountablePV
(pvName, mnemonic)[source]¶ Class to add fake ICountable support for generic PV.
Examples
>>> from py4syn.epics.CountablePVClass import CountablePV >>> >>> myCountable = CountablePV('LNLS:ANEL:corrente','corrente') >>> myCountable.getValue() >>>
Constructor See
py4syn.epics.StandardDevice
Seepy4syn.epics.ICountable
Parameters: - pvName : string
PV name (Process Variable)
- mnemonic : string
Mnemonic
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(t)[source]¶ Abstract method to set the count time of a countable target device.
Parameters: - t : value
The target count time to be set.
Returns: - out : None
EPICS Digital I/O¶
This is a Python class which allows the control of a set of digital I/O ports defined by the user. Ports are named with a common prefix followed by its number. Once it is based on EPICS resources, one can get and set PV values related to the ports. Its also possible to add and delete ports from the set, and list their names.
Using EPICS Digital I/O module¶
Usage of Python class for EPICS Digital I/O control
-
class
py4syn.epics.DigitalIOClass.
DigitalIO
(digitalIO_prefix, port_type, port_sequence)[source]¶ Class for Digital I/O using EPICS.
Constructor
Parameters: - digitalIO_prefix : string
Prefix of the ports.
- port_type : string
‘INPUT’ or ‘OUTPUT’.
- port_sequence : string
Index of the ports. Example: ‘0-3;7’ means ports from 0 to 3 and 7.
-
addPorts
(port_sequences)[source]¶ Add ports to name and PVs dictionaries.
Parameters: - port_sequences : string
Index of the ports to be added.
-
deletePorts
(port_sequences)[source]¶ Delete ports from name and PVs dictionaries.
Parameters: - port_sequences : string
Index of the ports to be deleted.
-
getName
(port_index)[source]¶ Returns the name of a port PV.
Parameters: - port_index : int
Index of the port.
Hyppie CCD Detector control¶
This is the basic Python class to help in the configuration and control of CCD devices by using EPICS set of tools to provide the minimal infrastructure for use in managing and operating motor devices by reading and/or setting their record fields - also known as PVs, Process Variables.
Charge-Coupled Device (CCD) is a silicon light sensor which converts incident light, or photons, into electrons.
Using EPICS-Hyppie CCD Detector control module¶
Usage of Python Class for EPICS LabView RT Detector control.
-
class
py4syn.epics.HyppieCCDClass.
HyppieCCD
(pvName, mnemonic, scalerObject='')[source]¶ Python class to help configuration and control of Charge-Coupled Devices (CCD) via Hyppie over EPICS.
CCD is the most common mechanism for converting optical images to electrical signals. In fact, the term CCD is know by many people because of their use of video cameras and digital still cameras.
Constructor
Parameters: - pvName : string
Charge-Coupled Device (CCD)’s naming of the PV (Process Variable)
- mnemonic : string
Device mnemonic
- scalerObject : object
It represents logically the Scaler device
-
acquire
(waitComplete=False)[source]¶ Start process of image capturing.
Parameters: - waitComplete : boolean [OPTIONAL]
Whether to wait for all of the reading process of the image to complete, or not.
Note
- True – Wait for all image reading conclusion;
- False [DEFAULT] – DON’T wait for all image reading conclusion.
-
disableAutoIncrement
()[source]¶ Set AutoIncrement property of device to 0 (ZERO), that is, disables it.
Parameters: - None
-
enableAutoIncrement
()[source]¶ Set AutoIncrement property of device to 1 (ONE), that is, enables it.
Parameters: - None
-
getCommandOutput
(cmd)[source]¶ Return the output of command the command sent to device.
Returns: - `string`
-
getCompleteFileName
()[source]¶ Return the full file name, with extension, of the current image which is being read.
Returns: - `string`
-
getCompletePreviousFileName
()[source]¶ Return the full file name, with extension, of the image which were read previously.
Returns: - `string`
-
getFileName
()[source]¶ Return the full file name of the current image which is being read.
Returns: - `string`
-
getFileNumber
()[source]¶ Return the number sequence of the file of current image which is being read.
Returns: - `integer`
-
getFilePath
()[source]¶ Return the full path where is the file of current image which is being read.
Returns: - `string`
-
isDone
()[source]¶ Check whether acquisition process has been concluded or not.
Returns: - `boolean`
- .. note::
- True – Acquisition has been concluded;
- False – Acquisition has NOT been concluded.
-
isDoneConfig
()[source]¶ Check whether configuration process has been concluded or not.
Returns: - `boolean`
- .. note::
- True – Configuration has been concluded;
- False – Configuration has NOT been concluded.
-
onAcquireChange
(value, **kw)[source]¶ Internal use method to check whether an acquisition in execution is done or not.
Parameters: - value : integer
0 (ZERO) Indicates the process has been concluded
- kw : matrix
Internal array of parameters
-
onWaitChange
(value, **kw)[source]¶ Internal use method to check whether a configuration change request sent to the Charge-Coupled device has been performed or not.
Parameters: - value : integer
0 (ZERO) Indicates the configuration change has been conclude
- kw : matrix
Internal array of parameters
-
setAcquireTime
(time)[source]¶ Set the acquisition time to the Charge-Coupled Device (CCD).
Parameters: - unit : float
Time value to be configured for the acquire-time property of CCD.
-
setCommandInput
(cmd)[source]¶ Set the input command to be submitted to the device.
Parameters: - unit : string
Command to send to device.
-
setFileName
(name)[source]¶ Set the full file name of current image which is being read.
Parameters: - unit : string
Name of image file to capture.
-
setFileNumber
(number)[source]¶ Set the number sequence of the file for the current image which is being read.
Parameters: - unit : integer
Sequence number to set to the image file.
-
setFilePath
(name)[source]¶ Set the full path where file of current image which is being read must be saved.
Parameters: - name : string
Description of path where image file should be stored.
-
setNumImages
(number)[source]¶ Set the number of images which should be read.
Parameters: - number : integer
Number of images to be captured.
-
setROI
(startX, sizeX, startY, sizeY)[source]¶ Method to determine the Region Of Interest (ROI) of a CCD device.
Parameters: - startX : float
X position to start the region of interest of the Charge-Coupled Device (CCD)
- sizeX : float
size of X positioning
- startY : float
Y position to start the region of interest of the Charge-Coupled Device (CCD)
- sizeY : float
size of Y positioning
Examples
>>> import py4syn.epics.HyppieCCDClass.HyppieCCD as hyppie_ccd >>> hyppie_ccd.setROI(32, 100, 15, 49)
Note
This method must be used only after default configuration was set in the Charge-Coupled Devide (CCD)
Keithley Programmable Electrometer model 6514¶
This is the basic Python class to …
Using EPICS Lauda thermostats module¶
Usage of Python class for EPICS Keithley Programmable Electrometer model 6514.
-
class
py4syn.epics.Keithley6514Class.
Keithley6514
(pvName, mnemonic, timeBased=False)[source]¶ Python class to help configuration and control the Keithley 6514 Electrometer.
Keithley is an electrical instrument for measuring electric charge or electrical potential difference. This instrument is capable of measuring extremely low currents. E.g.: pico (10e-12), i.e.: 0,000 000 000 001.
For more information, please, refer to: Model 6514 System Electrometer Instruction Manual
Constructor To use this Keithley Class you must pass the PV (Process Variable) prefix.
Note
e.g.: SXS:K6514
Examples
>>> from KeithleyClass import * >>> name = Keithley('SOL:K6514', 'k1')
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getAutoCurrentRange
()[source]¶ Get the status of Auto Current Range (enable/disable). Default: enable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getAutoCurrentRange() >>> True
-
getAutoZeroing
()[source]¶ Get the status of Auto Zero (enable/disable). Default: enable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getAutoZeroing() >>> True
-
getAverageCount
()[source]¶ Get the number of filter count. Default: 10.
Returns: - Value: Integer, i.e.: 2 to 100.
Examples
>>> name.getAverageCount() >>> 10.0
-
getAverageDigitalFilter
()[source]¶ Get the status of Digital Filter (enable/disable). Default: enable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getAverageDigitalFilter() >>> True
-
getAverageTControl
()[source]¶ Get the filter control. Default: REP.
Returns: - Value: String, i.e.: REP or MOV.
Examples
>>> name.getAverageTControl() >>> 'REP'
-
getCountNumberReading
()[source]¶ Count the number of reading(s).
Returns: - Value: Integer, e.g.: 963.
Examples
>>> name.CountNumberReading() >>> 161.0
-
getCurrentRange
()[source]¶ Get the value of range. Default: Auto range.
Returns: - Value: Integer, i.e.:
- 0 (Undefined ZERO), 1 (Indefined UM), 2 (20 mA), 3 (2 mA), 4 (200 uA), 5 (20 uA), 6 (2 uA), 7 (200 nA), 8 (20 nA), 9 (2 nA), 10 (200 pA), 11 (20 pA).
Examples
>>> name.getCurrentRange() >>> 11
-
getIntegrationTime
()[source]¶ Get the number of integration rate. Default: 1.
Returns: - Value: Float, i.e.: 0.01 to 10 (PLCs). Where 1 PLC for 60Hz is 16.67msec (1/60).
Examples
>>> name.getIntegrationTime() >>> 1.0
-
getMedianFilter
()[source]¶ Get the status of Median Filter (enable/disable). Default: enable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getMedianFilter() >>> True
-
getMedianRank
()[source]¶ Get the value of Median Rank, this number of sample readings are between 1 to 5. Default: 5.
Returns: - Value: Integer, i.e.: 1 to 5.
Examples
>>> name.getMedianRank() >>> 5.0
-
getStatusContinuesMode
()[source]¶ Get the status of Continues Mode (enable/disable). Default: enable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getStatusContinuesMode() >>> True
-
getTriggerReading
()[source]¶ Trigger and return reading(s).
Returns: - Value: Float, e.g.: -6.0173430000000003e-16.
Examples
>>> name.getTriggerReading() >>> -1.0221850000000001e-15
-
getValue
(**kwargs)[source]¶ Get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
getZeroCheck
()[source]¶ Get the status of Zero Check (enable/disable). Default: disable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getZeroCheck() >>> False
-
getZeroCorrect
()[source]¶ Get the status of Zero Correct (enable/disable). Default: disable.
Returns: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.getZeroCorrect() >>> False
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setAutoCurrentRange
(autorange)[source]¶ Set enable/disable for Auto Current Range.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Returns: - One value (1).
Examples
>>> name.setAutoCurrentRange(1) >>> 1
-
setAutoZeroing
(autozero)[source]¶ Set enable/disable for Auto Zero.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.setAutoZeroing(1)
-
setAverageCount
(avercoun)[source]¶ Set the number of filter count.
Parameters: - Value: Integer, i.e.: 2 to 100.
Examples
>>> name.setAverageCount(80)
-
setAverageDigitalFilter
(aver)[source]¶ Set enable/disable for Digital Filter.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.setAverageDigitalFilter(1)
-
setAverageTControl
(tcon)[source]¶ Set the filter control.
Parameters: - Value: String, i.e.: ‘REP’ or ‘MOV’, where REP means ‘Repeat’ and MOV means ‘Moving’.
Examples
>>> name.setAverageTControl('MOV')
-
setCountTime
(time)[source]¶ Method to set the count time of a Keithley device.
Note
Whenever the median filter is active, changing the count time results in the filter being reset, so the first measurement will take additional time to collect new data for the filter. The extra time is proportional to the median filter rank. After the first measurement, the following measurements will have the correct integration time.
Note
Unlike scalers, the count time is only an approximation. The requested integration time will be split into multiple parts, which includes the analog integration time (varying between approximatelly 10ms to 50ms), the digital integration time (that averages a set of 2 to 100 analog integrations), and other operations unrelated to integration, like auto zero calibration (triples the integration time) and calculation times. When calling this method, the digital average filter will be activated if it’s not already and the filter type will be set to repeat.
See also:
setIntegrationTime()
,setAverageCount()
Parameters: - time : value
The target count time to be set. The allowed time range is 100ms to 15s (limited by software).
Returns: - out : None
-
setCurrentRange
(curange)[source]¶ Set the range.
Parameters: - Value: Integer, i.e.:
- 0 (Undefined ZERO), 1 (Indefined UM), 2 (20 mA), 3 (2 mA), 4 (200 uA), 5 (20 uA), 6 (2 uA), 7 (200 nA), 8 (20 nA), 9 (2 nA), 10 (200 pA), 11 (20 pA).
Examples
>>> name.setCurrentRange(5)
-
setIntegrationTime
(nplc)[source]¶ Set the number of integration rate.
Parameters: - Value: Float, i.e.: 0.01 to 10 (PLCs). Where 1 PLC for 60Hz is 16.67msec (1/60).
Examples
>>> name.setIntegrationTime(0.01)
-
setMedianFilter
(med)[source]¶ Set enable/disable for Median Filter.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.setMedianFilter(1)
-
setMedianRank
(medrank)[source]¶ Set the number of sample readings used for the median calculation.
Parameters: - Value: Integer, i.e.: 1 to 5.
Examples
>>> name.setMedianRank(3)
-
setPresetValue
(channel, val)[source]¶ Abstract method to set the preset count of a countable target device.
Parameters: - channel : int
The monitor channel number
- val : int
The preset value
Returns: - out : None
-
setStatusContinuesMode
(cmode)[source]¶ Set enable/disable to continues mode. Let this enable if you want a continuing measuring.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Examples
>>> name.setStatusContinuesMode(0)
-
setZeroCheck
(check)[source]¶ Set enable/disable for Zero Check.
Parameters: - Value: Boolean, i.e.: 0 - False (Off/Disable), 1 - True (On/Enable).
Returns: - One value (1).
Examples
>>> name.setZeroCheck(1) >>> 1
-
Kepco BOP GL Power Supply¶
The Kepco BOP GL power supplies are programmable power supplies that operate in current or voltage mode. The current implementation supports the Kepco BOP 50-20GL model.
Using EPICS Kepco BOP GL power supply module¶
Usage of Python class for EPICS Kepco BOP GL power supplies.
-
class
py4syn.epics.KepcoBOPClass.
KepcoBOP
(pvName, mnemonic)[source]¶ Class to control Kepco BOP GL power supplies via EPICS.
Examples
>>> from py4syn.epics.KepcoBOPClass import KepcoBOP >>> >>> def configurePower(pv="", name="", voltage=5.0, currentLimit=1.0): ... bop = KepcoBOP(pv, name) ... bop.reset() ... bop.setCurrentLimits(currentLimit, currentLimit) ... bop.setVoltage(voltage) ... return bop ... >>> def smoothVoltageTransition(bop, initial=0.0, final=12.0, duration=2.0): ... bop.setRampWaveform(duration, final-initial, (initial+final)/2) ... bop.waveformStart() ... bop.waveformWait() ... >>> def noiseCurrent(bop): ... bop.reset() ... bop.setMode(KepcoBOP.MODE_CURRENT) ... bop.setVoltageLimits(20, 20) ... points = [random.uniform(-5, 5) for i in range(100)] ... bop.clearWaveform() ... bop.addWaveformPoints(points, [0.025]) ... bop.waveformStart() ...
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvName : string
Power supply base naming of the PV (Process Variable)
- mnemonic : string
Power supply mnemonic
-
addLevelWaveform
(length, offset)[source]¶ Adds a fixed level wave to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. The other way is sending the complete array of points for the waveform. This method is limited to a specific waveform type, but it’s faster to program than uploading individual points. When the final desired waveform can be composed of simple waveform segments, this is the best way to program the device.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
waveformStart()
,setLevelWaveform()
,addWaveformPoints()
,addSineWaveform()
,addRampWaveform()
,addTriangleWaveform()
,addSquareWaveform()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - length : float
The duration of the level waveform. The allowed range is 500µs to 5s. The number of points used is 60.
- offset : float
The level offset. The offset cannot exceed the configured device limits.
-
addRampWaveform
(length, height, offset)[source]¶ Adds a ramp wave to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. The other way is sending the complete array of points for the waveform. This method is limited to a specific waveform type and it also consumes a lot of points, but it’s faster to program than uploading individual points. When the final desired waveform can be composed of simple waveform segments, this is the best way to program the device.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
waveformStart()
,setRampWaveform()
,addWaveformPoints()
,addSineWaveform()
,addTriangleWaveform()
,addSquareWaveform()
,addLevelWaveform()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - length : float
The ramp length. The allowed range is [1/532, 100] (1.88ms to 100s). The number of points used vary from 20, for smaller ramps, to 3840, for larger ramps.
- height : float
The ramp height. The height can be positive or negative. It cannot exceed the range defined by the configured operating device limits.
- offset : float
The offset of the ramp middle height. The offset cannot exceed the configured device limits.
-
addSineWaveform
(frequency, amplitude, offset, start=0, stop=360)[source]¶ Adds a sine wave to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. The other way is sending the complete array of points for the waveform. This method is limited to a specific waveform type and it also consumes a lot of points, but it’s faster to program than uploading individual points. When the final desired waveform can be composed of simple waveform segments, this is the best way to program the device.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
waveformStart()
,setSineWaveform()
,addWaveformPoints()
,addTriangleWaveform()
,addRampWaveform()
,addSquareWaveform()
,addLevelWaveform()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - frequency : float
The sine wave frequency. The allowed range is 0.01Hz to 443Hz. The number of points used vary from 3840, for lower frequency waves to 24, for higher frequency waves.
- amplitude : float
The sine wave peak to peak amplitude. The peak to peak amplitude cannot exceed the range defined by the configured operating device limits.
- offset : float
The offset of the sine wave zero amplitude. The offset cannot exceed the configured device limits.
- start : float
The starting angle for the sine wave, in degrees. Allowed range is [0.0, 359.99]
- stop : float
The stop angle for the sine wave, in degrees. Allowed range is [0.01, 360.0]
-
addSquareWaveform
(frequency, amplitude, offset)[source]¶ Adds a square wave (constant 50% duty cycle, starts with positive excursion) to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. The other way is sending the complete array of points for the waveform. This method is limited to a specific waveform type and it also consumes a lot of points, but it’s faster to program than uploading individual points. When the final desired waveform can be composed of simple waveform segments, this is the best way to program the device.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
waveformStart()
,setSquareWaveform()
,addWaveformPoints()
,addSineWaveform()
,addTriangleWaveform()
,addRampWaveform()
,addLevelWaveform()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - frequency : float
The square wave frequency. The allowed range is 0.02Hz to 1000Hz. The number of points used vary from 3840, for lower frequency waves to 10, for higher frequency waves.
- amplitude : float
The square wave peak to peak amplitude. The peak to peak amplitude cannot exceed the range defined by the configured operating device limits.
- offset : float
The offset of the square wave zero amplitude. The offset cannot exceed the configured device limits.
-
addTriangleWaveform
(frequency, amplitude, offset, start=0, stop=360)[source]¶ Adds a triangle wave to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. The other way is sending the complete array of points for the waveform. This method is limited to a specific waveform type and it also consumes a lot of points, but it’s faster to program than uploading individual points. When the final desired waveform can be composed of simple waveform segments, this is the best way to program the device.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
waveformStart()
,setTriangleWaveform()
,addWaveformPoints()
,addSineWaveform()
,addRampWaveform()
,addSquareWaveform()
,addLevelWaveform()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - frequency : float
The triangle wave frequency. The allowed range is 0.01Hz to 443Hz. The number of points used vary from 3840, for lower frequency waves to 24, for higher frequency waves.
- amplitude : float
The triangle wave peak to peak amplitude. The peak to peak amplitude cannot exceed the range defined by the configured operating device limits.
- offset : float
The offset of the triangle wave zero amplitude. The offset cannot exceed the configured device limits.
- start : float
The starting angle for the triangle wave, in degrees. Allowed range is [0.0, 359.99]
- stop : float
The stop angle for the triangle wave, in degrees. Allowed range is [0.01, 360.0]
-
addWaveform
(tp, param1, param2, param3=None)[source]¶ Helper method that implements adding waveform segments.
-
addWaveformPoints
(points, times)[source]¶ Adds a set of points to the waveform program. This is one of the ways that the device can be programmed to generate a complex waveform. It’s the most flexible way, allowing arbitrary waveforms, but it’s also the slowest one (a 10 second waveform may take at least 4 seconds just to upload the program). This method adds more points to the current waveform program. It does not overwrite the existing program.
Adding points does not execute the program. The method
waveformStart()
must be called.See also:
setWaveformPoints()
,addSineWaveform()
,addTriangleWaveform()
,addRampWaveform()
,addSquareWaveform()
,addLevelWaveform()
,waveformStart()
Note
When changing operating mode, the waveform program must be cleared if necessary, because the device will prohibit mixing points from different modes.
Parameters: - points : array of floats
The array of points to be added to the program. The total number of allowed points may vary, depending on the times array. When the times array has exactly one element, the maximum number of points is 5900. When the times array has at most 126 distinct values, the maximum number of points is 3933. When the times array has more than 126 distinct values, the maximum number of points is 2950.
- times : array of floats
The dwell times for each point. Either there must be one time entry for each point, or the array of times must contain exactly one element, which sets the time for all points. The allowed time range is [93e-6, 34e-3] (93µs to 34ms).
-
clearWaveform
()[source]¶ Clears the programmed waveform data. This is required when building a new waveform program. Waveform data can only be cleared while the program is not running.
-
getCurrent
()[source]¶ Measures the current value. The measured value that is read back is known to have an error (less than 1%) and a delay (up to 320ms).
Returns: - `float`
-
getCurrentLimits
()[source]¶ Gets the negative and positive current limits allowed for operation. The specific limit type that is read depends on the operating mode. When in current mode, the limit set is a main channel limit: it defines the limits of the current that can be programmed by the user. When in voltage mode, the limit is a protection limit: it defines the current limits that the load may impose because of the requested voltage. When changing the operating modes, the set limits no longer apply: they are different for the new mode.
See also:
setMode()
Returns: - negative : float
The absolute value of the negative limit
- positive : float
The absolute value of the positive limit
-
getHighLimitValue
()[source]¶ Gets either the voltage or current high limit value, depending on operation mode.
Returns: - `float`
-
getLimits
(device, mode)[source]¶ Helper method that implements
getVoltageLimits()
and :meth: getCurrentLimits
-
getLowLimitValue
()[source]¶ Gets either the voltage or current low limit value, depending on operation mode.
Returns: - `float`
-
getOperationFlag
()[source]¶ Returns the real time value of the device operation condition register. The register contains a set of bits representing the following flags: “list running” (16384), “list complete” (4096), “sample complete” (2048), “constant current mode” (1024), “transient complete” (512)”, “constant voltage mode” (256), “transient armed” (64), “waiting for trigger” (32). Refer to the Kepco BOP GL manual for specific details. The relevant flag used by the library is the “list running” flag, which indicates that theres a waveform program running.
See also:
isWaveformRunning()
,waveformWait()
Returns: - `int`
-
getProgramLength
()[source]¶ Helper method that returns the number of points in current waveform program.
-
getValue
()[source]¶ Returns either the readback voltage or the current, depending on operating mode.
Returns: - `float`
-
getVoltage
()[source]¶ Measures the voltage value. The measured value that is read back is known to have an error (less than 1%) and a delay (up to 320ms).
Returns: - `float`
-
getVoltageLimits
()[source]¶ Gets the negative and positive voltage limits allowed for operation. The specific limit type that is read depends on the operating mode. When in voltage mode, the limit set is a main channel limit: it defines the limits of the voltages that can be programmed by the user. When in current mode, the limit is a protection limit: it defines the voltage limits that the load may impose because of the requested current. When changing the operating modes, the set limits no longer apply: they are different for the new mode.
See also:
setMode()
Returns: - negative : float
The absolute value of the negative limit
- positive : float
The absolute value of the positive limit
-
getWaveformRepeat
()[source]¶ Gets the last requested waveform repeat count.
See also:
setWaveformRepeat()
Returns: - `int`
-
isWaveformRunning
()[source]¶ Returns whether there’s a running waveform program.
See also:
getOperationFlag()
,waveformWait()
Returns: - `bool`
-
reset
()[source]¶ Resets the device to a known state. Possible reset states may vary with the device configuration, but generally will be a zero value output (either voltage or current) with low protection limits. The device error queue will be cleared.
-
setCurrent
(current, wait=True)[source]¶ Sets the current value. This method can only be used when in current mode. The current values must be within the power supply acceptable range and also within the configured limit values.
See also:
setMode()
,setCurrentLimits()
Parameters: - current : float
The desired current value
-
setCurrentLimits
(negative=None, positive=None)[source]¶ Sets the negative and positive current limits allowed for operation. The specific limit type that is set depends on the operating mode. When in current mode, the limit set is a main channel limit: it defines the limits of the current that can be programmed by the user. When in voltage mode, the limit is a protection limit: it defines the current limits that the load may impose because of the requested voltage. When changing the operating modes, the set limits no longer apply: they must be set again for the new mode.
See also:
setMode()
Parameters: - negative : float
The absolute value of the negative limit
- positive : float
The absolute value of the positive limit
-
setLevelWaveform
(length, offset)[source]¶ A shortcut to clearing the waveform program, adding a level waveform and setting the repeat count to 1.
See also:
clearWaveform()
,addLevelWaveform()
,setWaveformRepeat()
Parameters: - length : float
Parameter passed to
addLevelWaveform()
- offset : float
Parameter passed to
addLevelWaveform()
-
setLimits
(device, mode, negative=None, positive=None, maximum=1e+100)[source]¶ Helper method that implements
setVoltageLimits()
andsetCurrentLimits()
-
setMode
(mode)[source]¶ Changes the operating mode. Supported modes are voltage mode and current mode. In the voltage mode, the device tries to set a specific voltage, while staying within the current protection limits. In current mode, the device tries to set a specific current, while staying within the voltage protection limits. See also:
setCurrentLimits()
,setVoltageLimits()
Parameters: - mode : {KepcoBOP.MODE_CURRENT, KepcoBOP.MODE_VOLTAGE}
The desired mode
-
setRampWaveform
(length, height, offset)[source]¶ A shortcut to clearing the waveform program, adding ramp waveform and setting the repeat count to 1.
See also:
clearWaveform()
,addRampWaveform()
,setWaveformRepeat()
Parameters: - length : float
Parameter passed to
addRampWaveform()
- height : float
Parameter passed to
addRampWaveform()
- offset : float
Parameter passed to
addRampWaveform()
-
setSineWaveform
(frequency, amplitude, offset, start=0, stop=360)[source]¶ A shortcut to clearing the waveform program, adding sine waveform and setting the repeat count to 1.
See also:
clearWaveform()
,addSineWaveform()
,setWaveformRepeat()
Parameters: - frequency : float
Parameter passed to
addSineWaveform()
- amplitude : float
Parameter passed to
addSineWaveform()
- offset : float
Parameter passed to
addSineWaveform()
- start : float
Parameter passed to
addSineWaveform()
- stop : float
Parameter passed to
addSineWaveform()
-
setSquareWaveform
(frequency, amplitude, offset)[source]¶ A shortcut to clearing the waveform program, adding square waveform and setting the repeat count to 1.
See also:
clearWaveform()
,addSquareWaveform()
,setWaveformRepeat()
Parameters: - frequency : float
Parameter passed to
addSquareWaveform()
- amplitude : float
Parameter passed to
addSquareWaveform()
- offset : float
Parameter passed to
addSquareWaveform()
-
setTriangleWaveform
(frequency, amplitude, offset, start=0, stop=360)[source]¶ A shortcut to clearing the waveform program, adding triangle waveform and setting the repeat count to 1.
See
clearWaveform()
,addTriangleWaveform()
,setWaveformRepeat()
Parameters: - frequency : float
Parameter passed to
addTriangleWaveform()
- amplitude : float
Parameter passed to
addTriangleWaveform()
- offset : float
Parameter passed to
addTriangleWaveform()
- start : float
Parameter passed to
addTriangleWaveform()
- stop : float
Parameter passed to
addTriangleWaveform()
-
setValue
(v, wait=True)[source]¶ Sets either the current voltage or current, depending on operating mode.
Parameters: - v : float
Either voltage, or current to set, depending on operating mode.
-
setVoltage
(voltage, wait=True)[source]¶ Sets the voltage value. This method can only be used when in voltage mode. The voltage values must be within the power supply acceptable range and also within the configured limit values.
See also:
setMode()
,setVoltageLimits()
Parameters: - voltage : float
The desired voltage value
-
setVoltageLimits
(negative=None, positive=None)[source]¶ Sets the negative and positive voltage limits allowed for operation. The specific limit type that is set depends on the operating mode. When in voltage mode, the limit set is a main channel limit: it defines the limits of the voltages that can be programmed by the user. When in current mode, the limit is a protection limit: it defines the voltage limits that the load may impose because of the requested current. When changing the operating modes, the set limits no longer apply: they must be set again for the new mode.
See also:
setMode()
Parameters: - negative : float
The absolute value of the negative limit
- positive : float
The absolute value of the positive limit
-
setWaveformAngle
(start=0, stop=360)[source]¶ Helper method that configures start and stop angles for sine and triangle waveforms.
-
setWaveformPoints
(points, times)[source]¶ A shortcut to clearing the waveform program, adding waveform points and setting the repeat count to 1.
See also:
clearWaveform()
,addWaveformPoints()
,setWaveformRepeat()
Parameters: - points : array of floats
Parameter passed to
addWaveformPoints()
- times : array of floats
Parameter passed to
addWaveformPoints()
-
setWaveformRepeat
(repeat)[source]¶ Set the number of times the waveform program will run. By default, the program runs an indeterminate number of times, until it’s explicitly stopped. This method is used to specify the number of times the waveform program will repeat.
A waveform may also have separate one-shot part and repeatable part. Use the method
setWaveformRepeatMark()
to separate them.See also:
setWaveformRepeatMark()
,waveformStop()
,waveformAbort()
Parameters: - repeat : int
Number of times the programmed waveform will run. A value of zero means run until explicitly stopped.
-
setWaveformRepeatMark
(position=None)[source]¶ Separates the one-short part from the repeating part in the waveform program. By default, the whole waveform repeats, according to the repeat count. This method marks the separation point that allows the definition of an initial one-shot part of the wave. The part before the marked point will be the one-shot part and after the marked point will be the repeating part.
See also:
setWaveformRepeat()
Parameters: - position : int
Desired position of the setWaveformRepeatMark, representing the point in the waveform that starts the repeating part. If unset, the current first free position in the waveform is set as the mark.
-
wait
()[source]¶ Does the same as
waveformWait()
.
-
waveformAbort
()[source]¶ Immediatelly stops a running waveform. The final output value will be the value before running the waveform program.
See also:
waveformStop()
,waveformWait()
-
waveformStart
()[source]¶ Executes a waveform program. The program must be already defined by using the waveform add methods. This methods triggers the execution and returns immediatelly. It does not wait for the complete waveform execution to finish.
By default, the waveform will repeat until it is explicitly stopped, but this can be configured by the
setWaveformRepeat()
method. To stop the waveform execution, the methodswaveformStop()
andwaveformAbort()
can be used. For a program with finite repeat count, it’s possible to wait until the waveform finishes withwaveformWait()
.See also:
addWaveformPoints()
,addSineWaveform()
,addTriangleWaveform()
,addRampWaveform()
,addSquareWaveform()
,addLevelWaveform()
,waveformStop()
,waveformAbort()
,waveformWait()
,isWaveformRunning()
-
waveformStop
()[source]¶ Requests to stop a running waveform. The waveform will execute until the end and then will stop, without repeating the program again. The final output value will be the final point in the program.
See also:
waveformAbort()
,waveformWait()
Note
Because it’s not possible to reliably stop a program with finite repeat count without potentially triggering an “already finished” error, this command is only enabled for stopping waveform programs with inifinite repeat count. For finite repeat counts, use
waveformAbort()
, orwaveformWait()
instead.
-
waveformWait
()[source]¶ Waits until the whole waveform program finishes, including all repetitions. It’s only possible to wait for waveform programs with finite repeat counts.
Note
When using the Kepco power supply with a serial port, it’s not possible to receive a notification from the device when the waveform finishes, so this method works by repeatedly polling the device requesting the operation flag. Because of this, the recommended way to use this method is first sleeping for as much time as possible to avoid the loop and only on the last second call this method. Example of a helper function that accomplishes this:
Examples
>>> def runAndWait(bop, totalTime): ... bop.waveformStart() ... sleep(max(totalTime-1, 0)) ... bop.waveformWait() ...
Lauda thermostats¶
This is the basic Python class to control Lauda thermostats over EPICS.
Using EPICS Lauda thermostats module¶
Usage of Python class for EPICS Lauda thermostats.
-
class
py4syn.epics.LaudaClass.
Lauda
(pvName, mnemonic)[source]¶ Class to control Lauda temperature controllers via EPICS.
Examples
>>> from py4syn.epics.LaudaClass import Lauda >>> >>> def showTemperature(pv): ... lauda = Lauda(pv, 'lauda') ... print('Temperature is: %d' % lauda.getValue()) ... >>> def setTemperature(lauda, temperature): ... lauda.setValue(temperature) ... lauda.run()
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvName : string
Power supply base naming of the PV (Process Variable)
- mnemonic : string
Temperature controller mnemonic
-
changePump
(val)[source]¶ Same as
setPumpSpeed()
.See
setPumpSpeed()
Parameters: - val : int
The requested pump speed.
-
changeSetPoint
(val)[source]¶ Same as
setValue()
.See
setValue()
Parameters: - val : int
The requested temperature.
-
getInternalTemp
()[source]¶ Same as
getValue()
.See
getValue()
Returns: - `int`
-
getRealPosition
()[source]¶ Returns the same as
getValue()
.See:
getValue()
Returns: - `int`
-
onTemperatureChange
(**kwargs)[source]¶ Helper callback that indicates when the measured temperature changed.
-
setPumpSpeed
(speed)[source]¶ Changes the pump speed.
Parameters: - speed : int
The requested pump speed, ranging from 1 to 8.
-
setValue
(v)[source]¶ Changes the temperature to a new value.
Parameters: - v : int
The target temperature in °C
Lake Shore 331 temperature controller¶
This is the basic Python class to control the Lake Shore 331 temperature controller over EPICS.
Using EPICS Lake Shore 331 module¶
Usage of Python class for EPICS Lake Shore 331.
-
class
py4syn.epics.LakeShore331Class.
LakeShore331
(pvPrefix='', mnemonic='', channel=0)[source]¶ Python class to help configuration and control of LakeShore 331 devices via Hyppie over EPICS.
Examples
>>> from py4syn.epics.LakeShore331 import LakeShore331 >>> ls331 = LakeShore331("DXAS:LS331", "ls331", channel=0) # Use 1 for Ch B >>> ls331.setValue(120) # 120 degrees Celsius
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvPrefix : string
LakeShore331’s device base naming of the PV (Process Variable); Like DXAS:LS331;
- mnemonic : string
LakeShore331’s mnemonic
-
getAPIDD
()[source]¶ Returns Value D of PID for channel A.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getAPIDD() >>> 31
-
getAPIDI
()[source]¶ Returns Value I of PID for channel A.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getAPIDI() >>> 31
-
getAPIDP
()[source]¶ Returns Value P of PID for channel A.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getAPIDP() >>> 31
-
getASetPoint
()[source]¶ Returns setpoint value for channel A.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getASetPoint() >>> 67.87
-
getBPIDD
()[source]¶ Returns Value D of PID for channel B.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getBPIDD() >>> 32
-
getBPIDI
()[source]¶ Returns Value I of PID for channel B.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getBPIDI() >>> 32
-
getBPIDP
()[source]¶ Returns Value P of PID for channel B.
Returns: - Value: Integer, e.g.: 10
Examples
>>> ls331.getBPIDP() >>> 32
-
getBSetPoint
()[source]¶ Returns setpoint value for channel B.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getBSetPoint() >>> 67.87
-
getCTempA
()[source]¶ Returns channel A temperature in Celsius degrees.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getCTempA() >>> 32.56
-
getCTempB
()[source]¶ Returns channel B temperature in Celsius degrees.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getCTempB() >>> 32.56
-
getHeat
()[source]¶ Heater output query
Returns: - Value: Float, e.g.: 0.001
Examples
>>> ls331.getHeat() >>> 51.530
-
getHeaterRange
()[source]¶ Heater range command.
Returns: - Value: Float, e.g.: 0.001
Examples
>>> ls331.getHeaterRange() >>> 51.530
-
getKTempA
()[source]¶ Returns channel A temperature in Kelvin.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getKTempA() >>> 32.56
-
getKTempB
()[source]¶ Returns channel B temperature in Kelvin.
Returns: - Value: float, e.g.: 0.001
Examples
>>> ls331.getKTempB() >>> 32.56
EPICS - Linkam CI94 Temperature Controller¶
The Linkam CI94 is a temperature controller. It can be connected only to the temperature stage or also to the nitrogen pump (Linkam LNP94/2), which increases the controller precision. This class supports operating either with or without the nitrogen pump and supports configuring the pump to automatic mode.
Using EPICS MarCCD camera module¶
Usage of Python class for EPICS Linkam CI94.
-
class
py4syn.epics.LinkamCI94Class.
LinkamCI94
(pvName, mnemonic)[source]¶ Class to control Linkam CI94 temperature controllers via EPICS.
Examples
>>> from py4syn.epics.LinkamCI94Class import LinkamCI94 >>> >>> def showTemperature(pv='', name=''): ... ci94 = LinkamCI94(pv, name) ... print('Temperature is: %d' % ci94.getValue()) ... >>> def fastRaiseTemperature(ci94, amount, rate=30): ... ci94.setRate(rate) ... ci94.setValue(ci94.getValue() + amount) ... >>> def complexRamp(ci94): ... ci94.setPumpSpeed(-1) ... ci94.setRate(10) ... ci94.setValue(200) ... ci94.wait() ... ci94.setRate(2) ... ci94.setValue(220) ... ci94.wait() ... sleep(500) ... ci94.setRate(5) ... ci94.setValue(100) ... ci94.wait() ... ci94.stop() ... >>> import py4syn >>> from py4syn.epics.ScalerClass import Scaler >>> from py4syn.utils.counter import createCounter >>> from py4syn.utils.scan import scan >>> >>> def temperatureScan(start, end, rate, pv='', counter='', channel=2): ... ci94 = LinkamCI94(pv, 'ci94') ... py4syn.mtrDB['ci94'] = ci94 ... c = Scaler(counter, channel, 'simcountable') ... createCounter('counter', c, channel) ... ci94.setRate(rate) ... scan('ci94', start, end, 10, 1) ... ci94.stop() ...
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvName : string
Power supply base naming of the PV (Process Variable)
- mnemonic : string
Temperature controller mnemonic
-
getRealPosition
()[source]¶ Returns the same as
getValue()
.See:
getValue()
Returns: - `float`
-
isRunning
()[source]¶ Returns true if the controller is in program mode. Whenever it is program mode, it is following a target temperature.
Returns: - `bool`
-
onPendingChange
(value, **kwargs)[source]¶ Helper callback that tracks when the IOC finished changing to a requested temperature.
-
onTemperatureChange
(**kwargs)[source]¶ Helper callback that indicates when the measured temperature changed.
-
setPumpSpeed
(speed)[source]¶ Changes the nitrogen pump speed, or enables automatic pump speed control.
Note
The Linkam front panel only has 5 LEDs to indicate speed, but internally it supports 30 different speed levels.
Parameters: - speed : int
The requested pump speed, ranging from 0 (pump off) to 30 (pump top speed), or -1 to enable automatic pump control.
-
setRate
(r)[source]¶ Sets the ramp speed in degrees per minutes for use with
setValue()
.See:
setValue()
Parameters: - r : float
Ramp speed in °C/min
-
setValue
(v)[source]¶ Changes the temperature to a new value. The speed that the new temperature is reached is set with
setRate()
. The default rate is 5 °C/minute.See:
setRate()
Parameters: - v : float
The target temperature in °C
-
setVelocity
(velo)[source]¶ Same as
setRate()
.See:
setRate()
Parameters: - r : float
Ramp speed in °C/min
MarCCD X-ray Detector System¶
The MarCCD X-ray detectors are programmable cameras. Access to the camera is not done with EPICS. Instead, the camera host machine provides a TCP socket with a custom protocol for communication. The camera may be used as a standard Py4Syn ICountable, but instead of returning values to be plotted, the acquired images are stored into files.
The MarCCD Py4Syn class supports using software controlled shutters. The shutters supported can be one of two types: normal shutters and toggle shutters. Both shutters are accessed as EPICS PVs representing bits. The difference is that normal shutters have zero and one values to represent the open and closed states, while the toggle shutter uses one PV to toggle the shutter state and another to read back the current state.
Using EPICS MarCCD camera module¶
Usage of Python class for EPICS MarCCD cameras.
-
class
py4syn.epics.MarCCDClass.
MarCCD
(mnemonic, address)[source]¶ Class to control MarCCD cameras via TCP sockets.
Examples
>>> from shutil import move >>> from py4syn.epics.MarCCDClass import MarCCD >>> from py4syn.epics.ShutterClass import SimpleShutter >>> >>> def getImage(host='localhost', port=2222, fileName='image.tif', shutter=''): ... shutter = SimpleShutter(shutter, shutter) ... camera = MarCCD(name, (host, port)) ... camera.setCountTime(10) ... camera.startCount() ... shutter.open() ... camera.wait() ... camera.stopCount() ... shutter.close() ... camera.writeImage('/remote/' + fileName) ... move('/remote/' + fileName, '/home/user/' + fileName) ... camera.close() ... >>> def acquireSetWithCorrection(camera, shutter, exposure=10, count=10, prefix='data'): ... try: ... shutter.close() ... camera.darkNoise() ... camera.setCountTime(exposure) ... camera.setSubScan(count=2) ... ... for i in range(count): ... remote = '/remote/%s-%02d.tif' % (prefix, i) ... local = '/home/user/%s-%02d.tif' % (prefix, i) ... camera.startCount() ... shutter.open() ... camera.wait() ... camera.stopCount() ... shutter.close() ... camera.waitForIdle() ... camera.startCount() ... shutter.open() ... camera.wait() ... camera.stopCount() ... shutter.close() ... camera.dezinger() ... camera.correct() ... camera.writeImage(remote) ... move(remote, local) ... finally: ... camera.close() ... shutter.close() ...
Constructor See
py4syn.epics.StandardDevice
Parameters: - mnemonic : string
Camera mnemonic
- address : tuple
Camera host server Internet address
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
close
()[source]¶ Cleans up and closes camera remote connection. This method must be called when finishing operation with the camera.
-
correct
()[source]¶ Queues image correction on the MarCCD server. After the image is corrected, it can be saved to a file.
There are three corrections applied: dark noise image subtraction, flat field correction and geometric correction. The dark noise correction uses a dark image to fix the reference (zero) intensity levels for each pixel. The flat field correction uses a bright image to correct the gain for each pixel. The geometric correction fixes distortion from the fiber optic taper.
Note
The dark noise image should be frequently generated. Use the method
darkNoise()
for that.See:
darkNoise()
-
darkNoise
(delay=0)[source]¶ Prepares a dark noise image to be used as a correction image by the server. One of the steps after acquiring an image is to correct it by subtracting the dark noise image from it. This method is used to generate the dark noise image to be used later in the acquisitions. The method must be called with the camera covered. A dark noise image must be generated at least once after starting the MarCCD server.
Note
The following guideline is available on the MarCCD user guide: “The background doesn’t have to be retaken for every data image taken, but generally should be retaken at the start of every new data set, or once every half hour, whichever is sooner (depending on the thermal stability of the hutch). For the MarCCD detector, if a mismatch in the level of the 4 quadrants of data frames is noticed, the bias is probably drifting and should be recollected (and maybe should be set to be collected more often).”
Parameters: - delay : float
The time for each background acquisition. The MarCCD camera can either be calibrated with a zero delay between the acquisitions (this is called a bias frame acquisition in MarCCD manual), or with a non-zero (a standard dark frame acquisition). Note that 2 background acquisitions are done. They are then passed through the dezinger algorithm, which averages and removes outlier spots in the image.
-
dezinger
()[source]¶ Apply the dezinger correction algorithm in 2 images and store the resulting image in the MarCCD server. The dezinger algorithm averages corresponding pixels from each image, but if they deviate too much, it discards the brighter one and keeps the lower value. This removes the “zingers”, bright spots in the image, which are not caused by the input light.
To be able to use the dezinger method, 2 images must be present in server memory. This can be accomplished by calling
setSubScan()
before the acquisition.Note
The following guildeline is present in MarCCD manual: “Dezingering does require special care that the two images are truly identical (same X-ray dose, same movement of the sample, etc.); otherwise the statistical test will yield unpredictable results. In particular, if the X-ray beam is not constant intensity, or the sample is decaying, then the exposure times and diffractometer motions must compensate for that. If there are significant differences between the frames, then the artifacts created by dezingering may yield worse results than simply using normal, single-read images with zingers in them. Though they are not aethetically pleasing, some kinds of data analysis can tolerate many zingers.
Examples
>>> def acquireTwiceAndDezinger(marccd, time): ... marccd.setCountTime(time) ... marccd.setSubScan(count=2) ... marccd.startCount() ... marccd.wait() ... marccd.stopCount() ... marccd.waitForIdle() ... marccd.startCount() ... marccd.wait() ... marccd.stopCount() ... marccd.dezinger() ...
-
getState
(timeout=60)[source]¶ Returns the camera state. The state can be used to check for errors, to find out which operations are queued or being executed and if the server is busy interpreting a command.
The camera state is an integer with a 4-bit value, plus five 4-bit fields: acquire, read, correct, write and (highest) dezinger. The low 4-bit state value can be 0, for idle, 7 for bad request and 8 for busy. Each 4-bit field has 4 flags: queued (0x1), executing (0x2), error (0x4) and reserved (0x8). For example, the state 0x011200 means that a read is executing, a correction is queued and a write is queued. The state mask 0x444444 can be used to look for an error on any operation. The lowest field (state) uses the value 8 to indicate it’s busy processing a command, so state 0x8 means “interpreting command”.
Parameters: - timeout : float
Time to wait for camera answer
Returns: - `int`
-
getValue
(**kwargs)[source]¶ This is a dummy getValue method that always returns zero, which is part of the
py4syn.epics.ICountable
interface. The MarCCD does not return a value while scanning. Instead, it stores a file with the resulting image.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setImageSize
(width, height)[source]¶ Chooses the acquired image size.
Parameters: - width: `int`
Image width. Must be either 512, 1024 or 2048 and must be the equal to the image height.
- height: `int`
Image height. Must be either 512, 1024 or 2048 and must be the equal to the image width.
-
setPresetValue
(channel, val)[source]¶ Abstract method to set the preset count of a countable target device.
Parameters: - channel : int
The monitor channel number
- val : int
The preset value
Returns: - out : None
-
setState
(state, timeout=60)[source]¶ Changes the camera state bit field. This method does not change the operating state, just the reported integer value. It is a helper method to deal with a quirk in the MarCCD server that makes the error and busy bits to get stuck and never reset. Usually the only value that makes sense for the state is zero, to clear all the bits.
See:
getState()
Parameters: - state : int
Time to wait for camera answer
- timeout : float
Time to wait for camera answer
-
setSubScan
(count=2)[source]¶ Configure the MarCCD object to know that each acquisition will be done in multiple steps. This effectivelly means that a series of acquisitions will be done in sequence, which will be processed together, resulting in a single final image. This method is mainly required for the
dezinger()
method to work.Parameters: - count : int
Number of sub scans that will compose a single final image. Can be either 1, to disable sub scan logic, or 2, which will make
stopCount()
store images alternatedly in “scratch” (auxiliary) memory and “raw” (main) memory.
-
startCount
()[source]¶ Starts acquiring an image. This will acquire image data until asked to stop with
stopCount()
.Note
Due to way the camera protocol is currently implemented, this method ignores the configured acquisition count time. Because of that, the proper way to do a timed acquisition is to follow this method call with
wait()
, then immediatelly callstopCount()
. Thepy4syn.utils.scan.scan()
function in Py4Syn executes this method sequence.See:
setCountTime()
,stopCount()
,wait()
Examples
>>> def acquire(marccd, time): ... marccd.setCountTime(time) ... marccd.startCount() ... marccd.wait() ... marccd.stopCount() ...
-
stateRequest
(request, timeout=60)[source]¶ Helper method used to get or set camera state.
Parameters: - request : string
Command to be passed to the camera
- timeout : float
Time to wait for camera answer
Returns: - `int`
-
stopCount
()[source]¶ Stops acquiring the image and stores it into server memory. The acquired image will be available to apply corrections and to be written to an output file.
If no call to
startCount()
was done before calling this method, then nothing is done.
-
wait
()[source]¶ Blocks until the configured count time passes since the call to
startCount()
. The time amount is configured withsetCountTime()
, or 1 second by default.If an acquisition has not been started, this method returns immediatelly.
See:
setCountTime()
,startCount()
-
waitForIdle
()[source]¶ Blocks until the camera server is completely idle. This is required because the camera and the server are slow and certain operations, in particular, multiple sequential acquisitions would fail without waiting for some time. Acquiring two images and dezingering them only works with this method being called between the acquisitions.
-
waitForImage
()[source]¶ Blocks until the acquired image has been corrected and written to disk. This can be used any time after calling
stopCount()
to make sure file operations can be performed on the resulting image (copied, post-processed, etc.)
-
waitUntil
(condition, timeout=60)[source]¶ Blocks until the camera state asserts a certain condition. This method can be used to confirm that an operation has started, or if the camera is reporting an error. The condition is a bit mask with the same meanings as described in
getState()
. For example, calling this method with condition set to 0x20 blocks until an aquisition is executing.This method detects errors automatically by raising an exception if any error bit is set.
See:
getState()
Parameters: - condition : int
State condition mask. If any of the condition bits is set, the condition is considered to be true.
- timeout : float
Time to wait for the condition to be deasserted
-
waitWhile
(condition, timeout=60)[source]¶ Blocks while the camera state asserts a certain condition. This method can be used to confirm that an operation has finished, or if the camera is reporting an error. The condition is a bit mask with the same meanings as described in
getState()
. For example, calling this method with condition set to 0x30 blocks while an aquisition is either queued or executing. Similarly, it’s possible to block while the camera server is either processing or writing the image with condition set to 0x333308.This method detects errors automatically by raising an exception if any error bit is set.
See:
getState()
Parameters: - condition : int
State condition mask. If any of the condition bits is set, the condition is considered to be true.
- timeout : float
Time to wait for the condition to be deasserted
-
waitWhileOrUntil
(condition, timeout=60, until=False)[source]¶ Helper method that implements
waitWhile()
andwaitUntil()
-
writeImage
(fileName, wait=True)[source]¶ Write the image stored in MarCCD server memory in a file. This method does not store the resulting image in the local machine. Since current MarCCD server protocol does not allow locally downloading the resulting image, this method only asks for the MarCCD camera server to store the image in a remote location. To make the file accessible locally, other means must be used, for example, by instructing the server to save the image in shared storage.
Parameters: - fileName : string
Target file name in remote MarCCD server
- wait : bool
Set to True if the method should block until the image is written to disk
Modem control¶
This is the basic Python class to …
Motoman DX100 controller¶
This is the basic Python class to …
Motors control¶
This is the basic Python class to control motor devices by using EPICS set of tools to provide the minimal infrastructure for use in managing and operating motor devices by reading and/or setting their record fields - also known as PVs, Process Variables.
You will find below a set of methods which is available at this version of the Motor’s class with their expected input parameters and/or waited results (if any), describing involved data types.
Using the EPICS Motors control module¶
Usage of Python class using basic Motor Record fields.
-
class
py4syn.epics.MotorClass.
Motor
(pvName, mnemonic)[source]¶ Class to control motor devices via EPICS.
Examples
>>> from py4syn.epics.MotorClass import Motor >>> >>> def createMotor(pvName="", mne=""): ... ... new_motor = '' ... ... try: ... new_motor = Motor(pvName, mne) ... print "Motor " + pvName + " created with success!" ... except Exception,e: ... print "Error: ",e ... ... return new_motor
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvName : string
Motor’s base naming of the PV (Process Variable)
- mnemonic : string
Motor’s mnemonic
-
calculateBacklash
(target)[source]¶ Calculates the backlash distance of a given motor
Returns: - `double`
-
canPerformMovement
(target)[source]¶ Check if a movement to a given position is possible using the limit values and backlash distance
Returns: - `boolean`
- .. note::
- True – Motor CAN perform the desired movement;
- False – Motor CANNOT perform the desired movement.
-
canPerformMovementCalc
(target)[source]¶ Check if a movement to a given position is possible using the limit values and backlash distance calculating the values
Returns: - `boolean`
- .. note::
- True – Motor CAN perform the desired movement;
- False – Motor CANNOT perform the desired movement.
-
getAcceleration
()[source]¶ Get the motor acceleration time based on the ACCL (Seconds to Velocity) field from Motor Record
Returns: - `double`
-
getBacklashDistanceValue
()[source]¶ Read the motor backlash distance based on the BDST (Backlash Distance, EGU) field of Motor Record
Returns: - `double`
-
getDescription
()[source]¶ Read the motor descrition based on the DESC field of Motor Record
Returns: - `string`
-
getDialHighLimitValue
()[source]¶ Read the motor dial high limit based on the DHLM (Dial High Limit) field of Motor Record
Returns: - `double`
-
getDialLowLimitValue
()[source]¶ Read the motor dial low limit based on the DLLM (Dial Low Limit) field of Motor Record
Returns: - `double`
-
getDialPosition
()[source]¶ Read the motor target DIAL position based on the DVAL (Dial Desired Value) field of Motor Record
Returns: - `double`
-
getDialRealPosition
()[source]¶ Read the motor DIAL real position based on the DRBV (Dial Readback Value) field of Motor Record
Returns: - `double`
-
getDirection
()[source]¶ Read the motor direction based on the DIR (User Direction) field of Motor Record
Returns: - `integer`
- .. note::
- Positive direction;
- Negative direction.
-
getEGU
()[source]¶ Read the motor engineering unit based on the EGU (Engineering Units) field of Motor Record
Returns: - `string`
-
getFreezeOffset
()[source]¶ Read the motor freeze offset based on the FOF (Freeze Offset) field of Motor Record
Returns: - `integer`
-
getHighLimitValue
()[source]¶ Read the motor high limit based on the HLM (User High Limit) field of Motor Record
Returns: - `double`
-
getLVIO
()[source]¶ Read the motor limit violation LVIO (Limit Violation) field of Motor Record
Returns: - `short`
-
getLowLimitValue
()[source]¶ Read the motor low limit based on the LLM (User Low Limit) field of Motor Record
Returns: - `double`
-
getOffset
()[source]¶ Read the motor offset based on the OFF (User Offset, EGU) field of Motor Record
Returns: - `string`
-
getPosition
()[source]¶ Read the motor target position based on the VAL (User Desired Value) field of Motor Record
Returns: - `double`
-
getRawPosition
()[source]¶ Read the motor RAW position based on the RVAL (Raw Desired Value) field of Motor Record
Returns: - `double`
-
getRawRealPosition
()[source]¶ Read the motor RAW real position based on the RRBV (Raw Readback Value) field of Motor Record
Returns: - `double`
-
getRealPosition
()[source]¶ Read the motor real position based on the RBV (User Readback Value) field of Motor Record
Returns: - `double`
-
getSETMode
()[source]¶ Checks if the motor is in SET mode
Note
Motor will NOT move until it is in in USE mode
-
getValue
()[source]¶ Get the current position of the motor. See
py4syn.epics.IScannable
Returns: - `double`
Read the current value (Motor Real Position)
-
getVariableOffset
()[source]¶ Read the motor variable offset based on the VOF (Variable Offset) field of Motor Record
Returns: - `integer`
-
getVelocity
()[source]¶ Get the motor velocity based on the VELO (Velocity, EGU/s) field from Motor Record
Returns: - `double`
-
isAtHighLimitSwitch
()[source]¶ Check if a motor high limit switch is activated, based on the HLS (At High Limit Switch) field of Motor Record
Returns: - `boolean`
- .. note::
- True – Motor is at High Limit;
- False – Motor is NOT at High Limit.
-
isAtLowLimitSwitch
()[source]¶ Check if a motor low limit switch is activated, based on the LLS (At Low Limit Switch) field of Motor Record
Returns: - `boolean`
- .. note::
- True – Motor is at Low Limit;
- False – Motor is NOT at Low Limit.
-
isMoving
()[source]¶ Check if a motor is moving or not based on the callback
Returns: - `boolean`
- .. note::
- True – Motor is moving;
- False – Motor is stopped.
-
isMovingPV
()[source]¶ Check if a motor is moving or not from the PV
Returns: - `boolean`
- .. note::
- True – Motor is moving;
- False – Motor is stopped.
-
setAbsolutePosition
(pos, waitComplete=False)[source]¶ Move the motor to an absolute position received by an input parameter
Parameters: - pos : double
The desired position to set
- waitComplete : boolean (default is False)
Note
If True, the function will wait until the movement finish to return, otherwise don’t.
-
setAcceleration
(accl)[source]¶ Set the motor acceleration time based on the ACCL (Seconds to Velocity) field from Motor Record
Parameters: - accl : double
The desired acceleration to set
-
setDialHighLimitValue
(val)[source]¶ Set the motor dial high limit based on the DHLM (Dial High Limit) field of Motor Record
Parameters: - val : double
The desired value to set
-
setDialLowLimitValue
(val)[source]¶ Set the motor dial low limit based on the DLLM (Dial Low Limit) field of Motor Record
Parameters: - val : double
The desired value to set
-
setDialPosition
(pos, waitComplete=False)[source]¶ Set the motor target DIAL position based on the DVAL (Dial Desired Value) field of Motor Record
Parameters: - pos : double
The desired position to set
- waitComplete : boolean (default is False)
Note
If True, the function will wait until the movement finish to return, otherwise don’t.
-
setEGU
(unit)[source]¶ Set the motor engineering unit to the EGU (Engineering Units) field of Motor Record
Parameters: - unit : string
The desired engineering unit.
Note
Example: “mm.”, “deg.”
-
setFreezeOffset
(val)[source]¶ Set the motor freeze offset based on the FOF (Freeze Offset) field of Motor Record
Parameters: - val : integer
The desired value to set
-
setHighLimitValue
(val)[source]¶ Set the motor high limit based on the HLM (User High Limit) field of Motor Record
Parameters: - val : double
The desired value to set
-
setLowLimitValue
(val)[source]¶ Set the motor low limit based on the LLM (User Low Limit) field of Motor Record
Parameters: - val : double
The desired value to set
-
setOffset
(val)[source]¶ Set the motor offset based on the OFF (User Offset, EGU) field of Motor Record
Parameters: - val : double
The desired value to set
-
setRawPosition
(position)[source]¶ Sets the motor RAW position based on the RVAL (Raw Desired Value) field of Motor Record
Returns: - `double`
-
setRelativePosition
(pos, waitComplete=False)[source]¶ Move the motor a distance, received by an input parameter, to a position relative to that current one
Parameters: - pos : double
The desired distance to move based on current position
- waitComplete : boolean (default is False)
-
setUpdateRequest
(val)[source]¶ Set the motor update request flag based on the STUP (Status Update Request) field from Motor Record
Parameters: - val : integer
The desired value to set for the flag
-
setValue
(v)[source]¶ Set the desired motor position. See
py4syn.epics.IScannable
Parameters: - v : double
The desired value (Absolute Position) to set
-
setVariableOffset
(val)[source]¶ Set the motor variable offset based on the VOF (Variable Offset) field of Motor Record
Parameters: - val : integer
The desired value to set
-
setVelocity
(velo)[source]¶ Set the motor velocity up based on the VELO (Velocity, EGU/s) field from Motor Record
Parameters: - velo : double
The desired velocity to set
Mythen detectors¶
This is the basic Python class to controll Mythen detectors (Microstrip system for time-resolved experiments).
Using the Mythen detectors module¶
Usage of Python class for EPICS Mythen detectors (Microstrip system for time-resolved experiments).
-
class
py4syn.epics.MythenClass.
Mythen
(pvPrefix, mnemonic)[source]¶ -
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Abstract method to get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(t)[source]¶ Abstract method to set the count time of a countable target device.
Parameters: - t : value
The target count time to be set.
Returns: - out : None
-
Omron E5CK Temperature Controller¶
The Omron E5CK temperature controllers are programmable temperature controllers. The Py4Syn implementation is strongly software based, overcoming device programming limitations, allowing it to be used like an IScannable device and supporting tens of thousands of ramp steps.
Using EPICS Omron E5CK temperature controller module¶
Usage of Python class for EPICS Omron E5CK temperature controllers.
-
class
py4syn.epics.OmronE5CKClass.
OmronE5CK
(pvName, mnemonic)[source]¶ Class to control Omron E5CK temperature controllers via EPICS.
Examples
>>> from py4syn.epics.OmronE5CKClass import OmronE5CK >>> >>> def showTemperature(pv='', name=''): ... e5ck = OmronE5CK(pv, name) ... print('Temperature is: %d' % e5ck.getValue()) ... >>> def fastRaiseTemperature(e5ck, amount, rate=30): ... e5ck.setRate(rate) ... e5ck.setValue(e5ck.getValue() + amount) ... >>> def complexRamp(e5ck): ... e5ck.setRate(10) ... e5ck.setValue(200) ... e5ck.wait() ... e5ck.setRate(2) ... e5ck.setValue(220) ... e5ck.wait() ... sleep(500) ... e5ck.setRate(5) ... e5ck.setValue(100) ... e5ck.wait() ... e5ck.stop() ... >>> import py4syn >>> from py4syn.epics.ScalerClass import Scaler >>> from py4syn.utils.counter import createCounter >>> from py4syn.utils.scan import scan >>> >>> def temperatureScan(start, end, rate, pv='', counter='', channel=2): ... e5ck = OmronE5CK(pv, 'e5ck') ... py4syn.mtrDB['e5ck'] = e5ck ... c = Scaler(counter, channel, 'simcountable') ... createCounter('counter', c, channel) ... e5ck.setRate(rate) ... scan('e5ck', start, end, 10, 1) ... e5ck.stop() ...
Constructor See
py4syn.epics.StandardDevice
Parameters: - pvName : string
Power supply base naming of the PV (Process Variable)
- mnemonic : string
Temperature controller mnemonic
-
getRealPosition
()[source]¶ Returns the same as
getValue()
.See:
getValue()
Returns: - `float`
-
getStepNumberSync
()[source]¶ Helper module to retrieve an up-to-date value for the current program step number. Similar to
getStepNumber()
, but it doesn’t rely on monitor value and instead does a synchronous caget() call.See:
getStepNumber()
Returns: - `int`
-
getTarget
()[source]¶ Returns the current target temperature. If the device is running, the target temperature is the temperature the device is changing to. If the device is not running, the target temperature is ignored.
Returns: - `float`
-
getTimeScale
()[source]¶ Returns the time scale being used by the controller. The timescale can either be zero, for hours:minutes, or one, for minutes:seconds.
Returns: - `int`
-
isRunning
()[source]¶ Returns true if the controller is in program mode. Whenever it is program mode, it is following a target temperature.
Returns: - `bool`
-
onProgrammingChange
(value, **kwargs)[source]¶ Helper callback that tracks when the IOC finished programming the device.
-
onStepChange
(value, **kwargs)[source]¶ Helper callback that indicates when a new program step has been reached
-
onTemperatureChange
(value, **kwargs)[source]¶ Helper callback that indicates when the measured temperature has changed
-
preset
()[source]¶ Makes the controler enter a well defined known state. This method creates and runs an “empty” ramp program. The program simply mantains the current temperature forever, whatever that temperature is. This is mostly a helper function, to allow making complex temperature ramps starting from a known state and reusing the preset values.
Note
Running a new program requires stopping the current program. While the program is stopped, the controller power generation drops to zero. Because of this power drop, this method may be slow to stabilize.
-
sendCommand
(command)[source]¶ Helper method to send a custom command to the controller.
Parameters: - command : str
The command to be send
-
setRate
(r)[source]¶ Sets the ramp speed in degrees per minutes for use with
setValue()
. This method does not send a command to the controller, it only stores the rate for the next ramps.See:
setValue()
Parameters: - r : float
Ramp speed in °C/min
-
setTimeScale
(minutes)[source]¶ Changes the time scale being used by the controller. The timescale can either be zero, for hours:minutes, or one, for minutes:seconds. This operation requires switching the controller operation mode to be successful, and then a reset is issued after it. The whole operation takes more than 5 seconds.
Parameters: - minutes : int
Set to 1 for minutes:seconds, or 0 for hours:minutes
-
setValue
(v)[source]¶ Changes the temperature to a new value. This method calls preset if it has not already been called first. The speed that the new temperature is reached is set with
setRate()
. The default rate is 5 °C/minute.See:
setRate()
Parameters: - v : float
The target temperature in °C
-
setVelocity
(velo)[source]¶ Same as
setRate()
.See:
setRate()
Parameters: - r : float
Ramp speed in °C/min
-
stop
()[source]¶ Stops executing the current temperature program and puts the device in idle state. In the idle state, the device will not try to set a target temperature.
-
synchronizeStep
(current)[source]¶ Helper method to set up a constant temperature right before running a ramp program. This method detects if a current ramp program is running or not. If it’s not, then it doesn’t do anything. If there is a ramp running, then it configures and advances to a “synchronization step”, that is, a step where the temperature does not change. This step marks the beginning of the new ramp.
The method returns the resulting step number
Parameters: - current : float
The temperature target for the synchronization step
Returns: - `int`
PCO 2000 Camera¶
This is the basic Python class to …
Photonic CCD Detector control¶
This is the basic Python class to …
Pilatus Detector System¶
The Pilatus X-ray detectors are programmable cameras. Py4Syn uses the standard area detector EPIC IOC for communicating with them. Since the IOC provides a high level API, most of the acquisition logic is implemented in the IOC. The camera is implemented as a standard ICountable, but instead of returning values to be plotted, the acquired images are stored into files.
Using EPICS Pilatus camera module¶
Usage of Python class for EPICS Pilatus cameras.
-
class
py4syn.epics.PilatusClass.
Pilatus
(mnemonic, pv)[source]¶ Class to control Pilatus cameras via EPICS.
Examples
>>> from shutil import move >>> from py4syn.epics.PilatusClass import Pilatus >>> from py4syn.epics.ShutterClass import SimpleShutter >>> >>> def getImage(pv, fileName='image.tif', shutter=''): ... shutter = SimpleShutter(shutter, shutter) ... camera = Pilatus('pilatus', pv) ... camera.setImageName('/remote/' + fileName) ... camera.setCountTime(10) ... camera.startCount() ... shutter.open() ... camera.wait() ... camera.stopCount() ... shutter.close() ... move('/remote/' + fileName, '/home/user/' + fileName) ... camera.close() ...
Constructor See
py4syn.epics.StandardDevice
Parameters: - mnemonic : string
A mnemonic for the camera
- pv : string
Base name of the EPICS process variable
-
getValue
(**kwargs)[source]¶ This is a dummy method that always returns zero, which is part of the
py4syn.epics.ICountable
interface. Pilatus does not return a value while scanning. Instead, it stores a file with the resulting image.
-
isCounting
()[source]¶ Returns true if the camera is acquiring an image, or false otherwise.
Returns: - `bool`
-
setFileName
(name)[source]¶ Sets the output image file name. The image will be saved with this name after the acquisition.
Parameters: - name : string
The name of image to save.
-
setFilePath
(path)[source]¶ Sets the output image file path. The image will be saved in this location after the acquisition.
Parameters: - name : string
The path of location to save the image.
-
setImageName
(name)[source]¶ Sets the output image file name. The image will be saved with this name after the acquisition.
Parameters: - name : string
The full pathname of the image.
-
setTriggerMode
(mode)[source]¶ Trigger mode
Parameters: - mode : int
0 : Internal 1 : Ext. Enable 2 : Ext. Trigger 3 : Mult. Trigger 4 : Alignment
-
startCount
()[source]¶ Starts acquiring an image. It will acquire for the duration set with
setCountTime()
. The resulting file will be stored in the file set withsetImageName()
.See:
setCountTime()
,setImageName()
Examples
>>> def acquire(pilatus, time, filename): ... pilatus.setCountTime(time) ... pilatus.setImageName(filename) ... pilatus.startCount() ... pilatus.wait() ... pilatus.stopCount() ...
Pseudo-Counters control¶
This is the basic Python class that creates a pseudo counter that has, as value, the result of a calculation based on the values of other counters.
Using Pseudo-Counter control module¶
Usage of Python class for Pseudo-Counter control.
-
class
py4syn.epics.PseudoCounterClass.
PseudoCounter
(mnemonic, backwardFormula)[source]¶ Class to control Pseudo-Counter (virtual counter).
Examples
>>> # Create a Simulated Counter >>> scaler = SimCountable("SOL:SCALER01", 2) >>> >>> # Create two channels: det and mon >>> createCounter("mon", scaler, 1) >>> createCounter("det", scaler, 2) >>> >>> # Create a Pseudo counter with the formula >>> pseudoCounter = PseudoCounter("relation", "C[det]/C[mon]") >>> >>> # Create a new channel based on this pseudo-counter >>> createCounter("relation", pseudoCounter) >>> >>> # Start a count process >>> ct(1) >>>
Pseudo Counter class Constructor
Parameters: - mnemonic : string
Counter mnemonic
- backwardFormula : string
Mathematical Formula used to calculate the Pseudo counter value position based on other counters
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(t)[source]¶ Abstract method to set the count time of a countable target device.
Parameters: - t : value
The target count time to be set.
Returns: - out : None
Pseudo-Motors control¶
This is the basic Python class using a set of EPICS motors and formulas to create a Pseudo Motor.
Using EPICS Pseudo-Motors control module¶
Usage of Python class for Pseudo-Motors control.
-
class
py4syn.epics.PseudoMotorClass.
PseudoMotor
(mnemonic, description, backwardFormula, forwardFormulasDict)[source]¶ Class to control Pseudo-Motor (virtual Motor).
Examples
>>> from py4syn.epics.PseudoMotorClass import PseudoMotor >>> >>> def createPseudoMotor(mnemonic="", description="", backwardFormula="", forwardFormulasDict= []): ... ... new_pseudo_motor = '' ... ... try: ... new_motor = PseudoMotor("motorName", "pseudo-motor to help controlling experiment", "", []) ... print "Motor " + pvName + " created with success!" ... except Exception,e: ... print "Error: ",e ... ... return new_pseudo_motor
Pseudo Motor class Constructor
Parameters: - mnemonic : string
Motor mnemonic
- description : string
Motor Description
- backwardFormula : string
Mathematical Formula used to calculate the Pseudo motor position based on other motors
- forwardFormulasDict : dictionary
Dictionary containing mathematical relations to move each of the motors involved in the pseudo motor movement
-
canPerformMovement
(target)[source]¶ Check if a movement to a given position is possible using the limit values and backlash distance
Returns: - `boolean`
- .. note::
- True – Motor CAN perform the desired movement;
- False – Motor CANNOT perform the desired movement.
-
getBacklashDistanceValue
()[source]¶ Read the motor backlash distance based on the BDST (Backlash Distance, EGU) field of virtual Motor
Returns: - `double`
-
getDescription
()[source]¶ Read the motor description based on the DESC (Description) field of virtual Motor
Returns: - `string`
-
getDialHighLimitValue
()[source]¶ Read the motor dial high limit based on the DHLM (Dial High Limit) field of virtual Motor
Returns: - `double`
-
getDialLowLimitValue
()[source]¶ Read the motor dial low limit based on the DLLM (Dial Low Limit) field of virtual Motor
Returns: - `double`
-
getDialPosition
()[source]¶ Read the motor target DIAL position based on the DVAL (Dial Desired Value) field of virtual Motor
Returns: - `double`
-
getDialRealPosition
()[source]¶ Read the motor DIAL real position based on the DRBV (Dial Readback Value) field of virtual Motor
Returns: - `double`
-
getDirection
()[source]¶ Read the Pseudo motor direction
Returns: - `integer`
- .. note::
- Positive direction;
- Negative direction.
-
getEGU
()[source]¶ Read the motor engineering unit based on the EGU (Engineering Units) field of the virtual Motor
Returns: - `string`
-
getFreezeOffset
()[source]¶ Read the motor freeze offset based on the FOF (Freeze Offset) field of virtual Motor
Returns: - `integer`
-
getHighLimitValue
()[source]¶ Read the motor high limit based on the HLM (User High Limit) field of virtual Motor
Returns: - `double`
-
getLVIO
()[source]¶ Read the motor limit violation LVIO (Limit Violation) field of the virtual Motor
Returns: - `short`
-
getLimitValue
(high)[source]¶ Auxiliary method called by
getHighLimitValue()
andgetLowLimitValue()
to get the high and low limit values of a pseudo motor. The limits are calculated based on a maximization or minimization, depending on the high parameter, of the pseudo motor equation, considering the bounds of the real motors.See
getHighLimitValue()
,getLowLimitValue()
Parameters: - high : bool
True if the high limit value is requested, false if the low limit is requested.
Returns: - `double`
-
getLowLimitValue
()[source]¶ Read the motor low limit based on the LLM (User Low Limit) field of virtual Motor
Returns: - `double`
-
getOffset
()[source]¶ Read the motor offset based on the OFF (User Offset, EGU) field of virtual Motor
Returns: - `string`
-
getPosition
()[source]¶ Read the motor target position based on the VAL (User Desired Value) field of virtual Motor
Returns: - `double`
-
getRawPosition
()[source]¶ Read the motor RAW position based on the RVAL (Raw Desired Value) field of Motor Record
Returns: - `double`
-
getRawRealPosition
()[source]¶ Read the motor RAW real position based on the RRBV (Raw Readback Value) field of Motor Record
Returns: - `double`
-
getRealPosition
()[source]¶ Read the motor real position based on the RBV (User Readback Value) field of virtual Motor
Returns: - `double`
-
getValue
()[source]¶ Get the current position of the motor. See
py4syn.epics.IScannable
Returns: - `double`
Read the current value (virtual Motor Real Position)
-
getVariableOffset
()[source]¶ Read the motor variable offset based on the VOF (Variable Offset) field of virtual Motor
Returns: - `integer`
-
isAtHighLimitSwitch
()[source]¶ Check if the high limit switch of any of the motors is activated
Returns: - `int`
- .. note::
- 1 – At least one Motor is at High Limit;
- 0 – NO one of the Motors is at High Limit.
-
isAtLowLimitSwitch
()[source]¶ Check if the low limit switch of any of the motors is activated
Returns: - `int`
- .. note::
- 1 – At least one Motor is at Low Limit;
- 0 – NO one of the Motors is at Low Limit.
-
isMoving
()[source]¶ Check if any of the motors are moving
Returns: - `boolean`
- .. note::
- True – At least one Motor is being moved;
- False – NO one of the Motors is being moved.
-
setAbsolutePosition
(pos, waitComplete=False)[source]¶ Move the motor to an absolute position received by an input parameter
Parameters: - pos : double
The desired position to set
- waitComplete : boolean (default is False)
Note
If True, the function will wait until the movement finish to return, otherwise don’t.
-
setAcceleration
(accl)[source]¶ Set the motor acceleration time based on the ACCL (Seconds to Velocity) field from virtual Motor
Parameters: - accl : double
The desired acceleration to set
-
setDialHighLimitValue
(val)[source]¶ Set the motor dial high limit based on the DHLM (Dial High Limit) field of virtual Motor
Parameters: - val : double
The desired value to set
-
setDialLowLimitValue
(val)[source]¶ Set the motor dial low limit based on the DLLM (Dial Low Limit) field of virtual Motor
Parameters: - val : double
The desired value to set
-
setDialPosition
(pos, waitComplete=False)[source]¶ Set the motor target DIAL position based on the DVAL (Dial Desired Value) field of virtual Motor
Parameters: - pos : double
The desired position to set
- waitComplete : boolean (default is False)
Note
If True, the function will wait until the movement finish to return, otherwise don’t.
-
setEGU
(unit)[source]¶ Set the motor engineering unit to the EGU (Engineering Units) field of virtual Motor
Parameters: - unit : string
The desired engineering unit.
Note
Example: “mm.”, “deg.”
-
setFreezeOffset
(val)[source]¶ Set the motor freeze offset based on the FOF (Freeze Offset) field of virtual Motor
Parameters: - val : integer
The desired value to set
-
setHighLimitValue
(val)[source]¶ Set the motor high limit based on the HLM (User High Limit) field of virtual Motor
Parameters: - val : double
The desired value to set
-
setLowLimitValue
(val)[source]¶ Set the motor low limit based on the LLM (User Low Limit) field of virtual Motor
Parameters: - val : double
The desired value to set
-
setOffset
(val)[source]¶ Set the motor offset based on the OFF (User Offset, EGU) field of virtual Motor
Parameters: - val : double
The desired value to set
-
setRelativePosition
(pos, waitComplete=False)[source]¶ Move the motor a distance, received by an input parameter, to a position relative to that current one
Parameters: - pos : double
The desired distance to move based on current position
- waitComplete : boolean (default is False)
-
setUpdateRequest
(val)[source]¶ Set the motor update request flag based on the STUP (Status Update Request) field from virtual Motor
Parameters: - val : integer
The desired value to set for the flag
-
setValue
(v)[source]¶ Set the desired motor position. See
py4syn.epics.IScannable
Parameters: - v : double
The desired value (Absolute Position) to set
-
setVariableOffset
(val)[source]¶ Set the motor variable offset based on the VOF (Variable Offset) field of virtual Motor
Parameters: - val : integer
The desired value to set
-
setVelocity
(velo)[source]¶ Set the motor velocity up based on the VELO (Velocity, EGU/s) field from virtual Motor
Parameters: - velo : double
The desired velocity to set
-
class
py4syn.epics.PseudoMotorClass.
motorPosition
[source]¶ Class to globally control positioning of virtual Motor
-
__getitem__
(m)[source]¶ Get current value of the virtual Motor positionin
Parameters: - m : dictionary
Represents the device, virtual Motor, in the mtrDB global array of devices
Returns: - `double`
Read the current value (virtual Motor Real Position)
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
py4syn.epics.PseudoMotorClass.
motorPositionDial
[source]¶ Class to globally control positioning of virtual Motor using Dial fields
-
__getitem__
(m)[source]¶ Get current value of the virtual Motor positioning using Dial field
Parameters: - m : dictionary
Represents the device, virtual Motor, in the mtrDB global array of devices
Returns: - `double`
Read the current Positioning value of virtual Motor (Real) using Dial field
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
py4syn.epics.PseudoMotorClass.
motorTarget
[source]¶ Class to globally control virtual Motor targets
Constructor
Parameters: - None
-
__getitem__
(m)[source]¶ Get current value of the virtual Motor positioning
Parameters: - m : dictionary
Represents the device target, virtual Motor, in the mtrDB global array of devices
Returns: - `double` or `dictionary` item
Read the current Positioning value of virtual Motor (Real)
Note
If m parameter is received and it is in the targets list, then its correspondent target is returned (as a dictionary item), otherwise, real position of virtual Motor is returned (as a double value)
-
__setitem__
(m, pos)[source]¶ Set a position value to the virtual Motor target received as input parameter
Parameters: - m : dictionary
Represents the target device, virtual Motor, in the mtrDB global array of devices
- pos : double
The desired position to set
-
__weakref__
¶ list of weak references to the object (if defined)
-
class
py4syn.epics.PseudoMotorClass.
motorTargetDial
[source]¶ Class to globally control virtual Motor target using Dial fields
Constructor
Parameters: - None
-
__getitem__
(m)[source]¶ Get current value of the virtual Motor positioning using Dial field
Parameters: - m : dictionary
Represents the device target, virtual Motor, in the mtrDB global array of devices
Returns: - `double` or `dictionary` item
Read the current Positioning value of virtual Motor (Real)
Note
If m parameter is received and it is in the targets list, then its correspondent target is returned (as a dictionary item), otherwise, real position of virtual Motor, using the Dial field, is returned (as a double value)
-
__setitem__
(m, pos)[source]¶ Set a position value to the virtual Motor target received as input parameter
Parameters: - m : dictionary
Represents the target device, virtual Motor, in the mtrDB global array of devices
- pos : double
The desired position to set
-
__weakref__
¶ list of weak references to the object (if defined)
Scaler control¶
This is the basic Python class to …
Using EPICS Scaler control module¶
Usage of Python class using basic Motor Record fields.
-
class
py4syn.epics.ScalerClass.
Scaler
(pvScalerName='', numberOfChannels=1, mnemonic='', factor=1)[source]¶ -
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Abstract method to get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(time)[source]¶ Method to set the count time of a scaler device.
Parameters: - t : value
Count time to set to scaler device .
Returns: - out : None
-
Shutter control¶
This is the basic Python class to …
XIA Shutter control¶
This is the basic Python class which provides support for digital signal processor based multichannel analyzers from X-ray Instrumentation Associates (XIA).
Interfaces¶
Available interfaces to support Abstract Classes:
Standard Device Interface¶
Standard Device Class
Python Class for Standard Device informations.
platform: | Unix |
---|---|
synopsis: | Python Class for Standard Device informations. |
Countable Interface¶
Countable Interface
Python interface to support Abstract methods related to Counting process.
platform: | Unix |
---|---|
synopsis: | Python Interface with Abstract methods for Counting process (Countable Devices). |
-
class
py4syn.epics.ICountable.
ICountable
[source]¶ Python interface to be implemented in all devices in order to create default methods for Counting process
A countable is any device in which a counting process is feasible to be performed.
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Abstract method to get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(t)[source]¶ Abstract method to set the count time of a countable target device.
Parameters: - t : value
The target count time to be set.
Returns: - out : None
-
Scannable Interface¶
Scannable Interface
Python interface to support Abstract methods related to Scan process.
platform: | Unix |
---|---|
synopsis: | Python Interface with Abstract methods for Scan process (Scannable Devices). |
-
class
py4syn.epics.IScannable.
IScannable
[source]¶ Python interface to be implemented in all devices in order to create default methods for Scan process
A scannable is any device in which the scan process is feasible to be performed.
-
getHighLimitValue
()[source]¶ Abstract method to get the scannable device software high limit value
Parameters: - None
Returns: - `double`
-
getLowLimitValue
()[source]¶ Abstract method to get the scannable device software low limit value
Parameters: - None
Returns: - `double`
-
getValue
()[source]¶ Abstract method to get the current value of a scannable device.
Parameters: - None
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
Simulation¶
Available classes to support Simulations:
Countable Simulation¶
-
class
py4syn.epics.SimCountableClass.
SimCountable
(pvName, mnemonic)[source]¶ Class to add simulated ICountable support.
Examples
>>> from py4syn.epics.SimCountableClass import SimCountable >>> >>> myCountable = SimCountable('TEST:FAKE_COUNTER','myCounter') >>> myCountable.getValue() >>>
Constructor See
py4syn.epics.StandardDevice
Seepy4syn.epics.ICountable
Parameters: - pvName : string
PV name (Process Variable)
- mnemonic : string
Mnemonic
-
canMonitor
()[source]¶ Abstract method to check if the device can or cannot be used as monitor.
Returns: - out : bool
-
canStopCount
()[source]¶ Abstract method to check if the device can or cannot stop the count and return values.
Returns: - out : bool
-
getValue
(**kwargs)[source]¶ Get the current value of a countable device.
Parameters: - kwargs : value
Where needed informations can be passed, e.g. select which channel must be read.
Returns: - out : value
Returns the current value of the device. Type of the value depends on device settings.
-
isCounting
()[source]¶ Abstract method to check if the device is counting or not.
Returns: - out : bool
-
setCountTime
(t)[source]¶ Abstract method to set the count time of a countable target device.
Parameters: - t : value
The target count time to be set.
Returns: - out : None
Utils module¶
Available entities at py4syn.utils library:
Motor Functions¶
-
py4syn.utils.motor.
createMotor
(name='', PV='')[source]¶ Create and add a motor to the mtrDB dictionary
Parameters: - name : string
Mnemonic of the motor
- PV : string
The Epics PV for this Motor
Examples
>>> from py4syn.utils.motor import * >>> mtop = 'mtop' >>> mbot = 'mbot' >>> createMotor(mtop,'SOL:DMC1:m3') # creates a motor using the mnemonic and PV. >>> createMotor(mbot,'SOL:DMC1:m4') >>> umv(mtop, 10) # move the motor mtop to the position 10. >>> wa() # print the position of all motors registered. >>> mtopPosition = wmr(mtop) # store the motor mtop position in the variable mtopPosition.
-
py4syn.utils.motor.
createPseudoMotor
(name='', description='', backFormula='', forwardDict={})[source]¶ Create and add a pseudo-motor to the mtrDB dictionary
Parameters: - name : string
Mnemonic of the pseudo-motor
- description : string
Description of the pseudo-motor
- backFormula : string
Formula to define the pseudo-motor position based on other motors
Note
- Numpy and Math functions can be used on formulas, specially form numpy users must explicit declare it, e.g. numpy.linalg.solve(..)
- T refers to the motor Target position
- A refers to the motor Actual position
- forwardDict : dictionary
A dictionary that contains a formula to be applied for each motor when the pseudo-motor is moved
Note
- Numpy and Math functions can be used on formulas, specially form numpy users must explicit declare it, e.g. numpy.linalg.solve(..)
- T refers to the motor Target position
- A refers to the motor Actual position
Examples
>>> from py4syn.utils.motor import * >>> >>> # Define the formula to calculate the Bragg Value >>> braggBackFormula = "asin(1.977/A[energy])" >>> >>> # Define the relationship between thetaCrystal and bragg target value >>> braggForwardDict = {"thetaCrystal": "T[bragg]"} >>> >>> # Define the formula to calculate the Energy Value >>> energyBackFormula = "1.977/sin(A[thetaCrystal])" >>> >>> # Define the relationship between the needed motors and the energy target value >>> energyForwardDict = {"bragg": "asin(1.977/T[energy])", >>> "gap": "A[beamOffset]*tan(T[bragg])/ (sin(T[bragg])+(cos(T[bragg])*tan(T[bragg])))", >>> "trans":"A[beamOffset]/(sin(T[bragg])+(cos(T[bragg])*tan(T[bragg])))"} >>> >>> # Define the formula to calculate the Beam Offset and the >>> beamOffsetBackFormula = "2*A[trans]*tan(A[bragg])*cos(A[bragg])" >>> >>> # Define the relationship between the needed motors and the beam offset >>> beamOffsetForwardDict = {"trans": "T[beamOffset]/(sin(A[bragg])+cos(A[bragg])*tan(A[bragg]))", >>> "gap": "(T[beamOffset]*tan(A[bragg]))/(sin(A[bragg])+(cos(A[bragg])*tan(A[bragg])))"} >>> >>> # Crete a simple motor for the 2nd Crystal Translation >>> createMotor("trans", "SOL:DMC1:m1") >>> >>> # Crete a simple motor for the 2nd Crystal Gap >>> createMotor("gap", "SOL:DMC1:m3") >>> >>> # Crete a simple motor for the 1st Crystal Rotation >>> createMotor("thetaCrystal", "SOL:DMC1:m4") >>> >>> >>> # Create the Pseudo motor Bragg, Energy and BeamOffset with the respective formulas and relationships >>> createPseudoMotor("bragg", "Bragg Angle (radians)", backFormula=braggBackFormula, forwardDict=braggForwardDict) >>> createPseudoMotor("energy", "Energy (kev)", backFormula=energyBackFormula, forwardDict=energyForwardDict) >>> createPseudoMotor("beamOffset", "Beam offset (mm)", backFormula=beamOffsetBackFormula, forwardDict=beamOffsetForwardDict) >>> >>> # Print all motor positions >>> wa() >>> >>> # Move the motor Energy to the value 2. >>> mv("energy", 4, wait=True) >>> >>> # Print all motor positions >>> wa()
-
py4syn.utils.motor.
mmv
(**kargs)[source]¶ Perform absolute movement in multiple motors at almost the same time
Parameters: - kargs : string
The motor name and desired position, e.g. x=10,y=10
-
py4syn.utils.motor.
mmvr
(**kargs)[source]¶ Perform relative movement in multiple motors at almost the same time
Parameters: - kargs : string
The motor name and desired position, e.g. x=10,y=10
-
py4syn.utils.motor.
mv
(motor, position, wait=True)[source]¶ Move the desired motor to an absolute position, can or not wait until movement ends,**don’t** show the position while moving.
Parameters: - motor : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
The desired absolute position
- wait : bool
Optional parameter that indicates if this function must wait until the movement finishes. Default value is True
Note
- If wait is set to False the code will follow as the motor moves.
-
py4syn.utils.motor.
mvr
(motor, position, wait=True)[source]¶ Move the desired motor to a relative position, can or not wait until movement ends,**don’t** show the position while moving.
Parameters: - motor : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
The desired relative position
- wait : bool
Optional parameter that indicates if this function must wait until the movement finishes. Default value is True
Note
- If wait is set to False the code will follow as the motor moves.
-
py4syn.utils.motor.
print_no_newline
(s)[source]¶ Print information without an new line
Parameters: - s : string
Text to be printed
-
py4syn.utils.motor.
set
(mtr, position)[source]¶ Change the motor user coordinates
Parameters: - mtr : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
Desired position for user coordinates
-
py4syn.utils.motor.
set_dial
(mtr, position)[source]¶ Change the motor dial coordinates
Parameters: - mtr : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
Desired position for dial coordinates
-
py4syn.utils.motor.
set_lm
(mtr, ll, hl)[source]¶ Set the motor soft limits in user coordinates, will change DHLM and DLLM
Parameters: - mtr : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- ll : double
Low Soft Limit value
- hl : double
High Soft Limit value
-
py4syn.utils.motor.
tw
(mtr, step)[source]¶ Move the desired motor relative, wait the movement end and ask if you need to move again
Parameters: - mtr : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- step : double
Desired relative step size
-
py4syn.utils.motor.
ummv
(**kargs)[source]¶ Perform absolute movement in multiple motors at almost the same time and wait until movement finishes
Parameters: - kargs : string
The motor name and desired position, e.g. x=10,y=10
-
py4syn.utils.motor.
ummvr
(**kargs)[source]¶ Perform relative movement in multiple motors at almost the same time and wait until movement finishes
Parameters: - kargs : string
The motor name and desired position, e.g. x=10,y=10
-
py4syn.utils.motor.
umv
(motor, position)[source]¶ Move the desired motor to an absolute position, waiting until movement ends,and show the position while it happens.
Parameters: - motor : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
The desired absolute position
-
py4syn.utils.motor.
umvr
(motor, position)[source]¶ Move the desired motor to a relative position, waiting until movement ends,and show the position while it happens.
Parameters: - motor : string
Mnemonic of the motor used on the createMotor and createPseudoMotor functions
- position : double
The desired relative position
Counter Functions¶
-
py4syn.utils.counter.
createCounter
(mnemonic, device, channel=None, monitor=False, factor=1)[source]¶ Add a countable to the counterDB dictionary
Parameters: - mnemonic : string
Mnemonic of the counter
- device : ICountable
The device that handles this counter and implements ICountable interface
- channel : int
Specify where usable the channel index for this counter
- monitor : bool
If monitor is set to True the process will be by counts and not by time
- factor : int
Specify the factor to be used when reading the counter value
Examples
>>> scaler = Scaler("SOL:SCALER", 10, "scaler1") # Creates an EPICS Scaler >>> scalerSIM = SimCountable("ANY:PV:HERE", "simMnemonic") >>> createCounter("seconds", scaler, 1, factor=1e+7) # Create a channel using the real >>> # scaler, channel number 1 and a factor. >>> createCounter("det", scaler, 3) >>> createCounter("mon", scaler, 10, monitor=True) # Create a channel that will act as a monitor >>> createCounter("cyberSim", scalerSIM, 2) >>> ct(10000) # Start a count process until 10000 counts in the monitor >>> # and show the results for each channel at the end. >>> counts = ctr(2, use_monitor=False) # Start a count process with 2 seconds >>> # of integration time. Returns the counts as a map. >>> print("Counts on det: ", counts['det'])
-
py4syn.utils.counter.
ct
(t=1, use_monitor=False)[source]¶ Count all counters available using the given time
Parameters: - t : double
Time of Preset to be used
- use_monitor : bool
If monitor is set to True the process will be by counts and not by time
-
py4syn.utils.counter.
disableCounter
(mne)[source]¶ Disable an specific counter
Parameters: - mne : string
The counter mnemonic
Plot Functions¶
Based on the example provided by matplotlib 1.3.1 documentation.
See also: misc example code: multiprocess.py
Adapted to work without GTK and support multiple subplots and axis overlay.
Using the Plotter to plot graphics¶
Usage of Python utility classes to help plotting charts.
-
class
py4syn.utils.plotter.
Plotter
(title, daemon=True, priority=0)[source]¶ Python class to represent an almost real-time plotter. This Plotter spawn another process responsible for the data plot and graph update. Priority should be between 0 (default) and 19 (maximum allowed).
Constructor
Parameters: - title : string
Title of the plot
- daemon : bool
This parameters indicates if the spawned process should be daemon or not In general if daemon is set to True as the script ends it will close the graph, otherwise the script will end only when the graph is closed
-
createAxis
(title='', label='', xlabel='', ylabel='', grid=True, line_style='-', line_marker='o', line_color='red', parent=None)[source]¶ Creates a subplot in the plotter, also it’s possible to create an axis to a parent subplot through the parent parameter
Parameters: - title : string
Title of the plot
- label : string
Label for the Axis Legend, if blank or None will not appear in the legend
- xlabel : string
Label for the X axis
- ylabel : string
Label for the Y axis
- grid : bool
If True, will render grid to the graph area.
- lineStyle : string
The line style according to Matplotlib Line2D style list
- lineMarker : string
The line marker according to Matplotlib Markers list
- lineColor : string
The line color, accepts any matplotlib color
- parent : int
Index of the parent subplot
-
plot
(x, y, axis=1)[source]¶ Plot data to graph.
Parameters: - x : double
X data
- y : double
Y data
- axis : int
The axis index where data should be plot.
Scan Functions¶
So far Py4Syn can handle three scan types:
- Scan
- All devices must have the same number of steps and they will step toguether. You can specify as many devices as you want, there’s no limitation with this.
- The only restriction is that the used devices must implement the IScannable interface. For more information about IScannable Interface please check
py4syn.epics.IScannable
.
- Mesh
- No concern about devices number of steps. You can specify as many devices as you want.
- The only restriction is that the used device must implement the IScannable interface. For more information about IScannable Interface please check
py4syn.epics.IScannable
.
- Time
- No devices, scan runs over time. User specify the counting time and delay time in seconds, both default to 1.
Handling the Data¶
At Py4Syn all the scan data is stored in a memory dictionary in order to ensure great speed. Data inside the SCAN_DATA dictionary is organized as follows:
Index | Content |
---|---|
‘points’ | Array of points, [0, 1, 2, 3…N] |
‘scan_object’ | Reference to the Scan object |
devices mnemonic | For each device used in the scan an entry to store this device value across the scan is created, e.g. SCAN_DATA[‘tth’] represents the array of tth positions |
counters mnemonic | For each counter registered an entry to store this device value across the scan is created, e.g. SCAN_DATA[‘mon’] represents the array of mon values |
‘scan_start’ | Timestamp of scan start |
‘scan_end’ | Timestamp of scan end |
‘scan_duration’ | Scan duration. (‘scan_end’ - ‘scan_start’) |
Any other user data | Any value you want, but beware that this values must be created using the py4syn.utils.scan.createUserDefinedDataField() method in order to be saved in the file. |
Callbacks¶
There are 7 callbacks available:
- Pre Scan Callback
- This callback is executed at the beginning of the scan
- Pre Point Callback
- This callback is executed before the point (before motors movement, or any other device setup)
- Pre Operation Callback
- This callback is executed before the operation, before launching the counters
- Operation Callback
- This is the main callback, it’s executed while the counters are running
- Post Operation Callback
- This callback is executed after the operation, after the counters stop and before the plot and screen update
- Post Point Callback
- This callback is executed right after the operation callback and before a new movement
- Post Scan Callback
- This callback is executed at the end of the scan
If one wants to define specific callbacks it’s possible by following the recipe below:
# Creating my function that will be executed in the choosen callback
# This function needs to receive a parameter **kwargs
def myCallback(**kwargs):
scanObject = kwargs['scan']
indexArray = kwargs['idx']
positionArray = kwargs['pos']
print('Message from my callback')
# This shows how to move back to the default callback from py4syn
setPreScanCallback(defaultPreScanCallback)
# Set my function to the operation callback
setOperationCallback(mycallback)
# Run the scan with the new configurations
scan('m1', 0, 180, 10, 1)
Attention
By overwriting an existing callback you assume that you will handle all the operations that you have overwritten. Also, user is responsible by the dead-time generated by the custom callbacks.
Special variables in the Scan module¶
In the Scan module there are some GLOBAL variables that can be read and configured. To access this variables you can either use the scan module or the appropriate getter and setter methods.
Variable | Content | Getter | Setter |
---|---|---|---|
SCAN_DATA | Ordered Dictionary that contains all scan related data | getScanData() | |
SCAN_CMD | String with the last scan command executed | getScanCommand() | |
SCAN_COMMENT | String with a comment to be added to the scan file | getScanComment() | setScanComment() |
SCAN_PLOTTER | Scan Object to be used when plotting data | getScanPlotter() | setScanPlotter() |
SCAN_PLOTTER_AXIS | Axis index to be used in the plotter | getScanPlotterAxis() | setScanPlotterAxis() |
FILENAME | String that represents the filename to be used, if None stores only in memory. See setOutput for more information. | getOutput() | setOutput() |
XFIELD | String that represents the Mnemonic of the X axis. See setX for more information. | getX() | setX() |
YFIELD | String that represents the Mnemonic of the Y axis. See setY for more information. | getY() | setY() |
FWHM | Double that represents the FWHM value. | getFwhm() | |
FWHM_AT | Double that represents the FWHM position. | getFwhmAt() | |
COM | Double that represents the COM (Center of Mass) value. | getCom() | |
PEAK | Double that represents the Peak value. | getPeak() | |
PEAK_AT | Double that represents the Peak position. | getPeakAt() | |
MIN | Double that represents the Minimum value. | getMin() | |
MIN_AT | Double that represents the Minimum value position. | getMinAt() | |
FITTED_DATA | Array that represents the best fit values. | getFittedData() | |
FIT_RESULT | ModelFit with fit result information. | getFitResult() | |
FIT_SCAN | Boolean that represents if we should or not fit the scan data at end. Default is True | getFitScan() | setFitScan() |
PRINT_SCAN | Boolean that represents if we should or not print to the terminal the scan information. Default is True | getPrintScan() | setPrintScan() |
PLOT_GRAPH | Boolean that represents if we should or not create the real-time plot. Default is True | getPlotGraph() | setPlotGraph() |
PRE_SCAN_CALLBACK | Function pointer for the Pre Scan Callback. Default is defaultPreScanCallback. | getPreScanCallback() | setPreScanCallback() |
PRE_POINT_CALLBACK | Function pointer for the Pre Point Callback. Default is None. | getPrePointCallback() | setPrePointCallback() |
PRE_OPERATION_CALLBACK | Function pointer for the Pre Operation Callback. Default is None. | getPreOperationCallback() | setPreOperationCallback() |
OPERATION_CALLBACK | Function pointer for the Operation Callback. Default is defaultOperationCallback. | getOperationCallback() | setOperationCallback() |
POST_OPERATION_CALLBACK | Function pointer for the Post Operation Callback. Default is None. | getPostOperationCallback() | setPostOperationCallback() |
POST_POINT_CALLBACK | Function pointer for the Post Point Callback. Default is None. | getPostPointCallback() | setPostPointCallback() |
POST_SCAN_CALLBACK | Function pointer for the Post Scan Callback. Default is defaultPostScanCallback | getPostScanCallback() | setPostScanCallback() |
Functions from the Scan module¶
-
py4syn.utils.scan.
clearUserDefinedDataField
()[source]¶ Remove all user defined fields
Examples
>>> clearUserDefinedDataField()
-
py4syn.utils.scan.
createUserDefinedDataField
(field_name)[source]¶ Create an user defined field in the SCAN_DATA dictionary
Parameters: - field_name : string
Field name
Examples
>>> createUserDefinedDataField("norm")
-
py4syn.utils.scan.
fitData
(x, y)[source]¶ Try to fit a Gaussian to data and calculate the MAX, FWHM and COM (Center of Mass)
Parameters: - x : array
X data
- y : array
Y data
Examples
>>> fitData(myDataX, myDataY) >>> print("Peak ", PEAK, " at ", PEAK_AT) >>> print("Fwhm ", FWHM, " at ", FWHM_AT) >>> print("COM = ", COM)
-
py4syn.utils.scan.
getFileWriter
()[source]¶ Get the current File Writer. See
py4syn.writing.FileWriter
Returns: - `FileWriter`
-
py4syn.utils.scan.
getFitScan
()[source]¶ Get the global variable FIT_SCAN to enable or disable the scan fit at end
Returns: - `bool`
-
py4syn.utils.scan.
getFitValues
()[source]¶ Get the Fit values (Peak value, Peak Position, FWHM, FWHM Position and Center of Mass)
Returns: - `list`
-
py4syn.utils.scan.
getOutput
()[source]¶ Get the Output, if output is set to None then the data is only stored in the SCAN_DATA dictionary.
Returns: - `string`
-
py4syn.utils.scan.
getPostOperationCallback
(c)[source]¶ Get the post operation callback.
Returns: - `function`
-
py4syn.utils.scan.
getPreOperationCallback
(c)[source]¶ Get the pre operation callback.
Returns: - `function`
-
py4syn.utils.scan.
getScanComment
()[source]¶ Get the custom comment
Returns: - `string`
The comment to be inserted
Examples
>>> print(getScanComment())
-
py4syn.utils.scan.
getScanPlotter
()[source]¶ Get the current plotter
Returns: - `Plotter`
The current plotter
Examples
>>> p = getScanPlotter()
-
py4syn.utils.scan.
getScanPlotterAxis
()[source]¶ Get the current plotter axis
Returns: - `int`
The current axis
Examples
>>> p = getScanPlotterAxis()
-
py4syn.utils.scan.
getX
()[source]¶ Get which field will be used to plot in the X axis
Returns: - `string`
-
py4syn.utils.scan.
getY
()[source]¶ Get which field will be used to plot in the X axis
Returns: - `string`
-
py4syn.utils.scan.
mesh
(*kwargs)[source]¶ Run a mesh scan with the given parameters
Parameters: - kwargs : *
List of parameters in the following order: device, start, end, points, device2, start2, end2, points2, …, deviceN, startN, endN, pointsN, time, delay.
Note
To use variable time for each point instead of an value user should pass an array with the time to count in each point.
Note
Instead of the common use of start and end, one can use an array of points. Beware that the array length cannot be different of points parameter.
Note
To use delay between points one can use a scalar value representing the number of seconds to wait until acquire next point, for variable delay time instead of an value user should pass an array.
Examples
>>> createMotor('m1', 'SOL:DMC1:m1') >>> createMotor('m2', 'SOL:DMC1:m2') >>> scalerSOL = Scaler("SOL2:SCALER", 10, "scalerSOL") >>> createCounter("seconds", scalerSOL, 1, factor=1e+7) >>> createCounter("S10", scalerSOL, 10, monitor=True) >>> setX("points") >>> setY("S10") >>> setOutput("/home/ABTLUS/hugo.slepicka/mesh1.txt") >>> mesh('m1', 0, 1, 15, 'm2', 0, 180, 1001, 0.01) >>> print("Scan Ended") >>> print("Time elapsed: ", SCAN_DATA['scan_duration'])
-
py4syn.utils.scan.
plot
()[source]¶ Plot a graph using the fields set in XFIELD and YFIELD.
Examples
>>> setX("m1") >>> setY("det") >>> plot()
-
py4syn.utils.scan.
removeUserDefinedDataField
(field_name)[source]¶ Remove an user defined field in the SCAN_DATA dictionary
Parameters: - field_name : string
Field name
Examples
>>> removeUserDefinedDataField("norm")
-
py4syn.utils.scan.
scan
(*args, **kwargs)[source]¶ Run a scan with the given parameters
Parameters: - args : *
List of parameters in the following order: device, start, end, points, time or device, start, end, device2, start2, end2,…, deviceN, startN, endN, points, time, delay.
Note
To use variable time for each point instead of an value user should pass an array with the time to count in each point.
Note
Instead of the common use of start and end, one can use an array of points. Beware that the array length cannot be different of points parameter.
Note
To use delay between points one can use a scalar value representing the number of seconds to wait until acquire next point, for variable delay time instead of an value user should pass an array.
Examples
>>> createMotor('m1', 'SOL:DMC1:m1') >>> createMotor('m2', 'SOL:DMC1:m2') >>> scalerSOL = Scaler("SOL2:SCALER", 10, "scalerSOL") >>> createCounter("seconds", scalerSOL, 1, factor=1e+7) >>> createCounter("S10", scalerSOL, 10, monitor=True) >>> setX("points") >>> setY("S10") >>> setOutput("/home/ABTLUS/hugo.slepicka/scan1.txt") >>> scan('m1', 0, 1, 15, 0.01) >>> print("Scan Ended") >>> print("Time elapsed: ", SCAN_DATA['scan_duration'])
-
py4syn.utils.scan.
setFileWriter
(writer)[source]¶ Set the file writer to be used in order to save the data. If None is informed the DefaultWriter is used, generating a PyMCA-like file.
Parameters: - writer : FileWriter
Examples
>>> writer = DefaultWriter("/tmp/test.txt") >>> setFileWrite(writer)
-
py4syn.utils.scan.
setFitScan
(b)[source]¶ Set the global variable FIT_SCAN to enable or disable the scan fit at end
Parameters: - b : bool
-
py4syn.utils.scan.
setOperationCallback
(c)[source]¶ Set the operation callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setOperationCallback(myCallback) >>>
-
py4syn.utils.scan.
setOutput
(out)[source]¶ Set the Output, if output is set to None then the data is only stored in the SCAN_DATA dictionary.
Parameters: - out : string
The complete filename.
Note
The files will be renamed to fit the format: filename_000N.ext.
Each file represents one scan and they are automatically incremented.
Examples
>>> setOutput("/home/user/teste.txt")
-
py4syn.utils.scan.
setPartialWrite
(partial)[source]¶ Set enable or disable the Partial Write, if partial is set to True then the data written every iteration, otherwise data is only saved at the end.
Parameters: - partial : bool
Examples
>>> setPartialWrite(True)
-
py4syn.utils.scan.
setPlotDaemon
(b)[source]¶ Configure if the scan plot should or not be daemon
Parameters: - b : bool
True of False indicating if should be daemon
Examples
>>> setPlotDaemon(True)
-
py4syn.utils.scan.
setPlotGraph
(b)[source]¶ Set the global variable PLOT_GRAPH to enable or disable the live plot
Parameters: - b : bool
-
py4syn.utils.scan.
setPostOperationCallback
(c)[source]¶ Set the post operation callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPostOperationCallback(myCallback) >>>
-
py4syn.utils.scan.
setPostPointCallback
(c)[source]¶ Set the post point callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPostPointCallback(myCallback) >>>
-
py4syn.utils.scan.
setPostScanCallback
(c)[source]¶ Set the post scan callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPostScanCallback(myCallback) >>>
-
py4syn.utils.scan.
setPreOperationCallback
(c)[source]¶ Set the pre operation callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPreOperationCallback(myCallback) >>>
-
py4syn.utils.scan.
setPrePointCallback
(c)[source]¶ Set the pre point callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPrePointCallback(myCallback) >>>
-
py4syn.utils.scan.
setPreScanCallback
(c)[source]¶ Set the pre scan callback.
Parameters: - c : function
A function to be executed
Note
This function must receive an argument **kwargs
Examples
>>> def myCallback(**kwargs): >>> print("Print from my callback") >>> >>> setPreScanCallback(myCallback) >>>
-
py4syn.utils.scan.
setPrintScan
(b)[source]¶ Set the global variable PRINT_SCAN to enable or disable the scan print on terminal
Parameters: - b : bool
-
py4syn.utils.scan.
setScanComment
(c)[source]¶ Insert a custom comment in the scan file
Parameters: - c : string
The comment to be inserted
Examples
>>> setScanComment("Scan of sample X, using Y")
-
py4syn.utils.scan.
setScanPlotter
(p)[source]¶ Define the Plotter to be used in the scan
Parameters: - p : Plotter
The plotter to be used
Examples
>>> p = Plotter("My Plotter ", daemon=False) >>> setScanPlotter(p)
-
py4syn.utils.scan.
setScanPlotterAxis
(ax)[source]¶ Define the axis index to be used when plotting
Parameters: - ax : int
The axis index to be used when plotting
Examples
>>> p = Plotter("My Plotter ", daemon=False) >>> p.createAxis("", label="Data label", xlabel="Energy", ylabel="I0", >>> grid=True, line_style="-", line_marker=".", line_color="blue") >>> setScanPlotter(p) >>> setScanPlotterAxis(1)
-
py4syn.utils.scan.
setX
(x)[source]¶ Set which field will be used to plot in the X axis
Parameters: - x : string
Mneumonic of the data, e.g. “m1”, “tth”, “det”, “mon”
Examples
>>> setX("tth")
Fit Functions¶
-
py4syn.utils.fit.
fitGauss
(xarray, yarray)[source]¶ This function mix a Linear Model with a Gaussian Model (LMFit).
See also: Lmfit Documentation
Parameters: - xarray : array
X data
- yarray : array
Y data
Returns: - peak value: `float`
- peak position: `float`
- min value: `float`
- min position: `float`
- fwhm: `float`
- fwhm positon: `float`
- center of mass: `float`
- fit_Y: `array`
- fit_result: `ModelFit`
Examples
>>> import pylab as pl >>> data = 'testdata.txt' >>> X = pl.loadtxt(data); >>> x = X[:,0]; >>> y = X[:,7]; >>> >>> pkv, pkp, minv, minp, fwhm, fwhmp, com = fitGauss(x, y) >>> print("Peak ", pkv, " at ", pkp) >>> print("Min ", minv, " at ", minp) >>> print("Fwhm ", fwhm, " at ", fwhmp) >>> print("COM = ", com) >>>
-
py4syn.utils.fit.
tvDenoising1D
(data, lamb)[source]¶ This function implements a 1-D Total Variation denoising according to Condat, L. (2013) “A direct algorithm for 1-D total variation denoising.”
Parameters: - data : array
Data to be fit
- lamb : float
Note
lamb must be nonnegative. lamb = 0 will result in output = data.
Returns: - fitData: `array`
Examples
>>> import pylab as pl >>> data = 'testdata.txt' >>> X = pl.loadtxt(data); >>> x = X[:,0]; >>> data = X[:,7]; >>> >>> denoised = tvDenoising1D(data, lamb=200) >>> >>> pl.plot(x, data, 'b') >>> pl.hold(True) >>> pl.plot(x, denoised, 'r--') >>> pl.show()
Timer Functions¶
-
class
py4syn.utils.timer.
Timer
(timeout)[source]¶ A class to track elapsed time and timeouts. The timer class stores an initial time and a timeout value. These can be used to check or wait for a certain moment in time.
Examples
>>> from py4syn.utils.timer import Timer >>> >>> def waitAcquisition(device, timeout=60): ... timer = Timer(timeout) ... while device.isAcquiring() and timer.check(): ... device.updateState() ... ... if timer.expired(): ... raise TimeoutError() ...
The constructor receives a timeout parameter, which is saved and marks the initial time.
See:
mark()
Parameters: - timeout : float
Timeout limit
-
check
()[source]¶ Checks if the timeout has been expired by reading the current time value and comparing it against the initial time and the timeout. The expiration value is saved and can be read later with
expired()
. Returns True if the timeout hasn’t been reached, or False if the timer expired.See:
expired()
Returns: - `bool`
-
mark
()[source]¶ Resets the initial time value and resets the expired flag. After calling this method, timeout checking or waiting will use the new time value as the initial moment.
-
wait
(file=None)[source]¶ Blocks until the timeout has expired, or, if the file parameter is not empty, until the file becomes ready with input data. The expiration value is saved and can be read later with
expired()
. Returns False if the timeout expired, or True if the file is ready for reading before the timer is expired.This method only checks if the file is ready for reading, but it does not read anything from it. It will continuously return True while the file is not read and the timeout does not expire.
See:
expired()
Returns: - `bool`
Writing module¶
Available entities at py4syn.epics library:
Interfaces¶
Available interfaces to support Abstract Classes:
File Writer Interface¶
-
class
py4syn.writing.FileWriter.
FileWriter
(fileName)[source]¶ Class to be inherited by all data output classes in order to be transparently used in scan functions.
By default some informations such as username, start and end timestamp, command and others are already filled by the scan routines using the getters and setters bellow.
Constructor
Parameters: - fileName : string
The output filename
-
getDevicesData
()[source]¶ Returns the map containing all devices data in a map where the device mnemonic is the key and the values are an array.
Returns: - `map`
-
getSignalsData
()[source]¶ Returns the map containing all signals data in a map where the device mnemonic is the key and the values are an array.
Returns: - `map`
-
insertComment
(value)[source]¶ Insert a new comment in the list
Parameters: - value : string
Comment information
-
insertDevice
(value)[source]¶ Insert a new device in the list
Parameters: - value : string
Device mnemonic
-
insertDeviceData
(device, value)[source]¶ Insert a new data value for the informed device in the map.
Parameters: - device : string
Device mnemonic
- value : float, int, str, etc
Collected value
-
insertSignal
(value)[source]¶ Insert a new signal in the list
Parameters: - value : string
Signal mnemonic
-
insertSignalData
(signal, value)[source]¶ Insert a new data value for the informed signal in the map.
Parameters: - signal : string
Signal mnemonic
- value : float, int, str, etc
Collected value
-
setCommand
(value)[source]¶ Set the command information
Parameters: - value : string
Command information
-
setEndDate
(value)[source]¶ Set the end date
Parameters: - value : string
Date when the process finished
-
setStartDate
(value)[source]¶ Set the start date
Parameters: - value : string
Date when the process started
-
setUsername
(value)[source]¶ Set the username information
Parameters: - value : string
Username information
Writers¶
Available writers:
Default Writer¶
The default writer class is responsible for generating the Py4Syn PyMCA/SPEC-like output.
Bellow it’s possible to check an example of the generated file:
#E 1423501786
#D Mon Feb 09 15:09:46 2015
#C py4syn User = hugo.slepicka
#C0 Comment 1
#C1 Comment 2
#C2 Comment 3
#S 1 python3.4 test.py
#D Mon Feb 09 15:09:44 2015
#N 2
#L dev-1 signal-1
88 0.579816377007323
55 0.7587818137112776
84 0.42957633904075676
84 0.553745066476392
87 0.14826338543188655
75 0.968795965439634
20 0.26124651064977344
66 0.5235828320576064
94 0.3908435592403231
95 0.5678979857080083
Using the Default File Writer module¶
-
class
py4syn.writing.DefaultWriter.
DefaultWriter
(fileName)[source]¶ Class to be used when generating PyMCA/SPEC-like output.
For more informations see
py4syn.writing.FileWriter
Constructor
Parameters: - fileName : string
The output filename
Release Notes¶
Version 0.3.0:
- Release Date: 2015-11-05
- New RotaryMagnet class.
- New Keithley6485 class.
- New PylonCCDTriggered class.
- Plotter now supports shrinking method to improve plot window appearance.
- MarCCD now supports binning (changing the acquired image size).
- New LinkamCI94 class.
- Fix handling MarCCD delays.
- Pseudo counter now does not crash if the user formula raises exception.
- Pseudo motors now support setting the reference position and getting limits.
- E5CK now supports programming ramps with the raw IOC table.
- E5CK now has PID methods.
- E5CK now has a method to check if the ramp is paused and to read the power.
- New LakeShore331 class.
- Plotter now supports updating the plot title.
- Plotter now has a method to check if the window was closed.
- Shutters used by MarCCD were moved to their own file and can be generally used.
- Fixed invalid exception in the mesh function.
- Motor class now has methods for performing homing.
- Removed warning from Kepco BOP documentation, since it’s correctly working.
- Fixes in motor set/use mode logic.
- New Pilatus class.
- Other minor bug fixes.
Version 0.2.1:
- Release Date: 2015-03-18
- Scan and Mesh now support a Delay array as optional parameter.
- New Pseudo-Counters class.
- New PylonCCD class.
- New library dependency - LMFit 0.8.3 or higher.
- New fit function based on LMFit package.
- New 1-D Total Variation Denoising function.
- New Partial Write behaviour in scan through the setPartial Write configuration.
- New interface for custom data output - FileWriter.
- Default writer set to DefaultWriter - PyMCA/SPEC-like data output.
- Pre and Post scan callbacks are available without the need to rewrite code from Py4Syn.
- Scan now returns the fit data and fit results also.
- PostPointCallback was never being called on Mesh and Timescan.
- Positions and Indexes array in callbacks were never being cleaned.
- Updates on MarCCD class.
- KepcoBOP is now a IScannable.
- Fix on scan YFIELD when no counters were present.
- Fix on Plotter valid axes count.
- Fix on Scan XField and YField when running on iPython.
- Improvements on documentations.
- General performance improvements.
Version 0.2.0:
- Release Date: 2014-11-19
- Fixed some documentation issues.
- Keithley now supports Time Preset when needed.
- Fixed bug on scan and mesh when count time was not integer.
Version 0.1.9:
- Release Date: 2014-10-31
- Fixed some documentation issues.
- Added Release Notes to online documentation and PDF.
- Added option to choose wether or not to Fit the Scan Data.
- New format routine at Scan Module to print data using scientific format where needed.
- Upgrade on Mythen class to work as a Countable Device.
- Upgrade on Shutter class to select the if the operation is direct or inverse.
- Adjusts on Counter module to accept arrays as return.
- Adjusts on ICountable Interface to set Infinty as 32bits.
- Added array support to plotter, improvements on performance.
- Added RRBV and RVAL fields to Motor and PseudoMotor classes.
- Removing unused prints at Plotter module.
Version 0.1.8:
- Release Date: 2014-10-21
- Fixed scannable device position in scan, was getting the setpoint and not the real value.
- Added Simulated Countable Device.
- Now the plotter supports multiple plots in one windows and also axis overlay.
- Improvements in Documentation.
Version 0.1.7:
- Release Date: 2014-10-11
- Fixed error on ScanToFile, the columns count were not counting the user defined data fields. This could lead to a problem in the file analysis using PyMCA like tools.
Version 0.1.6:
- Release Date: 2014-10-11
- Possibility to set the default plotter as a daemon process at Scan Module.
- Variable time for each point and proper documentation.
- Keithley6514 - OneMeasure field added allowing better precision with lower deadtime.
- MANIFEST - removed dist folder.
Version 0.1.5:
- Release Date: 2014-10-07
- Kepco BOP power supply class added.
- Adjusts in scan callbacks.
- Added user defined fields.
- Moved timescan to the scan module.
- Added the possibility to disable or enable counters.
- Removed empty lines from motor functions.
Version 0.1.4:
- Release Date: 2014-09-26
- New class CountablePV to provide ICountable functionality to any PV.
- Added wait method to ICountable Interface that was missing.
- Refactor in CanPerformMovementCalc from MotorClass
- Fixed problem when FILENAME was equals to empty at Scan Module.
- Adjusted ScanToFile header and separator to work with PyMCA and NewPlot.
- Created Getter and Setter for all Global Variables.
- Adjusted Fit Class to return the value of other statistics either if was not possible to fit the gaussian.
- Sometimes the Scaler value returned was one before the last. Fixed with auto_monitor = False on S# pvs.
- Improvements on Scan Documentation.
- Added CountablePV documentation.
Version 0.1.3b:
- Release Date: 2014-09-22
- Getters and Setters for Globals on scan module.
- Added support for ICountable on Keithley.
- Added the EPEL Repo step to Setup Documentation.
- Updated the examples to change the callbacks in Scan Documentation.
Version 0.1.2b:
- Release Date: 2014-09-17
- Fixed bug on Plotter.
- Fixed bug on scan, when interrupted was not saving data correctly and was not able to calculate the elapsed time.
Version 0.1.1b:
- Release Date: 2014-09-16
- Fixed bug in FitGauss, under a certain condition data was not returning.
- Fixed bug in PseudoMotorClass, after moving mtrDB to py4syn __init__ PseudoMotor reference was not updated.
- Improves in documentation.
Version 0.1.0b:
- Release Date: 2014-09-15
- Beta Version Released
Download this documentation in a PDF version
.