Exemplo n.º 1
0
 def __init__(self, host, platform, prefix, ioc_prefix, ioc_name):
     super(DaqDriver, self).__init__()
     self.run = True
     self.connected = False
     self.prefix = prefix
     self.pvdb = pvdb
     self.setParam('HOST', host)
     self.setParam('PLATFORM', platform)
     self.ioc = IocAdmin(ioc_name, ioc_prefix, self)
     self.host = self.getParam('HOST')
     self.platform = self.getParam('PLATFORM')
     self.confpv = self.get_tagged_pvs('config')
     self.readonly = self.get_tagged_pvs('readonly')
     self.cmds = self.get_tagged_pvs('daqcmd')
     self.daq = self.daq = pydaq.Control(host=self.host,
                                         platform=self.platform)
     self.refresh = 1.0
     for pv in self.pvdb.keys():
         # remove the invalid state
         self.setParamStatus(pv, Alarm.NO_ALARM, Severity.NO_ALARM)
     self.eid = Queue.Queue()
     self.sig = threading.Event()
     self.lock = threading.Lock()
     self.lock.acquire()
     self.tid = threading.Thread(target=self.runDAQ)
     self.tid.setDaemon(True)
     self.tid.start()
     self.nid = threading.Thread(target=self.runNumEvent)
     self.nid.setDaemon(True)
     self.nid.start()
Exemplo n.º 2
0
def get_src_info(src):
    """
    Encodes a detinfo src string into its integer equivalent 
    """
    daq = pydaq.Control('test')
    detname, detid, devname, devid = src.split("/")
    det = daq.detectors().index(detname) & 0xff
    detid = int(detid) & 0xff
    dev = daq.devices().index(devname) & 0xff
    devid = int(devid) & 0xff
    return (det << 24) | (detid << 16) | (dev << 8) | devid
Exemplo n.º 3
0
def get_db_from_daq(daqinfo):
    try:
        host, platform = daqinfo.split(":")
    except ValueError:
        host = daqinfo
        platform = 0
    daq = pydaq.Control(host, platform)
    daq.connect()
    dbalias = daq.dbalias()
    dbpath = daq.dbpath()
    daq.disconnect()
    return dbpath, dbalias
Exemplo n.º 4
0
    def __init__(self, daq_host, daq_platform, laser_delay_pv_name,
                 tt_stage_position_pv_name, t0_pv_name, laser_lock_pv_name):
        """
        Create a Timescaner instance, providing control over the timetool
        and laser delay stages.

        Parameters
        ----------
        daq_host : str
        daq_platform : int
        laser_delay_pv_name : str
        tt_stage_position_pv_name : str
        t0_pv_name : str
        laser_lock_pv_name : str

        See Also
        --------
        Timescaner.from_rc() : function
            Create a timescaner instance from a file.
        """

        self._daq_host = daq_host
        self._daq_platform = daq_platform
        self.daq = pydaq.Control(daq_host, daq_platform)

        self._laser_delay = epics.PV(laser_delay_pv_name)
        self._tt_stage_position = epics.PV(tt_stage_position_pv_name)
        self._t0 = epics.PV(t0_pv_name)
        self._laser_lock = epics.PV(laser_lock_pv_name)

        self.tt_travel_offset = 0.0
        self.tt_fit_coeff = np.array([0.0, 1.0, 0.0])
        self.calibrated = False

        time.sleep(0.1)  # time for PVs to connect
        for pv in [
                self._laser_delay, self._tt_stage_position, self._t0,
                self._laser_lock
        ]:
            if not pv.connected:
                raise RuntimeError('Cannot connect to PV: %s' % pv.pvname)

        return
Exemplo n.º 5
0
  def init(self):
    self.pvLaserShutter = None
    if self.iShutter > 0 and self.iShutter <= len(self.lPvShutter):
      self.pvLaserShutter = self.lPvShutter[self.iShutter-1]

    fBeamFullRate = float(caget(pvBeamRate));
    if not self.bSimMode:
      print "\n## Beam rate = %.1f HZ" % (fBeamFullRate)
      if not (self.dictBeamToBurstRate.has_key(fBeamFullRate)):
        print "!!! Beam rate is not stable, please wait for beam to stablize and run the script again"
        return 1
      self.mccBurst.mccBurstCheckInit()

    if self.fBurstRate == -1:
      if self.bSimMode:
        self.fBurstRate = 120.0
      else:
        self.fBurstRate = fBeamFullRate

    if not self.bSimMode:
      self.mccBurst.mccBurstSetNumShot(self.iNumShot, self.dictBeamToBurstRate[self.fBurstRate])

    print "## Burst rate = %.1f HZ"   % (self.fBurstRate)
    print "## Multiple shot: %d" % (self.iNumShot)

    self.daq = pydaq.Control(self.daq_host, self.daq_platform)

    print ' *** DaqMultipleShot.init(): self.controls =', self.controls

    #
    #  Send the structure the first time to put the control variables
    #    in the file header

    print "daq connect...",
    sys.stdout.flush()
    try:
      self.daq.connect() # get dbpath and key from DAQ
    except Exception, e:
      print e
      print "Please select devices and click Select in the DAQ Control window"
Exemplo n.º 6
0
def _get_device_config_handlers():
    special_handlers = {
        'Jungfrau': JungfrauConfig,
        'Epix10ka': EpixConfig,
        'Epix10kaQuad': EpixConfig,
        'Epix10ka2M': EpixConfig,
    }
    excluded_handlers = {
        'NoDevice',
        'Evr',
        'Acqiris',
        'Ipimb',
        'Encoder',
        'AcqTDC',
        'Xamps',
        'Fexamp',
        'Gsc16ai',
        'OceanOptics',
        'USDUSB',
        'Imp',
        'Epix',
        'EpixSampler',
        'Wave8',
        'LeCroy',
        'JungfrauSegment',
        'JungfrauSegmentM2',
        'JungfrauSegmentM3',
        'JungfrauSegmentM4',
        'QuadAdc',
    }
    daq = pydaq.Control(0)

    return {
        dev: special_handlers.get(dev, SimpleConfig)
        for dev in daq.devices() if dev not in excluded_handlers
    }
Exemplo n.º 7
0
  def init(self):
    self.pvLaserShutter = None
    if self.iShutter > 0 and self.iShutter <= len(self.lPvShutter):
      self.pvLaserShutter = self.lPvShutter[self.iShutter-1]

    fBeamFullRate = float(caget(pvBeamRate));
    if not self.bSimMode:
      print "\n## Beam rate = %.1f HZ" % (fBeamFullRate)
      if not (self.dictBeamToBurstRate.has_key(fBeamFullRate)):
        print "!!! Beam rate is not stable, please wait for beam to stablize and run the script again"
        return 1
      self.mccBurst.mccBurstCheckInit()

    caput(pvPlayMode         , 0) # PlayMode = Once
    caput(pvMccSeqSyncMarker , 6) # Set sequencer sync marker to 120Hz
    caput(pvMccSeqBeamRequest, 0) # Set seuqencer rate to be 120Hz (TS4|TS1)
    if self.bSimMode:
      caput(pvMccSynEvtBurst   , 0) # Diable SEB support
    else:
      caput(pvMccSynEvtBurst   , 1) # Enable SEB support

    if self.fBurstRate == -1:
      if self.bSimMode:
        self.fBurstRate = 120.0
      else:
        self.fBurstRate = fBeamFullRate

    if not self.bSimMode:
      self.mccBurst.mccBurstSetNumShot(self.iNumShot, self.dictBeamToBurstRate[self.fBurstRate])

    print "## Burst rate = %.1f HZ"   % (self.fBurstRate)
    print "## Multiple shot: %d" % (self.iNumShot)

    self.codeCommand = self.setPrincetonExposureSequence()

    # Exposure Time =
    #     delay from "real" princeton open and SEB burst start event (0 second)
    #     delay from SEB burst start event and MCC firing beam ( max( 1/60, 1/self.fBurstRate) )
    #     (x) + laser shutter open delay (Pv set + shutter physical open) (0.5 second)
    #     + manual sleep (fExpDelay)
    #     + exposure Time ((self.iNumShot / self.fBurstRate) second)
    #   = 0.0 + (self.iNumShot / self.fBurstRate) + fExpDelay  second

    # Setup Time =
    #     delay between setting pvPlayCtrl and the "real" princeton open (0.2 second)
    #   = 0.2

    self.fSetupTime    = 0.1
    self.fExposureTime = 0.0 + self.fExpDelay + self.iNumShot / float(self.fBurstRate) + max(1.0/120, 1.0/self.fBurstRate) + self.iSlowCamOpenDelay / 360.0

    self.daq = pydaq.Control(self.daq_host, self.daq_platform)

    print ' *** PrincetonDaqMultipleShot.init(): self.controls =', self.controls

    #
    #  Send the structure the first time to put the control variables
    #    in the file header

    print "daq connect...",
    sys.stdout.flush()
    try:
      self.daq.connect() # get dbpath and key from DAQ
    except Exception, e:
      print e
      print "Please select devices and click Select button in DAQ Control window"
Exemplo n.º 8
0
    print 'steps   ', options.steps
    print 'detector', hex(options.detector)
    if (options.deviceOffset > 0):
        print 'deviceOffset', options.deviceOffset, "so detector now", hex(
            options.detector + options.deviceOffset)
        options.detector = options.detector + options.deviceOffset
    print 'typeID  ', hex(options.typeID)
    time.sleep(1)
    print 'shutter ', options.shutter
    time.sleep(0)
    print 'exclude ', options.exclude

    shutterActive = options.shutter != 'None'

    # Connect to the daq system
    daq = pydaq.Control(options.host, options.platform)
    daq.connect()
    print 'dark    ', options.dark, 'events'
    print 'bright  ', options.events, 'events'
    index = 0.0
    if shutterActive:
        ser = serial.Serial(options.shutter)
        ser.write(chr(128))  ## close shutter
    nodeFound = 'No'
    partition = daq.partition()
    if options.exclude != 'None':
        for node in partition:
            if node['id'] == options.exclude:
                node['record'] = False
                nodeFound = 'Yes'
                print 'gap     ', options.gap, 'events'
Exemplo n.º 9
0
def scan_parameter(device, configtype, parameter, values, enumkey=None):
    import sys

    parser = OptionParser()
    parser.add_option("-a",
                      "--address",
                      dest="host",
                      default='localhost',
                      help="connect to DAQ at HOST",
                      metavar="HOST")
    parser.add_option("-p",
                      "--platform",
                      dest="platform",
                      type="int",
                      default=3,
                      help="connect to DAQ at PLATFORM",
                      metavar="PLATFORM")
    parser.add_option("-D",
                      "--detector",
                      dest="detector",
                      type="string",
                      default='NoDetector',
                      help="detector to scan, default NoDetector",
                      metavar="DET")
    parser.add_option("-I",
                      "--detectorID",
                      dest="detectorID",
                      type="int",
                      default=0,
                      help="detector ID  to scan, default 0",
                      metavar="D_ID")
    parser.add_option("-i",
                      "--deviceID",
                      dest="deviceID",
                      type="int",
                      default=0,
                      help="device ID to scan, default 0",
                      metavar="DEV_ID")
    parser.add_option("-t",
                      "--typeIdVersion",
                      dest="typeIdVersion",
                      type="int",
                      default=1,
                      help="type ID Version in use, default 1",
                      metavar="typeIdVersion")
    parser.add_option("-A",
                      "--dbalias",
                      dest="dbalias",
                      type="string",
                      help="data base key in use",
                      metavar="DBALIAS")
    parser.add_option("-e",
                      "--events",
                      dest="events",
                      type="int",
                      default=1000,
                      help="record N events/cycle",
                      metavar="EVENTS")
    parser.add_option("-u",
                      "--user",
                      dest="userFlag",
                      type="int",
                      default=1,
                      help="Iff zero then no user, default=1",
                      metavar="DARKEVENTS")

    (options, args) = parser.parse_args()

    options.device = device
    options.typeId = configtype

    print 'host', options.host
    print 'platform', options.platform
    print 'dbalias', options.dbalias
    print 'detector', options.detector
    print 'detectorID', options.detectorID
    print 'device', options.device
    print 'deviceID', options.deviceID
    print 'events', options.events
    print 'userFlag', options.userFlag

    print 'device', device
    print 'configtype', configtype
    print 'parameter', parameter
    print 'values', values

    # Connect to the daq system
    daq = pydaq.Control(options.host, options.platform)
    daq.connect()
    print 'Partition is', daq.partition()
    detectors = daq.detectors()
    devices = daq.devices()
    types = daq.types()
    #    print 'types are :\n', types

    found = [False, False, False]
    index = 0
    for member in detectors:
        if member == options.detector:
            detectorValue = (index << 24) | ((options.detectorID & 0xff) << 16)
            found[0] = True
        index = index + 1
    index = 0
    for member in devices:
        if member == options.device:
            detectorValue = detectorValue | (index << 8) | (options.deviceID
                                                            & 0xff)
            found[1] = True
        index = index + 1
    index = 0
    for member in types:
        if member == options.typeId:
            typeIdValue = index | (options.typeIdVersion << 16)
            found[2] = True
        index = index + 1
    if found[0] and found[1] and found[2]:
        print "detector hex value", hex(detectorValue)
        print 'typeId', hex(typeIdValue)
    else:
        if not found[0]:
            print "Detector", options.detector, "not found!"
        if not found[1]:
            print "Device", options.device, "not found!"
        if not found[2]:
            print "Type", options.typeId, "not found!"
        print "Exiting"
        exit()
#
#  First, get the current configuration key in use and set the value to be used
#

    cdb = pycdb.Db(daq.dbpath())
    key = daq.dbkey()
    alias = daq.dbalias()
    print 'Retrieved key ' + hex(key) + ' alias ' + alias

    #
    #  Generate a new key with different epix and EVR configuration for each cycle
    #
    if options.dbalias == None:
        newkey = cdb.clone(alias)
    else:
        newkey = cdb.clone(options.dbalias)

    print 'Generated key ', hex(newkey)
    print 'key', hex(key)
    print 'detectorValue', hex(detectorValue)
    print 'typeIdValue', hex(typeIdValue)
    xtc = cdb.get(key=key, src=detectorValue, typeid=typeIdValue)[0]
    print 'xtc is', xtc
    config = xtc.get(0)
    if enumkey is not None:
        enums = xtc.get_enums()[enumkey]
    else:
        enums = None
    print 'Composing the sequence of configurations ...'
    cycle = 0  # cycle number excluding skipped
    for value in values:
        if parameter in config:
            if enums is not None:
                config[parameter] = enums[value]
            else:
                config[parameter] = value
        print config, cycle
        xtc.set(config, cycle)
        cycle += 1

    cdb.substitute(newkey, xtc)
    cdb.unlock()
    print '    done'

    #  Send the structure the first time to put the control variables
    #    in the file header
    #

    daq.configure(key=newkey, events=options.events)

    print "Configured."

    #
    #  Wait for the user to declare 'ready'
    #    Setting up monitoring displays for example
    #
    if options.userFlag > 0:
        ready = raw_input('--Hit Enter when Ready-->')

    for value in values:
        print 'parameter', parameter, 'value', value
        daq.begin(events=options.events)
        daq.end()

#
#  Wait for the user to declare 'done'
#    Saving monitoring displays for example
#
    if options.userFlag > 0:
        ready = raw_input('-- Finished, hit Enter to exit -->')
    print 'Restoring key', hex(key)
    daq.configure(key=key, events=1)
Exemplo n.º 10
0
def scan_offset(device, configtype):
    import sys

    parser = OptionParser()
    parser.add_option("-a",
                      "--address",
                      dest="host",
                      default='localhost',
                      help="connect to DAQ at HOST",
                      metavar="HOST")
    parser.add_option("-p",
                      "--platform",
                      dest="platform",
                      type="int",
                      default=0,
                      help="connect to DAQ at PLATFORM",
                      metavar="PLATFORM")
    parser.add_option("-D",
                      "--detector",
                      dest="detector",
                      type="string",
                      default='NoDetector',
                      help="detector to scan, default NoDetector",
                      metavar="DET")
    parser.add_option("-I",
                      "--detectorID",
                      dest="detectorID",
                      type="int",
                      default=0,
                      help="detector ID  to scan, default 0",
                      metavar="D_ID")
    #    parser.add_option("-d","--device",dest="device",type="string",default='Epix10ka',
    #                      help="device to scan, default Epix10ka",metavar="DEV")
    parser.add_option("-i",
                      "--deviceID",
                      dest="deviceID",
                      type="int",
                      default=0,
                      help="device ID to scan, default 0",
                      metavar="DEV_ID")
    parser.add_option("-t",
                      "--typeIdVersion",
                      dest="typeIdVersion",
                      type="int",
                      default=1,
                      help="type ID Version in use, default 1",
                      metavar="typeIdVersion")
    parser.add_option("-A",
                      "--dbalias",
                      dest="dbalias",
                      type="string",
                      help="data base key in use",
                      metavar="DBALIAS")
    parser.add_option("-s",
                      "--space",
                      dest="space",
                      type="int",
                      default=7,
                      help="space is the spacing in the array",
                      metavar="SPACE")
    parser.add_option("-e",
                      "--events",
                      dest="events",
                      type="int",
                      default=4608,
                      help="record N events/cycle",
                      metavar="EVENTS")
    parser.add_option("-v",
                      "--value0",
                      dest="Value0",
                      type="int",
                      default=0,
                      help="Value0 for most of the pixel array, default=0 ",
                      metavar="VALUE0")
    parser.add_option(
        "-V",
        "--value1",
        dest="Value1",
        type="int",
        default=1,
        help="Value1 for pixels under test in the pixel array, default=1",
        metavar="VALUE1")
    parser.add_option("-d",
                      "--darkEvents",
                      dest="darkEvents",
                      type="int",
                      default=1200,
                      help="Number of events in each Dark, default=1200 ",
                      metavar="DARKEVENTS")
    parser.add_option("-u",
                      "--user",
                      dest="userFlag",
                      type="int",
                      default=1,
                      help="Iff zero then no user, default=1",
                      metavar="USERFLAG")
    parser.add_option("-o",
                      "--cycleStart",
                      dest="cycleStart",
                      type="int",
                      default=0,
                      help="Starting at cycle number, default=0",
                      metavar="CYCLESTART")
    parser.add_option("-O",
                      "--cycleStop",
                      dest="cycleStop",
                      type="int",
                      default=105,
                      help="Stopping at cycle number, default=105",
                      metavar="CYCLESTOP")

    (options, args) = parser.parse_args()

    options.device = device
    options.typeId = configtype
    # currently only the Epix10kaQuads and Epix10ka2M support the ghost correction
    options.ghostCorrect = True if device in ['Epix10kaQuad', 'Epix10ka2M'
                                              ] else False

    print 'host', options.host
    print 'platform', options.platform
    print 'dbalias', options.dbalias
    print 'detector', options.detector
    print 'detectorID', options.detectorID
    print 'device', options.device
    print 'deviceID', options.deviceID
    if options.space > 7:
        print 'Space is too large, truncated to 7'
        options.space = 7
    print 'space', options.space
    print 'Values', options.Value0, ',', options.Value1
    print 'darkEvents', options.darkEvents
    print 'events', options.events
    print 'userFlag', options.userFlag
    print 'cycleStart', options.cycleStart
    print 'cycleStop', options.cycleStop
    print 'ghostCorrection', options.ghostCorrect

    #Fixed High Gain , pixel matrix to 0xc trbit 1
    #Fixed Medium Gain pixel matrix to 0xc trbit 0
    #Fixed Low Gain pixel matrix to to 0x8 trbit don't care
    #Auto High to Low pixel matrix to 0x0 trbit 1
    #Auto Medium to low pixel matrix to 0x0 trbit 0
    hasGhostCorrection = False
    numberOfDarks = 5
    darkValues = [0xc, 0xc, 0x8, 0, 0]
    trBitValues = [1, 0, 0, 1, 0]
    darkMessages = [
        'Fixed High Gain', 'Fixed Medium Gain', 'Fixed Low Gain',
        'Auto High to Low', 'Auto Medium to Low'
    ]

    # Connect to the daq system
    daq = pydaq.Control(options.host, options.platform)
    daq.connect()
    print 'Partition is', daq.partition()
    detectors = daq.detectors()
    devices = daq.devices()
    types = daq.types()
    #    print 'types are :\n', types

    found = [False, False, False]
    index = 0
    for member in detectors:
        if member == options.detector:
            detectorValue = (index << 24) | ((options.detectorID & 0xff) << 16)
            found[0] = True
        index = index + 1
    index = 0
    for member in devices:
        if member == options.device:
            detectorValue = detectorValue | (index << 8) | (options.deviceID
                                                            & 0xff)
            found[1] = True
        index = index + 1
    index = 0
    for member in types:
        if member == options.typeId:
            typeIdValue = index | (options.typeIdVersion << 16)
            found[2] = True
        index = index + 1
    if found[0] and found[1] and found[2]:
        print "detector hex value", hex(detectorValue)
        print 'typeId', hex(typeIdValue)
    else:
        if not found[0]:
            print "Detector", options.detector, "not found!"
        if not found[1]:
            print "Device", options.device, "not found!"
        if not found[2]:
            print "Type", options.typeId, "not found!"
        print "Exiting"
        exit()
#
#  First, get the current configuration key in use and set the value to be used
#

    cdb = pycdb.Db(daq.dbpath())
    key = daq.dbkey()
    alias = daq.dbalias()
    print 'Retrieved key ' + hex(key) + ' alias ' + alias

    #
    #  Generate a new key with different epix and EVR configuration for each cycle
    #
    if options.dbalias == None:
        newkey = cdb.clone(alias)
    else:
        newkey = cdb.clone(options.dbalias)

    print 'Generated key ', hex(newkey)
    print 'key', hex(key)
    print 'detectorValue', hex(detectorValue)
    print 'typeIdValue', hex(typeIdValue)
    xtc = cdb.get(key=key, src=detectorValue, typeid=typeIdValue)[0]
    print 'xtc is', xtc
    epix = xtc.get(0)
    print 'Composing the sequence of configurations ...'
    gcycle = 0  # cycle number if nothing skipped
    cycle = 0  # cycle number excluding skipped
    for dark in range(numberOfDarks):
        if gcycle >= options.cycleStart and gcycle < options.cycleStop:
            if 'elemCfg' in epix:
                for e in epix['elemCfg']:
                    mask = e['asicMask']
                    for rows in range(352):
                        for cols in range(384):
                            e['asicPixelConfigArray'][rows][cols] = darkValues[
                                dark]
                    for asicNum in range(4):
                        if mask & (1 << asicNum):
                            e['asics'][asicNum]['trbit'] = trBitValues[dark]
            else:
                mask = epix['AsicMask']
                for rows in range(352):
                    for cols in range(384):
                        epix['asicPixelConfigArray'][rows][cols] = darkValues[
                            dark]
                for asicNum in range(4):
                    if mask & (1 << asicNum):
                        epix['asics'][asicNum]['trbit'] = trBitValues[dark]
            xtc.set(epix, cycle)
            cycle += 1
        gcycle += 1

    for trbit in [0, 1]:
        for position in range(options.space**2):
            if gcycle >= options.cycleStart and gcycle < options.cycleStop:
                maskedpixels = pixel_mask(options.Value0, options.Value1,
                                          options.space, position)
                if 'elemCfg' in epix:
                    for e in epix['elemCfg']:
                        mask = e['asicMask']
                        for rows in range(352):
                            for cols in range(384):
                                e['asicPixelConfigArray'][rows][
                                    cols] = maskedpixels[rows][cols]
                        for asicNum in range(4):
                            if mask & (1 << asicNum):
                                e['asics'][asicNum]['atest'] = 1
                                e['asics'][asicNum]['test'] = 1
                                e['asics'][asicNum]['trbit'] = trbit
                                e['asics'][asicNum]['Pulser'] = 0
                                if options.ghostCorrect:
                                    e['asics'][asicNum]['PulserSync'] = 1
                else:
                    mask = epix['AsicMask']
                    for rows in range(352):
                        for cols in range(384):
                            epix['asicPixelConfigArray'][rows][
                                cols] = maskedpixels[rows][cols]
                    for asicNum in range(4):
                        if mask & (1 << asicNum):
                            epix['asics'][asicNum]['atest'] = 1
                            epix['asics'][asicNum]['test'] = 1
                            epix['asics'][asicNum]['trbit'] = trbit
                            epix['asics'][asicNum]['Pulser'] = 0
                            if options.ghostCorrect:
                                epix['asics'][asicNum]['PulserSync'] = 1
                if options.ghostCorrect:
                    if 'quads' in epix:
                        for q in epix['quads']:
                            q['asicAcqLToPPmatL'] = 1000
                    else:
                        epix['asicAcqLToPPmatL'] = 1000
                xtc.set(epix, cycle)
                cycle += 1
            gcycle += 1
#            print 'xtc.set(, epix', position + (trbit*(options.space**2)), ')'
    cdb.substitute(newkey, xtc)
    cdb.unlock()
    print '    done'

    #  Send the structure the first time to put the control variables
    #    in the file header
    #

    cycle_label = [
        ('%s offset scan' % device, ''),
    ]
    daq.configure(key=newkey, events=options.events, labels=cycle_label)

    print "Configured."

    #
    #  Wait for the user to declare 'ready'
    #    Setting up monitoring displays for example
    #
    if options.userFlag > 0:
        ready = raw_input('--Hit Enter when Ready-->')

    gcycle = 0
    for dark in range(numberOfDarks):
        if gcycle >= options.cycleStart and gcycle < options.cycleStop:
            print 'dark', darkMessages[dark]
            cycle_label = [
                ('%s offset scan' % device, 'dark %s' % darkMessages[dark]),
            ]
            daq.begin(events=options.darkEvents, labels=cycle_label)
            daq.end()
        gcycle += 1

    for trbit in [0, 1]:
        for position in range(((options.space**2))):
            if gcycle >= options.cycleStart and gcycle < options.cycleStop:
                print 'position', position, 'trbit', trbit
                cycle_label = [
                    ('%s offset scan' % device,
                     'position %d trbit %d' % (position, trbit)),
                ]
                daq.begin(events=options.events, labels=cycle_label)
                daq.end()
            gcycle += 1


#
#  Wait for the user to declare 'done'
#    Saving monitoring displays for example
#
    if options.userFlag > 0:
        ready = raw_input('-- Finished, hit Enter to exit -->')
    print 'Restoring key', hex(key)
    daq.configure(key=key, events=1)
Exemplo n.º 11
0
def scan_exponential(device, configtype):

    import sys

    parser = OptionParser()
    parser.add_option("-a",
                      "--address",
                      dest="host",
                      default='localhost',
                      help="connect to DAQ at HOST",
                      metavar="HOST")
    parser.add_option("-p",
                      "--platform",
                      dest="platform",
                      type="int",
                      default=3,
                      help="connect to DAQ at PLATFORM",
                      metavar="PLATFORM")
    parser.add_option("-D",
                      "--detector",
                      dest="detector",
                      type="string",
                      default='NoDetector',
                      help="detector to scan, default NoDetector",
                      metavar="DET")
    parser.add_option("-I",
                      "--detectorID",
                      dest="detectorID",
                      type="int",
                      default=0,
                      help="detector ID  to scan, default 0",
                      metavar="D_ID")
    parser.add_option("-i",
                      "--deviceID",
                      dest="deviceID",
                      type="int",
                      default=0,
                      help="device ID to scan, default 0",
                      metavar="DEV_ID")
    parser.add_option("-t",
                      "--typeIdVersion",
                      dest="typeIdVersion",
                      type="int",
                      default=1,
                      help="type ID Version in use, default 1",
                      metavar="typeIdVersion")
    parser.add_option("-P",
                      "--parameter",
                      dest="parameter",
                      type="string",
                      help="epix parameter to scan",
                      metavar="PARAMETER")
    parser.add_option("-A",
                      "--dbalias",
                      dest="dbalias",
                      type="string",
                      help="data base key in use",
                      metavar="DBALIAS")
    parser.add_option("-s",
                      "--start",
                      dest="start",
                      type="float",
                      default=200,
                      help="parameter start",
                      metavar="START")
    parser.add_option("-f",
                      "--finish",
                      dest="finish",
                      type="int",
                      nargs=1,
                      default=2000,
                      help="parameter finish",
                      metavar="FINISH")
    parser.add_option(
        "-m",
        "--multiplier",
        dest="multiplier",
        type="float",
        nargs=1,
        default=-1.0,
        help=
        "parameter multiplier in case you want to enter it directly, ignoring FINISH",
        metavar="MULTIPLIER")
    parser.add_option("-n",
                      "--steps",
                      dest="steps",
                      type="int",
                      default=20,
                      help="run N parameter steps",
                      metavar="N")
    parser.add_option("-e",
                      "--events",
                      dest="events",
                      type="int",
                      default=105,
                      help="record N events/cycle",
                      metavar="EVENTS")
    parser.add_option(
        "-L",
        "--linear",
        dest="linear",
        type="string",
        default="no",
        help="Set to yes for linear scanning instead of exponential",
        metavar="LINEAR")
    parser.add_option(
        "-l",
        "--limit",
        dest="limit",
        type="int",
        default=99,
        help="limit number of configs to less than number of steps",
        metavar="LIMIT")
    parser.add_option("-S",
                      "--shutter",
                      dest="shutter",
                      default="None",
                      help="path to shutter serial port",
                      metavar="SHUTTER")
    parser.add_option("-u",
                      "--use_l3t",
                      dest="use_l3t",
                      action="store_true",
                      default=False,
                      help="Use L3Trigger to filter events",
                      metavar="L3T")

    (options, args) = parser.parse_args()

    options.device = device
    options.typeId = configtype

    print 'host', options.host
    print 'platform', options.platform
    print 'dbalias', options.dbalias
    print 'parameter', options.parameter
    print 'start', options.start, options.start
    print 'steps', options.steps
    print 'finish', options.finish
    #    print 'multiplier', options.multiplier
    print 'events', options.events
    print 'detector', options.detector
    print 'detectorID', options.detectorID
    print 'device', options.device
    print 'deviceID', options.deviceID
    #    print 'linear', options.linear
    print 'shutter', options.shutter
    print 'use_l3t', options.use_l3t

    if options.steps < options.limit: options.limit = options.steps
    else:        print 'Warning, range will be covered in', options.limit, \
      'but will still do', options.steps, 'steps with wrapping'

    adder = 0.0
    if options.linear == "no":
        if (options.start == 0):
            options.start = 0.49
        if (options.multiplier < 0):
            options.multiplier = math.exp(
                (math.log(float(options.finish) / options.start)) /
                options.limit)
        print 'multiplier in use is', options.multiplier, 'and will scan from', options.start, 'to', options.finish
    else:
        adder = (float(options.finish) - options.start) / float(options.limit)
        print 'will do linear scanning from', options.start, 'to', options.finish, "in ", options.limit, "steps and with adder of ", adder

# Connect to the daq system
    daq = pydaq.Control(options.host, options.platform)
    daq.connect()
    print 'Partition is', daq.partition()
    detectors = daq.detectors()
    devices = daq.devices()
    types = daq.types()
    #    print 'types are :\n', types

    found = [False, False, False]
    index = 0
    for member in detectors:
        if member == options.detector:
            detectorValue = (index << 24) | ((options.detectorID & 0xff) << 16)
            found[0] = True
        index = index + 1
    index = 0
    for member in devices:
        if member == options.device:
            detectorValue = detectorValue | (index << 8) | (options.deviceID
                                                            & 0xff)
            found[1] = True
        index = index + 1
    index = 0
    for member in types:
        if member == options.typeId:
            typeIdValue = index | (options.typeIdVersion << 16)
            found[2] = True
        index = index + 1
    if found[0] and found[1] and found[2]:
        print "detector hex value", hex(detectorValue)
        print 'typeId', hex(typeIdValue)
    else:
        if not found[0]:
            print "Detector", options.detector, "not found!"
        if not found[1]:
            print "Device", options.device, "not found!"
        if not found[2]:
            print "Type", options.typeId, "not found!"
        print "Exiting"
        exit()
#
#  First, get the current configuration key in use and set the value to be used
#

    cdb = pycdb.Db(daq.dbpath())
    key = daq.dbkey()
    alias = daq.dbalias()
    print 'Retrieved key ' + hex(key) + ' alias ' + alias

    #
    #  Generate a new key with different epix and EVR configuration for each cycle
    #
    if options.dbalias == None:
        newkey = cdb.clone(alias)
    else:
        newkey = cdb.clone(options.dbalias)

    print 'Generated key ', hex(newkey)
    print 'key', hex(key)
    print 'detectorValue', hex(detectorValue)
    print 'typeIdValue', hex(typeIdValue)
    #    xtcSet = cdb.get(key=key)
    #    print 'xtcSet members :\n'
    #    for member in xtcSet :
    #        for attr in dir(member) :
    #            print getattr(member,attr)
    #    print 'Done printing xtcSet\n'
    #    print "cdb.get opened\n", cdb.get(key=key)
    xtc = cdb.get(key=key, src=detectorValue, typeid=typeIdValue)[0]
    print 'xtc is', xtc
    epix = xtc.get(0)

    if set_dict(epix, options.parameter, float(options.start)) == False:
        dump_dict(epix)
        sys.exit(1)

    else:
        print 'Composing the sequence of configurations ...'
        value = float(options.start)
        cycleLength = 1
        shutterActive = options.shutter != 'None'
        if shutterActive:
            cycleLength = 2
        denom = float(options.limit + 1)
        #        mask = epix['AsicMask']
        values = []
        for cycle in range(options.limit + 1):
            print cycle
            index = float(cycle % (options.limit + 1)) + 1.0
            set_dict(epix, options.parameter, value)
            xtc.set(epix, cycle)
            values.append(value)
            if options.linear == "no":
                #                print cycle, int(round(value))
                value = value * options.multiplier
            else:
                #                print cycle, int(round(value))
                value = value + adder
        cdb.substitute(newkey, xtc)
        cdb.unlock()
        for cycle in range(len(values)):
            print cycle, "value of", options.parameter, "is", values[cycle]
        print '    done'
        #
        #  Could scan EVR simultaneously
        #
        #    evr   = Evr  .ConfigV4().read(cdb.xtcpath(key.value,Evr  .DetInfo,Evr  .TypeId))
        #    newxtc = cdb.remove_xtc(newkey,Evr.DetInfo,Evr.TypeId)

        #
        #  Send the structure the first time to put the control variables
        #    in the file header
        #

        if options.use_l3t:
            print "Acquiring %s events passing L3Trigger" % (options.events)
            daq.configure(key=newkey,
                          l3t_events=options.events,
                          controls=[(options.parameter[0:29],
                                     int(round(options.start)))])
        else:
            daq.configure(key=newkey,
                          events=options.events,
                          controls=[(options.parameter[0:29],
                                     int(round(options.start)))])

        print "Configured."

        # set up shutter
        if shutterActive:
            ser = serial.Serial(options.shutter)
            ser.write(chr(129))  ## close shutter

#
#  Wait for the user to declare 'ready'
#    Setting up monitoring displays for example
#
        ready = raw_input('--Hit Enter when Ready-->')
        for cycle in range(options.steps + 1):
            if cycle % (options.limit + 1) == 0:
                index = 0.0
                subcycle = 0
            if shutterActive:
                ser.write(chr(129))  ## close shutter
                print "Cycle", cycle, " closed -", options.parameter, "=", values[
                    subcycle]
            else:
                print "Cycle", cycle, "-", options.parameter, "=", values[
                    subcycle]
            if options.use_l3t:
                daq.begin(l3t_events=options.events,
                          controls=[(options.parameter[0:29], values[subcycle])
                                    ])
            else:
                daq.begin(controls=[(options.parameter[0:29],
                                     values[subcycle])])
            # wait for enabled , then enable the EVR sequence
            # wait for disabled, then disable the EVR sequence
            daq.end()
            if shutterActive:
                print "        opened -", options.parameter, "=", values[
                    subcycle]
                ser.write(chr(128))  ## open shutter
                if options.use_l3t:
                    daq.begin(l3t_events=options.events,
                              controls=[(options.parameter[0:29],
                                         values[subcycle])])
                else:
                    daq.begin(controls=[(options.parameter[0:29],
                                         values[subcycle])])
                daq.end()
                ser.write(chr(129))  ## close shutter
            subcycle += 1


#
#  Wait for the user to declare 'done'
#    Saving monitoring displays for example
#
    ready = raw_input('-- Finished, hit Enter to exit -->')
    print 'Restoring key', hex(key)
    daq.configure(key=key, events=1)
Exemplo n.º 12
0
    def init(self, controls=None, bDaqBegin=True):
        while True:
            fBeamFullRate = float(caget(pvBeamRate))
            if fBeamFullRate == 0.5 or float(
                    int(fBeamFullRate)) == fBeamFullRate:
                break

        if not self.bSimMode:
            if not (self.mccBurst.isLegalBeamRate(fBeamFullRate)):
                print "!!! Beam rate %g is not stable, please wait for beam to stablize and run the script again" % (
                    fBeamFullRate)
                return 1
            self.mccBurst.mccBurstCheckInit()

        if self.fBurstRate == -1:
            self.fBurstRate = fBeamFullRate

        if not (self.fBurstRate in dictRateToSyncMarker):
            print "!!! Burst rate %g not supported" % (self.fBurstRate)
            return 1

        caput(pvPlayMode, 0)  # PlayMode = Once
        caput(pvMccSeqSyncMarker, dictRateToSyncMarker[self.fBurstRate])
        caput(pvMccSeqBeamRequest,
              0)  # Set seuqencer rate to be 120Hz (TS4|TS1)

        caget(pvMccSeqSyncMarker
              )  # caget bug: need to get twice to have latest value
        print "\n## Beam rate = %g HZ, Sync marker = %g HZ" % (
            fBeamFullRate, dictSyncMarkerToRate[int(
                caget(pvMccSeqSyncMarker, bGetNumEnum=True))])

        if not self.bSimMode:
            if caget(pvBeamOwner) != caget(pvHutchId):
                if self.fBurstRate == 60:
                    print "!!! Test Burst rate %g is not supported by MCC" % (
                        self.fBurstRate)
                    return 1
                self.mccBurst.mccBurstSetRate(self.fBurstRate)
            elif self.fBurstRate == fBeamFullRate:
                self.mccBurst.mccBurstSetRate(0)
            elif self.fBurstRate < fBeamFullRate:
                if self.fBurstRate == 60:
                    print "!!! Burst rate %g is not supported by MCC" % (
                        self.fBurstRate)
                    return 1
                self.mccBurst.mccBurstSetRate(self.fBurstRate)
            else:
                print "!!! Burst rate %g is faster than Beam rate %g" % (
                    self.fBurstRate, fBeamFullRate)
                return 1

        print "## Multiple shot: %d" % (self.iNumShot)

        # Exposure Time =
        #     camear open (clean CCD) delay ( self.iSlowCamOpenDelay: 0 for PI, 5*120Hz for FLI)
        #     + manual sleep (fExpDelay)
        #     + exposure Time ((self.iNumShot / self.fBurstRate) second)
        #   = 0.0 + max(1, self.iSlowCamOpenDelay)/120.0 + (self.iNumShot / self.fBurstRate) + fExpDelay  second
        self.fExposureTime = 0.0 + self.iSlowCamOpenDelay / 120.0 + self.fExpDelay + self.iNumShot / float(
            self.fBurstRate)

        print "CREATE DAQ CONTROL OBJECT"
        self.daq = pydaq.Control(self.daq_host, self.daq_platform)
        try:
            print "daq connect...",
            sys.stdout.flush()
            self.daq.connect()  # get dbpath and key from DAQ
            print " done."
        except:
            print "!! daq.connect() failed"
            print "!! Possibly because 1. DAQ devices has NOT been allocated"
            print "!!               or 2. You are running DAQ control GUI in remote machines"
            print "!! Please check 1. DAQ is in good state and re-select the devices"
            print "!!              2. If the restart script actually runs DAQ in another machine"
            print "ERROR", sys.exc_info()[0]
            return 1

        if self.bSimMode:
            self.alias = "PRINCETON_SIM"
        else:
            self.alias = "SLOW_CAMERA"

        if self.daq.dbalias() != self.alias:
            print "!!! the current DAQ config type is %s" % (
                self.daq.dbalias())
            print "!!! please switch to %s to run this script" % (self.alias)

            print "daq disconnect...",
            sys.stdout.flush()
            self.daq.disconnect()
            print " done."
            return 2

        print "CONFIGURE DAQ"
        if controls is None:
            iFail = self.configure(controls=[])
        else:
            iFail = self.configure(controls=controls)
        if iFail != 0:
            print "daq disconnect...",
            sys.stdout.flush()
            self.daq.disconnect()
            print " done."
            return 3

        if self.bShutterMode:
            if ShutterInit(self.iNumShot) != 0:
                print "Shutter Init Failed"
                return 4

        print "SET CAMERA CONTROL SEQUENCE"
        self.setCameraControlSequence()

        self.iNumTotalImage = 0

        print "## Please make sure"
        if not self.bSimMode:
            print "##   - MCC has switched to Burst Mode,"
        print "##   - Andor/Princeton camera is selected (if you need it),"
        print "##   - chiller is running and the cooling temperature is set properly."

        if bDaqBegin:
            # cpo changed this line
            self.beginCycle(controls)
        return 0
Exemplo n.º 13
0
 def _reinit_pydaq(self):
     del self.daq
     self.daq = pydaq.Control(host=self.host, platform=self.platform)
Exemplo n.º 14
0
  low  = float(options.opts['from'])
  high = float(options.opts['to'])
  steps = int(options.opts['steps'])
  events = int(options.opts['events'])
  doOnce = False
  if options.opts.has_key('once'):
    doOnce = True

  print 'Stepping %s from %f to %f with %d events at each of %d steps'%(motorpvname,low,high,events,steps)
  if doOnce:
    print '(once: stopping after one scan)
  
  evtmask = pyca.DBE_VALUE | pyca.DBE_LOG | pyca.DBE_ALARM 

#  Initialize DAQ control
  daq = pydaq.Control('sxr-daq')


#  Let user setup plots                    
  ready = raw_input('--Hit Enter when Ready-->')
  
  
#  Configure DAQ                    
  doRecord = False
  if (options.opts['record'].upper()=='Y'):
    doRecord = True
    
  daq.configure(record=doRecord,
                events=int(options.opts['events']),
                controls=[(motorpvname,low)])
Exemplo n.º 15
0
def scan_calibration(devtypes, options):

    # if only a single device type was passed change to a list
    if isinstance(devtypes, str):
        devtypes = [devtypes]

    if logger.isEnabledFor(logging.INFO):
        logger.info('Detector pedestal/calibration script settings to use:')
        logger.info('  host: %s', options.host)
        logger.info('  platform: %s', options.platform)
        logger.info('  dbalias: %s', options.dbalias)
        logger.info('  devtypes: %s', devtypes)
        if options.space > 7:
            logger.warning('Space is too large, truncated to 7')
            options.space = 7
        logger.info('  space: %s', options.space)
        logger.info('  Values: %s, %s', options.Value0, options.Value1)
        logger.info('  darkEvents: %s', options.darkEvents)
        logger.info('  events: %s', options.events)
        logger.info('  userFlag: %s', options.userFlag)
        logger.info('  cycleStart: %s', options.cycleStart)
        logger.info('  cycleStop: %s', options.cycleStop)
        logger.info('  fullCalib: %s', options.fullCalib)
        logger.info('  record: %s', options.record)
        logger.info('  simMode: %s', options.sim)

    # configuration handlers for each detector
    configs = {}
    ncycles = 0
    # Connect to the daq system
    logger.debug('Connecting to the DAQ at %s with platform %d', options.host,
                 options.platform)
    daq = pydaq.Control(options.host, options.platform)
    daq.connect()
    info = PartitionInfo(daq)
    logger.debug('Current DAQ partition: %s', info.partition)
    devices = info.find_devices(devtypes)
    logger.info('Selected the following detectors to scan in the partition:')
    max_label_size = daq.sizes().get('LabelNameSize')
    logger.debug('Maximum allowed length of label names: %d', max_label_size)
    for devtype, devs in sorted(devices.items()):
        # only print devtype if there are devices of that type
        if devs:
            logger.info('  %s:', devtype)
        for name, src in devs:
            logger.info('    %s', name)
            if devtype in DEVICE_CONFIG_HANDLERS:
                handler = DEVICE_CONFIG_HANDLERS[devtype]
                logger.debug(
                    'Creating configuration handler of type %s for %s',
                    handler.__name__, name)
                configs[name] = handler(devtype,
                                        name,
                                        src,
                                        options.space,
                                        (options.Value0, options.Value1),
                                        namesize=max_label_size)
                # check which detector has the highest max_cycles/max_dark
                if options.fullCalib:
                    if configs[name].max_cycle > ncycles:
                        ncycles = configs[name].max_cycle
                else:
                    if configs[name].max_dark > ncycles:
                        ncycles = configs[name].max_dark
            else:
                logger.warning('Unsupported detector type: %s', devtype)

    # select the default number of events for each cycle
    nevents = [options.darkEvents] * ncycles
    # prepare the database
    key = daq.dbkey()
    alias = daq.dbalias()
    newkey = None
    logger.info('Retrieved key %x with alias %s from the DAQ', key, alias)
    # override the alias to use if one is passed to the script
    if options.dbalias is not None:
        logger.debug('Switching to user specified alias %s', options.dbalias)
        alias = options.dbalias

    with ConfigDB(daq.dbpath(), alias, sim=options.sim) as cdb:
        logger.info('Cloned the alias %s to new key %x', cdb.alias, cdb.key)
        logger.info('Composing the sequence of configurations ...')
        for cycle in range(ncycles):
            if cycle >= options.cycleStart and cycle < options.cycleStop:
                for name, config in configs.items():
                    logger.debug("Creating cycle %d for %s", cycle, name)
                    if config.configure(cdb, cycle):
                        nevents[cycle] = options.events
        # complete the database update
        for name, config in configs.items():
            logger.debug("Completing configuration for %s", name)
            config.complete(cdb)
        logger.info(' Done')
        # save the value of the keyy before closing db
        newkey = key if options.sim else cdb.key

    try:
        # Configure the DAQ and add pvlabels with scan metadata
        cycle_labels = [(configs[name].scan_name, '')
                        for devs in devices.values() for name, _ in devs]
        logger.debug(
            "Configuring with key=%x, events=%d, labels=%s, record=%s", newkey,
            options.events, cycle_labels, options.record)
        if options.record is None:
            daq.configure(key=newkey,
                          events=options.events,
                          labels=cycle_labels)
        else:
            daq.configure(key=newkey,
                          events=options.events,
                          labels=cycle_labels,
                          record=options.record)

        logger.info("Configured.")

        #
        #  Wait for the user to declare 'ready'
        #    Setting up monitoring displays for example
        #
        if options.userFlag > 0:
            ready = input('--Hit Enter when Ready-->')

        for cycle in range(ncycles):
            if cycle >= options.cycleStart and cycle < options.cycleStop:
                cycle_labels = []
                logger.info('Scan info for calib cycle %d:', cycle)
                logger.debug('  Number of events: %d', nevents[cycle])
                for devs in devices.values():
                    for name, _ in devs:
                        scan_name = str(configs[name].scan_name)
                        cycle_name = str(configs[name].cycle_name(cycle))
                        cycle_labels.append((scan_name, cycle_name))
                        logger.info('  %s: %s', scan_name, cycle_name)
                if not options.sim:
                    logger.debug(
                        'Starting calib cycle %d with events=%d, labels=%s',
                        cycle, nevents[cycle], cycle_labels)
                    daq.begin(events=nevents[cycle], labels=cycle_labels)
                    daq.wait()
                    logger.debug('Finished calib cycle %d', cycle)

        #
        #  Wait for the user to declare 'done'
        #    Saving monitoring displays for example
        #
        if options.userFlag > 0:
            ready = input('-- Finished, hit Enter to exit -->')
    finally:
        logger.info('Restoring key: %x', key)
        daq.configure(key=key, events=1)
        logger.debug('Disconnecting from the DAQ')
        daq.disconnect()