def count(n, *detlist, **presets): """Perform **n** counts while the TIFF image filename of the DECTRIS Pilatus detector will be set to a temporary value that remains unchanged during execution of this command. With preset arguments, this preset is used instead of the default preset. With detector devices as arguments, these detectors are used instead of the default detectors set with `SetDetectors()`. Examples: >>> # count 100 times without changing presets >>> count(100) >>> >>> # count 10 times and set the temporary filename to 'tmp.tif' >>> count(10, filename='tmp.tif') >>> >>> # count once with time preset of 10 seconds >>> count(1, t=10) Within a manual scan, this command is also used to perform the count as one point of the manual scan. """ filename = presets.pop('filename', 'tmpcount.tif') galaxi_sinks = { sink: sink.settypes for sink in session.datasinks if isinstance(sink, (MythenSink, PilatusSink)) } try: for sink in galaxi_sinks: # deactivate during count sink._setROParam('settypes', [SCAN]) for _ in range(n): for det in session.experiment.detectors: if isinstance(det, PilatusDetector): det.imagedir = path.join(str(datetime.now().year), session.experiment.proposal) det.nextfilename = filename measure.count(*detlist, **presets) session.breakpoint(2) # allow daemon to stop here finally: for sink, settypes in galaxi_sinks.items(): sink._setROParam('settypes', settypes)
def AddHeCellToPolariserHkl(h_index, k_index, l_index, count_time, polariser_cell_name, polariser_cell_pressure): """Add new 3He cell to polariser (only).""" gamma = session.getDevice('gamma') wavelength = session.getDevice('wavelength') det = session.getDevice('det') printinfo(LARGE_SEP) printinfo('Add new 3He cell to polariser (only)') printinfo(SMALL_SEP) printinfo('Go to hkl ({} {} {})'.format(h_index, k_index, l_index)) printinfo(SMALL_SEP) pos(h_index, k_index, l_index) gamma_hkl = gamma() gamma_cell = 60.0 printinfo(SMALL_SEP) printinfo('Measurement without cell. {}'.format(format_datetime())) printinfo(SMALL_SEP) cells0 = count(det, count_time) wavelen = wavelength() AddPolariserHeaderToCellsFile(polariser_cell_name, polariser_cell_pressure, wavelen) AddCountsToCellsFile(False, False, cells0) maw(gamma, gamma_cell) pause( 'Insert cell {} into polariser and press "Continue script" after that.' .format(polariser_cell_name)) maw(gamma, gamma_hkl) printinfo(SMALL_SEP) printinfo('Measurement with 1 cell: {} [{} bar] in polariser. {}'.format( polariser_cell_name, polariser_cell_pressure, format_datetime())) printinfo(SMALL_SEP) cells1 = count(det, count_time) AddCountsToCellsFile(False, True, cells1) polariser_cell_transmission = polariser_trans(cells0, cells1) AddPolariserTransToCellsFile(polariser_cell_transmission) pause('Cell is inserted.\n\nPolariser cell {}:\n' ' Pressure = {} bar, Transmission = {:8.2f} %'.format( polariser_cell_name, polariser_cell_pressure, polariser_cell_transmission)) printinfo(SMALL_SEP) printinfo('Cell is inserted.') printinfo('Polariser cell {}: pressure = {} bar, transmission = {:9.4f} %'. format(polariser_cell_name, polariser_cell_pressure, polariser_cell_transmission)) printinfo(LARGE_SEP)
def test_Attributes(self, session): template = { 'entry:NXentry': {'title': DeviceAttribute('Exp', 'title'), 'units': NXAttribute('mm', 'string'), } } session.experiment.update(title='GurkenTitle') setTemplate(template) self.setScanCounter(session, 47) session.experiment.setDetectors(['det', ]) count(t=.1) fin = h5py.File(path.join(session.experiment.datapath, 'test%sn000048.hdf' % year), 'r') g = fin['entry'] assert (g.attrs['title'] == b'GurkenTitle') assert (g.attrs['units'] == b'mm') fin.close()
def test_hierarchy(self, session): template = { 'instrument': 'test', 'entry:NXentry': {}, } setTemplate(template) session.experiment.setDetectors(['det', ]) self.setScanCounter(session, 44) count(t=0.1) fin = h5py.File(path.join(session.experiment.datapath, 'test%sn000045.hdf' % year), 'r') att = fin.attrs['instrument'] assert (att == b'test') g = fin['entry'] att = g.attrs['NX_class'] assert (att == b'NXentry') fin.close()
def test_Detector(self, session): template = { 'data:NXdata': { 'time': DetectorDataset('timer', 'float32'), 'mon': DetectorDataset('mon1', 'uint32'), 'counts': ImageDataset(0, 0, signal=NXAttribute(1, 'int32')), }, } setTemplate(template) self.setScanCounter(session, 49) session.experiment.setDetectors(['det', ]) count(t=.1) fin = h5py.File(path.join(session.experiment.datapath, 'test%sn000050.hdf' % year), 'r') ds = fin['data/time'] ds = fin['data/mon'] ds = fin['data/counts'] assert (ds.attrs['signal'] == 1) fin.close()
def test_manualscan(session): mot = session.getDevice('motor') c = session.getDevice('coder') det = session.getDevice('det') mm = session.getDevice('manual') mm.maw(0) slow_motor = session.getDevice('slow_motor') slow_motor.maw(0) # normal with manualscan(mot, det, t=0.): assert mot in session._manualscan._envlist for i in range(3): mot.maw(i) count_result = count() assert raises(NicosError, manualscan) assert isinstance(count_result, CountResult) and len(count_result) == 5 # with multistep SetEnvironment('slow_motor') try: with manualscan(mot, c, det, 'manscan', manual=[0, 1], t=0.): assert c in session._manualscan._envlist for i in range(3): mot.maw(i) count_result = count() finally: SetEnvironment() dataman = session.experiment.data dataset = dataman.getLastScans()[-1] assert dataset.info.startswith('manscan') # note: here, the env devices given in the command come first assert dataset.envvaluelists == [[0., 0., 0.], [0., 0., 0.], [1., 1., 0.], [1., 1., 0.], [2., 2., 0.], [2., 2., 0.]] assert isinstance(count_result, list) assert isinstance(count_result[0], CountResult)
def prepare(session, dataroot): """Prepare a dataset for TOFTOF""" session.experiment.setDetectors(['det']) session.experiment.setEnvironment(['B', 'P', 'T']) # Create devices needed in data sinks for dev in [ 'slit', 'vac0', 'vac1', 'vac2', 'vac3', 'gx', 'gy', 'gz', 'gphi', 'gcx', 'gcy' ]: session.getDevice(dev) rc = session.getDevice('rc') rc.maw('on') assert rc.read(0) == 'on' assert session.getDevice('chRatio').read(0) == 1 assert session.getDevice('chCRC').read(0) == 1 assert session.getDevice('chST').read(0) == 1 for disc in ['d1', 'd2', 'd3', 'd4', 'd6', 'd7']: assert session.getDevice(disc).read(0) == 6000 assert session.getDevice('d5').read(0) == -6000 chSpeed = session.getDevice('chSpeed') chSpeed.maw(6000) chWL = session.getDevice('chWL') assert chWL.read(0) == 4.5 ngc = session.getDevice('ngc') ngc.maw('focus') count(t=0.15) # test to write the intermediate: file t > det.saveinterval count(mon1=150) yield
def _tomo(title, angles, moveables, imgsperangle, *detlist, **preset): if moveables is None: # TODO: currently, sry is the common name on nectar and antares for the # sample rotation (phi - around y axis). Is this convenience function # ok, or should it be omitted and added to the instrument custom? moveables = (session.getDevice('sry'), ) elif isinstance(moveables, Moveable): moveables = (moveables, ) moveables = tuple(moveables) session.log.debug('used angles: %r', angles) with manualscan(*(moveables + detlist), _title=title) as scan: for angle in angles: # Move the given movable to the target angle try: scan.moveDevices(moveables, [angle] * len(moveables)) # Capture the desired amount of images for _ in range(imgsperangle): for i in range(2, -1, -1): try: count(**preset) except NicosError: if not i: raise session.log.warning( 'Count failed, try it again.' '%d remaining tries', i) if detlist: reset(*detlist) else: reset(*session.experiment.detectors) else: break except SkipPoint: pass
def test_detector(adet): assert adet.liveinterval == 5 adet.reset() assert adet.read() == [1, 0, 0, 0] adet.liveinterval = 0.5 assert adet.liveinterval == 0.5 assert adet.resosteps == 40 assert adet._step_size == adet.range/adet.resosteps adet.resosteps = 2 assert adet.resosteps == 2 assert adet.range == 2 assert adet._step_size == 1 count(t=0.01) assert adet._startpos == 1 assert adet._attached_motor.speed == 0 assert adet._attached_motor.read(0) == 0 adet.setPreset(t=0.5) adet.prepare() # The implementation of 'pause' and 'resume' command on MeasureSequencer # are missing at the moment # adet.start() # adet.pause() # adet.resume() count(resosteps=1, t=0.01) # Result should contain 4 elements assert len(adet.read()) == 4 # Detector should be on the first reso step assert adet.read()[0] == 1
def RemoveHeCellFromPolariserHkl(h_index, k_index, l_index, count_time): """Remove old 3He cell from polariser (only).""" gamma = session.getDevice('gamma') det = session.getDevice('det') printinfo(LARGE_SEP) printinfo('Remove old 3He cell from polariser (only)') printinfo(SMALL_SEP) printinfo('Go to hkl ({} {} {})'.format(h_index, k_index, l_index)) printinfo(SMALL_SEP) pos(h_index, k_index, l_index) gamma_hkl = gamma() gamma_cell = 60.0 printinfo(SMALL_SEP) printinfo('Measurement with 1 cell: in polariser. {}'.format( format_datetime())) printinfo(SMALL_SEP) cells1 = count(det, count_time) AddCountsToCellsFile(False, True, cells1) maw(gamma, gamma_cell) pause('Remove cell from polariser and press "Continue script" after that.') maw(gamma, gamma_hkl) printinfo(SMALL_SEP) printinfo('Measurement without cells. {}'.format(format_datetime())) printinfo(SMALL_SEP) cells0 = count(det, count_time) AddCountsToCellsFile(False, False, cells0) polariser_cell_transmission = polariser_trans(cells0, cells1) AddPolariserTransToCellsFile(polariser_cell_transmission) AddFooterToCellsFile() pause('Cell is removed.\n\nPolariser cell:\n Transmission = {:8.2f} %'. format(polariser_cell_transmission)) printinfo(SMALL_SEP) printinfo('Cell is removed.') printinfo('Polariser cell: transmission = {:9.4f} %'.format( polariser_cell_transmission)) printinfo(LARGE_SEP)
def test_Link(self, session): template = { 'entry:NXentry': {'sry': DeviceDataset('sry'), }, 'data:NXdata': {'srlink': NXLink('/entry/sry'), } } maw(session.getDevice('sry'), 77.7) session.experiment.setDetectors(['det', ]) setTemplate(template) self.setScanCounter(session, 50) count(t=.1) fin = h5py.File(path.join(session.experiment.datapath, 'test%sn000051.hdf' % year), 'r') ds = fin['entry/sry'] assert (ds[0] == 77.7) ds = fin['data/srlink'] assert (ds[0] == 77.7) assert (ds.attrs['target'] == b'/entry/sry') fin.close()
def test_count(self, session, log): """Check count() command.""" motor = session.getDevice('motor') assert raises(UsageError, count, motor) count()
def AddHeCells(h_index, k_index, l_index, count_time, analyser_cell_name, analyser_cell_pressure, polariser_cell_name, polariser_cell_pressure): """Add new 3He cells to analyser and polariser.""" gamma = session.getDevice('gamma') wavelength = session.getDevice('wavelength') det = session.getDevice('det') printinfo(LARGE_SEP) printinfo('Add new 3He cells') printinfo(SMALL_SEP) printinfo('Go to hkl ({} {} {})'.format(h_index, k_index, l_index)) printinfo(SMALL_SEP) pos(h_index, k_index, l_index) gamma_hkl = gamma() gamma_cell = 60.0 printinfo(SMALL_SEP) printinfo('Measurement without cells. {}'.format(format_datetime())) printinfo(SMALL_SEP) cells0 = count(det, count_time) wavelen = wavelength() AddHeaderToCellsFile(analyser_cell_name, analyser_cell_pressure, polariser_cell_name, polariser_cell_pressure, wavelen) AddCountsToCellsFile(False, False, cells0) maw(gamma, gamma_cell) pause('Insert cell {} into analyser/decpol.'.format(analyser_cell_name)) maw(gamma, gamma_hkl) printinfo(SMALL_SEP) printinfo( 'Measurement with 1 cell: {} [{} bar] in analyser/decpol. {}'.format( analyser_cell_name, analyser_cell_pressure, format_datetime())) printinfo(SMALL_SEP) cells1 = count(det, count_time) AddCountsToCellsFile(True, False, cells1) analyser_cell_transmission = analyser_trans(cells0, cells1) maw(gamma, gamma_cell) pause('Analyser/decpol cell {}:\n Pressure = {} bar, ' 'Transmission = {:8.2f} %.\n\nNow, insert cell {} into polariser.'. format(analyser_cell_name, analyser_cell_pressure, analyser_cell_transmission, polariser_cell_name)) maw(gamma, gamma_hkl) printinfo(SMALL_SEP) printinfo('Measurement with 2 cells: {} [{} bar] in analyser/decpol and ' '{} [{} bar] in polariser. {}'.format(analyser_cell_name, analyser_cell_pressure, polariser_cell_name, polariser_cell_pressure, format_datetime())) printinfo(SMALL_SEP) cells2 = count(det, count_time) AddCountsToCellsFile(True, True, cells2) polariser_cell_transmission = polariser_trans(cells1, cells2) AddTransToCellsFile(analyser_cell_transmission, polariser_cell_transmission) pause('Cells are inserted.\n\nAnalyser/decpol cell {}:\n' ' Pressure = {} bar, Transmission = {:8.2f} %,\n\n' 'Polariser cell {}:\n Pressure = {} bar, Transmission = {:8.2f} %'. format(analyser_cell_name, analyser_cell_pressure, analyser_cell_transmission, polariser_cell_name, polariser_cell_pressure, polariser_cell_transmission)) printinfo(SMALL_SEP) printinfo('Cells are inserted.') printinfo( 'Analyser/decpol cell {}: pressure = {} bar, transmission = {:9.4f} %'. format(analyser_cell_name, analyser_cell_pressure, analyser_cell_transmission)) printinfo('Polariser cell {}: pressure = {} bar, transmission = {:9.4f} %'. format(polariser_cell_name, polariser_cell_pressure, polariser_cell_transmission)) printinfo(LARGE_SEP)
def kwscount(**arguments): """Move sample and devices into place followed by a count. This takes KWS-specific circumstances such as sample time factor into account. Example: >>> kwscount(sample=1, selector='12A', resolution='2m', sample_pos='1.3m', time=3600) Keywords for standard instrument components are: * sample (sample number or name if unique, defaults to no sample change) * selector (must be present) * resolution (must be present) * sample_pos (must be present) * detector (must be present) * beamstop (defaults to out) * polarizer (defaults to out) * chopper (defaults to off) Any other keywords are interpreted as devices names and the target values. """ def sort_key(kv): try: # main components move first, in selected order return (0, DEFAULT.index(kv[0])) except ValueError: # all other devices move last, sorted by devname return (1, kv[0]) # check that all required components are present, and put defaults for # optional components if 'selector' not in arguments: raise UsageError('kwscount must have a value for the selector') if 'detector' not in arguments: raise UsageError('kwscount must have a value for the detector') if 'sample_pos' not in arguments: raise UsageError('kwscount must have a value for the sample_pos') if 'detector' not in arguments: raise UsageError('kwscount must have a value for the detector') if 'beamstop' not in arguments: arguments['beamstop'] = 'out' if 'polarizer' not in arguments: arguments['polarizer'] = 'out' if 'chopper' not in arguments: arguments['chopper'] = 'off' # leave space between kwscounts session.log.info('') # measurement time meastime = arguments.pop('time', 0) # select sample sample = arguments.pop('sample', None) # move devices waiters = [] # the order is important! devs = listitems(arguments) devs.sort(key=sort_key) # add moved devices to sampleenv _fixupSampleenv(devs) # start devices for devname, value in devs: if devname == 'chopper': # currently a no-op continue dev = session.getDevice(devname, Moveable) dev.start(value) if devname == 'selector': dev2 = session.getDevice('sel_speed') session.log.info('%-12s --> %s (%s)', devname, dev.format(value), dev2.format(dev2.target, unit=True)) else: session.log.info('%-12s --> %s', devname, dev.format(value, unit=True)) waiters.append(dev) # select and wait for sample here if sample is not None: session.experiment.sample.select(sample) # now wait for everyone else multiWait(waiters) # count session.log.info('Now counting for %d seconds...', meastime) count(t=meastime)