Пример #1
0
    def makeFiles(self):
        simpleapi.CreateWorkspace(OutputWorkspace='data',
                                  DataX='1,2,3,4,5',
                                  DataY='1,0,1,4,4',
                                  DataE='1,0,1,2,2')
        simpleapi.CreateWorkspace(OutputWorkspace='sim',
                                  DataX='1,2,3,4,5',
                                  DataY='1,1,1,1,1',
                                  DataE='0,0,0,0,0')
        simpleapi.CreateWorkspace(OutputWorkspace='simwrong',
                                  DataX='1,2,3,4',
                                  DataY='1,1,1,1',
                                  DataE='0,0,0,0')

        self.datafile = os.path.join(config.getString('defaultsave.directory'),
                                     'DakotaChiSquared_data.nxs')
        self.simfile = os.path.join(config.getString('defaultsave.directory'),
                                    'DakotaChiSquared_sim.nxs')
        self.simwrongfile = os.path.join(
            config.getString('defaultsave.directory'),
            'DakotaChiSquared_simwrong.nxs')
        self.chifile = os.path.join(config.getString('defaultsave.directory'),
                                    'DakotaChiSquared_chi.txt')

        simpleapi.SaveNexus('data', self.datafile)
        simpleapi.SaveNexus('sim', self.simfile)
        simpleapi.SaveNexus('simwrong', self.simwrongfile)

        ads = AnalysisDataServiceImpl.Instance()
        ads.remove("data")
        ads.remove("sim")
        ads.remove("simwrong")
Пример #2
0
def _focus_mode_groups(cycle_information, output_file_paths, save_range,
                       calibrated_spectra):
    output_list = []
    to_save = _sum_groups_of_three_ws(calibrated_spectra, output_file_paths)

    workspaces_4_to_9_name = output_file_paths["output_name"] + "_mods4-9"
    workspaces_4_to_9 = mantid.Plus(LHSWorkspace=to_save[1],
                                    RHSWorkspace=to_save[2])
    workspaces_4_to_9 = mantid.Scale(InputWorkspace=workspaces_4_to_9,
                                     Factor=0.5,
                                     OutputWorkspace=workspaces_4_to_9_name)
    to_save.append(workspaces_4_to_9)
    append = False
    index = 1
    for ws in to_save:
        if cycle_information["instrument_version"] == "new":
            mantid.SaveGSS(InputWorkspace=ws,
                           Filename=output_file_paths["gss_filename"],
                           Append=append,
                           Bank=index)
        elif cycle_information["instrument_version"] == "new2":
            mantid.SaveGSS(InputWorkspace=ws,
                           Filename=output_file_paths["gss_filename"],
                           Append=False,
                           Bank=index)

        workspace_names = ws.name()
        dspacing_ws = mantid.ConvertUnits(InputWorkspace=ws,
                                          OutputWorkspace=workspace_names,
                                          Target="dSpacing")
        remove_intermediate_workspace(ws)
        output_list.append(dspacing_ws)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=dspacing_ws,
                         Append=append)
        append = True
        index += 1

    for i in range(0, save_range):
        monitor_ws_name = output_file_paths["output_name"] + "_mod" + str(i +
                                                                          10)

        monitor_ws = calibrated_spectra[i + 9]
        to_save = mantid.CloneWorkspace(InputWorkspace=monitor_ws,
                                        OutputWorkspace=monitor_ws_name)

        mantid.SaveGSS(InputWorkspace=to_save,
                       Filename=output_file_paths["gss_filename"],
                       Append=True,
                       Bank=i + 5)
        to_save = mantid.ConvertUnits(InputWorkspace=to_save,
                                      OutputWorkspace=monitor_ws_name,
                                      Target="dSpacing")
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=to_save,
                         Append=True)

        output_list.append(to_save)

    return output_list
Пример #3
0
def _focus_mode_trans(output_file_paths, atten, instrument,
                      calibrated_spectra):
    summed_ws = mantid.CloneWorkspace(InputWorkspace=calibrated_spectra[0])
    for i in range(1, 9):  # Add workspaces 2-9 to workspace 1
        summed_ws = mantid.Plus(LHSWorkspace=summed_ws,
                                RHSWorkspace=calibrated_spectra[i])

    summed_ws = mantid.Scale(InputWorkspace=summed_ws,
                             Factor=0.111111111111111)

    if atten:
        # Clone a workspace which is not attenuated
        no_att = output_file_paths["output_name"] + "_noatten"
        mantid.CloneWorkspace(InputWorkspace=summed_ws, OutputWorkspace=no_att)

        summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws,
                                        Target="dSpacing")
        summed_ws = instrument._attenuate_workspace(summed_ws)
        summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws, Target="TOF")

    mantid.SaveGSS(InputWorkspace=summed_ws,
                   Filename=output_file_paths["gss_filename"],
                   Append=False,
                   Bank=1)
    mantid.SaveFocusedXYE(InputWorkspace=summed_ws,
                          Filename=output_file_paths["tof_xye_filename"],
                          Append=False,
                          IncludeHeader=False)

    summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws,
                                    Target="dSpacing")

    # Rename to user friendly name:
    summed_ws_name = output_file_paths["output_name"] + "_mods1-9"
    summed_ws = mantid.RenameWorkspace(InputWorkspace=summed_ws,
                                       OutputWorkspace=summed_ws_name)

    mantid.SaveFocusedXYE(InputWorkspace=summed_ws,
                          Filename=output_file_paths["dspacing_xye_filename"],
                          Append=False,
                          IncludeHeader=False)
    mantid.SaveNexus(InputWorkspace=summed_ws,
                     Filename=output_file_paths["nxs_filename"],
                     Append=False)

    output_list = [summed_ws]

    for i in range(0, 9):
        workspace_name = output_file_paths["output_name"] + "_mod" + str(i + 1)
        to_save = mantid.ConvertUnits(InputWorkspace=calibrated_spectra[i],
                                      Target="dSpacing",
                                      OutputWorkspace=workspace_name)
        output_list.append(to_save)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=to_save,
                         Append=True)

    return output_list
Пример #4
0
def _focus_mode_trans(output_file_paths, attenuation_filepath,
                      calibrated_spectra):
    summed_ws = mantid.MergeRuns(InputWorkspaces=calibrated_spectra[:9])
    xList = summed_ws.readX(0)

    summed_ws = mantid.CropWorkspace(InputWorkspace=summed_ws,
                                     XMin=xList[1],
                                     Xmax=xList[-2])
    summed_ws = mantid.Scale(InputWorkspace=summed_ws,
                             Factor=0.111111111111111)

    if attenuation_filepath:
        summed_ws = _attenuate_workspace(
            output_file_paths=output_file_paths,
            attenuated_ws=summed_ws,
            attenuation_filepath=attenuation_filepath)

    summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws, Target="TOF")
    mantid.SaveGSS(InputWorkspace=summed_ws,
                   Filename=output_file_paths["gss_filename"],
                   Append=False,
                   Bank=1)

    mantid.SaveFocusedXYE(InputWorkspace=summed_ws,
                          Filename=output_file_paths["tof_xye_filename"],
                          Append=False,
                          IncludeHeader=False)

    summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws,
                                    Target="dSpacing")

    # Rename to user friendly name:
    summed_ws_name = output_file_paths["output_name"] + "_mods1-9"
    summed_ws = mantid.RenameWorkspace(InputWorkspace=summed_ws,
                                       OutputWorkspace=summed_ws_name)

    mantid.SaveFocusedXYE(InputWorkspace=summed_ws,
                          Filename=output_file_paths["dspacing_xye_filename"],
                          Append=False,
                          IncludeHeader=False)
    mantid.SaveNexus(InputWorkspace=summed_ws,
                     Filename=output_file_paths["nxs_filename"],
                     Append=False)

    output_list = [summed_ws]

    for i in range(0, 9):
        workspace_name = output_file_paths["output_name"] + "_mod" + str(i + 1)
        to_save = mantid.ConvertUnits(InputWorkspace=calibrated_spectra[i],
                                      Target="dSpacing",
                                      OutputWorkspace=workspace_name)
        output_list.append(to_save)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=to_save,
                         Append=True)

    return output_list
Пример #5
0
def _focus_mode_all(output_file_paths, processed_spectra,
                    attenuation_filepath):
    summed_spectra_name = output_file_paths["output_name"] + "_mods1-9"
    summed_spectra = mantid.MergeRuns(InputWorkspaces=processed_spectra[:9],
                                      OutputWorkspace=summed_spectra_name)

    summed_spectra = mantid.Scale(InputWorkspace=summed_spectra,
                                  Factor=0.111111111111111,
                                  OutputWorkspace=summed_spectra_name)
    if attenuation_filepath:
        summed_spectra = _attenuate_workspace(
            output_file_paths=output_file_paths,
            attenuated_ws=summed_spectra,
            attenuation_filepath=attenuation_filepath)

    summed_spectra = mantid.ConvertUnits(InputWorkspace=summed_spectra,
                                         Target="TOF",
                                         OutputWorkspace=summed_spectra_name)

    mantid.SaveGSS(InputWorkspace=summed_spectra,
                   Filename=output_file_paths["gss_filename"],
                   Append=False,
                   Bank=1)

    summed_spectra = mantid.ConvertUnits(InputWorkspace=summed_spectra,
                                         Target="dSpacing",
                                         OutputWorkspace=summed_spectra_name)
    mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                     InputWorkspace=summed_spectra,
                     Append=False)

    output_list = [summed_spectra]
    for i in range(0, 5):
        spectra_index = (i + 9)  # Compensate for 0 based index
        ws_to_save = processed_spectra[
            spectra_index]  # Save out workspaces 10/11/12
        output_name = output_file_paths["output_name"] + "_mod" + str(
            spectra_index + 1)

        ws_to_save = mantid.ConvertUnits(InputWorkspace=ws_to_save,
                                         OutputWorkspace=ws_to_save,
                                         Target="TOF")
        mantid.SaveGSS(InputWorkspace=ws_to_save,
                       Filename=output_file_paths["gss_filename"],
                       Append=True,
                       Bank=i + 2)
        ws_to_save = mantid.ConvertUnits(InputWorkspace=ws_to_save,
                                         OutputWorkspace=output_name,
                                         Target="dSpacing")
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=ws_to_save,
                         Append=True)

        output_list.append(ws_to_save)

    return output_list
Пример #6
0
def filter_cross_sections(file_path, events=True, histo=False):
    """
        Filter events according to polarization state.
        :param str file_path: file to read
        :param bool events: if True, an event nexus file will be written
        :param bool histo: if True, a histo nexus file will be written
    """
    cross_sections = {}
    cross_sections_histo = {}

    xs_list = api.MRFilterCrossSections(file_path,
                                        PolState=POL_STATE,
                                        AnaState=ANA_STATE,
                                        PolVeto=POL_VETO,
                                        AnaVeto=ANA_VETO)

    if len(xs_list) > 0:
        tof_min, tof_max = get_tof_range(xs_list[0])

    for workspace in xs_list:
        if "cross_section_id" in workspace.getRun():
            entry = workspace.getRun().getProperty("cross_section_id").value
        else:
            entry = 'Off_Off'
            api.AddSampleLog(Workspace=workspace,
                             LogName='cross_section_id',
                             LogText=entry)
        if workspace.getNumberEvents() < 5:
            logging.warn("No events in %s", entry)
            continue

        run_number = workspace.getRunNumber()
        if events:
            events_file = "/tmp/filtered_%s_%s_%s.nxs" % (run_number, entry,
                                                          "events")
            api.SaveNexus(InputWorkspace=workspace,
                          Filename=events_file,
                          Title='entry_%s' % entry)
            cross_sections['entry-%s' % entry] = events_file
        if histo:
            #tof_min = workspace.getTofMin()
            #tof_max = workspace.getTofMax()
            ws_binned = api.Rebin(InputWorkspace=workspace,
                                  Params="%s, %s, %s" %
                                  (tof_min, TOF_BIN, tof_max),
                                  PreserveEvents=False)
            histo_file = "/tmp/filtered_%s_%s_%s.nxs" % (run_number, entry,
                                                         "histo")
            api.SaveNexus(InputWorkspace=ws_binned,
                          Filename=histo_file,
                          Title='entry_%s' % entry)
            cross_sections_histo['entry-%s' % entry] = histo_file

    return cross_sections, cross_sections_histo
Пример #7
0
def _save_out(run_number, focus_directory, focus_general, output, enginx_file_name_format, bank_id):
    """
    save out the files required for the focus

    @param run_number :: the run number of the focused run
    @param focus_directory :: the user directory to save to
    @param focus_general :: the general folder to copy the saved out files to
    @param output :: the workspace to save
    @param enginx_file_name_format :: the naming scheme of the files
    @param bank_id :: the bank being saved

    """
    # work out where to save the files
    dat_name, genie_filename, gss_name, hdf5_name, nxs_name = _find_focus_file_location(bank_id, focus_directory,
                                                                                        enginx_file_name_format,
                                                                                        run_number)
    if not str(bank_id).isnumeric():
        bank_id = 0
    # save the files out to the user directory
    simple.SaveFocusedXYE(InputWorkspace=output, Filename=dat_name, SplitFiles=False,
                          StartAtBankNumber=bank_id)
    simple.SaveGSS(InputWorkspace=output, Filename=gss_name, SplitFiles=False, Bank=bank_id)
    simple.SaveOpenGenieAscii(InputWorkspace=output, Filename=genie_filename, OpenGenieFormat="ENGIN-X Format")
    simple.SaveNexus(InputWorkspace=output, Filename=nxs_name)
    simple.ExportSampleLogsToHDF5(InputWorkspace=output, Filename=hdf5_name, Blacklist="bankid")
    if not focus_general == focus_directory:
        if not os.path.exists(focus_general):
            os.makedirs(focus_general)
        # copy the files to the general directory
        copy2(dat_name, focus_general)
        copy2(gss_name, focus_general)
        copy2(genie_filename, focus_general)
        copy2(nxs_name, focus_general)
        copy2(hdf5_name, focus_general)
Пример #8
0
def populate_Ei_data(sim_out, nxs):
    import shutil
    nxs_withmons = nxsfilename_with_monitors(nxs)
    shutil.copyfile(nxs, nxs_withmons)
    populate_monitor_data(sim_out, nxs_withmons)
    print((" * Created ARCS NeXus file with monitor data: %s" % nxs_withmons))
    #
    import ast
    props = ast.literal_eval(open(os.path.join(sim_out, 'props.json')).read())
    Ei, unit = props['average energy'].split()
    assert unit == 'meV'
    t0, unit = props['emission time'].split()
    assert unit == 'microsecond'
    from mantid import simpleapi as msa
    if sys.version_info < (3, 0) and isinstance(nxs, unicode):
        nxs = nxs.encode('utf-8')
    ws = msa.Load(nxs_withmons)
    msa.AddSampleLog(ws,
                     LogName='mcvine-Ei',
                     LogText=str(Ei),
                     LogType='Number')
    msa.AddSampleLog(ws,
                     LogName='mcvine-t0',
                     LogText=str(t0),
                     LogType='Number')
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    msa.SaveNexus(ws, filename)
    mv(filename, nxs)
    return
Пример #9
0
def _focus_mode_mods(output_file_paths, calibrated_spectra):
    append = False
    output_list = []
    for index, ws in enumerate(calibrated_spectra):
        output_name = output_file_paths["output_name"] + "_mod" + str(index +
                                                                      1)
        tof_ws = mantid.ConvertUnits(InputWorkspace=ws,
                                     OutputWorkspace=output_name,
                                     Target=WORKSPACE_UNITS.tof)
        mantid.SaveFocusedXYE(InputWorkspace=tof_ws,
                              Filename=output_file_paths["tof_xye_filename"],
                              Append=False,
                              IncludeHeader=False)
        mantid.SaveGSS(InputWorkspace=tof_ws,
                       Filename=output_file_paths["gss_filename"],
                       Append=append,
                       Bank=index + 1)
        dspacing_ws = mantid.ConvertUnits(InputWorkspace=ws,
                                          OutputWorkspace=output_name,
                                          Target=WORKSPACE_UNITS.d_spacing)
        output_list.append(dspacing_ws)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=dspacing_ws,
                         Append=append)

        append = True
    return output_list
Пример #10
0
def populate_metadata(sim_out, nxs, sample, detector):
    if sys.version_info < (3, 0) and isinstance(nxs, unicode):
        nxs = nxs.encode('utf-8')
    import h5py
    f = h5py.File(nxs, 'a')
    entry = f['entry']
    from mcvine.instruments.HYSPEC.nxs.raw import populateMetadata
    populateMetadata(entry, sim_out, sample, detector)
    f.close()
    # add log entries
    import ast, os
    props = ast.literal_eval(open(os.path.join(sim_out, 'props.json')).read())
    Ei, unit = props['average energy'].split()
    assert unit == 'meV'
    t0, unit = props['emission time'].split()
    assert unit == 'microsecond'
    from mantid import simpleapi as msa
    ws = msa.Load(nxs)
    msa.AddSampleLog(ws,
                     LogName='mcvine-Ei',
                     LogText=str(Ei),
                     LogType='Number')
    msa.AddSampleLog(ws,
                     LogName='mcvine-t0',
                     LogText=str(t0),
                     LogType='Number')
    msa.SaveNexus(ws, nxs)
    return
Пример #11
0
    def create_solid_angle_corrections(self, vanadium, run_details):
        """
        Creates the solid angle corrections from a vanadium run, only applicable on HRPD otherwise return None
        :param vanadium: The vanadium used to create this
        :param run_details: the run details of to use
        """
        if not self._inst_settings.do_solid_angle:
            return
        solid_angle = mantid.SolidAngle(InputWorkspace=vanadium)

        scale = mantid.CreateSingleValuedWorkspace(DataValue='100')
        correction = mantid.Multiply(LHSWorkspace=solid_angle,
                                     RHSWorkspace=scale)

        eff = mantid.Divide(LHSWorkspace=vanadium, RHSWorkspace=correction)
        eff = mantid.ConvertUnits(InputWorkspace=eff, Target='Wavelength')
        eff = mantid.Integration(InputWorkspace=eff,
                                 RangeLower='1.3999999999999999',
                                 RangeUpper='3')

        correction = mantid.Multiply(LHSWorkspace=correction, RHSWorkspace=eff)
        scale = mantid.CreateSingleValuedWorkspace(DataValue='100000')
        correction = mantid.Divide(LHSWorkspace=correction, RHSWorkspace=scale)

        name = "sac" + common.generate_splined_name(run_details.run_number, [])
        path = run_details.van_paths

        mantid.SaveNexus(InputWorkspace=correction,
                         Filename=os.path.join(path, name))

        common.remove_intermediate_workspace(solid_angle)
        common.remove_intermediate_workspace(scale)
        common.remove_intermediate_workspace(eff)
        common.remove_intermediate_workspace(correction)
Пример #12
0
    def create_solid_angle_corrections(self, vanadium, run_details):
        """
        Creates the solid angle corrections from a vanadium run, only applicable on HRPD otherwise return None
        :param vanadium: The vanadium used to create this
        :param run_details: the run details of to use
        """
        settings = self._inst_settings
        if not settings.do_solid_angle:
            return
        solid_angle = mantid.SolidAngle(InputWorkspace=vanadium)
        solid_angle = mantid.Scale(InputWorkspace=solid_angle, Factor=100, Operation='Multiply')

        eff = mantid.Divide(LHSWorkspace=vanadium, RHSWorkspace=solid_angle)
        eff = mantid.ConvertUnits(InputWorkspace=eff, Target='Wavelength')
        integration_range = settings.eff_integration_range
        # use full range if no range is supplied
        integration_range = integration_range if integration_range is not None else (None, None)
        eff = mantid.Integration(InputWorkspace=eff,
                                 RangeLower=integration_range[0],
                                 RangeUpper=integration_range[1])

        correction = mantid.Multiply(LHSWorkspace=solid_angle, RHSWorkspace=eff)
        correction = mantid.Scale(InputWorkspace=correction, Factor=1e-5,
                                  Operation='Multiply')
        name = "sac" + common.generate_splined_name(run_details.run_number, [])
        path = run_details.van_paths

        mantid.SaveNexus(InputWorkspace=correction, Filename=os.path.join(path, name))
        common.remove_intermediate_workspace(eff)
        common.remove_intermediate_workspace(correction)
Пример #13
0
def _focus_mode_all(output_file_paths, calibrated_spectra):
    first_spectrum = calibrated_spectra[0]
    summed_spectra = mantid.CloneWorkspace(InputWorkspace=first_spectrum)

    for i in range(1, 9):  # TODO why is this 1-8
        summed_spectra = mantid.Plus(LHSWorkspace=summed_spectra,
                                     RHSWorkspace=calibrated_spectra[i])

    summed_spectra_name = output_file_paths["output_name"] + "_mods1-9"

    summed_spectra = mantid.Scale(InputWorkspace=summed_spectra,
                                  Factor=0.111111111111111,
                                  OutputWorkspace=summed_spectra_name)
    mantid.SaveGSS(InputWorkspace=summed_spectra,
                   Filename=output_file_paths["gss_filename"],
                   Append=False,
                   Bank=1)

    summed_spectra = mantid.ConvertUnits(InputWorkspace=summed_spectra,
                                         Target="dSpacing",
                                         OutputWorkspace=summed_spectra_name)
    mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                     InputWorkspace=summed_spectra,
                     Append=False)

    output_list = [summed_spectra]
    for i in range(0, 3):
        spectra_index = (
            i + 9
        )  # We want workspaces 10/11/12 so compensate for 0 based index
        ws_to_save = calibrated_spectra[
            spectra_index]  # Save out workspaces 10/11/12
        output_name = output_file_paths["output_name"] + "_mod" + str(
            spectra_index + 1)
        mantid.SaveGSS(InputWorkspace=ws_to_save,
                       Filename=output_file_paths["gss_filename"],
                       Append=True,
                       Bank=i + 2)
        ws_to_save = mantid.ConvertUnits(InputWorkspace=ws_to_save,
                                         OutputWorkspace=output_name,
                                         Target="dSpacing")
        output_list.append(ws_to_save)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=ws_to_save,
                         Append=True)

    return output_list
Пример #14
0
def handle_van_curves(van_curves, van_path):
    if len(van_curves) == 2:
        curves_ws = simple.AppendSpectra(InputWorkspace1=van_curves[0], InputWorkspace2=van_curves[1])
        simple.DeleteWorkspace(van_curves[1])
    else:
        curves_ws = van_curves[0]
    simple.SaveNexus(curves_ws, van_path)
    simple.DeleteWorkspace(van_curves[0])
    simple.DeleteWorkspace(curves_ws)
Пример #15
0
def _save_output_files(focus_dirs,
                       sample_ws_foc,
                       calibration,
                       van_run,
                       rb_num=None):
    # set bankid for use in fit tab
    foc_suffix = calibration.get_foc_ws_suffix()
    xunit = sample_ws_foc.getDimension(0).name
    xunit_suffix = XUNIT_SUFFIXES[xunit]
    sample_run_no = sample_ws_foc.run().get('run_number').value
    # save all spectra to single ASCII files
    ascii_fname = _generate_output_file_name(calibration.get_instrument(),
                                             sample_run_no,
                                             van_run,
                                             calibration.get_group_suffix(),
                                             xunit_suffix,
                                             ext='')

    for focus_dir in focus_dirs:
        if not path.exists(focus_dir):
            makedirs(focus_dir)
        mantid.SaveGSS(InputWorkspace=sample_ws_foc,
                       Filename=path.join(focus_dir, ascii_fname + '.gss'),
                       SplitFiles=False,
                       UseSpectrumNumberAsBankID=True)
        mantid.SaveFocusedXYE(InputWorkspace=sample_ws_foc,
                              Filename=path.join(focus_dir,
                                                 ascii_fname + ".abc"),
                              SplitFiles=False,
                              Format="TOPAS")
        # Save nxs per spectrum
        nxs_paths = []
        mantid.AddSampleLog(Workspace=sample_ws_foc,
                            LogName="Vanadium Run",
                            LogText=van_run)
        for ispec in range(sample_ws_foc.getNumberHistograms()):
            # add a bankid and vanadium to log that is read by fitting model
            bankid = foc_suffix if sample_ws_foc.getNumberHistograms(
            ) == 1 else f'{foc_suffix}_{ispec + 1}'
            mantid.AddSampleLog(Workspace=sample_ws_foc,
                                LogName="bankid",
                                LogText=bankid.replace('_', ' '))  # overwrites
            # save spectrum as nexus
            filename = _generate_output_file_name(calibration.get_instrument(),
                                                  sample_run_no,
                                                  van_run,
                                                  bankid,
                                                  xunit_suffix,
                                                  ext=".nxs")
            nxs_path = path.join(focus_dir, filename)
            mantid.SaveNexus(InputWorkspace=sample_ws_foc,
                             Filename=nxs_path,
                             WorkspaceIndexList=[ispec])
            nxs_paths.append(nxs_path)
    return nxs_paths  # from last focus_dir only
Пример #16
0
def create_vanadium(van_run, calibration_directory):
    """
    create the vanadium run for the run number set of the object

    @param van_run :: the run number for the vanadium
    @param calibration_directory :: the directory to save the output to
    """
    # find and load the vanadium
    van_file = _gen_filename(van_run)
    van_curves_file, van_int_file = _get_van_names(van_run, calibration_directory)
    van_name = "eng_vanadium_ws"
    simple.Load(van_file, OutputWorkspace=van_name)

    # make the vanadium corrections
    simple.EnggVanadiumCorrections(VanadiumWorkspace=van_name,
                                   OutIntegrationWorkspace="eng_vanadium_integration",
                                   OutCurvesWorkspace="eng_vanadium_curves")

    # save out the vanadium and delete the original workspace
    simple.SaveNexus("eng_vanadium_integration", van_int_file)
    simple.SaveNexus("eng_vanadium_curves", van_curves_file)
    simple.DeleteWorkspace(van_name)
Пример #17
0
def generate_vanadium_absorb_corrections(van_ws, output_filename):
    shape_ws = mantid.CloneWorkspace(InputWorkspace=van_ws)
    shape_ws = mantid.ConvertUnits(InputWorkspace=shape_ws, OutputWorkspace=shape_ws, Target="Wavelength")
    mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>')

    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=output_filename,
                     InputWorkspace=absorb_ws, Append=False)
    common.remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #18
0
def _create_vanadium_splines(focused_spectra, instrument, run_details):
    splined_ws_list = instrument._spline_vanadium_ws(focused_spectra)
    out_spline_van_file_path = run_details.splined_vanadium_file_path
    append = False
    for ws in splined_ws_list:
        mantid.SaveNexus(Filename=out_spline_van_file_path, InputWorkspace=ws, Append=append)
        append = True
    # Group for user convenience
    group_name = "Van_spline_data"
    tt_mode = instrument._get_current_tt_mode()
    if tt_mode:
        group_name = group_name + '_' + tt_mode

    mantid.GroupWorkspaces(InputWorkspaces=splined_ws_list, OutputWorkspace=group_name)
Пример #19
0
def save_unsplined_vanadium(vanadium_ws, output_path):
    converted_workspaces = []
    for ws_index in range(vanadium_ws.getNumberOfEntries()):
        ws = vanadium_ws.getItem(ws_index)
        previous_units = ws.getAxis(0).getUnit().unitID()

        if previous_units != WORKSPACE_UNITS.tof:
            ws = mantid.ConvertUnits(InputWorkspace=ws, Target=WORKSPACE_UNITS.tof)

        ws = mantid.RenameWorkspace(InputWorkspace=ws, OutputWorkspace="van_bank_{}".format(ws_index + 1))
        converted_workspaces.append(ws)

    converted_group = mantid.GroupWorkspaces(",".join(ws.name() for ws in converted_workspaces))
    mantid.SaveNexus(InputWorkspace=converted_group, Filename=output_path, Append=False)
    mantid.DeleteWorkspace(converted_group)
Пример #20
0
    def checkWorkspacesMatch(self, ws1, ws2):
        checker = ms.AlgorithmManager.create("CompareWorkspaces")
        checker.setLogging(True)
        checker.setPropertyValue("Workspace1", ws1)
        checker.setPropertyValue("Workspace2", ws2)
        checker.setPropertyValue("Tolerance", str(self.tolerance))
        checker.setPropertyValue("CheckInstrument","0")

        checker.execute()

        if not checker.getProperty("Result"):
            print self.__class__.__name__
            ms.SaveNexus(InputWorkspace=ws2,Filename=self.__class__.__name__+'-mismatch.nxs')
            return False

        return True
Пример #21
0
def generate_vanadium_absorb_corrections(van_ws):
    raise NotImplementedError("Generating absorption corrections needs to be implemented correctly")

    # TODO are these values applicable to all instruments
    shape_ws = mantid.CloneWorkspace(InputWorkspace=van_ws)
    mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>')

    calibration_full_paths = None
    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=calibration_full_paths["vanadium_absorption"],
                     InputWorkspace=absorb_ws, Append=False)
    common.remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #22
0
def save_calibration(ceria_run, calibration_directory, calibration_general, name, bank_names, zeros, difcs,
                     difas, bk2bk_params):
    """
    save the calibration data

    @param ceria_run :: the run number of the ceria
    @param calibration_directory :: the user specific calibration directory to save to
    @param calibration_general :: the general calibration directory to save to
    @param name ::  the name of the banks being saved
    @param bank_names :: the list of banks to save
    @param difas :: the list of difa values to save
    @param difcs :: the list of difc values to save
    @param zeros :: the list of tzero values to save

    """
    file_save_prefix = os.path.join(calibration_directory, "ENGINX_" + ceria_run + "_")
    gsas_iparm_fname = file_save_prefix + name + ".prm"
    pdcals_to_save = dict()  # fname: workspace
    # work out what template to use, and which PDCalibration files to save
    if name == "all_banks":
        template_file = None
        pdcals_to_save[file_save_prefix + "bank_North.nxs"] = 'engg_calibration_bank_1'
        pdcals_to_save[file_save_prefix + "bank_South.nxs"] = 'engg_calibration_bank_2'
    elif name == "bank_2":
        template_file = "template_ENGINX_241391_South_bank.prm"
        pdcals_to_save[file_save_prefix + "bank_South.nxs"] = 'engg_calibration_bank_2'
    elif name == "bank_1":
        template_file = "template_ENGINX_241391_North_bank.prm"
        pdcals_to_save[file_save_prefix + "bank_North.nxs"] = 'engg_calibration_bank_1'
    else:  # cropped uses North bank template
        template_file = "template_ENGINX_241391_North_bank.prm"
        pdcals_to_save[file_save_prefix + "cropped.nxs"] = 'engg_calibration_cropped'
    # write out the param file to the users directory

    Utils.write_ENGINX_GSAS_iparam_file(output_file=gsas_iparm_fname, bank_names=bank_names, difa=difas, difc=difcs,
                                        tzero=zeros, ceria_run=ceria_run,
                                        template_file=template_file, bk2bk_params=bk2bk_params)
    for fname, ws in pdcals_to_save.items():
        simple.SaveNexus(InputWorkspace=ws, Filename=fname)
    if not calibration_general == calibration_directory:
        # copy the param file to the general directory
        if not os.path.exists(calibration_general):
            os.makedirs(calibration_general)
        copy2(gsas_iparm_fname, calibration_general)
        for fname in pdcals_to_save.keys():
            copy2(fname, calibration_general)
Пример #23
0
def populate_Ei_data(sim_out, nxs):
    import ast, os
    props = ast.literal_eval(open(os.path.join(sim_out, 'props.json')).read())
    Ei, unit = props['average energy'].split(); assert unit=='meV'
    t0, unit = props['emission time'].split(); assert unit=='microsecond'
    setEnergyRequest(nxs, float(Ei))
    from mantid import simpleapi as msa
    if sys.version_info<(3,0) and isinstance(nxs, unicode):
        nxs = nxs.encode('utf-8')
    ws = msa.Load(nxs)
    msa.AddSampleLog(ws, LogName='mcvine-Ei', LogText=str(Ei), LogType='Number')
    msa.AddSampleLog(ws, LogName='mcvine-t0', LogText=str(t0), LogType='Number')
    (fd, filename) = tempfile.mkstemp(); os.close(fd)
    msa.SaveNexus(ws, filename)
    from ...ARCS.applications.nxs import mv
    mv(filename, nxs)
    return
Пример #24
0
def _generate_vanadium_absorb_corrections(calibration_full_paths, ws_to_match):
    # TODO are these values applicable to all instruments
    shape_ws = mantid.CloneWorkspace(InputWorkspace=ws_to_match)
    mantid.CreateSampleShape(
        InputWorkspace=shape_ws,
        ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>'
    )

    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=calibration_full_paths["vanadium_absorption"],
                     InputWorkspace=absorb_ws,
                     Append=False)
    remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #25
0
def _save_out(run_number, focus_directory, focus_general, output, join_string,
              bank_id):
    """
    save out the files required for the focus

    @param run_number :: the run number of the focused run
    @param focus_directory :: the user directory to save to
    @param focus_general :: the general folder to copy the saved out files to
    @param output :: the workspace to save
    @param join_string :: the nameing scheme of the files
    @param bank_id :: the bank being saved

    """
    # work out where to save the files
    filename = os.path.join(focus_directory,
                            join_string.format(run_number, bank_id))
    hdf5_name = os.path.join(focus_directory, run_number + ".hdf5")
    if not unicode(bank_id).isnumeric():
        bank_id = 0
    # save the files out to the user directory
    simple.SaveFocusedXYE(InputWorkspace=output,
                          Filename=filename + ".dat",
                          SplitFiles=False,
                          StartAtBankNumber=bank_id)
    simple.SaveGSS(InputWorkspace=output,
                   Filename=filename + ".gss",
                   SplitFiles=False,
                   Bank=bank_id)
    simple.SaveOpenGenieAscii(InputWorkspace=output,
                              Filename=filename + ".his",
                              OpenGenieFormat="ENGIN-X Format")
    simple.SaveNexus(InputWorkspace=output, Filename=filename + ".nxs")
    simple.ExportSampleLogsToHDF5(InputWorkspace=output,
                                  Filename=hdf5_name,
                                  Blacklist="bankid")
    if not focus_general == focus_directory:
        if not os.path.exists(focus_general):
            os.makedirs(focus_general)
        # copy the files to the general directory
        copy2(filename + ".dat", focus_general)
        copy2(filename + ".gss", focus_general)
        copy2(filename + ".his", focus_general)
        copy2(filename + ".nxs", focus_general)
        copy2(hdf5_name, focus_general)
Пример #26
0
def populate_Ei_data(sim_out, nxs):
    import ast, os
    props = ast.literal_eval(open(os.path.join(sim_out, 'props.json')).read())
    Ei, unit = props['average energy'].split()
    assert unit == 'meV'
    t0, unit = props['emission time'].split()
    assert unit == 'microsecond'
    from mantid import simpleapi as msa
    ws = msa.Load(nxs)
    msa.AddSampleLog(ws,
                     LogName='mcvine-Ei',
                     LogText=str(Ei),
                     LogType='Number')
    msa.AddSampleLog(ws,
                     LogName='mcvine-t0',
                     LogText=str(t0),
                     LogType='Number')
    msa.SaveNexus(ws, nxs)
    return
Пример #27
0
def create_output_files(calibration_dir, calibration, ws_foc):
    """
    Create output files (.prm for GSAS and .nxs of calibration table) from the algorithms in the specified directory
    :param calibration_dir: The directory to save the files into.
    :param calibration: CalibrationInfo object with details of calibration and grouping
    :param ws_foc: focused ceria workspace
    """
    # create calibration dir of not exist
    if not path.exists(calibration_dir):
        makedirs(calibration_dir)

    # save grouping ws if custom or cropped
    if not calibration.group.banks:
        calibration.save_grouping_workspace(calibration_dir)

    # save prm file(s)
    prm_filepath = path.join(calibration_dir,
                             calibration.generate_output_file_name())
    write_prm_file(ws_foc, prm_filepath)
    calibration.set_prm_filepath(prm_filepath)
    # save pdcal output as nexus
    filepath, ext = path.splitext(prm_filepath)
    nxs_filepath = filepath + '.nxs'
    mantid.SaveNexus(InputWorkspace=calibration.get_calibration_table(),
                     Filename=nxs_filepath)

    # if both banks calibrated save individual banks separately as well
    if calibration.group == GROUP.BOTH:
        # output a separate prm for North and South when both banks included
        for ibank, bank in enumerate(calibration.group.banks):
            # get prm filename for individual banks by passing group enum as argument to generate_output_file_name
            prm_filepath_bank = path.join(
                calibration_dir,
                calibration.generate_output_file_name(GROUP(str(ibank + 1))))
            write_prm_file(ws_foc, prm_filepath_bank, spec_nums=[ibank])
            # copy pdcal output nxs for both banks
            filepath, ext = path.splitext(prm_filepath_bank)
            nxs_filepath_bank = filepath + '.nxs'
            copy2(nxs_filepath, nxs_filepath_bank)
    logger.notice(f"\n\nCalibration files saved to: \"{calibration_dir}\"\n\n")
Пример #28
0
    def checkWorkspacesMatch(self, ws1, ws2):
        """
        Function to check two workspaces match
        Used when the result of a test produces more than a single workspace
        """

        checker = ms.AlgorithmManager.create("CompareWorkspaces")
        checker.setLogging(True)
        checker.setPropertyValue("Workspace1", ws1)
        checker.setPropertyValue("Workspace2", ws2)
        checker.setPropertyValue("Tolerance", str(self.tolerance))
        checker.setPropertyValue("CheckInstrument", "0")

        checker.execute()

        if not checker.getProperty("Result"):
            print(self.__class__.__name__)
            ms.SaveNexus(InputWorkspace=ws2,
                         Filename=self.__class__.__name__ + '-mismatch.nxs')
            return False

        return True
Пример #29
0
def _focus_mode_mods(output_file_paths, calibrated_spectra):
    index = 1
    append = False
    output_list = []
    for ws in calibrated_spectra:

        mantid.SaveGSS(InputWorkspace=ws,
                       Filename=output_file_paths["gss_filename"],
                       Append=append,
                       Bank=index)
        output_name = output_file_paths["output_name"] + "_mod" + str(index)
        dspacing_ws = mantid.ConvertUnits(InputWorkspace=ws,
                                          OutputWorkspace=output_name,
                                          Target="dSpacing")
        output_list.append(dspacing_ws)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"],
                         InputWorkspace=dspacing_ws,
                         Append=append)

        append = True
        index += 1
    return output_list
Пример #30
0
def create_vanadium_integration(van_run, calibration_directory):
    """
    create the vanadium integration for the run number set of the object

    @param van_run :: the run number for the vanadium
    @param calibration_directory :: the directory to save the output to
    """
    # find and load the vanadium
    van_file = _gen_filename(van_run)
    _, van_int_file = _get_van_names(van_run, calibration_directory)
    van_name = "eng_vanadium_ws"
    van_ws = simple.Load(van_file, OutputWorkspace=van_name)

    # make the integration workspace
    simple.NormaliseByCurrent(InputWorkspace=van_ws, OutputWorkspace=van_ws)
    # sensitivity correction for van
    ws_van_int = simple.Integration(InputWorkspace=van_ws)
    ws_van_int /= van_ws.blocksize()
    # save out the vanadium and delete the original workspace
    simple.SaveNexus(ws_van_int, van_int_file)
    simple.DeleteWorkspace(van_name)
    simple.DeleteWorkspace(ws_van_int)