Beispiel #1
0
    def testDoNotAdjustDetector(self):
        # Ensure detector position does not change when no offsets are given
        orig = LoadMD("HB3A_data.nxs", LoadHistory=False)
        orig_pos = orig.getExperimentInfo(0).getInstrument().getDetector(1).getPos()
        result = HB3AAdjustSampleNorm(InputWorkspaces=orig,
                                      DetectorHeightOffset=0.0,
                                      DetectorDistanceOffset=0.0)
        new_pos = result.getExperimentInfo(0).getInstrument().getDetector(1).getPos()

        # Verify detector adjustment
        self.__checkAdjustments(orig_pos, new_pos, 0.0, 0.0)

        DeleteWorkspace(orig, result)
 def runTest(self):
     # Load raw data (bank 1)
     wsMD = LoadMD(
         "WISH38237_MD.nxs")  # default so doesn't get overwrite van
     # For each mod vec, predict and integrate peaks and combine
     qs = [(0.15, 0, 0.3), (-0.15, 0, 0.3)]
     all_pks = CreatePeaksWorkspace(InstrumentWorkspace=wsMD,
                                    NumberOfPeaks=0,
                                    OutputWorkspace="all_pks")
     LoadIsawUB(InputWorkspace=all_pks,
                Filename='Wish_Diffuse_Scattering_ISAW_UB.mat')
     # PredictPeaks
     parent = PredictPeaks(InputWorkspace=all_pks,
                           WavelengthMin=0.8,
                           WavelengthMax=9.3,
                           MinDSpacing=0.5,
                           ReflectionCondition="Primitive")
     self._pfps = []
     self._saved_files = []
     for iq, q in enumerate(qs):
         wsname = f'pfp_{iq}'
         PredictFractionalPeaks(Peaks=parent,
                                IncludeAllPeaksInRange=True,
                                Hmin=0,
                                Hmax=0,
                                Kmin=1,
                                Kmax=1,
                                Lmin=0,
                                Lmax=1,
                                ReflectionCondition='Primitive',
                                MaxOrder=1,
                                ModVector1=",".join([str(qi) for qi in q]),
                                FracPeaks=wsname)
         FilterPeaks(InputWorkspace=wsname,
                     OutputWorkspace=wsname,
                     FilterVariable='Wavelength',
                     FilterValue=9.3,
                     Operator='<')  # should get rid of one peak in q1 table
         FilterPeaks(InputWorkspace=wsname,
                     OutputWorkspace=wsname,
                     FilterVariable='Wavelength',
                     FilterValue=0.8,
                     Operator='>')
         IntegratePeaksMD(InputWorkspace=wsMD,
                          PeakRadius='0.1',
                          BackgroundInnerRadius='0.1',
                          BackgroundOuterRadius='0.15',
                          PeaksWorkspace=wsname,
                          OutputWorkspace=wsname,
                          IntegrateIfOnEdge=False,
                          UseOnePercentBackgroundCorrection=False)
         all_pks = CombinePeaksWorkspaces(LHSWorkspace=all_pks,
                                          RHSWorkspace=wsname)
         self._pfps.append(ADS.retrieve(wsname))
     self._filepath = os.path.join(config['defaultsave.directory'],
                                   'WISH_IntegratedSatellite.int')
     SaveReflections(InputWorkspace=all_pks,
                     Filename=self._filepath,
                     Format='Jana')
     self._all_pks = all_pks
Beispiel #3
0
    def testAdjustDetector(self):
        # Test a slight adjustment of the detector position
        height_adj = 0.75
        dist_adj = 0.25
        orig = LoadMD("HB3A_data.nxs", LoadHistory=False)
        # Get the original detector position before adjustment
        orig_pos = orig.getExperimentInfo(0).getInstrument().getDetector(1).getPos()
        result = HB3AAdjustSampleNorm(InputWorkspaces=orig,
                                      DetectorHeightOffset=height_adj,
                                      DetectorDistanceOffset=dist_adj)
        # Get the updated detector position
        new_pos = result.getExperimentInfo(0).getInstrument().getDetector(1).getPos()

        # Verify detector adjustment
        self.__checkAdjustments(orig_pos, new_pos, height_adj, dist_adj)

        DeleteWorkspace(orig, result)
Beispiel #4
0
from mantid.simpleapi import LoadMD, CreateMDHistoWorkspace
from mantid.geometry import SpaceGroupFactory
from astropy.convolution import convolve, convolve_fft, Gaussian1DKernel
import numpy as np
import matplotlib.pyplot as plt

filename = '/SNS/CORELLI/IPTS-16344/shared/symm_007K_long_all_ub_13feb.nxs'
filename = '/home/rwp/symm_007K_long_all_ub_13feb_small.nxs'
space_group = 'I 2 3'

ws = LoadMD(filename, LoadHistory=False)

# Check alignment
if not np.all(
        ws.getExperimentInfo(0).run().getLogData('W_MATRIX').value ==
    [1., 0., 0., 0., 1., 0., 0., 0., 1.]):
    print('Not alligned with HKL')
    exit()

# Check dimensions
# Check centered on zero
# Should also check center bin is 0
dim_list = []
dim_names = ['[H,0,0]', '[0,K,0]', '[0,0,L]']
for d in range(ws.getNumDims()):
    dim = ws.getDimension(d)
    if dim.name not in dim_names:
        print("Dimensions must be one of ", dim_names)
        exit()
    if dim.getMaximum() != -dim.getMinimum():
        print('Workspace dimensions must be centered on zero')
Beispiel #5
0
from mantid.simpleapi import LoadMD
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import reconstruction, ball, disk, erosion, closing, opening
from skimage.feature import peak_local_max
from skimage.restoration import inpaint
from scipy import ndimage as ndi

filename = '/SNS/CORELLI/IPTS-16344/shared/symm_007K_long_all_ub_13feb.nxs'

ws = LoadMD(filename, LoadHistory=False)
signal = ws.getSignalArray().copy()

# Do something with nan's and inf's
signal[np.isnan(signal)] = 0
signal[np.isinf(signal)] = 0

image = signal[251]
seed = np.copy(image)
seed[1:-1, 1:-1] = image.min()
mask = image
dilated = reconstruction(seed, mask, method='dilation')

dilated2 = reconstruction(seed, mask, method='dilation', selem=disk(3))

plt.imshow(dilated, vmax=1e-4)
plt.show()

eros = erosion(image)

eros = erosion(image, selem=disk(2))
Beispiel #6
0
from mantid.simpleapi import LoadMD
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.transforms as mtransforms
import numpy as np

benzil = LoadMD('/SNS/users/rwp/benzil/benzil_300K_bkg_subtract_sym_All_noCC_flat2_fft.nxs')
signal = benzil.getSignalArray()


x, y = np.meshgrid(np.linspace(-10,10,501),np.linspace(-10,10,501))
plt.pcolormesh(x, y, signal[:,:,252], norm=colors.SymLogNorm(linthresh=0.2, linscale=0, vmin=-1.0, vmax=1.0), cmap='coolwarm')
plt.colorbar()
plt.show()

plt.pcolormesh(x, y, signal[:,260,:], norm=colors.SymLogNorm(linthresh=0.05, linscale=1, vmin=-1.0, vmax=1.0), cmap='coolwarm')
plt.colorbar()
plt.show()


fig = plt.pcolormesh(x, y, signal[:,:,252].transpose(), vmax=1,vmin=0,cmap='viridis')
trans_data = mtransforms.Affine2D().skew(np.arctan(np.sin(np.deg2rad(-30))), 0) + fig.get_transform()
fig.set_transform(trans_data)
plt.show()


fig = plt.pcolormesh(x, y, signal[:,:,252], norm=colors.SymLogNorm(linthresh=0.1, linscale=1, vmin=-1.0, vmax=1.0), cmap='coolwarm')
trans_data = mtransforms.Affine2D().skew(np.arctan(np.sin(np.deg2rad(-30))), 0) + fig.get_transform()
fig.set_transform(trans_data)
plt.colorbar()
plt.show()
Beispiel #7
0
from mantid.simpleapi import LoadMD
from mantid.kernel import version_str
import json
import sys
import getpass
import datetime

output_file = sys.argv[1]

md = LoadMD(output_file)

if not md.isMDHistoWorkspace():
    raise ValueError('Needs to be MDHistoWorkspace')

output = {}

output['output_files'] = [{'location': output_file,
                           'type': 'processed',
                           'purpose': 'reduced-data',
                           'fields':{'mdhistoworkspace.experiment0.sample.material.temperature':'temperature',
                                     'mdhistoworkspace.data.signal@axes':'axes',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.orientation_matrix':'orientation_matrix',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_a':'unit_cell_a',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_b':'unit_cell_b',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_c':'unit_cell_c',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_alpha':'unit_cell_alpha',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_beta':'unit_cell_beta',
                                     'mdhistoworkspace.experiment0.sample.oriented_lattice.unit_cell_gamma':'unit_cell_gamma'
                           }}]
output['user'] = getpass.getuser()
output['created'] = datetime.datetime.now().replace(microsecond=0).isoformat()+'.00-05:00'
 def _load_MDWorkspace_and_test_it(self, save_name):
     filename = self.working_directory + '/' + save_name + ".nxs"
     ws = LoadMD(Filename=filename)
     ws_is_a_mdworkspace = isinstance(ws, IMDEventWorkspace) or isinstance(
         ws, MDHistoWorkspace)
     self.assertEqual(ws_is_a_mdworkspace, True)
Beispiel #9
0
    def PyExec(self):
        load_van = not self.getProperty("VanadiumFile").isDefault
        load_files = not self.getProperty("Filename").isDefault

        output = self.getProperty("OutputType").value

        if load_files:
            datafiles = self.getProperty("Filename").value
        else:
            datafiles = list(
                map(str.strip,
                    self.getProperty("InputWorkspaces").value.split(",")))

        prog = Progress(self, 0.0, 1.0, len(datafiles) + 1)

        vanadiumfile = self.getProperty("VanadiumFile").value
        vanws = self.getProperty("VanadiumWorkspace").value
        height = self.getProperty("DetectorHeightOffset").value
        distance = self.getProperty("DetectorDistanceOffset").value

        wslist = []

        out_ws = self.getPropertyValue("OutputWorkspace")
        out_ws_name = out_ws

        if load_van:
            vanws = LoadMD(vanadiumfile, StoreInADS=False)

        has_multiple = len(datafiles) > 1

        for in_file in datafiles:
            if load_files:
                scan = LoadMD(in_file,
                              LoadHistory=False,
                              OutputWorkspace="__scan")
            else:
                scan = mtd[in_file]

            # Make sure the workspace has experiment info, otherwise SetGoniometer will add some, causing issues.
            if scan.getNumExperimentInfo() == 0:
                raise RuntimeError(
                    "No experiment info was found in '{}'".format(in_file))

            prog.report()
            self.log().information("Processing '{}'".format(in_file))

            SetGoniometer(Workspace=scan,
                          Axis0='omega,0,1,0,-1',
                          Axis1='chi,0,0,1,-1',
                          Axis2='phi,0,1,0,-1',
                          Average=False)
            # If processing multiple files, append the base name to the given output name
            if has_multiple:
                if load_files:
                    out_ws_name = out_ws + "_" + os.path.basename(
                        in_file).strip(',.nxs')
                else:
                    out_ws_name = out_ws + "_" + in_file
                wslist.append(out_ws_name)

            exp_info = scan.getExperimentInfo(0)
            self.__move_components(exp_info, height, distance)

            # Get the wavelength from experiment info if it exists, or fallback on property value
            wavelength = self.__get_wavelength(exp_info)

            # set the run number to be the same as scan number, this will be used for peaks
            if not exp_info.run().hasProperty('run_number') and exp_info.run(
            ).hasProperty('scan'):
                try:
                    exp_info.mutableRun().addProperty(
                        'run_number',
                        int(exp_info.run().getProperty('scan').value), True)
                except ValueError:
                    # scan must be a int
                    pass

            # Use ConvertHFIRSCDtoQ (and normalize van), or use ConvertWANDSCtoQ which handles normalization itself
            if output == "Q-sample events":
                norm_data = self.__normalization(scan, vanws, load_files)
                minvals = self.getProperty("MinValues").value
                maxvals = self.getProperty("MaxValues").value
                merge = self.getProperty("MergeInputs").value
                ConvertHFIRSCDtoMDE(InputWorkspace=norm_data,
                                    Wavelength=wavelength,
                                    MinValues=minvals,
                                    MaxValues=maxvals,
                                    OutputWorkspace=out_ws_name)
                DeleteWorkspace(norm_data)
            elif output == 'Q-sample histogram':
                bin0 = self.getProperty("BinningDim0").value
                bin1 = self.getProperty("BinningDim1").value
                bin2 = self.getProperty("BinningDim2").value
                # Convert to Q space and normalize with from the vanadium
                ConvertWANDSCDtoQ(
                    InputWorkspace=scan,
                    NormalisationWorkspace=vanws,
                    Frame='Q_sample',
                    Wavelength=wavelength,
                    NormaliseBy=self.getProperty("NormaliseBy").value,
                    BinningDim0=bin0,
                    BinningDim1=bin1,
                    BinningDim2=bin2,
                    OutputWorkspace=out_ws_name)
                if load_files:
                    DeleteWorkspace(scan)
            else:
                norm_data = self.__normalization(scan, vanws, load_files)
                RenameWorkspace(norm_data, OutputWorkspace=out_ws_name)

        if has_multiple:
            out_ws_name = out_ws
            if output == "Q-sample events" and merge:
                MergeMD(InputWorkspaces=wslist, OutputWorkspace=out_ws_name)
                DeleteWorkspaces(wslist)
            else:
                GroupWorkspaces(InputWorkspaces=wslist,
                                OutputWorkspace=out_ws_name)

        # Don't delete workspaces if they were passed in
        if load_van:
            DeleteWorkspace(vanws)

        self.setProperty("OutputWorkspace", out_ws_name)
Beispiel #10
0
from mantid.simpleapi import LoadNexus, LoadMD

for _ in range(5):
    ws1 = LoadNexus('/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_3000.nxs')
    ws2 = LoadNexus(
        '/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_3000_group_4x4.nxs')
    md1 = LoadMD('/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_3000_MDE.nxs')
    md2 = LoadMD(
        '/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_3000_group_4x4_MDE.nxs')
    print()
Beispiel #11
0
# Load data and accumulate to Q sample MD event workspace

iptsdir = '/HFIR/HB2C/IPTS-{}/'.format(IPTS)

name_MDE = name + '_MDE'

if not append and name_MDE in mtd:
    DeleteWorkspace(name_MDE)

for run in range(first_run, last_run + 1, load_every):
    if use_autoreduced:
        filename = iptsdir + 'shared/autoreduce/HB2C_{}_MDE.nxs'.format(run)
        try:
            LoadMD(Filename=filename,
                   LoadHistory=False,
                   OutputWorkspace='__md')
        except ValueError:
            filename = iptsdir + 'nexus/HB2C_{}.nxs.h5'.format(run)
            LoadWAND(filename, OutputWorkspace='__ws')
            ConvertToMD('__ws',
                        QDimensions='Q3D',
                        dEAnalysisMode='Elastic',
                        Q3DFrames='Q_sample',
                        OutputWorkspace='__md',
                        MinValues='-10,-1,-10',
                        MaxValues='10,1,10')
    accumulateMD('__md', OutputWorkspace=name_MDE)

SaveMD(
    name_MDE, iptsdir + 'shared/' + name +