def setUp(self):
     ws1 = CreateSampleWorkspace()
     self.ws1 = ws1
     ws2 = CreateSampleWorkspace()
     self.ws2 = ws2
     lognames = 'run_title,deterota,wavelength,polarisation,flipper'
     logvalues = 'ws1,-10.0,4.2,x,ON'
     AddSampleLogMultiple(Workspace=ws1, LogNames=lognames, LogValues=logvalues, ParseType=True)
     logvalues = 'ws2,-12.0,4.2,x,OFF'
     AddSampleLogMultiple(Workspace=ws2, LogNames=lognames, LogValues=logvalues, ParseType=True)
Exemplo n.º 2
0
    def setUp(self):
        input_ws = Load(Filename="TOFTOFTestdata.nxs")
        self._input_ws_base = input_ws
        self._input_good = input_ws
        AddSampleLogMultiple(Workspace=self._input_good, LogNames=['run_number'], LogValues=[001])

        self._input_bad_entry = input_ws+0
        # remove a compulsory entry in Logs
        DeleteLog(self._input_bad_entry, 'duration')

        self._input_bad_value = input_ws+0
        AddSampleLogMultiple(Workspace=self._input_bad_value, LogNames=['wavelength'], LogValues=[0.])
    def prepare_background(input_md, reference_sample_mde, background_md: str):
        """Prepare background MDEventWorkspace from reduced sample Matrix
        This is the previous solution to merge all the ExperimentInfo
        """
        dgs_data = CloneWorkspace(input_md)
        data_MDE = mtd[reference_sample_mde]
        if mtd.doesExist('background_MDE'):
            DeleteWorkspace('background_MDE')

        for i in range(data_MDE.getNumExperimentInfo()):
            phi, chi, omega = data_MDE.getExperimentInfo(
                i).run().getGoniometer().getEulerAngles('YZY')
            AddSampleLogMultiple(Workspace=dgs_data,
                                 LogNames='phi, chi, omega',
                                 LogValues='{},{},{}'.format(phi, chi, omega))
            SetGoniometer(Workspace=dgs_data, Goniometers='Universal')
            ConvertToMD(InputWorkspace=dgs_data,
                        QDimensions='Q3D',
                        dEAnalysisMode='Direct',
                        Q3DFrames="Q_sample",
                        MinValues='-11,-11,-11,-25',
                        MaxValues='11,11,11,49',
                        PreprocDetectorsWS='-',
                        OverwriteExisting=False,
                        OutputWorkspace=background_md)
Exemplo n.º 4
0
    def setUp(self):
        # create sample workspace
        self.xmin = 2123.33867005 + 4005.75
        self.xmax = 2123.33867005 + 7995.75

        self._input_ws = CreateSampleWorkspace(
            Function="User Defined",
            UserDefinedFunction="name=LinearBackground, \
                                               A0=0.3;name=Gaussian, PeakCentre=8190, Height=5, Sigma=75",
            NumBanks=2,
            BankPixelWidth=1,
            XMin=self.xmin,
            XMax=self.xmax,
            BinWidth=10.5,
            BankDistanceFromSample=4.0,
            SourceDistanceFromSample=1.4,
            OutputWorkspace="ws")
        lognames = "wavelength,TOF1"
        logvalues = "6.0,2123.33867005"
        AddSampleLogMultiple(self._input_ws, lognames, logvalues)
        # create EPP table
        self._table = CreateEmptyTableWorkspace(OutputWorkspace="epptable")
        self._table.addColumn(type="double", name="PeakCentre")
        table_row = {'PeakCentre': 8189.5}
        for i in range(2):
            self._table.addRow(table_row)
Exemplo n.º 5
0
    def PyExec(self):
        input_file = self.getProperty("InputFile").value
        output_ws = self.getPropertyValue("OutputWorkspace")
        logs = ''

        with h5py.File(input_file, 'r') as hf:
            data = numpy.array(hf.get('entry1/data1/DATA'), dtype='float')
            if data.ndim > 2:
                raise RuntimeError(
                    'Data with more than 2 dimensions are not supported.')
            errors = numpy.array(hf.get('entry1/data1/errors'), dtype='float')
            x = numpy.array(hf.get('entry1/data1/X'), dtype='float')
            if "entry1/data1/PARAMETERS" in hf:
                logs = str(
                    hf.get('entry1/data1/PARAMETERS')[0].decode('UTF-8'))
            y = numpy.array([0])
            nspec = 1
            if data.ndim == 2:
                y = numpy.array(hf.get('entry1/data1/Y'), dtype='float')
                nspec = data.shape[0]
                if x.ndim == 1:
                    x = numpy.tile(x, nspec)

        CreateWorkspace(DataX=x,
                        DataY=data,
                        DataE=errors,
                        NSpec=nspec,
                        VerticalAxisUnit='Label',
                        VerticalAxisValues=y,
                        OutputWorkspace=output_ws)

        if logs:
            log_names = []
            log_values = []
            for log in logs.split('\n'):
                split = log.strip().split('=')
                if len(split) == 2:
                    name = split[0]
                    value = split[1]
                    if name and value:
                        log_names.append(name)
                        log_values.append(value)
            if log_names:
                try:
                    AddSampleLogMultiple(Workspace=output_ws,
                                         LogNames=log_names,
                                         LogValues=log_values)
                except RuntimeError as e:
                    self.log().warning(
                        'Unable to set the sample logs, reason: ' + str(e))

        self.setProperty('OutputWorkspace', output_ws)
Exemplo n.º 6
0
 def setUp(self):
     # create sample workspace
     ws_tof = CreateSampleWorkspace(
         Function="User Defined",
         UserDefinedFunction="name=LinearBackground, \
                                    A0=0.3;name=Gaussian, PeakCentre=6000, Height=5, Sigma=75",
         NumBanks=2,
         BankPixelWidth=1,
         XMin=4005.75,
         XMax=7995.75,
         BinWidth=10.5,
         BankDistanceFromSample=4.0)
     # add required sample logs
     lognames = "channel_width,chopper_ratio,chopper_speed,Ei,wavelength,EPP"
     logvalues = "10.5,5,14000,2.27,6,190.0"
     AddSampleLogMultiple(ws_tof, lognames, logvalues)
     self._input_ws = ws_tof
Exemplo n.º 7
0
 def setUp(self):
     # create sample workspace
     ws_tof = CreateSampleWorkspace(
         Function="User Defined",
         UserDefinedFunction="name=LinearBackground, \
                                    A0=0.3;name=Gaussian, PeakCentre=8000, Height=5, Sigma=75",
         NumBanks=2,
         BankPixelWidth=1,
         XMin=6005.75,
         XMax=9995.75,
         BinWidth=10.5,
         BankDistanceFromSample=4.0,
         SourceDistanceFromSample=8.0)
     # add required sample logs
     lognames = "channel_width,EPP,TOF1"
     logvalues = "10.5,190.0,2000.0"
     AddSampleLogMultiple(ws_tof, lognames, logvalues)
     self._input_ws = ws_tof
Exemplo n.º 8
0
    def PyExec(self):
        fn = self.getPropertyValue("Filename")
        wsn = self.getPropertyValue("OutputWorkspace")
        #print (fn, wsn)

        self.fxml = self.getPropertyValue("InstrumentXML")

        #load data

        parms_dict, det_udet, det_count, det_tbc, data = self.read_file(fn)
        nrows = int(parms_dict['NDET'])
        #nbins=int(parms_dict['NTC'])
        xdata = np.array(det_tbc)
        xdata_mon = np.linspace(xdata[0], xdata[-1], len(xdata))
        ydata = data.astype(np.float)
        ydata = ydata.reshape(nrows, -1)
        edata = np.sqrt(ydata)
        #CreateWorkspace(OutputWorkspace=wsn,DataX=xdata,DataY=ydata,DataE=edata,
        #                NSpec=nrows,UnitX='TOF',WorkspaceTitle='Data',YUnitLabel='Counts')
        nr, nc = ydata.shape
        ws = WorkspaceFactory.create("Workspace2D",
                                     NVectors=nr,
                                     XLength=nc + 1,
                                     YLength=nc)
        for i in range(nrows):
            ws.setX(i, xdata)
            ws.setY(i, ydata[i])
            ws.setE(i, edata[i])
        ws.getAxis(0).setUnit('tof')
        AnalysisDataService.addOrReplace(wsn, ws)

        #self.setProperty("OutputWorkspace", wsn)
        #print ("ws:", wsn)
        #ws=mtd[wsn]

        # fix the x values for the monitor
        for i in range(nrows - 2, nrows):
            ws.setX(i, xdata_mon)
        self.log().information("set detector IDs")
        #set detetector IDs
        for i in range(nrows):
            ws.getSpectrum(i).setDetectorID(det_udet[i])
        #Sample_logs the header values are written into the sample logs
        log_names = [sl.encode('ascii', 'ignore') for sl in parms_dict.keys()]
        log_values = [
            sl.encode('ascii', 'ignore')
            if isinstance(sl, types.UnicodeType) else str(sl)
            for sl in parms_dict.values()
        ]
        AddSampleLogMultiple(Workspace=wsn,
                             LogNames=log_names,
                             LogValues=log_values)
        SetGoniometer(Workspace=wsn, Goniometers='Universal')
        if (self.fxml == ""):
            LoadInstrument(Workspace=wsn,
                           InstrumentName="Exed",
                           RewriteSpectraMap=True)
        else:
            LoadInstrument(Workspace=wsn,
                           Filename=self.fxml,
                           RewriteSpectraMap=True)
        RotateInstrumentComponent(
            Workspace=wsn,
            ComponentName='Tank',
            Y=1,
            Angle=-float(parms_dict['phi'].encode('ascii', 'ignore')),
            RelativeRotation=False)
        # Separate monitors into seperate workspace
        ExtractSpectra(InputWorkspace=wsn,
                       WorkspaceIndexList=','.join(
                           [str(s) for s in range(nrows - 2, nrows)]),
                       OutputWorkspace=wsn + '_Monitors')
        MaskDetectors(Workspace=wsn,
                      WorkspaceIndexList=','.join(
                          [str(s) for s in range(nrows - 2, nrows)]))
        RemoveMaskedSpectra(InputWorkspace=wsn, OutputWorkspace=wsn)

        self.setProperty("OutputWorkspace", wsn)
Exemplo n.º 9
0
    def PyExec(self):
        fn = self.getPropertyValue("Filename")
        wsn = self.getPropertyValue("OutputWorkspace")
        monitor_workspace_name = self.getPropertyValue(
            "OutputMonitorWorkspace")
        if monitor_workspace_name == "":
            self.setPropertyValue("OutputMonitorWorkspace", wsn + '_Monitors')
        # print (fn, wsn)
        self.override_angle = self.getPropertyValue("AngleOverride")
        self.fxml = self.getPropertyValue("InstrumentXML")

        # load data

        parms_dict, det_udet, det_count, det_tbc, data = self.read_file(fn)
        nrows = int(parms_dict['NDET'])
        # nbins=int(parms_dict['NTC'])
        xdata = np.array(det_tbc)
        xdata_mon = np.linspace(xdata[0], xdata[-1], len(xdata))
        ydata = data.astype(float)
        ydata = ydata.reshape(nrows, -1)
        edata = np.sqrt(ydata)
        # CreateWorkspace(OutputWorkspace=wsn,DataX=xdata,DataY=ydata,DataE=edata,
        #                NSpec=nrows,UnitX='TOF',WorkspaceTitle='Data',YUnitLabel='Counts')
        nr, nc = ydata.shape
        ws = WorkspaceFactory.create("Workspace2D",
                                     NVectors=nr,
                                     XLength=nc + 1,
                                     YLength=nc)
        for i in range(nrows):
            ws.setX(i, xdata)
            ws.setY(i, ydata[i])
            ws.setE(i, edata[i])
        ws.getAxis(0).setUnit('tof')
        AnalysisDataService.addOrReplace(wsn, ws)

        # self.setProperty("OutputWorkspace", wsn)
        # print ("ws:", wsn)
        # ws=mtd[wsn]

        # fix the x values for the monitor
        for i in range(nrows - 2, nrows):
            ws.setX(i, xdata_mon)
        self.log().information("set detector IDs")
        # set detetector IDs
        for i in range(nrows):
            ws.getSpectrum(i).setDetectorID(det_udet[i])
        # Sample_logs the header values are written into the sample logs
        log_names = [
            str(sl.encode('ascii', 'ignore').decode())
            for sl in parms_dict.keys()
        ]
        log_values = [
            str(sl.encode('ascii', 'ignore').decode()) if isinstance(
                sl, UnicodeType) else str(sl) for sl in parms_dict.values()
        ]
        for i in range(len(log_values)):
            if ('nan' in log_values[i]) or ('NaN' in log_values[i]):
                log_values[i] = '-1.0'
        AddSampleLogMultiple(Workspace=wsn,
                             LogNames=log_names,
                             LogValues=log_values)
        SetGoniometer(Workspace=wsn, Goniometers='Universal')
        if (self.fxml == ""):
            LoadInstrument(Workspace=wsn,
                           InstrumentName="Exed",
                           RewriteSpectraMap=True)
        else:
            LoadInstrument(Workspace=wsn,
                           Filename=self.fxml,
                           RewriteSpectraMap=True)
        try:
            RotateInstrumentComponent(
                Workspace=wsn,
                ComponentName='Tank',
                Y=1,
                Angle=-float(parms_dict['phi'].encode('ascii', 'ignore')),
                RelativeRotation=False)
        except:
            self.log().warning(
                "The instrument does not contain a 'Tank' component. "
                "This means that you are using a custom XML instrument definition. "
                "OMEGA_MAG will be ignored.")
            self.log().warning(
                "Please make sure that the detector positions in the instrument definition are correct."
            )
        # Separate monitors into seperate workspace
        __temp_monitors = ExtractSpectra(
            InputWorkspace=wsn,
            WorkspaceIndexList=','.join(
                [str(s) for s in range(nrows - 2, nrows)]),
            OutputWorkspace=self.getPropertyValue("OutputMonitorWorkspace"))
        # ExtractSpectra(InputWorkspace = wsn, WorkspaceIndexList = ','.join([str(s) for s in range(nrows-2, nrows)]),
        # OutputWorkspace = wsn + '_Monitors')
        MaskDetectors(Workspace=wsn,
                      WorkspaceIndexList=','.join(
                          [str(s) for s in range(nrows - 2, nrows)]))
        RemoveMaskedSpectra(InputWorkspace=wsn, OutputWorkspace=wsn)

        self.setProperty("OutputWorkspace", wsn)
        self.setProperty("OutputMonitorWorkspace", __temp_monitors)