Пример #1
0
def test_devicevaluedict():
    dvd = DeviceValueDict()

    val = '0 mm'
    dvd['a.b.c'] = val

    assert dvd['a.b.c'].raw == val
    assert dvd['a.b.c'].formatted == val

    val2 = DeviceValue(12, '12 cm', 'cm', 'meta')
    dvd['x.y'] = val2

    assert dvd['x.y'].raw == 12
    assert dvd['x.y'].formatted == '12 cm'
    assert dvd['x.y'].unit == 'cm'
Пример #2
0
    def expandNameTemplates(self, nametemplates, additionalinfo=None):
        """Expand the given *nametemplates* with the current counter values
        and the proposal information for the current experiment.

        A dictionary of supplementary template values can be provided using
        the `additionalinfo` keyword argument.
        """
        if isinstance(nametemplates, string_types):
            nametemplates = [nametemplates]
        exc = None  # stores first exception if any
        # translate entries
        filenames = []
        for nametmpl in nametemplates:
            kwds = dict(additionalinfo) if additionalinfo else dict()
            kwds.update(session.experiment.propinfo)
            kwds.update(self.getCounters())
            try:
                filename = nametmpl % DeviceValueDict(kwds)
            except KeyError as err:
                if not exc:
                    exc = KeyError('can\'t create datafile, illegal key %s in '
                                   'filename template %r!' % (err, nametmpl))
                continue
            except TypeError as err:
                if not exc:
                    exc = TypeError('error expanding data file name: %s, check '
                                    'filename template %r!' % (err, nametmpl))
                continue
            except ValueError as err:
                if not exc:
                    exc = ValueError('error expanding data file name: %s, check '
                                     'filename template %r!' % (err, nametmpl))
                continue
            filenames.append(filename)
        if exc and not filenames:
            # pylint: disable=raising-bad-type
            raise exc
        return filenames
Пример #3
0
    def writeHeader(self, fp, metainfo, image):
        shape = image.shape

        try:
            SD = '%.4f' % ((session.getDevice('det1_z').read() -
                            session.getDevice('st1_x').read()) / 1000)
        except Exception:
            self.log.warning(
                "can't determine SD (detector distance), "
                "using 0 instead",
                exc=1)
            SD = 0

        finished = currenttime()
        # totalTime = finished - self.dataset.started
        Sum = image.sum()
        Moni1 = 0
        Moni2 = 0
        Time = 0
        try:
            Moni1 = float(session.getDevice('det1_mon1').read()[0])
            Moni2 = float(session.getDevice('det1_mon2').read()[0])
            Time = float(session.getDevice('det1_timer').read()[0])
        except Exception:
            self.log.warning(
                "can't determine all monitors, "
                "using 0.0 instead", exc=1)

        try:
            # Setupfile = session.getDevice('det1_image').histogramfile
            Histfile = metainfo['det1_image', 'histogramfile'][1]
        except Exception:
            Histfile = ''

        try:
            # Listfile = session.getDevice('det1_image').listmodefile.split('\'')[1]
            Listfile = metainfo['det1_image', 'listmodefile'][1].split('\'')[1]
        except Exception:
            Listfile = ''

        try:
            # Setupfile = session.getDevice('det1_image').configfile
            Setupfile = metainfo['det1_image', 'configfile'][1]
        except Exception:
            Setupfile = 'setup'

        try:
            # LookUpTable = session.getDevice('det1_image').calibrationfile
            LookUpTable = metainfo['det1_image', 'calibrationfile'][1]
        except Exception:
            LookUpTable = 'lookup'

        time_format = '%I:%M:%S %p'
        date_format = '%m/%d/%Y'

        metadata = DeviceValueDict(
            fileName=os.path.basename(self._file.filepath),
            fileDate=strftime(date_format, localtime(self.dataset.started)),
            fileTime=strftime(time_format, localtime(self.dataset.started)),
            FromDate=strftime(date_format, localtime(self.dataset.started)),
            FromTime=strftime(time_format, localtime(self.dataset.started)),
            ToDate=strftime(date_format, localtime(finished)),
            ToTime=strftime(time_format, localtime(finished)),
            DataSize=shape[0] * shape[1],
            DataSizeX=shape[1],
            DataSizeY=shape[0],
            Environment='_'.join(session.explicit_setups),
            SD=SD,
            Sum='%d' % Sum,
            Moni1='%d' % Moni1,
            Moni2='%d' % Moni2,
            Sum_Time='%.6f' % (Sum / Time) if Time else 'Inf',
            Sum_Moni1='%.6f' % (Sum / Moni1) if Moni1 else 'Inf',
            Sum_Moni2='%.6f' % (Sum / Moni2) if Moni2 else 'Inf',
            Histfile=Histfile,
            Listfile=Listfile,
            Setupfile=Setupfile,
            LookUpTable=LookUpTable,
            Command=self.dataset.info,
        )

        nicosheader = []

        # no way to map nicos-categories to BerSANS sections :(
        # also ignore some keys :(
        ignore = ('det1_lastlistfile', 'det1_lasthistfile')
        for (dev, param), (value, strvalue, _unit, _category) in \
                iteritems(self.dataset.metainfo):
            devname_key = '%s_%s' % (dev, param)
            if devname_key in ignore:
                continue
            metadata[devname_key] = value
            nicosheader.append('%s=%s' % (devname_key, strvalue))

        nicosheader = b'\n'.join(sorted(map(to_ascii_escaped, nicosheader)))
        self.log.debug('nicosheader starts with: %40s', nicosheader)

        # write Header
        header = BERSANSHEADER
        if 'tisane' in session.explicit_setups:
            header += TISANEHEADER
        for line in header.split('\n'):
            self.log.debug('testing header line: %r', line)
            self.log.debug(line % metadata)
            fp.write(to_utf8(line % metadata))
            fp.write(b'\n')

        # also append nicos header
        fp.write(nicosheader.replace(b'\\n', b'\n'))  # why needed?
        fp.write(b'\n\n%Counts\n')
        fp.flush()
Пример #4
0
    def writeData(self, fp, image):
        _collslit = 'aperture_%02d' % session.getDevice('coll_guides').read()
        _exposuretime = session.getDevice('timer').read(0)[0]

        textfp = TextIOWrapper(fp, encoding='utf-8')
        w = textfp.write

        # sample envs
        sample_env = ['Temperature dummy line'] * 4
        for (i, (info, val)) in enumerate(zip(self.dataset.envvalueinfo,
                                              self.dataset.envvaluelist)):
            if i >= 4:  # only four lines allowed
                break
            try:
                val = info.fmtstr % val
            except Exception:
                val = str(val)
            sample_env[i] = '%s is Active %s %s' % (info.name, val, info.unit)

        if 'hexapod' in session.loaded_setups:
            hexapod_0 = '(* Hexapod position (tx, ty, tz, rx, ry, rz, dt) *)'
            hexapod_1 = ''
            for axis in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'dt'):
                try:
                    hexapod_1 += ' %9.3f' % session.getDevice('hexapod_' + axis).read()
                except Exception:
                    hexapod_1 += ' unknown'
        else:
            hexapod_0 = '(* Measurement stop state *)'
            hexapod_1 = 'measurement STOPPED by USER command'

        detpos = self.getDetectorPos()

        # write header
        data = DeviceValueDict()
        data.update(
            instr = self.sink.instrname,
            startdate = strftime('%d-%b-%Y %H:%M:%S.00',
                                 localtime(self.dataset.started)),
            counter = self.dataset.counter,
            filename = path.basename(fp.filepath),
            coll_x = '%d' % round(session.getDevice(_collslit).width.read()),
            coll_y = '%d' % round(session.getDevice(_collslit).height.read()),
            exptime = '%d min' % (_exposuretime / 60.),
            realtime = '%d sec' % _exposuretime,
            detoffset_m = session.experiment.sample.detoffset / 1000.,
            sample_env_0 = sample_env[0],
            sample_env_1 = sample_env[1],
            sample_env_2 = sample_env[2],
            sample_env_3 = sample_env[3],
            hexapod_0 = hexapod_0,
            hexapod_1 = hexapod_1,
            det_x_entry = detpos[0],
            det_y_entry = detpos[1],
            det_z_entry = detpos[2],
            mon3_entry = self.getMon3(),
        )
        w(KWSHEADER % data)

        # write "data sum"
        w('(* Detector Data Sum (Sum_Data_Field = 32 values = 6 * 5 and 2) *)\n')
        w('@\n')
        sums = [image.sum()] + [0.0] * 31
        for (i, val) in enumerate(sums):
            w('%E' % val)
            if (i + 1) % 6:
                w(' ')
            else:
                w('\n')
        w('\n\n')

        # write detector data
        if len(image.shape) == 2:
            self._writedet_standard(w, image)
        else:
            self._writedet_tof(w, image, textfp)
        textfp.detach()