This commit is contained in:
2018-08-15 17:04:21 +02:00
parent 1de8ced3d5
commit 3e41debde1
55 changed files with 1015 additions and 277 deletions
+2 -1
View File
@@ -3,7 +3,7 @@
is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
#time.sleep(4)
print is_panel, get_exec_pars().source
ret = []
@@ -11,4 +11,5 @@ for i in range(10):
ret.extend([i])
print "OK"
#raise Exception("test ex")
set_return(ret)
-1
View File
@@ -1,6 +1,5 @@
from jeputils import *
def gfitoff(x, y, off=None, amp=None, com=None, sigma=None):
ret = call_jep("cpython/GaussFit", "gfitoff", [to_npa(x), to_npa(y), off, amp, com, sigma])
return ret if ret is None or is_list(ret) else ret.data
+17 -32
View File
@@ -15,7 +15,7 @@
# Library loading and Hardware setup
###################################################################################################
#1- Create a MontorGroup with the diffractometer motors
#1- Create a MotorGroup with the diffractometer motors
# e.g. 'sixc', containing mu, delta, gam, eta, chi, phi motors (gam = nu)
# or 'fivec', containing delta, gam, eta, chi, phi motors
# or 'fourc', containing delta, eta, chi, phi motors
@@ -35,7 +35,7 @@ if not diffcalc_path in sys.path:
import diffcalc
from diffcalc import settings
from diffcalc.hkl.you.geometry import SixCircle, FiveCircle, FourCircle
from diffcalc.hkl.you.geometry import YouGeometry,SixCircle, FiveCircle, FourCircle, YouPosition
from diffcalc.hardware import HardwareAdapter
from diffcalc.ub.persistence import UbCalculationNonPersister
from diffcalc.gdasupport.minigda.scannable import ScannableBase, ScannableGroup
@@ -80,31 +80,13 @@ class PositionerScannable(ScannableBase):
class PositionerScannableGroup(ScannableGroup):
def __init__(self, name, motors):
self.name = name
if len(motors)==6:
[mu, delta, gam, eta, chi, phi] = motors
self.mu = PositionerScannable(mu, "mu")
self.delta = PositionerScannable(delta, "delta")
self.gam = PositionerScannable(gam, "gam")
self.eta = PositionerScannable(eta, "eta")
self.chi = PositionerScannable(chi, "chi")
self.phi = PositionerScannable(phi, "phi")
ScannableGroup.__init__(self, self.name, [self.mu, self.delta, self.gam, self.eta, self.chi, self.phi])
elif len(motors)==5:
[delta, gam, eta, chi, phi] = motors
self.delta = PositionerScannable(delta, "delta")
self.gam = PositionerScannable(gam, "gam")
self.eta = PositionerScannable(eta, "eta")
self.chi = PositionerScannable(chi, "chi")
self.phi = PositionerScannable(phi, "phi")
ScannableGroup.__init__(self, self.name, [self.delta, self.gam, self.eta, self.chi, self.phi])
elif len(motors)==4:
[delta, eta, chi, phi] = motors
self.delta = PositionerScannable(delta, "delta")
self.eta = PositionerScannable(eta, "eta")
self.chi = PositionerScannable(chi, "chi")
self.phi = PositionerScannable(phi, "phi")
ScannableGroup.__init__(self, self.name, [self.delta, self.eta, self.chi, self.phi])
print self.getInputNames()
positioners = []
for m in motors:
exec('self.' + m.name + ' = PositionerScannable(' + m.name + ', "' + m.name + '")')
exec('positioners.append(self.' + m.name + ')' )
ScannableGroup.__init__(self, self.name, positioners)
class MotorGroupScannable(PositionerScannableGroup):
def __init__(self, motor_group):
self.motor_group = motor_group
@@ -223,18 +205,21 @@ class HklGroup(RegisterBase, Register.RegisterArray):
you = None
dc, ub, hardware, hkl = None, None, None, None
_motor_group = None
def setup_diff(diffractometer, energy):
def setup_diff(diffractometer, energy, geometry=None):
"""
diffractometer: Motor group containing:
- mu, delta, gam, eta, chi, phi (six circle) or
- delta, gam, eta, chi, phi (ficve circle) or
- delta, eta, chi, phi (four circle)
energy: Positioner having energy in kev
geometry: YouGeometry extension. If none, uses default
"""
global you, dc, ub, hardware, hkl, _motor_group
_motor_group = diffractometer
you =None
if len(diffractometer.motors) == 6:
you = None
if geometry is not None:
settings.geometry = geometry
elif len(diffractometer.motors) == 6:
settings.geometry = SixCircle()
elif len(diffractometer.motors) == 5:
settings.geometry = FiveCircle()
@@ -348,14 +333,14 @@ def hklscan(vector, readables,latency = 0.0, passes = 1, **pars):
return scan.result
def test_difcalc():
def test_diffcalc():
en.move(20.0)
delta.config.maxSpeed = 50.0
delta.speed = 50.0
delta.move(1.0)
#Setup
setup_sixc(sixc, en)
setup_diff(sixc, en)
setup_axis('gam', 0, 179)
setup_axis('delta', 0, 179)
setup_axis('delta', min=0)
+1
View File
@@ -77,6 +77,7 @@ hkl_group.sim([0.0,1.0,1.0])
hkl_group.write([0.0,1.0,1.0])
###################################################################################################\
#Scans
###################################################################################################
+16
View File
@@ -0,0 +1,16 @@
"""
class DevConfig(DeviceConfig):
def __init__(self):
self.i = 1
self.d = 1.0
self.b = True
self.s = "Test"
"""
class Dev(DeviceBase):
def __init__(self, name):
#DeviceBase.__init__(self, name, DevConfig())
DeviceBase.__init__(self, name, DeviceConfig({"i":1, "d":1.0, "b":True, "s": "Test"}))
raise Exception("test ex")
add_device(Dev("test_cfg"), True)
+3 -3
View File
@@ -1,6 +1,6 @@
import traceback
is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
is_panel = False #get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
#set_exec_pars(provider="txt")
@@ -10,8 +10,8 @@ BPM_SENSORS = [("x","X1"), ("y","Y1"), ("q","Q1")] #(logic name sufix, channel s
prefix = args[0] if is_panel else "S30CB09-DWSC440" #"SINDI01-DWSC090"
scan_type = args[1] if is_panel else "X1"
scan_range = args[2] if is_panel else [-200, 200, -200, 200]
cycles = args[3] if is_panel else 3
velocity = args[4] if is_panel else 200
cycles = args[3] if is_panel else 1
velocity = args[4] if is_panel else 400
bpms = args[5] if is_panel else ["BPM1", "BPM2"]
blms = args[6] if is_panel else ["BLM1", "BLM2"]
bkgrd = args[7] if is_panel else 10
+3 -3
View File
@@ -6,11 +6,11 @@
#iavg = create_averager("ca://TESTIOC:TESTSINUS:SinCalc", 3, interval = -1)
iavg = create_averager("bs://Int8Scalar", 3, interval = 0.1)
iavg = create_averager("ca://TESTIOC:TESTSINUS:SinCalc", 3, interval = -1)
#iavg = create_averager("bs://Int8Scalar", 3, interval = 0.1)
tscan (iavg, 10, 0.5)
tscan (iavg, 10, 0.2, layout = "sf", domain_axis = "Time")
#$iavg.close()
+23
View File
@@ -0,0 +1,23 @@
###################################################################################################
# Example of using ImageJ functionalities through ijutils.
###################################################################################################
from ijutils import *
import java.awt.Color as Color
#Image Loading
ip = load_image("images/img.png", title="Image")
aux = grayscale(ip, in_place = False)
bin = ip.duplicate()
ip_bin = auto_threshold(aux, in_place=False)
create_stack([ ip_bin,
#binary_fill_holes(ip_bin, in_place=False),
#binary_outline(ip_bin, in_place=False),
#binary_outline(binary_fill_holes(ip_bin, in_place=False)),
binary_dilate(ip_bin, in_place=False),
binary_erode(ip_bin, in_place=False),
binary_open(ip_bin, in_place=False),
binary_close(ip_bin, in_place=False),
binary_skeletonize(ip_bin, in_place=False)], title = "Binarization").show()
+7
View File
@@ -0,0 +1,7 @@
def add(a1, a2):
return a1+a2
if __name__ == "__main__":
print add(4,3)
+114
View File
@@ -0,0 +1,114 @@
en.move(20.0)
delta.config.maxSpeed = 50.0
delta.speed = 50.0
delta.move(1.0)
run("diffcalc/diffutils")
###################################################################################################\
#Setup
###################################################################################################
class FourCircleX04SA_V(YouGeometry):
"""For a diffractometer with angles:
mu, delta, nu, eta
"""
def __init__(self):
YouGeometry.__init__(self, 'fourcv', {'phi': 0, 'chi': 0})
def physical_angles_to_internal_position(self, physical_angle_tuple):
# mu, delta, nu, eta, chi, phi
mu, delta, nu, eta = physical_angle_tuple
return YouPosition(mu, delta, nu, eta, 0, 0)
def internal_position_to_physical_angles(self, internal_position):
mu, delta, nu, eta, _, _ = internal_position.totuple()
return mu, delta, nu, eta
###################################################################################################\
#Setup
###################################################################################################
#alp, del, gam, ov
FourCircleX04SA_V()
setup_diff(fourcv, en, FourCircleX04SA_V())
# Set some limits
setup_axis('delta', 0, 90)
setup_axis('delta', min=0)
#setup_axis('gam', 0, 180)
#setup_axis('eta', cut=-180.0)
print_axis_setup()
###################################################################################################\
#Orientation
###################################################################################################
help(ub.ub)
ub.listub()
# Create a new ub calculation and set lattice parameters
ub.newub('test')
ub.setlat('cubic', 1, 1, 1, 90, 90, 90)
# Add 1st reflection (demonstrating the hardware adapter)
settings.hardware.wavelength = 1
ub.c2th([1, 0, 0]) # energy from hardware
settings.hardware.position = 0, 60, 0, 30, 0, 0
ub.addref([1, 0, 0])# energy and position from hardware
# Add 2nd reflection (this time without the harware adapter)
ub.c2th([0, 1, 0], 12.39842)
ub.addref([0, 1, 0], [60, 30, 0, 90], 12.39842)
# check the state
ub.ub()
ub.checkub()
###################################################################################################\
#Constraints
###################################################################################################
help(hkl.con)
hkl.con('a_eq_b')
###################################################################################################\
#Motion
###################################################################################################
print angles_to_hkl((0.0, 60., 0.0, 30.))
print hkl_to_angles(1, 0, 0)
fourc.write([60, 30, 90, 0])
print "fourc=" , fourc.position
wl.write(1.0)
print "wl = ", wl.read()
# Load the last ub calculation used
ub.lastub()
ub.setu ([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
ub.showref()
ub.swapref(1,2)
#print you.hkl
#pos(get_hkl())
hkl_group.read()
#you.hkl.simulateMoveTo([0,1,1])
#sim(get_hkl(), [0,1,1])
hkl_group.sim([0.0,1.0,1.0])
#pos(get_hkl(), [0,1,1])
hkl_group.write([0.0,1.0,1.0])
###################################################################################################\
#Scans
###################################################################################################
lscan(l, [sin], 0.5, 1.0, 0.1)
ascan([k,l], [sin], [1.0, 1.0], [1.2, 1.3], [0.1, 0.1], latency=0.5, zigzag=True, parallel_positioning = False)
vector = [[1.0,1.0,1.0], [1.0,1.0,1.1], [1.0,1.0,1.2], [1.0,1.0,1.4]]
hklscan(vector, [sin, arr])
+8
View File
@@ -0,0 +1,8 @@
def add(a1, a2):
print __name__
return a1+a2
if __name__ == "__main__":
print add(4,3)
+8
View File
@@ -0,0 +1,8 @@
def testwsm():
from startup import run, get_return
ret = run ("test/WireScanMock")
print "Ret:", ret
+3
View File
@@ -0,0 +1,3 @@
from testws import testwsm
testwsm()
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Find IOCs providing an EPICS record using a web service
#
# $Id: findrecord.py,v 1.25 2016/07/01 12:15:30 lauk Exp $
# ----------------------------------------------------------------------
import getopt
import os
import socket
import sys
import urllib
import urllib2
import xml.sax
PROGRAM = os.path.basename(sys.argv[0])
CVS_REVISION = "$Revision: 1.25 $"
__version__ = CVS_REVISION
WS_URL = 'http://epics-boot-info.psi.ch/find-channel.aspx'
TIMEOUT = 15 # seconds
HEADER_FIELDS = {
'active': (('RECORD', 40, 'Channel'),
('RECORD TYPE', 16, 'RecordType'),
('DESCRIPTION', 40, 'Description'),
('IOC', 25, 'IOC'),
('FACILITY', 8, 'Facility')),
'deleted': (('RECORD', 40, 'Channel'),
('RECORD TYPE', 16, 'RecordType'),
('DESCRIPTION', 40, 'Description'),
('IOC', 25, 'IOC'),
('FACILITY', 8, 'Facility'),
('LAST SEEN', 19, 'LastSeenOn'),
('DELETED ON', 19, 'DeletedOn'))
}
class FindChannelHandler(xml.sax.ContentHandler):
"""
SAX handler for parsing the XML of the find-channel.aspx web service.
"""
attr_names = ('Channel', 'RecordType', 'Description', 'IOC', 'Facility', 'LastSeenOn', 'DeletedOn')
def __init__(self, channel_callback):
self._channel_callback = channel_callback
def startElement(self, name, attrs):
if name == 'entry':
d = {}
for a in FindChannelHandler.attr_names:
d[a] = attrs.get(a, None)
self._channel_callback(d)
class OutputProcessor:
"""
A base class for processing results to output. This class defines the common interface.
"""
def __init__(self, out):
"""
Create a new instance.
:param out: A stream to write to (any object with a ``write`` method, that takes a string).
"""
self.__out = out
def write(self, s):
"""
Write ``s`` to this processors stream.
:param s: The ``string`` to write.
"""
self.__out.write(s.encode('utf-8'))
def print_header(self):
"""
API for printing a header.
"""
pass
def print_channel(self, channel):
"""
API for handling a single result entry.
:param channel: A ``dict`` with keys set from the XML handler.
"""
pass
def print_footer(self):
"""
API for printing a footer
"""
pass
class TableOutputProcessor(OutputProcessor):
"""
An output processor that generates ASCII tables
"""
def __init__(self, out, field_separator, header_labels, field_lengths, field_names):
"""
Create a new instance.
:param out: The stream to ``write`` to.
:param field_separator: The field separator, separating columns from each other.
:param header_labels: The labels for displaying a header line.
:param field_lengths: The width of each column.
"""
OutputProcessor.__init__(self, out)
self._header_labels = dict(zip(field_names, header_labels))
self._header_lines = dict(zip(field_names, tuple(['-' * x for x in field_lengths])))
self._format = field_separator.join(['%%(%s)-%ds' % (f, n) for (f, n) in zip(field_names, field_lengths)]) + "\n"
def print_header(self):
self.write(self._format % self._header_labels)
self.write(self._format % self._header_lines)
def print_channel(self, channel):
self.write(self._format % channel)
class ListPVsOutputProcessor(OutputProcessor):
def __init__(self, out):
OutputProcessor.__init__(self, out)
def print_channel(self, channelDict):
self.write(channelDict['Channel'])
self.write('\n')
class Counter:
"""
A simple counter, because for closures to work, Python needs an object, not a primitive.
"""
def __init__(self, start_from=0):
self.count = start_from
def increment(self, amount=1):
self.count += amount
def main():
opts, args = getopt.getopt(sys.argv[1:], 'df:hi:lrt:u:vx',
['deleted', 'exact-search', 'facility=', 'help', 'ioc=', 'limit=', 'listpvs', 'regex',
'timeout=', 'url=', 'version'])
url = WS_URL
timeout = TIMEOUT
search_opts = {'source': 'active', 'limit': 100}
display_opts = {'outputmode': 'table',
'header_fields': HEADER_FIELDS['active'],
'field_separator': ' '
}
for o, a in opts:
if o in ('-d', '--deleted'):
search_opts['source'] = 'deleted'
timeout = 60
if o in ('-f', '--facility'):
search_opts['facility'] = a
if o in ('-h', '--help'):
usage(sys.stdout)
return 0
if o in ('-i', '--ioc'):
search_opts['ioc'] = a
if o in ('-l', '--listpvs'):
display_opts['outputmode'] = 'listpvs'
if o in ('--limit',):
search_opts['limit'] = int(a)
timeout = 60
if o in ('-r', '--regex'):
search_opts['match'] = 'regex'
if o in ('-t', '--timeout'):
timeout = float(a)
if o in ('-u', '--url'):
url = a
if o in ('-v', '--version'):
sys.stdout.write('%s - %s\n' % (PROGRAM, __version__))
return 0
if o in ('-x', '--exact-search'):
search_opts['match'] = 'exact'
if len(args) == 0:
raise RuntimeError('No search pattern given. Try -h for help.')
if len(args) > 1:
raise RuntimeError('Too many arguments. Try -h for help.')
display_opts['header_fields'] = HEADER_FIELDS[search_opts['source']]
output_processor = create_output_processor(sys.stdout, display_opts)
output_processor.print_header()
pattern = args[0]
num_results = Counter() # need instance, because of closure
def channel_callback(channel):
num_results.increment()
output_processor.print_channel(channel)
search(url, pattern, search_opts, timeout, FindChannelHandler(channel_callback))
output_processor.print_footer()
if num_results.count and num_results.count == search_opts['limit']:
sys.stderr.write('%s: WARNING! Number of search results exactly matches limit. Maybe there is more data...\n'
% PROGRAM)
def usage(out):
out.write('''
Usage: findrecord [OPTIONS] PVSEARCH
OPTIONS:
-d, --deleted Search for deleted records
-f FACILITY, --facility FACILITY Limit search to FACILITY
-h, --help Display instructions and exit
-i IOC, --ioc IOC Limit search to IOC
-l, --listpvs Display only PV names (one per line)
--limit COUNT Limit number of results to COUNT
(default: 100, 0=no limit)
-r, --regex Treat PATTERN as a regular expression
-t SEC, --timeout SEC Timeout in seconds (default = 15)
-u URL, --url URL Set base URL of web service.
-v, --version Display version and exit
-x, --exact-search Disable wildcard searches
NOTE: PVSEARCH must be preceded with '--' if PVSEARCH itself starts
with a '-' (see examples below).
EXAMPLES:
1. Search for all PVs that contain 'VME' anywhere in the name
(implicit wildcard search):
findrecord VME
2. Search for all PVs that start with 'ARIDI-PCT':
findrecord ARIDI-PCT%
findrecord -r '^ARIDI-PCT'
3. Search for all PVs ending in ':CURRENT':
findrecord %:CURRENT
findrecord -r ':CURRENT$'
4. Search for all PVs containing '-PCT' (note the '--'):
findrecord -- -PCT
5. Search for all PVs starting with 'ARIDI' and ending in ':CURRENT'
(note that no implicit prefix and suffix % are added for you):
findrecord ARIDI%:CURRENT
findrecord -r '^ARIDI.*:CURRENT$'
6. Search for all PVs with 'ARIDI' anywhere in the name, followed by
':CURRENT' anywhere behind that (note the exmplicit prefix and
suffix % around the search term):
findrecord %ARIDI%:CURRENT%
findrecord -r 'ARIDI.*:CURRENT'
''')
def create_output_processor(out, display_opts):
if display_opts['outputmode'] == 'table':
labels, widths, field_names = zip(*display_opts['header_fields'])
result = TableOutputProcessor(out, display_opts['field_separator'], labels, widths, field_names)
elif display_opts['outputmode'] == 'listpvs':
result = ListPVsOutputProcessor(out)
else:
raise RuntimeError('Unsupported output mode: %s' % display_opts['outputmode'])
return result
def search(url, pattern, search_opts, timeout, xml_handler):
"""
Search the webservice at `url` for `pattern`.
:param url: The URL to the web service.
:param pattern: The pattern to search for.
:param ioc: Limit search to this IOC
:param timeout: The number of seconds to wait for an HTTP connection.
:param xml_handler: The SAX content handler to use when parsing the HTTP response.
"""
# Workaround for https://tracker.psi.ch/jira/browse/CTRLIT-3391
if pattern[-1] == ':':
if 'match' not in search_opts:
pattern = '%' + pattern + '%'
elif search_opts['match'] == 'regex':
pattern = pattern + '.*'
elif search_opts['match'] == 'exact':
raise ValueError('Unfortunately you found a known bug. Your search pattern must not end in ":" when using the exact matching mode.')
query = search_opts.copy()
query['format'] = 'xml'
full_url = '%s/%s?%s' % (url, urllib.quote(pattern), urllib.urlencode(query))
# In Python 2.4 (SL5), `urlopen` does not have a `timeout` parameter.
# We have to use the timeout mechanism of the `socket` module.
socket.setdefaulttimeout(timeout)
try:
f = urllib2.urlopen(full_url)
try:
parser = xml.sax.make_parser()
parser.setContentHandler(xml_handler)
parser.parse(f)
finally:
f.close()
except urllib2.HTTPError, e:
if e.code == 500: # internal server error
raise RuntimeError('The web service encountered an error. Please inform Controls IT.')
if e.code == 503: # service not available
raise RuntimeError('The web service is currently not available. Try again in a few minutes.')
raise e # nothing special; just raise it again
if __name__ == '__main__':
print "a"
sys.argv = ["findrecord.py", "AVG"]
main()
+14
View File
@@ -0,0 +1,14 @@
from startup import inject, set_return
def test():
#from startup import lscan
#print lscan
inject()
global motor
print motor
motor=1
print motor
inject()
print motor
set_return("VIVA")